From 91161c74ebd7cf64e1016b925a3c13e205a663df Mon Sep 17 00:00:00 2001 From: Owen Wu <1449069+yubing744@users.noreply.github.com> Date: Sat, 21 Sep 2024 00:11:30 +0800 Subject: [PATCH 1/7] Owen/issues 2654/example cosmwasm bitseed generator (#2656) * feat: rebase from upstream main * feat: add test for inscribe_verify * feat: update examples bitseed_generator README.md * feat: simple inscribe_generate * feat: fmt code * feat: add rooch network copyright * feat: rebase from upstream main 2 * feat: rebase from upstream main 3 * feat: rebase from upstream main 4 * feat: fix lint error * feat: update bitseed generator README.md * feat: change bitseed generator README * feat: add empty move project in bitseed_generator --- .cargo/config.toml | 4 + Cargo.lock | 178 ++++++++++++- Cargo.toml | 1 + examples/bitseed_generator/.gitignore | 2 + examples/bitseed_generator/Cargo.toml | 12 + examples/bitseed_generator/Makefile | 17 ++ examples/bitseed_generator/Move.toml | 14 + examples/bitseed_generator/README.md | 58 +++++ examples/bitseed_generator/sources/empty.move | 6 + examples/bitseed_generator/src/lib.rs | 246 ++++++++++++++++++ 10 files changed, 528 insertions(+), 10 deletions(-) create mode 100644 examples/bitseed_generator/.gitignore create mode 100644 examples/bitseed_generator/Cargo.toml create mode 100644 examples/bitseed_generator/Makefile create mode 100644 examples/bitseed_generator/Move.toml create mode 100644 examples/bitseed_generator/README.md create mode 100644 examples/bitseed_generator/sources/empty.move create mode 100644 examples/bitseed_generator/src/lib.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index b5c5a2195b..75c9564058 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -16,3 +16,7 @@ rustflags = [ "-C", "link-arg=/STACK:8000000" # Set stack to 8 MB ] + +[alias] +wasm = "build --target wasm32-unknown-unknown --release" +wasm-debug = "build --target wasm32-unknown-unknown" diff --git a/Cargo.lock b/Cargo.lock index dfb4c9afa7..3ed75cbeac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -143,7 +143,7 @@ dependencies = [ "bytes", "cfg-if", "const-hex", - "derive_more", + "derive_more 0.99.18", "hex-literal", "itoa", "k256 0.13.3", @@ -332,6 +332,7 @@ dependencies = [ "hashbrown 0.13.2", "itertools 0.10.5", "num-traits 0.2.19", + "rayon", "zeroize", ] @@ -369,6 +370,7 @@ dependencies = [ "num-bigint 0.4.5", "num-traits 0.2.19", "paste", + "rayon", "rustc_version 0.4.0", "zeroize", ] @@ -531,6 +533,7 @@ checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" dependencies = [ "num-traits 0.2.19", "rand 0.8.5", + "rayon", ] [[package]] @@ -1208,6 +1211,14 @@ dependencies = [ "typenum", ] +[[package]] +name = "bitseed_generator" +version = "0.1.0" +dependencies = [ + "cosmwasm-std", + "serde 1.0.210", +] + [[package]] name = "bitvec" version = "0.20.4" @@ -1338,6 +1349,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "bnum" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e31ea183f6ee62ac8b8a8cf7feddd766317adfb13ff469de57ce033efd6a790" + [[package]] name = "bollard-stubs" version = "1.42.0-rc.3" @@ -2122,6 +2139,69 @@ dependencies = [ "windows-sys 0.33.0", ] +[[package]] +name = "cosmwasm-core" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d905990ef3afb5753bb709dc7de88e9e370aa32bcc2f31731d4b533b63e82490" + +[[package]] +name = "cosmwasm-crypto" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b2a7bd9c1dd9a377a4dc0f4ad97d24b03c33798cd5a6d7ceb8869b41c5d2f2d" +dependencies = [ + "ark-bls12-381", + "ark-ec", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "cosmwasm-core", + "digest 0.10.7", + "ecdsa 0.16.9", + "ed25519-zebra", + "k256 0.13.3", + "num-traits 0.2.19", + "p256", + "rand_core 0.6.4", + "rayon", + "sha2 0.10.8", + "thiserror", +] + +[[package]] +name = "cosmwasm-derive" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "029910b409398fdf81955d7301b906caf81f2c42b013ea074fbd89720229c424" +dependencies = [ + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.65", +] + +[[package]] +name = "cosmwasm-std" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51dec99a2e478715c0a4277f0dbeadbb8466500eb7dec873d0924edd086e77f1" +dependencies = [ + "base64 0.22.1", + "bech32 0.11.0", + "bnum", + "cosmwasm-core", + "cosmwasm-crypto", + "cosmwasm-derive", + "derive_more 1.0.0", + "hex", + "rand_core 0.6.4", + "schemars", + "serde 1.0.210", + "serde-json-wasm", + "sha2 0.10.8", + "static_assertions", + "thiserror", +] + [[package]] name = "cpp_demangle" version = "0.4.3" @@ -2436,7 +2516,7 @@ dependencies = [ "console", "cucumber-codegen", "cucumber-expressions", - "derive_more", + "derive_more 0.99.18", "drain_filter_polyfill", "either", "futures", @@ -2476,7 +2556,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d794fed319eea24246fb5f57632f7ae38d61195817b7eb659455aa5bdd7c1810" dependencies = [ - "derive_more", + "derive_more 0.99.18", "either", "nom 7.1.3", "nom_locate", @@ -2484,6 +2564,33 @@ dependencies = [ "regex-syntax 0.7.5", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version 0.4.0", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.65", +] + [[package]] name = "curve25519-dalek-ng" version = "4.1.1" @@ -2837,6 +2944,27 @@ dependencies = [ "syn 2.0.65", ] +[[package]] +name = "derive_more" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a9b99b9cbbe49445b21764dc0625032a89b145a2642e67603e1c936f5458d05" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" +dependencies = [ + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.65", + "unicode-xid 0.2.4", +] + [[package]] name = "deunicode" version = "1.6.0" @@ -3121,6 +3249,21 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ed25519-zebra" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d9ce6874da5d4415896cd45ffbc4d1cfc0c4f9c079427bd870742c30f2f65a9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "hashbrown 0.14.5", + "hex", + "rand_core 0.6.4", + "sha2 0.10.8", + "zeroize", +] + [[package]] name = "either" version = "1.12.0" @@ -3686,7 +3829,7 @@ dependencies = [ "blst", "bs58 0.4.0", "curve25519-dalek-ng", - "derive_more", + "derive_more 0.99.18", "digest 0.10.7", "ecdsa 0.16.9", "ed25519-consensus", @@ -3737,7 +3880,7 @@ dependencies = [ "blst", "bs58 0.4.0", "curve25519-dalek-ng", - "derive_more", + "derive_more 0.99.18", "digest 0.10.7", "ecdsa 0.16.9", "ed25519-consensus", @@ -3808,7 +3951,7 @@ dependencies = [ "ark-snark", "blst", "byte-slice-cast", - "derive_more", + "derive_more 0.99.18", "fastcrypto 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "ff 0.13.0", "im", @@ -3880,6 +4023,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "filetime" version = "0.2.23" @@ -7493,7 +7642,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb572a6faac38e826e5a6e8a143d6104d47ce75757a93dfd31912a0b91cada8d" dependencies = [ "bitcoin 0.30.2", - "derive_more", + "derive_more 0.99.18", "serde 1.0.210", "serde_with 3.9.0", "thiserror", @@ -9041,7 +9190,7 @@ dependencies = [ "bitvec 1.0.1", "c-kzg", "cfg-if", - "derive_more", + "derive_more 0.99.18", "dyn-clone", "enumn", "hashbrown 0.14.5", @@ -9989,7 +10138,7 @@ dependencies = [ "bs58 0.5.1", "chacha20poly1305", "clap 4.5.17", - "derive_more", + "derive_more 0.99.18", "enum_dispatch", "ethers", "eyre", @@ -10367,7 +10516,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eca070c12893629e2cc820a9761bedf6ce1dcddc9852984d1dc734b8bd9bd024" dependencies = [ "cfg-if", - "derive_more", + "derive_more 0.99.18", "parity-scale-codec 3.6.12", "scale-info-derive", ] @@ -10659,6 +10808,15 @@ dependencies = [ "serde 0.8.23", ] +[[package]] +name = "serde-json-wasm" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05da0d153dd4595bdffd5099dc0e9ce425b205ee648eb93437ff7302af8c9a5" +dependencies = [ + "serde 1.0.210", +] + [[package]] name = "serde-reflection" version = "0.3.6" diff --git a/Cargo.toml b/Cargo.toml index 9fe48227ce..6c8859c089 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,7 @@ members = [ "frameworks/moveos-stdlib", "frameworks/rooch-framework", "frameworks/rooch-nursery", + "examples/bitseed_generator", ] default-members = [ diff --git a/examples/bitseed_generator/.gitignore b/examples/bitseed_generator/.gitignore new file mode 100644 index 0000000000..d6b374c175 --- /dev/null +++ b/examples/bitseed_generator/.gitignore @@ -0,0 +1,2 @@ +/target +/artifacts diff --git a/examples/bitseed_generator/Cargo.toml b/examples/bitseed_generator/Cargo.toml new file mode 100644 index 0000000000..ae38c02171 --- /dev/null +++ b/examples/bitseed_generator/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "bitseed_generator" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +cosmwasm-std = { version = "2.1.3", features = ["staking"] } +serde = { version = "1.0.103", default-features = false, features = ["derive"] } + diff --git a/examples/bitseed_generator/Makefile b/examples/bitseed_generator/Makefile new file mode 100644 index 0000000000..6c66a67f2d --- /dev/null +++ b/examples/bitseed_generator/Makefile @@ -0,0 +1,17 @@ +.PHONY: all clean build test optimize + +all: build + +build: + cargo wasm --target-dir="./target" + +test: + cargo test + +optimize: build + @mkdir -p ./artifacts + @wasm-opt -Os --signext-lowering "./target/wasm32-unknown-unknown/release/bitseed_generator.wasm" -o "./artifacts/bitseed_generator_opt.wasm" + @wasm-snip --snip-rust-fmt-code --snip-rust-panicking-code --skip-producers-section ./artifacts/bitseed_generator_opt.wasm -o ./artifacts/bitseed_generator_snip.wasm + +clean: + rm -rf ./artifacts && rm -rf ./target diff --git a/examples/bitseed_generator/Move.toml b/examples/bitseed_generator/Move.toml new file mode 100644 index 0000000000..e63c75d2c5 --- /dev/null +++ b/examples/bitseed_generator/Move.toml @@ -0,0 +1,14 @@ +[package] +name = "bitseed_generator" +version = "0.0.1" + +[dependencies] +MoveosStdlib = { local = "../../frameworks/moveos-stdlib" } + +[addresses] +rooch_examples = "_" +moveos_std = "0x2" +rooch_framework = "0x3" + +[dev-addresses] +rooch_examples = "0x42" \ No newline at end of file diff --git a/examples/bitseed_generator/README.md b/examples/bitseed_generator/README.md new file mode 100644 index 0000000000..bd144ffe1e --- /dev/null +++ b/examples/bitseed_generator/README.md @@ -0,0 +1,58 @@ +# Inscribe Generate Bitseed Contract + +A CosmWasm smart contract for generating and verifying custom attributes for bitseed assets or NFTs. + +## Features + +- Custom attribute generation rules (e.g., range, list) +- Deterministic generation based on seed and user input +- Attribute verification +- Extensible design + +## Build, Test, and Optimize + +### Prerequisites + +Before building and optimizing the contract, you need to install the following dependencies: + +1. Rust and Cargo (https://www.rust-lang.org/tools/install) +2. wasm-pack (https://rustwasm.github.io/wasm-pack/installer/) +3. wasm-opt (part of the Binaryen toolkit): + - On Ubuntu/Debian: `sudo apt-get install binaryen` + - On macOS with Homebrew: `brew install binaryen` + - For other systems, visit: https://github.com/WebAssembly/binaryen +4. wasm-snip: + ``` + cargo install wasm-snip + ``` + +### Build + +``` +cargo wasm +``` + +### Test + +``` +cargo test +``` + +### Optimize + +To optimize the WASM binary, run: + +``` +make optimize +``` + +This command will build the contract, optimize it using `wasm-opt`, and apply `wasm-snip` to further reduce the binary size. The optimized WASM file will be placed in the `./artifacts` directory. + +## Usage + +Deploy to a CosmWasm-compatible blockchain and interact using: +- `InscribeGenerate`: Generate attributes +- `InscribeVerify`: Verify attributes +- `IndexerGenerate`: Generate for indexing + +Refer to the contract's query messages for input/output structures. diff --git a/examples/bitseed_generator/sources/empty.move b/examples/bitseed_generator/sources/empty.move new file mode 100644 index 0000000000..dd61e2760d --- /dev/null +++ b/examples/bitseed_generator/sources/empty.move @@ -0,0 +1,6 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +module rooch_examples::empty { + fun init() {} +} diff --git a/examples/bitseed_generator/src/lib.rs b/examples/bitseed_generator/src/lib.rs new file mode 100644 index 0000000000..b9f2cf7ecf --- /dev/null +++ b/examples/bitseed_generator/src/lib.rs @@ -0,0 +1,246 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use cosmwasm_std::{ + entry_point, to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct InstantiateMsg {} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum QueryMsg { + InscribeGenerate(InputData), + InscribeVerify { + input: InputData, + output: OutputData, + }, + IndexerGenerate(InputData), +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct InputData { + seed: String, + user_input: String, + attributes: Vec, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct AttributeGenerateRule { + key: String, + rule_type: AttributeRuleType, + parameters: Vec, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub enum AttributeRuleType { + Range, + List, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct OutputData { + amount: u32, + attributes: Vec, + content: Binary, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct Attribute { + key: String, + value: String, +} + +#[entry_point] +pub fn instantiate( + _deps: DepsMut, + _env: Env, + _info: MessageInfo, + _msg: InstantiateMsg, +) -> StdResult { + Ok(Response::default()) +} + +#[entry_point] +pub fn query(_deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { + match msg { + QueryMsg::InscribeGenerate(input) => to_json_binary(&inscribe_generate(input)?), + QueryMsg::InscribeVerify { input, output } => { + to_json_binary(&inscribe_verify(input, output)?) + } + QueryMsg::IndexerGenerate(input) => to_json_binary(&indexer_generate(input)?), + } +} + +fn inscribe_generate(input: InputData) -> StdResult { + let hash_value = hash_str_uint32(&format!("{}{}", input.seed, input.user_input)); + + let mut attributes = vec![Attribute { + key: "id".to_string(), + value: input.user_input.clone(), + }]; + + for attr in input.attributes { + let value = match attr.rule_type { + AttributeRuleType::Range => { + if attr.parameters.len() == 2 { + if let (Ok(min), Ok(max)) = ( + attr.parameters[0].parse::(), + attr.parameters[1].parse::(), + ) { + let random_value = min + (hash_value % (max - min + 1)); + random_value.to_string() + } else { + continue; // Skip this attribute if parsing fails + } + } else { + continue; // Skip this attribute if parameters are incorrect + } + } + AttributeRuleType::List => { + if !attr.parameters.is_empty() { + let index = (hash_value as usize) % attr.parameters.len(); + attr.parameters[index].clone() + } else { + continue; // Skip this attribute if the list is empty + } + } + }; + + attributes.push(Attribute { + key: attr.key, + value, + }); + } + + Ok(OutputData { + amount: 1000, + attributes, + content: Binary::default(), + }) +} + +fn inscribe_verify(input: InputData, output: OutputData) -> StdResult { + let generated_output = inscribe_generate(input)?; + Ok(generated_output == output) +} + +fn indexer_generate(input: InputData) -> StdResult { + inscribe_generate(input) +} + +fn hash_str_uint32(str: &str) -> u32 { + let mut hash: u32 = 0x811c9dc5; + let prime: u32 = 0x1000193; + + for &byte in str.as_bytes() { + hash ^= u32::from(byte); + hash = hash.wrapping_mul(prime); + } + + hash +} + +#[cfg(test)] +mod tests { + use super::*; + use cosmwasm_std::from_json; + use cosmwasm_std::testing::{mock_dependencies, mock_env}; + + #[test] + fn test_inscribe_generate() { + // Step 1: Set up the test environment + let deps = mock_dependencies(); + let env = mock_env(); + + // Step 2: Prepare test data + let input = InputData { + seed: "test_seed".to_string(), + user_input: "test_user_input".to_string(), + attributes: vec![ + AttributeGenerateRule { + key: "test_range".to_string(), + rule_type: AttributeRuleType::Range, + parameters: vec!["1".to_string(), "10".to_string()], + }, + AttributeGenerateRule { + key: "test_list".to_string(), + rule_type: AttributeRuleType::List, + parameters: vec!["A".to_string(), "B".to_string(), "C".to_string()], + }, + ], + }; + + // Step 3: Call the query function + let query_msg = QueryMsg::InscribeGenerate(input); + let binary_response = query(deps.as_ref(), env, query_msg).unwrap(); + + // Step 4: Parse the response + let output: OutputData = from_json(binary_response).unwrap(); + + // Step 5: Validate the results + assert_eq!(output.amount, 1000); + assert_eq!(output.attributes.len(), 3); // id + test_range + test_list + + // Validate id attribute + assert_eq!(output.attributes[0].key, "id"); + assert_eq!(output.attributes[0].value, "test_user_input"); + + // Validate test_range attribute + assert_eq!(output.attributes[1].key, "test_range"); + let range_value: u32 = output.attributes[1].value.parse().unwrap(); + assert!((1..=10).contains(&range_value)); + + // Validate test_list attribute + assert_eq!(output.attributes[2].key, "test_list"); + assert!(["A", "B", "C"].contains(&output.attributes[2].value.as_str())); + + // Verify that content is empty + assert_eq!(output.content, Binary::default()); + } + + #[test] + fn test_inscribe_verify() { + // Set up dependencies and environment + let deps = mock_dependencies(); + let env = mock_env(); + + // Prepare test data + let input = InputData { + seed: "test_seed".to_string(), + user_input: "test_user_input".to_string(), + attributes: vec![AttributeGenerateRule { + key: "test_range".to_string(), + rule_type: AttributeRuleType::Range, + parameters: vec!["1".to_string(), "10".to_string()], + }], + }; + + // Generate expected output + let expected_output = inscribe_generate(input.clone()).unwrap(); + + // Test verification with correct output + let query_msg = QueryMsg::InscribeVerify { + input: input.clone(), + output: expected_output.clone(), + }; + let binary_response = query(deps.as_ref(), env.clone(), query_msg).unwrap(); + let result: bool = from_json(binary_response).unwrap(); + assert!(result); + + // Test verification with incorrect output + let incorrect_output = OutputData { + amount: 999, // Incorrect amount + ..expected_output + }; + let query_msg = QueryMsg::InscribeVerify { + input, + output: incorrect_output, + }; + let binary_response = query(deps.as_ref(), env, query_msg).unwrap(); + let result: bool = from_json(binary_response).unwrap(); + assert!(!result); + } +} From c482a277f559763e88b6bd431e45769f35358dd7 Mon Sep 17 00:00:00 2001 From: popcnt <142196625+popcnt1@users.noreply.github.com> Date: Sat, 21 Sep 2024 14:33:33 +0800 Subject: [PATCH 2/7] feat(rooch-da): add data length tracking to segments (#2664) * feat(rooch-da): add data length tracking to segments Added a data_len field to SegmentV0 for tracking data length. Refactored related methods to handle the data length field, ensuring accurate serialization and deserialization. This improves segment management within the chunk processing. * fix(rooch-da): validate byte length in segment Prevent out-of-bounds errors by ensuring byte array length suffices before processing segment data. This adds a check for the minimum required length to avoid runtime panics. --- crates/rooch-da/src/chunk.rs | 1 + crates/rooch-da/src/segment.rs | 27 ++++++++++++++----- .../src/server/openda/actor/server.rs | 21 ++++++++++++--- 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/crates/rooch-da/src/chunk.rs b/crates/rooch-da/src/chunk.rs index b8825672c9..3f5789d113 100644 --- a/crates/rooch-da/src/chunk.rs +++ b/crates/rooch-da/src/chunk.rs @@ -97,6 +97,7 @@ impl Chunk for ChunkV0 { segment_number: i as u64, }, is_last: i == segments_count - 1, // extra info overhead is much smaller than max_block_size - max_segment_size + data_len: data.len() as u64, // *_checksum will be filled in to_bytes method of Segment data_checksum: 0, checksum: 0, diff --git a/crates/rooch-da/src/segment.rs b/crates/rooch-da/src/segment.rs index 354105d8ab..61cd75a285 100644 --- a/crates/rooch-da/src/segment.rs +++ b/crates/rooch-da/src/segment.rs @@ -16,13 +16,14 @@ pub trait Segment: fmt::Debug + Send { fn is_last(&self) -> bool; } -pub const SEGMENT_V0_DATA_OFFSET: usize = 42; -pub const SEGMENT_V0_CHECKSUM_OFFSET: usize = 34; +pub const SEGMENT_V0_DATA_OFFSET: usize = 50; +pub const SEGMENT_V0_CHECKSUM_OFFSET: usize = 42; #[derive(Serialize, Debug, PartialEq, Clone)] pub struct SegmentV0 { pub id: SegmentID, pub is_last: bool, // is last segment in chunk + pub data_len: u64, // length of data pub data_checksum: u64, // checksum of data, xxh3_64 pub checksum: u64, // checksum of above fields(exclude data) and version after to_bytes, xxh3_64 @@ -44,9 +45,20 @@ impl SegmentV0 { let chunk_id = u128::from_le_bytes(bytes[1..17].try_into()?); let segment_number = u64::from_le_bytes(bytes[17..25].try_into()?); let is_last = bytes[25] != 0; - let data_checksum = u64::from_le_bytes(bytes[26..34].try_into()?); - let checksum = u64::from_le_bytes(bytes[34..SEGMENT_V0_DATA_OFFSET].try_into()?); - let data = bytes[SEGMENT_V0_DATA_OFFSET..].to_vec(); + let data_len = u64::from_le_bytes(bytes[26..34].try_into()?); + let data_checksum = u64::from_le_bytes(bytes[34..42].try_into()?); + let checksum = u64::from_le_bytes(bytes[42..SEGMENT_V0_DATA_OFFSET].try_into()?); + // check bytes has enough length + if bytes.len() < SEGMENT_V0_DATA_OFFSET + data_len as usize { + return Err(anyhow::anyhow!(format!( + "segment_v0: bytes:{} less than exp header:{} + data:{}", + bytes.len(), + SEGMENT_V0_DATA_OFFSET, + data_len as usize + ))); + } + let data = + bytes[SEGMENT_V0_DATA_OFFSET..SEGMENT_V0_DATA_OFFSET + data_len as usize].to_vec(); let exp_checksum = xxh3_64(&bytes[0..SEGMENT_V0_CHECKSUM_OFFSET]); if exp_checksum != checksum { @@ -64,6 +76,7 @@ impl SegmentV0 { segment_number, }, is_last, + data_len, data_checksum, checksum, data, @@ -73,11 +86,12 @@ impl SegmentV0 { impl Segment for SegmentV0 { fn to_bytes(&self) -> Vec { - let mut bytes = Vec::with_capacity(SEGMENT_V0_DATA_OFFSET + self.data.len()); + let mut bytes = Vec::with_capacity(SEGMENT_V0_DATA_OFFSET + self.data_len as usize); bytes.push(ChunkVersion::V0.into()); // version bytes.extend_from_slice(&self.id.chunk_id.to_le_bytes()); bytes.extend_from_slice(&self.id.segment_number.to_le_bytes()); bytes.push(self.is_last as u8); + bytes.extend_from_slice(&self.data_len.to_le_bytes()); let data_checksum = xxh3_64(&self.data); bytes.extend_from_slice(&data_checksum.to_le_bytes()); let checksum = xxh3_64(&bytes[0..SEGMENT_V0_CHECKSUM_OFFSET]); @@ -179,6 +193,7 @@ mod tests { segment_number: 12345678, }, is_last: true, + data_len: 5, data_checksum: 1234567890, checksum: 12345678, data: vec![1, 2, 3, 4, 5], diff --git a/crates/rooch-da/src/server/openda/actor/server.rs b/crates/rooch-da/src/server/openda/actor/server.rs index 4db1bcd310..06b0a19d64 100644 --- a/crates/rooch-da/src/server/openda/actor/server.rs +++ b/crates/rooch-da/src/server/openda/actor/server.rs @@ -16,12 +16,14 @@ use crate::chunk::{Chunk, ChunkV0}; use rooch_config::da_config::{DAServerOpenDAConfig, OpenDAScheme}; use crate::messages::PutBatchInternalDAMessage; +use crate::segment::SegmentID; pub struct DAServerOpenDAActor { max_segment_size: usize, operator: Operator, } +pub const CHUNK_V0_PREFIX: &str = "chunk_v0"; pub const DEFAULT_MAX_SEGMENT_SIZE: u64 = 4 * 1024 * 1024; pub const DEFAULT_MAX_RETRY_TIMES: usize = 4; @@ -119,9 +121,9 @@ impl DAServerOpenDAActor { let segments = chunk.to_segments(self.max_segment_size); for segment in segments { let bytes = segment.to_bytes(); + match self - .operator - .write(&segment.get_id().to_string(), bytes) + .write_segment(segment.get_id(), bytes, CHUNK_V0_PREFIX.to_string()) .await { Ok(_) => { @@ -136,13 +138,26 @@ impl DAServerOpenDAActor { segment.get_id(), e, ); - return Err(e.into()); + return Err(e); } } } Ok(()) } + + async fn write_segment( + &self, + segment_id: SegmentID, + segment_bytes: Vec, + prefix: String, + ) -> Result<()> { + let path = format!("{}/{}", prefix, segment_id); + let mut w = self.operator.writer(&path).await?; + w.write(segment_bytes).await?; + w.close().await?; + Ok(()) + } } fn check_config_exist( From 621cef6a970228158f62d7f59fb173d573d1da4a Mon Sep 17 00:00:00 2001 From: popcnt <142196625+popcnt1@users.noreply.github.com> Date: Sat, 21 Sep 2024 16:43:42 +0800 Subject: [PATCH 3/7] fix(da): rm open-da(gcs) for mainnet deploy workflow (#2665) 1. rm open-da(gcs) for mainnet deploy workflow 2. switch to save last block instead of a map: Replaced BTreeMap with an Option to store only the last block in StateCommitmentChain. Updated methods for adding and retrieving the last block accordingly, streamlining state management. --- .github/workflows/deploy_mainnet.yml | 4 +--- crates/rooch-proposer/src/scc/mod.rs | 18 ++++++++---------- scripts/deploy_rooch_mainnet.sh | 5 +---- 3 files changed, 10 insertions(+), 17 deletions(-) diff --git a/.github/workflows/deploy_mainnet.yml b/.github/workflows/deploy_mainnet.yml index cfddcd1d37..d49b3e15a0 100644 --- a/.github/workflows/deploy_mainnet.yml +++ b/.github/workflows/deploy_mainnet.yml @@ -72,6 +72,4 @@ jobs: "cd /root/rooch && git fetch origin && git checkout -B $BRANCH origin/$BRANCH || git checkout $BRANCH && bash scripts/deploy_rooch_mainnet.sh \ '${{ env.REF }}' \ '${{ secrets.BTC_MAIN_RPC_URL }}' \ - '${{ secrets.BTC_MAIN_RPC_PWD }}' \ - '${{ secrets.OPENDA_GCP_MAINNET_BUCKET }}' \ - '${{ secrets.OPENDA_GCP_MAINNET_CREDENTIAL }}'" + '${{ secrets.BTC_MAIN_RPC_PWD }}'" diff --git a/crates/rooch-proposer/src/scc/mod.rs b/crates/rooch-proposer/src/scc/mod.rs index 02d23796c1..e59a8e8a5c 100644 --- a/crates/rooch-proposer/src/scc/mod.rs +++ b/crates/rooch-proposer/src/scc/mod.rs @@ -1,8 +1,6 @@ // Copyright (c) RoochNetwork // SPDX-License-Identifier: Apache-2.0 -use std::collections::BTreeMap; - use crate::actor::messages::TransactionProposeMessage; use moveos_types::h256; use moveos_types::h256::H256; @@ -14,7 +12,7 @@ use rooch_types::block::Block; /// This SCC is a mirror of the on-chain SCC pub struct StateCommitmentChain { //TODO save to the storage - blocks: BTreeMap, + last_block: Option, buffer: Vec, da: DAProxy, } @@ -23,7 +21,7 @@ impl StateCommitmentChain { /// Create a new SCC pub fn new(da_proxy: DAProxy) -> Self { Self { - blocks: BTreeMap::new(), + last_block: None, buffer: Vec::new(), da: da_proxy, } @@ -33,19 +31,19 @@ impl StateCommitmentChain { self.buffer.push(tx); } - /// Append a new block to the SCC - fn append_block(&mut self, block: Block) { - self.blocks.insert(block.block_number, block); + /// Update last block of the SCC + fn update_last_block(&mut self, block: Block) { + self.last_block = Some(block); } /// Get the last block of the SCC pub fn last_block(&self) -> Option<&Block> { - self.blocks.values().last() + self.last_block.as_ref() } /// Get the last block number of the SCC pub fn last_block_number(&self) -> Option { - self.blocks.keys().last().copied() + self.last_block.as_ref().map(|block| block.block_number) } /// Trigger the proposer to propose a new block @@ -104,7 +102,7 @@ impl StateCommitmentChain { tx_accumulator_root, state_roots, ); - self.append_block(new_block); + self.update_last_block(new_block); self.buffer.clear(); self.last_block() } diff --git a/scripts/deploy_rooch_mainnet.sh b/scripts/deploy_rooch_mainnet.sh index e611a30998..9736676880 100644 --- a/scripts/deploy_rooch_mainnet.sh +++ b/scripts/deploy_rooch_mainnet.sh @@ -5,8 +5,6 @@ REF="$1" BTC_MAIN_RPC_URL="$2" BTC_MAIN_RPC_PWD="$3" -OPENDA_GCP_MAINNET_BUCKET="$4" -OPENDA_GCP_MAINNET_CREDENTIAL="$5" sleep 30 docker image prune -a -f @@ -17,5 +15,4 @@ docker run -d --name rooch-mainnet --restart unless-stopped -v /data:/root -p 67 server start -n main \ --btc-rpc-url "$BTC_MAIN_RPC_URL" \ --btc-rpc-username rooch-main \ - --btc-rpc-password "$BTC_MAIN_RPC_PWD" \ - --da "{\"internal-da-server\": {\"servers\": [{\"open-da\": {\"scheme\": \"gcs\", \"config\": {\"bucket\": \"$OPENDA_GCP_MAINNET_BUCKET\", \"credential\": \"$OPENDA_GCP_MAINNET_CREDENTIAL\"}}}]}}" + --btc-rpc-password "$BTC_MAIN_RPC_PWD" From e5a9566a7de6f965f843766867a1c825519c3def Mon Sep 17 00:00:00 2001 From: jolestar Date: Sat, 21 Sep 2024 22:46:50 +0800 Subject: [PATCH 4/7] [cli] Migrate Bitseed cli to rooch (#2635) * [cli] Migrate bitseed cli to rooch * [rpc] Rename BitcoinOutPointView to OutPointView, and add some From implements * fix bitseed cli * [generator] Migrate the generator file * [cli] Add bitseed subcommands * [cli] Temporary ignore the wasm tests * fix generator * [testsuite] Replace bitseed image with bitseed command * [bitseed] Remove block hash from seed * [bitseed] Remove arbitrary_precision from serde_json and fix testcase --- Cargo.lock | 5 + Cargo.toml | 5 +- .../rooch-open-rpc-spec/schemas/openrpc.json | 36 +- .../src/jsonrpc_types/btc/ord.rs | 78 +- .../src/jsonrpc_types/btc/utxo.rs | 92 +- crates/rooch-rpc-client/Cargo.toml | 1 + crates/rooch-rpc-client/src/rooch_client.rs | 33 +- crates/rooch-types/src/address.rs | 13 + crates/rooch-types/src/bitcoin/ord.rs | 213 +- crates/rooch-types/src/bitcoin/ord/tag.rs | 108 + crates/rooch-types/src/bitcoin/types.rs | 4 + crates/rooch/Cargo.toml | 4 + .../src/commands/bitcoin/broadcast_tx.rs | 2 +- .../commands/bitcoin/transaction_builder.rs | 81 +- crates/rooch/src/commands/bitcoin/transfer.rs | 10 +- .../src/commands/bitcoin/utxo_selector.rs | 48 +- .../src/commands/bitseed/commands/deploy.rs | 70 + .../commands/bitseed/commands/generator.rs | 40 + .../src/commands/bitseed/commands/merge.rs | 39 + .../src/commands/bitseed/commands/mint.rs | 42 + .../src/commands/bitseed/commands/mod.rs | 9 + .../src/commands/bitseed/commands/split.rs | 40 + .../src/commands/bitseed/commands/view.rs | 61 + .../src/commands/bitseed/generator/hash.rs | 16 + .../commands/bitseed/generator/mock/mod.rs | 4 + .../generator/mock/random_amount_generator.rs | 40 + .../src/commands/bitseed/generator/mod.rs | 154 + .../commands/bitseed/generator/wasm/mod.rs | 4 + .../bitseed/generator/wasm/wasm_generator.rs | 657 + crates/rooch/src/commands/bitseed/inscribe.rs | 1277 + .../rooch/src/commands/bitseed/inscription.rs | 212 + crates/rooch/src/commands/bitseed/mod.rs | 52 + .../rooch/src/commands/bitseed/operation.rs | 311 + crates/rooch/src/commands/bitseed/sft.rs | 93 + crates/rooch/src/commands/bitseed/split.rs | 28 + crates/rooch/src/commands/mod.rs | 1 + crates/rooch/src/lib.rs | 6 +- crates/testsuite/Cargo.toml | 3 +- crates/testsuite/features/bitseed.feature | 62 +- crates/testsuite/features/multisign.feature | 23 +- crates/testsuite/tests/integration.rs | 3 +- .../sources/inscribe_factory.move | 34 +- generator/cpp/Makefile | 38 + generator/cpp/generator.cpp | 132 + generator/cpp/generator.js | 1 + generator/cpp/generator.wasm | Bin 0 -> 46257 bytes generator/cpp/nlohmann/json.hpp | 24766 ++++++++++++++++ generator/rust/.gitignore | 3 + generator/rust/Cargo.lock | 163 + generator/rust/Cargo.toml | 21 + generator/rust/Makefile | 43 + generator/rust/jest.config.js | 4 + generator/rust/package.json | 13 + generator/rust/pkg/generator.d.ts | 2 + generator/rust/pkg/generator.js | 4 + generator/rust/pkg/generator_bg.js | 5 + generator/rust/pkg/generator_bg.wasm | Bin 0 -> 42952 bytes generator/rust/pkg/generator_bg.wasm.d.ts | 9 + generator/rust/pkg/package.json | 16 + generator/rust/rust-analyzer.json | 6 + generator/rust/src/constants.rs | 6 + generator/rust/src/debug.rs | 53 + generator/rust/src/lib.rs | 147 + generator/rust/src/stack_alloc.rs | 48 + generator/rust/src/types.rs | 288 + generator/rust/src/utils.rs | 81 + generator/rust/tests/generator.test.js | 112 + generator/rust/yarn.lock | 2158 ++ moveos/moveos-types/src/move_std/option.rs | 8 + moveos/moveos-types/src/move_std/string.rs | 14 + scripts/bitcoin/README.md | 22 +- scripts/pr.sh | 1 + .../rooch-sdk/src/client/types/generated.ts | 4 +- 73 files changed, 31982 insertions(+), 200 deletions(-) create mode 100644 crates/rooch-types/src/bitcoin/ord/tag.rs create mode 100644 crates/rooch/src/commands/bitseed/commands/deploy.rs create mode 100644 crates/rooch/src/commands/bitseed/commands/generator.rs create mode 100644 crates/rooch/src/commands/bitseed/commands/merge.rs create mode 100644 crates/rooch/src/commands/bitseed/commands/mint.rs create mode 100644 crates/rooch/src/commands/bitseed/commands/mod.rs create mode 100644 crates/rooch/src/commands/bitseed/commands/split.rs create mode 100644 crates/rooch/src/commands/bitseed/commands/view.rs create mode 100644 crates/rooch/src/commands/bitseed/generator/hash.rs create mode 100644 crates/rooch/src/commands/bitseed/generator/mock/mod.rs create mode 100644 crates/rooch/src/commands/bitseed/generator/mock/random_amount_generator.rs create mode 100644 crates/rooch/src/commands/bitseed/generator/mod.rs create mode 100644 crates/rooch/src/commands/bitseed/generator/wasm/mod.rs create mode 100644 crates/rooch/src/commands/bitseed/generator/wasm/wasm_generator.rs create mode 100644 crates/rooch/src/commands/bitseed/inscribe.rs create mode 100644 crates/rooch/src/commands/bitseed/inscription.rs create mode 100644 crates/rooch/src/commands/bitseed/mod.rs create mode 100644 crates/rooch/src/commands/bitseed/operation.rs create mode 100644 crates/rooch/src/commands/bitseed/sft.rs create mode 100644 crates/rooch/src/commands/bitseed/split.rs create mode 100644 generator/cpp/Makefile create mode 100644 generator/cpp/generator.cpp create mode 100644 generator/cpp/generator.js create mode 100644 generator/cpp/generator.wasm create mode 100644 generator/cpp/nlohmann/json.hpp create mode 100644 generator/rust/.gitignore create mode 100644 generator/rust/Cargo.lock create mode 100644 generator/rust/Cargo.toml create mode 100644 generator/rust/Makefile create mode 100644 generator/rust/jest.config.js create mode 100644 generator/rust/package.json create mode 100644 generator/rust/pkg/generator.d.ts create mode 100644 generator/rust/pkg/generator.js create mode 100644 generator/rust/pkg/generator_bg.js create mode 100644 generator/rust/pkg/generator_bg.wasm create mode 100644 generator/rust/pkg/generator_bg.wasm.d.ts create mode 100644 generator/rust/pkg/package.json create mode 100644 generator/rust/rust-analyzer.json create mode 100644 generator/rust/src/constants.rs create mode 100644 generator/rust/src/debug.rs create mode 100644 generator/rust/src/lib.rs create mode 100644 generator/rust/src/stack_alloc.rs create mode 100644 generator/rust/src/types.rs create mode 100644 generator/rust/src/utils.rs create mode 100644 generator/rust/tests/generator.test.js create mode 100644 generator/rust/yarn.lock diff --git a/Cargo.lock b/Cargo.lock index 3ed75cbeac..fce60843f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9339,7 +9339,9 @@ dependencies = [ "bcs", "bitcoin 0.32.2", "bitcoin-move", + "bitcoincore-rpc", "chrono", + "ciborium", "clap 4.5.17", "codespan-reporting", "csv", @@ -9411,11 +9413,13 @@ dependencies = [ "smt", "tempfile", "termcolor", + "tiny-keccak", "tokio", "tracing", "tracing-subscriber", "vergen-git2", "vergen-pretty", + "wasmer", "xorf", "xxhash-rust", ] @@ -10004,6 +10008,7 @@ dependencies = [ "anyhow", "bcs", "bitcoin 0.32.2", + "bitcoincore-rpc", "futures", "hex", "jsonrpsee 0.23.2", diff --git a/Cargo.toml b/Cargo.toml index 6c8859c089..c192d7a19f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,10 @@ default-members = [ "crates/rooch-oracle" ] +exclude = [ + "generator/rust", +] + # All workspace members should inherit these keys # for package declarations. [workspace.package] @@ -201,7 +205,6 @@ reqwest = { version = "0.12", features = ["json"] } schemars = { version = "0.8.21", features = ["either"] } serde = { version = "1.0.210", features = ["derive", "rc"] } serde_bytes = "0.11.15" -#serde_json = { version = "1.0.111", features = ["preserve_order", "arbitrary_precision"] } serde_json = { version = "1.0.127", features = ["preserve_order"] } serde_yaml = "0.9" serde_repr = "0.1" diff --git a/crates/rooch-open-rpc-spec/schemas/openrpc.json b/crates/rooch-open-rpc-spec/schemas/openrpc.json index 6ad91bce2e..79ce1698b3 100644 --- a/crates/rooch-open-rpc-spec/schemas/openrpc.json +++ b/crates/rooch-open-rpc-spec/schemas/openrpc.json @@ -940,23 +940,6 @@ } } }, - "BitcoinOutPointView": { - "type": "object", - "required": [ - "txid", - "vout" - ], - "properties": { - "txid": { - "$ref": "#/components/schemas/bitcoin::blockdata::transaction::Txid" - }, - "vout": { - "type": "integer", - "format": "uint32", - "minimum": 0.0 - } - } - }, "DisplayFieldsView": { "type": "object", "required": [ @@ -2378,6 +2361,23 @@ } ] }, + "OutPointView": { + "type": "object", + "required": [ + "txid", + "vout" + ], + "properties": { + "txid": { + "$ref": "#/components/schemas/bitcoin::blockdata::transaction::Txid" + }, + "vout": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + } + } + }, "PageView_for_BalanceInfoView_and_IndexerStateIDView": { "description": "`next_cursor` points to the last item in the page; Reading with `next_cursor` will start from the next item after `next_cursor` if `next_cursor` is `Some`, otherwise it will start from the first item.", "type": "object", @@ -2720,7 +2720,7 @@ "$ref": "#/components/schemas/u64" }, "output": { - "$ref": "#/components/schemas/BitcoinOutPointView" + "$ref": "#/components/schemas/OutPointView" } } }, diff --git a/crates/rooch-rpc-api/src/jsonrpc_types/btc/ord.rs b/crates/rooch-rpc-api/src/jsonrpc_types/btc/ord.rs index 4e0e85bd54..6e3e8f7485 100644 --- a/crates/rooch-rpc-api/src/jsonrpc_types/btc/ord.rs +++ b/crates/rooch-rpc-api/src/jsonrpc_types/btc/ord.rs @@ -1,12 +1,14 @@ // Copyright (c) RoochNetwork // SPDX-License-Identifier: Apache-2.0 -use super::utxo::BitcoinOutPointView; +use super::utxo::OutPointView; +use crate::jsonrpc_types::ObjectStateView; use crate::jsonrpc_types::{ BytesView, IndexerObjectStateView, IndexerStateIDView, MoveStringView, ObjectIDVecView, ObjectMetaView, StrView, UnitedAddressView, }; use anyhow::Result; +use moveos_types::move_std::option::MoveOption; use moveos_types::move_std::string::MoveString; use moveos_types::state::MoveState; use moveos_types::state::MoveStructType; @@ -33,6 +35,12 @@ impl Display for InscriptionIDView { } } +impl From for InscriptionID { + fn from(view: InscriptionIDView) -> Self { + view.0 + } +} + #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum InscriptionFilterView { @@ -68,7 +76,7 @@ impl InscriptionFilterView { #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] pub struct SatPointView { - pub output: BitcoinOutPointView, + pub output: OutPointView, pub offset: StrView, } @@ -81,6 +89,15 @@ impl From for SatPointView { } } +impl From for SatPoint { + fn from(view: SatPointView) -> Self { + SatPoint { + outpoint: view.output.into(), + offset: view.offset.0, + } + } +} + #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] pub struct InscriptionView { pub id: InscriptionIDView, @@ -117,6 +134,28 @@ impl From for InscriptionView { } } +impl From for Inscription { + fn from(view: InscriptionView) -> Self { + let inscription_number = view.inscription_number; + Inscription { + id: view.id.0, + location: view.location.into(), + sequence_number: view.sequence_number, + inscription_number: inscription_number.unsigned_abs(), + is_cursed: inscription_number < 0, + charms: view.charms, + body: view.body.0, + content_encoding: view.content_encoding.map(|v| v.0).into(), + content_type: view.content_type.map(|v| v.0).into(), + metadata: view.metadata.0, + metaprotocol: view.metaprotocol.map(|v| v.0).into(), + parents: view.parents.into_iter().map(Into::into).collect(), + pointer: view.pointer.map(|v| v.0).into(), + rune: MoveOption::none(), + } + } +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct InscriptionStateView { #[serde(flatten)] @@ -139,3 +178,38 @@ impl TryFrom for InscriptionStateView { }) } } + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct InscriptionObjectView { + #[serde(flatten)] + pub metadata: ObjectMetaView, + pub value: InscriptionView, +} + +impl InscriptionObjectView { + pub fn location(&self) -> SatPoint { + self.value.location.clone().into() + } +} + +impl From for InscriptionObjectView { + fn from(state: InscriptionStateView) -> Self { + InscriptionObjectView { + metadata: state.metadata, + value: state.value, + } + } +} + +impl TryFrom for InscriptionObjectView { + type Error = anyhow::Error; + + fn try_from(state: ObjectStateView) -> Result { + let inscription = Inscription::from_bytes(&state.value.0)?; + let inscription_view = InscriptionView::from(inscription); + Ok(InscriptionObjectView { + metadata: state.metadata, + value: inscription_view, + }) + } +} diff --git a/crates/rooch-rpc-api/src/jsonrpc_types/btc/utxo.rs b/crates/rooch-rpc-api/src/jsonrpc_types/btc/utxo.rs index 73e611f6a1..5feacd61b3 100644 --- a/crates/rooch-rpc-api/src/jsonrpc_types/btc/utxo.rs +++ b/crates/rooch-rpc-api/src/jsonrpc_types/btc/utxo.rs @@ -4,14 +4,15 @@ use crate::jsonrpc_types::btc::transaction::TxidView; use crate::jsonrpc_types::{ H256View, IndexerObjectStateView, IndexerStateIDView, ObjectIDVecView, ObjectIDView, - ObjectMetaView, StrView, UnitedAddressView, + ObjectMetaView, ObjectStateView, StrView, UnitedAddressView, }; use anyhow::Result; use bitcoin::hashes::Hash; -use bitcoin::{Amount, Txid}; +use bitcoin::{Amount, TxOut, Txid}; use moveos_types::move_std::string::MoveString; use moveos_types::state::{MoveState, MoveStructType}; +use rooch_types::address::BitcoinAddress; use rooch_types::bitcoin::types::OutPoint; use rooch_types::bitcoin::utxo::{self, UTXO}; use rooch_types::indexer::state::ObjectStateFilter; @@ -22,20 +23,29 @@ use std::collections::HashMap; use std::str::FromStr; #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, JsonSchema)] -pub struct BitcoinOutPointView { +pub struct OutPointView { pub txid: TxidView, pub vout: u32, } -impl From for bitcoin::OutPoint { - fn from(view: BitcoinOutPointView) -> Self { - bitcoin::OutPoint::new(view.txid.into(), view.vout) +impl From for bitcoin::OutPoint { + fn from(view: OutPointView) -> Self { + bitcoin::OutPoint::new(view.txid.0, view.vout) } } -impl From for BitcoinOutPointView { +impl From for OutPoint { + fn from(view: OutPointView) -> Self { + OutPoint { + txid: view.txid.0.into_address(), + vout: view.vout, + } + } +} + +impl From for OutPointView { fn from(outpoint: OutPoint) -> Self { - BitcoinOutPointView { + OutPointView { txid: Txid::from_address(outpoint.txid).into(), vout: outpoint.vout, } @@ -110,7 +120,7 @@ impl UTXOView { let mut seals_view: HashMap> = HashMap::new(); utxo.seals.data.into_iter().for_each(|element| { seals_view.insert( - format!("0x{}", element.key), + element.key.to_string(), element .value .into_iter() @@ -190,3 +200,67 @@ impl TryFrom for UTXOStateView { }) } } + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct UTXOObjectView { + #[serde(flatten)] + pub metadata: ObjectMetaView, + pub value: UTXOView, +} + +impl From for UTXOObjectView { + fn from(state: UTXOStateView) -> Self { + UTXOObjectView { + metadata: state.metadata, + value: state.value, + } + } +} + +impl UTXOObjectView { + pub fn owner_bitcoin_address(&self) -> Option { + self.metadata + .owner_bitcoin_address + .as_ref() + .and_then(|addr| BitcoinAddress::from_str(addr).ok()) + } + + pub fn outpoint(&self) -> OutPoint { + self.value.outpoint() + } + + pub fn amount(&self) -> Amount { + self.value.amount() + } + + pub fn tx_output(&self) -> Result { + // Rooch UTXO does keep the original tx output script_pubkey, + // We convert the owner bitcoin address to script_pubkey here. + // But if the TxOut is a non-standard script_pubkey, we can not convert it back to bitcoin address. + // Find a way to keep the original script_pubkey in UTXO. + let script_pubkey = self + .owner_bitcoin_address() + .map(|addr| addr.script_pubkey()) + .transpose()? + .ok_or_else(|| { + anyhow::anyhow!("Can not recognize the owner of UTXO {}", self.outpoint()) + })?; + Ok(TxOut { + value: self.amount(), + script_pubkey, + }) + } +} + +impl TryFrom for UTXOObjectView { + type Error = anyhow::Error; + + fn try_from(state: ObjectStateView) -> Result { + let utxo = UTXO::from_bytes(&state.value.0)?; + let utxo_view = UTXOView::try_new_from_utxo(utxo)?; + Ok(UTXOObjectView { + metadata: state.metadata, + value: utxo_view, + }) + } +} diff --git a/crates/rooch-rpc-client/Cargo.toml b/crates/rooch-rpc-client/Cargo.toml index 6ed3b56f70..47eb2268f9 100644 --- a/crates/rooch-rpc-client/Cargo.toml +++ b/crates/rooch-rpc-client/Cargo.toml @@ -24,6 +24,7 @@ serde_json = { workspace = true } log = { workspace = true } hex = { workspace = true } bitcoin = { workspace = true } +bitcoincore-rpc = { workspace = true } tracing = { workspace = true } move-core-types = { workspace = true } diff --git a/crates/rooch-rpc-client/src/rooch_client.rs b/crates/rooch-rpc-client/src/rooch_client.rs index f943d0a965..cdd57c3d46 100644 --- a/crates/rooch-rpc-client/src/rooch_client.rs +++ b/crates/rooch-rpc-client/src/rooch_client.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use anyhow::{Ok, Result}; +use bitcoincore_rpc::RawTx; use jsonrpsee::http_client::HttpClient; use move_core_types::account_address::AccountAddress; use moveos_types::h256::H256; @@ -12,8 +13,8 @@ use moveos_types::state::{FieldKey, MoveStructState}; use moveos_types::{access_path::AccessPath, state::ObjectState, transaction::FunctionCall}; use rooch_rpc_api::api::btc_api::BtcAPIClient; use rooch_rpc_api::api::rooch_api::RoochAPIClient; -use rooch_rpc_api::jsonrpc_types::btc::ord::InscriptionFilterView; -use rooch_rpc_api::jsonrpc_types::btc::utxo::UTXOFilterView; +use rooch_rpc_api::jsonrpc_types::btc::ord::{InscriptionFilterView, InscriptionObjectView}; +use rooch_rpc_api::jsonrpc_types::btc::utxo::{UTXOFilterView, UTXOObjectView}; use rooch_rpc_api::jsonrpc_types::transaction_view::TransactionFilterView; use rooch_rpc_api::jsonrpc_types::{ account_view::BalanceInfoView, transaction_view::TransactionWithInfoView, @@ -35,6 +36,7 @@ use rooch_types::framework::address_mapping::RoochToBitcoinAddressMapping; use rooch_types::indexer::state::IndexerStateID; use rooch_types::transaction::RoochTransactionData; use rooch_types::{address::RoochAddress, transaction::rooch::RoochTransaction}; +use std::str::FromStr; use std::sync::Arc; #[derive(Clone, Debug)] @@ -399,11 +401,32 @@ impl RoochRpcClient { })?) } - pub async fn broadcast_bitcoin_tx( + pub async fn broadcast_bitcoin_tx( &self, - raw_tx: BytesView, + raw_tx: T, maxfeerate: Option, + maxburnamount: Option, ) -> Result { - Ok(self.http.broadcast_tx(raw_tx, maxfeerate, None).await?) + let hex = raw_tx.raw_hex(); + let bytes_view = BytesView::from_str(&hex)?; + Ok(self + .http + .broadcast_tx(bytes_view, maxfeerate, maxburnamount) + .await?) + } + + pub async fn get_utxo_object(&self, utxo_obj_id: ObjectID) -> Result> { + let objects = self.get_object_states(vec![utxo_obj_id], None).await?; + let obj_state = objects.into_iter().next().flatten(); + obj_state.map(UTXOObjectView::try_from).transpose() + } + + pub async fn get_inscription_object( + &self, + ins_obj_id: ObjectID, + ) -> Result> { + let objects = self.get_object_states(vec![ins_obj_id], None).await?; + let obj_state = objects.into_iter().next().flatten(); + obj_state.map(InscriptionObjectView::try_from).transpose() } } diff --git a/crates/rooch-types/src/address.rs b/crates/rooch-types/src/address.rs index 9aeeceb026..08693dd119 100644 --- a/crates/rooch-types/src/address.rs +++ b/crates/rooch-types/src/address.rs @@ -719,6 +719,11 @@ impl BitcoinAddress { Ok(addr) } + pub fn script_pubkey(&self) -> Result { + let bitcoin_address = self.to_bitcoin_address(network::Network::Bitcoin)?; + Ok(bitcoin_address.script_pubkey()) + } + /// Format the base58 as a hexadecimal string pub fn format>(&self, network: N) -> Result { if self.bytes.is_empty() { @@ -752,6 +757,14 @@ impl BitcoinAddress { } } } + + pub fn is_witness(&self) -> bool { + if self.bytes.is_empty() { + return false; + } + let payload_type = BitcoinAddressPayloadType::try_from(self.bytes[0]).unwrap(); + payload_type == BitcoinAddressPayloadType::WitnessProgram + } } impl MoveStructType for BitcoinAddress { diff --git a/crates/rooch-types/src/bitcoin/ord.rs b/crates/rooch-types/src/bitcoin/ord.rs index 107a0daa74..b30df3d49b 100644 --- a/crates/rooch-types/src/bitcoin/ord.rs +++ b/crates/rooch-types/src/bitcoin/ord.rs @@ -5,6 +5,8 @@ use super::types::{OutPoint, Transaction}; use crate::addresses::BITCOIN_MOVE_ADDRESS; use crate::into_address::{FromAddress, IntoAddress}; use anyhow::{bail, Result}; +use bitcoin::constants::MAX_SCRIPT_ELEMENT_SIZE; +use bitcoin::{opcodes, script}; use move_core_types::language_storage::{StructTag, TypeTag}; use move_core_types::value::MoveTypeLayout; use move_core_types::{account_address::AccountAddress, ident_str, identifier::IdentStr}; @@ -23,8 +25,13 @@ use serde::de::DeserializeOwned; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt::{Debug, Display}; use std::str::FromStr; +use tag::Tag; pub const MODULE_NAME: &IdentStr = ident_str!("ord"); +pub const PROTOCOL_ID: [u8; 3] = *b"ord"; +pub const BODY_TAG: [u8; 0] = []; + +pub mod tag; #[derive(PartialEq, Clone, Copy, Hash, Eq, PartialOrd, Ord)] pub struct InscriptionID { @@ -42,8 +49,11 @@ impl Default for InscriptionID { } impl InscriptionID { - pub fn new(txid: AccountAddress, index: u32) -> Self { - Self { txid, index } + pub fn new(txid: TID, index: u32) -> Self { + Self { + txid: txid.into_address(), + index, + } } pub fn object_id(&self) -> ObjectID { @@ -222,6 +232,66 @@ impl Inscription { self.inscription_number as i32 } } + + pub fn metaprotocol(&self) -> Option<&str> { + self.metaprotocol.as_ref().map(|s| s.as_str()) + } + + pub fn metadata(&self) -> &[u8] { + &self.metadata + } + + pub fn parents(&self) -> &[InscriptionID] { + &self.parents + } + + pub fn content_type(&self) -> Option<&str> { + self.content_type.as_ref().map(|s| s.as_str()) + } + + pub fn content_encoding(&self) -> Option<&str> { + self.content_encoding.as_ref().map(|s| s.as_str()) + } + + pub fn pointer(&self) -> Option { + self.pointer.as_ref().map(|p| *p) + } + + pub fn body(&self) -> &[u8] { + &self.body + } + + pub fn set_metaprotocol(&mut self, metaprotocol: String) { + self.metaprotocol = Some(metaprotocol.into()).into(); + } + + pub fn set_metadata(&mut self, metadata: Vec) { + self.metadata = metadata; + } + + pub fn set_parents(&mut self, parents: Vec) { + self.parents = parents; + } + + pub fn set_content_type(&mut self, content_type: String) { + self.content_type = Some(content_type.into()).into(); + } + + pub fn set_content_encoding(&mut self, content_encoding: String) { + self.content_encoding = Some(content_encoding.into()).into(); + } + + pub fn set_pointer(&mut self, pointer: u64) { + self.pointer = Some(pointer).into(); + } + + pub fn set_body(&mut self, body: Vec) { + self.body = body; + } + + pub fn set_rune(&mut self, rune: u128) { + self.rune = Some(rune).into(); + } } pub fn derive_inscription_id(inscription_id: &InscriptionID) -> ObjectID { @@ -292,6 +362,137 @@ pub struct InscriptionRecord { pub rune: Option, } +impl InscriptionRecord { + pub fn body(&self) -> &[u8] { + &self.body + } + + pub fn content_type(&self) -> Option<&str> { + self.content_type.as_ref().map(|s| s.as_str()) + } + + pub fn content_encoding(&self) -> Option<&str> { + self.content_encoding.as_ref().map(|s| s.as_str()) + } + + pub fn metadata(&self) -> &[u8] { + &self.metadata + } + + pub fn metaprotocol(&self) -> Option<&str> { + self.metaprotocol.as_ref().map(|s| s.as_str()) + } + + pub fn parents(&self) -> &[InscriptionID] { + &self.parents + } + + pub fn pointer(&self) -> Option { + self.pointer.as_ref().map(|p| *p) + } + + pub fn rune(&self) -> Option { + self.rune + } + + pub fn set_content_type(&mut self, content_type: String) { + self.content_type = Some(content_type.into()).into(); + } + + pub fn set_content_encoding(&mut self, content_encoding: String) { + self.content_encoding = Some(content_encoding.into()).into(); + } + + pub fn set_metadata(&mut self, metadata: Vec) { + self.metadata = metadata; + } + + pub fn set_metaprotocol(&mut self, metaprotocol: String) { + self.metaprotocol = Some(metaprotocol.into()).into(); + } + + pub fn set_parents(&mut self, parents: Vec) { + self.parents = parents; + } + + pub fn set_pointer(&mut self, pointer: u64) { + self.pointer = Some(pointer).into(); + } + + pub fn set_rune(&mut self, rune: u128) { + self.rune = Some(rune); + } + + pub fn append_reveal_script_to_builder(&self, mut builder: script::Builder) -> script::Builder { + builder = builder + .push_opcode(opcodes::OP_FALSE) + .push_opcode(opcodes::all::OP_IF) + .push_slice(PROTOCOL_ID); + + Tag::ContentType.append( + &mut builder, + &self + .content_type + .as_ref() + .map(|content_type| content_type.as_str().as_bytes().to_vec()), + ); + Tag::ContentEncoding.append( + &mut builder, + &self + .content_encoding + .as_ref() + .map(|content_encoding| content_encoding.as_str().as_bytes().to_vec()), + ); + Tag::Metaprotocol.append( + &mut builder, + &self + .metaprotocol + .as_ref() + .map(|metaprotocol| metaprotocol.as_str().as_bytes().to_vec()), + ); + Tag::Parent.append_array( + &mut builder, + &self + .parents + .iter() + .map(|parent| { + let mut buffer = parent.txid.to_vec(); + buffer.extend_from_slice(&parent.index.to_le_bytes()); + buffer + }) + .collect(), + ); + //TODO should support delegate + //Tag::Delegate.append(&mut builder, &self.delegate); + Tag::Pointer.append( + &mut builder, + &self + .pointer + .as_ref() + .map(|pointer| pointer.to_le_bytes().to_vec()), + ); + let metadata = if self.metadata.is_empty() { + None + } else { + Some(self.metadata.clone()) + }; + Tag::Metadata.append(&mut builder, &metadata); + Tag::Rune.append( + &mut builder, + &self.rune.as_ref().map(|rune| rune.to_le_bytes().to_vec()), + ); + + if !self.body.is_empty() { + builder = builder.push_slice(BODY_TAG); + for chunk in self.body.chunks(MAX_SCRIPT_ELEMENT_SIZE) { + builder = builder.push_slice::<&script::PushBytes>(chunk.try_into().unwrap()); + } + } + + builder.push_opcode(opcodes::all::OP_ENDIF) + } +} + impl Debug for InscriptionRecord { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("InscriptionRecord") @@ -390,6 +591,12 @@ pub struct SatPoint { pub offset: u64, } +impl SatPoint { + pub fn outpoint(&self) -> bitcoin::OutPoint { + self.outpoint.clone().into() + } +} + impl MoveStructType for SatPoint { const ADDRESS: AccountAddress = BITCOIN_MOVE_ADDRESS; const MODULE_NAME: &'static IdentStr = MODULE_NAME; @@ -492,8 +699,6 @@ pub struct OrdModule<'a> { impl<'a> OrdModule<'a> { pub const PARSE_INSCRIPTION_FROM_TX_FUNCTION_NAME: &'static IdentStr = ident_str!("parse_inscription_from_tx"); - pub const MATCH_UTXO_AND_GENERATE_SAT_POINT_FUNCTION_NAME: &'static IdentStr = - ident_str!("match_utxo_and_generate_sat_point"); pub fn parse_inscription_from_tx( &self, diff --git a/crates/rooch-types/src/bitcoin/ord/tag.rs b/crates/rooch-types/src/bitcoin/ord/tag.rs new file mode 100644 index 0000000000..25962a2467 --- /dev/null +++ b/crates/rooch-types/src/bitcoin/ord/tag.rs @@ -0,0 +1,108 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +//Source file from https://github.com/ordinals/ord/blob/5953ccaaeb10eb79bc7672159778a81a8bf2c262/src/inscriptions/tag.rs + +use bitcoin::{constants::MAX_SCRIPT_ELEMENT_SIZE, script}; +use std::{collections::BTreeMap, mem}; + +#[derive(Copy, Clone)] +#[repr(u8)] +pub enum Tag { + Pointer = 2, + #[allow(unused)] + Unbound = 66, + + ContentType = 1, + Parent = 3, + Metadata = 5, + Metaprotocol = 7, + ContentEncoding = 9, + Delegate = 11, + Rune = 13, + #[allow(unused)] + Note = 15, + #[allow(unused)] + Nop = 255, +} + +impl Tag { + fn chunked(self) -> bool { + matches!(self, Self::Metadata) + } + + pub(crate) fn bytes(self) -> [u8; 1] { + [self as u8] + } + + pub(crate) fn append(self, builder: &mut script::Builder, value: &Option>) { + if let Some(value) = value { + let mut tmp = script::Builder::new(); + mem::swap(&mut tmp, builder); + + if self.chunked() { + for chunk in value.chunks(MAX_SCRIPT_ELEMENT_SIZE) { + tmp = tmp + .push_slice::<&script::PushBytes>( + self.bytes().as_slice().try_into().unwrap(), + ) + .push_slice::<&script::PushBytes>(chunk.try_into().unwrap()); + } + } else { + tmp = tmp + .push_slice::<&script::PushBytes>(self.bytes().as_slice().try_into().unwrap()) + .push_slice::<&script::PushBytes>(value.as_slice().try_into().unwrap()); + } + + mem::swap(&mut tmp, builder); + } + } + + pub(crate) fn append_array(self, builder: &mut script::Builder, values: &Vec>) { + let mut tmp = script::Builder::new(); + mem::swap(&mut tmp, builder); + + for value in values { + tmp = tmp + .push_slice::<&script::PushBytes>(self.bytes().as_slice().try_into().unwrap()) + .push_slice::<&script::PushBytes>(value.as_slice().try_into().unwrap()); + } + + mem::swap(&mut tmp, builder); + } + + pub fn take(self, fields: &mut BTreeMap<&[u8], Vec<&[u8]>>) -> Option> { + if self.chunked() { + let value = fields.remove(self.bytes().as_slice())?; + + if value.is_empty() { + None + } else { + Some(value.into_iter().flatten().cloned().collect()) + } + } else { + let values = fields.get_mut(self.bytes().as_slice())?; + + if values.is_empty() { + None + } else { + let value = values.remove(0).to_vec(); + + if values.is_empty() { + fields.remove(self.bytes().as_slice()); + } + + Some(value) + } + } + } + + pub fn take_array(self, fields: &mut BTreeMap<&[u8], Vec<&[u8]>>) -> Vec> { + fields + .remove(self.bytes().as_slice()) + .unwrap_or_default() + .into_iter() + .map(|v| v.to_vec()) + .collect() + } +} diff --git a/crates/rooch-types/src/bitcoin/types.rs b/crates/rooch-types/src/bitcoin/types.rs index 738995f6b4..3adcbcea90 100644 --- a/crates/rooch-types/src/bitcoin/types.rs +++ b/crates/rooch-types/src/bitcoin/types.rs @@ -301,6 +301,10 @@ impl OutPoint { pub fn is_null(&self) -> bool { *self == OutPoint::null() } + + pub fn txid(&self) -> Txid { + Txid::from_address(self.txid) + } } impl From for OutPoint { diff --git a/crates/rooch/Cargo.toml b/crates/rooch/Cargo.toml index f9b894b26b..7e26fa3170 100644 --- a/crates/rooch/Cargo.toml +++ b/crates/rooch/Cargo.toml @@ -52,6 +52,10 @@ prometheus = { workspace = true } lazy_static = { workspace = true } schemars = { workspace = true } bitcoin = { workspace = true } +bitcoincore-rpc = { workspace = true } +ciborium = { workspace = true } +wasmer = { workspace = true } +tiny-keccak = { workspace = true } move-bytecode-utils = { workspace = true } move-binary-format = { workspace = true } diff --git a/crates/rooch/src/commands/bitcoin/broadcast_tx.rs b/crates/rooch/src/commands/bitcoin/broadcast_tx.rs index eeccd8fc2a..4bf6b9774b 100644 --- a/crates/rooch/src/commands/bitcoin/broadcast_tx.rs +++ b/crates/rooch/src/commands/bitcoin/broadcast_tx.rs @@ -22,7 +22,7 @@ impl CommandAction for BroadcastTx { Ok(client .rooch - .broadcast_bitcoin_tx(self.input.data.into(), None) + .broadcast_bitcoin_tx(&self.input.data, None, None) .await?) } } diff --git a/crates/rooch/src/commands/bitcoin/transaction_builder.rs b/crates/rooch/src/commands/bitcoin/transaction_builder.rs index fc6366a843..77ccc6e22d 100644 --- a/crates/rooch/src/commands/bitcoin/transaction_builder.rs +++ b/crates/rooch/src/commands/bitcoin/transaction_builder.rs @@ -1,8 +1,6 @@ // Copyright (c) RoochNetwork // SPDX-License-Identifier: Apache-2.0 -use std::str::FromStr; - use super::utxo_selector::UTXOSelector; use anyhow::{anyhow, bail, Result}; use bitcoin::{ @@ -10,12 +8,9 @@ use bitcoin::{ OutPoint, Psbt, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness, }; use moveos_types::{module_binding::MoveFunctionCaller, moveos_std::object::ObjectID}; -use rooch_rpc_api::jsonrpc_types::{btc::utxo::UTXOView, ObjectMetaView}; +use rooch_rpc_api::jsonrpc_types::btc::utxo::UTXOObjectView; use rooch_rpc_client::{wallet_context::WalletContext, Client}; -use rooch_types::{ - address::BitcoinAddress, - bitcoin::multisign_account::{self}, -}; +use rooch_types::bitcoin::multisign_account::{self}; use tracing::debug; #[derive(Debug)] @@ -113,10 +108,13 @@ impl<'a> TransactionBuilder<'a> { + Self::ADDITIONAL_OUTPUT_VBYTES) as u64, ) .ok_or_else(|| anyhow!("Failed to estimate fee: {}", self.fee_rate))?; - let mut utxos = self.select_utxos(total_output + estimate_fee).await?; + let mut utxos = self + .utxo_selector + .select_utxos(total_output + estimate_fee) + .await?; let mut tx_inputs = vec![]; let mut total_input = Amount::from_sat(0); - for (_, utxo) in utxos.iter() { + for utxo in utxos.iter() { tx_inputs.push(Self::utxo_to_txin(utxo)); total_input += utxo.amount(); } @@ -141,15 +139,15 @@ impl<'a> TransactionBuilder<'a> { .ok_or_else(|| anyhow!("Failed to estimate fee: {}", self.fee_rate))?; if fee > estimate_fee && total_input < total_output + fee { //we need to add more inputs - let additional_utxos = self.select_utxos(total_output + fee - total_input).await?; - tx.input.extend( - additional_utxos - .iter() - .map(|(_, utxo)| Self::utxo_to_txin(utxo)), - ); + let additional_utxos = self + .utxo_selector + .select_utxos(total_output + fee - total_input) + .await?; + tx.input + .extend(additional_utxos.iter().map(Self::utxo_to_txin)); total_input += additional_utxos .iter() - .map(|(_, utxo)| utxo.amount()) + .map(|utxo| utxo.amount()) .sum::(); utxos.extend(additional_utxos); } @@ -166,35 +164,24 @@ impl<'a> TransactionBuilder<'a> { let multisign_account_module = self .client .as_module_binding::(); - for (idx, (utxo_obj_meta, utxo)) in utxos.iter().enumerate() { + for (idx, utxo) in utxos.iter().enumerate() { let input = &mut psbt.inputs[idx]; - let bitcoin_addr_str = - utxo_obj_meta - .owner_bitcoin_address - .as_ref() - .ok_or_else(|| { - anyhow!("Can not recognize the owner of UTXO {}", utxo.outpoint()) - })?; - let bitcoin_addr = Address::from_str(bitcoin_addr_str)?; - let bitcoin_addr = bitcoin_addr.assume_checked(); - - let is_witness = match bitcoin_addr.address_type() { - Some(addr_type) => !matches!( - addr_type, - bitcoin::AddressType::P2pkh | bitcoin::AddressType::P2sh - ), - None => true, - }; - if is_witness { + + let bitcoin_addr = utxo.owner_bitcoin_address().ok_or_else(|| { + anyhow!("Can not recognize the owner of UTXO {}", utxo.outpoint()) + })?; + + if bitcoin_addr.is_witness() { input.witness_utxo = Some(TxOut { value: utxo.amount(), - script_pubkey: bitcoin_addr.script_pubkey(), + script_pubkey: bitcoin_addr.script_pubkey()?, }); } else { //TODO add non-witness utxo + bail!("Non-witness UTXO is not supported yet"); } - let rooch_addr = BitcoinAddress::from(bitcoin_addr.clone()).to_rooch_address(); + let rooch_addr = bitcoin_addr.to_rooch_address(); if multisign_account_module.is_multisign_account(rooch_addr.into())? { let account_info = self @@ -217,25 +204,7 @@ impl<'a> TransactionBuilder<'a> { Ok(psbt) } - async fn select_utxos( - &mut self, - expected_amount: Amount, - ) -> Result> { - let mut utxos = vec![]; - let mut total_input = Amount::from_sat(0); - while total_input < expected_amount { - let utxo = self.utxo_selector.next_utxo().await?; - if utxo.is_none() { - bail!("not enough BTC funds"); - } - let utxo = utxo.unwrap(); - total_input += utxo.1.amount(); - utxos.push(utxo); - } - Ok(utxos) - } - - fn utxo_to_txin(utxo: &UTXOView) -> TxIn { + fn utxo_to_txin(utxo: &UTXOObjectView) -> TxIn { TxIn { previous_output: utxo.outpoint().into(), script_sig: ScriptBuf::default(), diff --git a/crates/rooch/src/commands/bitcoin/transfer.rs b/crates/rooch/src/commands/bitcoin/transfer.rs index 1b64c52386..5ae83049ca 100644 --- a/crates/rooch/src/commands/bitcoin/transfer.rs +++ b/crates/rooch/src/commands/bitcoin/transfer.rs @@ -6,7 +6,6 @@ use super::transaction_builder::TransactionBuilder; use crate::cli_types::{CommandAction, WalletContextOptions}; use crate::commands::bitcoin::sign_tx::sign_psbt; use async_trait::async_trait; -use bitcoin::consensus::Encodable; use bitcoin::{Amount, FeeRate}; use clap::Parser; use rooch_types::address::ParsedAddress; @@ -76,14 +75,7 @@ impl CommandAction for Transfer { "The sender address should not be a multisig address".to_string(), )) } - SignOutput::Tx(tx) => { - let mut raw_tx = vec![]; - tx.consensus_encode(&mut raw_tx)?; - Ok(client - .rooch - .broadcast_bitcoin_tx(raw_tx.into(), None) - .await?) - } + SignOutput::Tx(tx) => Ok(client.rooch.broadcast_bitcoin_tx(&tx, None, None).await?), } } } diff --git a/crates/rooch/src/commands/bitcoin/utxo_selector.rs b/crates/rooch/src/commands/bitcoin/utxo_selector.rs index 39ca21c8fa..afdbbeb85d 100644 --- a/crates/rooch/src/commands/bitcoin/utxo_selector.rs +++ b/crates/rooch/src/commands/bitcoin/utxo_selector.rs @@ -1,14 +1,17 @@ // Copyright (c) RoochNetwork // SPDX-License-Identifier: Apache-2.0 +use std::collections::VecDeque; + use anyhow::{bail, Result}; use bitcoin::{Address, Amount}; use moveos_types::moveos_std::object::{ObjectID, GENESIS_STATE_ROOT}; use rooch_rpc_api::jsonrpc_types::{ - btc::utxo::{UTXOFilterView, UTXOStateView, UTXOView}, - IndexerStateIDView, ObjectMetaView, + btc::utxo::{UTXOFilterView, UTXOObjectView, UTXOStateView}, + IndexerStateIDView, }; use rooch_rpc_client::Client; +use rooch_types::bitcoin::{types::OutPoint, utxo::derive_utxo_id}; use tracing::debug; #[derive(Debug)] @@ -17,7 +20,7 @@ pub struct UTXOSelector { sender: Address, specific_utxos: Vec, loaded_page: Option<(Option, bool)>, - candidate_utxos: Vec<(ObjectMetaView, UTXOView)>, + candidate_utxos: VecDeque, skip_seal_check: bool, } @@ -33,7 +36,7 @@ impl UTXOSelector { sender, specific_utxos, loaded_page: None, - candidate_utxos: vec![], + candidate_utxos: VecDeque::new(), skip_seal_check, }; selector.load_specific_utxos().await?; @@ -69,8 +72,7 @@ impl UTXOSelector { utxo_state_view.metadata ); } - self.candidate_utxos - .push((utxo_state_view.metadata, utxo_state_view.value)); + self.candidate_utxos.push_front(utxo_state_view.into()); } Ok(()) } @@ -105,23 +107,49 @@ impl UTXOSelector { ); continue; } - self.candidate_utxos - .push((utxo_view.metadata, utxo_view.value)); + // We use deque to make sure the utxos are popped in the order they are loaded, the oldest utxo will be popped first + // Avoid bad-txns-premature-spend-of-coinbase error + self.candidate_utxos.push_front(utxo_view.into()); } self.loaded_page = Some((utxo_page.next_cursor, utxo_page.has_next_page)); Ok(()) } + /// Get the next utxo from the candidate utxos - pub async fn next_utxo(&mut self) -> Result> { + pub async fn next_utxo(&mut self) -> Result> { if self.candidate_utxos.is_empty() { self.load_utxos().await?; } - Ok(self.candidate_utxos.pop()) + Ok(self.candidate_utxos.pop_back()) + } + + pub async fn select_utxos(&mut self, expected_amount: Amount) -> Result> { + let mut utxos = vec![]; + let mut total_input = Amount::from_sat(0); + while total_input < expected_amount { + let utxo = self.next_utxo().await?; + if utxo.is_none() { + bail!("not enough BTC funds"); + } + let utxo = utxo.unwrap(); + total_input += utxo.amount(); + utxos.push(utxo); + } + Ok(utxos) } pub fn specific_utxos(&self) -> &[ObjectID] { &self.specific_utxos } + + pub async fn get_utxo(&self, outpoint: &OutPoint) -> Result { + let utxo_obj_id = derive_utxo_id(outpoint); + self.client + .rooch + .get_utxo_object(utxo_obj_id) + .await? + .ok_or_else(|| anyhow::anyhow!("UTXO {} not found", outpoint)) + } } fn skip_utxo(utxo_state_view: &UTXOStateView, minimal_non_dust: Amount) -> bool { diff --git a/crates/rooch/src/commands/bitseed/commands/deploy.rs b/crates/rooch/src/commands/bitseed/commands/deploy.rs new file mode 100644 index 0000000000..c9b5c2b2c3 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/commands/deploy.rs @@ -0,0 +1,70 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::cli_types::CommandAction; +use crate::cli_types::WalletContextOptions; +use crate::commands::bitseed::inscribe::InscribeOptions; +use crate::commands::bitseed::inscribe::InscribeOutput; +use crate::commands::bitseed::inscribe::Inscriber; +use crate::commands::bitseed::operation::deploy_args_cbor_encode; +use async_trait::async_trait; +use clap::Parser; +use rooch_types::bitcoin::ord::InscriptionID; +use rooch_types::error::RoochResult; + +#[derive(Debug, Parser)] +pub struct DeployCommand { + #[arg(long, help = "The SFT tick name.")] + tick: String, + + #[arg(long, help = "The amount of the tick total supply.")] + amount: u64, + + #[arg(long, help = "The generator Inscription id on Bitcoin.")] + generator: Option, + + #[arg(long, help = "The mint factory name.")] + factory: Option, + + #[arg( + long, + help = "The number of allowed the SFT attributes repeats. 0 means do not limit.", + default_value = "0" + )] + repeat: u64, + + #[arg(long, help = "The deploy arguments to the generator program.")] + deploy_args: Vec, + + #[clap(flatten)] + inscribe_options: InscribeOptions, + + #[clap(flatten)] + pub context_options: WalletContextOptions, +} + +#[async_trait] +impl CommandAction for DeployCommand { + async fn execute(self) -> RoochResult { + let context = self.context_options.build_require_password()?; + //TODO how to encode the factory args. + let deploy_args = deploy_args_cbor_encode(self.deploy_args)?; + + //TODO check the tick name is valid + let tick = self.tick.to_uppercase(); + let output = Inscriber::new(context, self.inscribe_options) + .await? + .with_deploy( + tick, + self.amount, + self.generator, + self.factory, + self.repeat, + deploy_args, + ) + .await? + .inscribe() + .await?; + Ok(output) + } +} diff --git a/crates/rooch/src/commands/bitseed/commands/generator.rs b/crates/rooch/src/commands/bitseed/commands/generator.rs new file mode 100644 index 0000000000..6a86235d19 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/commands/generator.rs @@ -0,0 +1,40 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::cli_types::CommandAction; +use crate::cli_types::WalletContextOptions; +use crate::commands::bitseed::inscribe::InscribeOptions; +use crate::commands::bitseed::inscribe::InscribeOutput; +use crate::commands::bitseed::inscribe::Inscriber; +use async_trait::async_trait; +use clap::Parser; +use rooch_types::error::RoochResult; +use std::path::PathBuf; + +/// Inscribe a new generator bytecode to Bitcoin +#[derive(Debug, Parser)] +pub struct GeneratorCommand { + #[arg(long, help = "Name of the generator.")] + name: String, + #[arg(long, help = "Path to the generator bytecode file.")] + generator: PathBuf, + #[clap(flatten)] + inscribe_options: InscribeOptions, + #[clap(flatten)] + pub context_options: WalletContextOptions, +} + +#[async_trait] +impl CommandAction for GeneratorCommand { + async fn execute(self) -> RoochResult { + let context = self.context_options.build_require_password()?; + let output = Inscriber::new(context, self.inscribe_options) + .await? + .with_generator(self.name, self.generator) + .await? + .inscribe() + .await?; + + Ok(output) + } +} diff --git a/crates/rooch/src/commands/bitseed/commands/merge.rs b/crates/rooch/src/commands/bitseed/commands/merge.rs new file mode 100644 index 0000000000..447510c0cb --- /dev/null +++ b/crates/rooch/src/commands/bitseed/commands/merge.rs @@ -0,0 +1,39 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::cli_types::CommandAction; +use crate::cli_types::WalletContextOptions; +use crate::commands::bitseed::inscribe::InscribeOptions; +use crate::commands::bitseed::inscribe::InscribeOutput; +use crate::commands::bitseed::inscribe::Inscriber; +use async_trait::async_trait; +use clap::Parser; +use rooch_types::bitcoin::ord::InscriptionID; +use rooch_types::error::RoochResult; + +#[derive(Debug, Parser)] +pub struct MergeCommand { + #[arg(long, help = "The merge SFT inscription IDs.")] + sft_inscription_ids: Vec, + + #[clap(flatten)] + inscribe_options: InscribeOptions, + + #[clap(flatten)] + pub context_options: WalletContextOptions, +} + +#[async_trait] +impl CommandAction for MergeCommand { + async fn execute(self) -> RoochResult { + let context = self.context_options.build_require_password()?; + let output = Inscriber::new(context, self.inscribe_options) + .await? + .with_merge(self.sft_inscription_ids) + .await? + .inscribe() + .await?; + + Ok(output) + } +} diff --git a/crates/rooch/src/commands/bitseed/commands/mint.rs b/crates/rooch/src/commands/bitseed/commands/mint.rs new file mode 100644 index 0000000000..290c7915e4 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/commands/mint.rs @@ -0,0 +1,42 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::cli_types::CommandAction; +use crate::cli_types::WalletContextOptions; +use crate::commands::bitseed::inscribe::InscribeOptions; +use crate::commands::bitseed::inscribe::InscribeOutput; +use crate::commands::bitseed::inscribe::Inscriber; +use async_trait::async_trait; +use clap::Parser; +use rooch_types::bitcoin::ord::InscriptionID; +use rooch_types::error::RoochResult; + +#[derive(Debug, Parser)] +pub struct MintCommand { + #[arg(long, help = "The deploy inscription id.")] + deploy_inscription_id: InscriptionID, + + #[arg(long, help = "The user input argument to the generator.")] + user_input: Option, + + #[clap(flatten)] + inscribe_options: InscribeOptions, + + #[clap(flatten)] + pub context_options: WalletContextOptions, +} + +#[async_trait] +impl CommandAction for MintCommand { + async fn execute(self) -> RoochResult { + let context = self.context_options.build_require_password()?; + let output = Inscriber::new(context, self.inscribe_options) + .await? + .with_mint(self.deploy_inscription_id, self.user_input) + .await? + .inscribe() + .await?; + + Ok(output) + } +} diff --git a/crates/rooch/src/commands/bitseed/commands/mod.rs b/crates/rooch/src/commands/bitseed/commands/mod.rs new file mode 100644 index 0000000000..67c18a8f0c --- /dev/null +++ b/crates/rooch/src/commands/bitseed/commands/mod.rs @@ -0,0 +1,9 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +pub mod deploy; +pub mod generator; +pub mod merge; +pub mod mint; +pub mod split; +pub mod view; diff --git a/crates/rooch/src/commands/bitseed/commands/split.rs b/crates/rooch/src/commands/bitseed/commands/split.rs new file mode 100644 index 0000000000..b968db0f9c --- /dev/null +++ b/crates/rooch/src/commands/bitseed/commands/split.rs @@ -0,0 +1,40 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::{ + cli_types::{CommandAction, WalletContextOptions}, + commands::bitseed::inscribe::{InscribeOptions, InscribeOutput, Inscriber}, +}; +use async_trait::async_trait; +use clap::Parser; +use rooch_types::{bitcoin::ord::InscriptionID, error::RoochResult}; + +#[derive(Debug, Parser)] +pub struct SplitCommand { + #[arg(long, help = "The split SFT inscription ID.")] + sft_inscription_id: InscriptionID, + + #[arg(long, help = "The split amounts.", num_args = 1..)] + amounts: Vec, + + #[clap(flatten)] + inscribe_options: InscribeOptions, + + #[clap(flatten)] + pub context_options: WalletContextOptions, +} + +#[async_trait] +impl CommandAction for SplitCommand { + async fn execute(self) -> RoochResult { + let context = self.context_options.build_require_password()?; + let output = Inscriber::new(context, self.inscribe_options) + .await? + .with_split(self.sft_inscription_id, self.amounts) + .await? + .inscribe() + .await?; + + Ok(output) + } +} diff --git a/crates/rooch/src/commands/bitseed/commands/view.rs b/crates/rooch/src/commands/bitseed/commands/view.rs new file mode 100644 index 0000000000..439d1664c3 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/commands/view.rs @@ -0,0 +1,61 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use async_trait::async_trait; +use clap::Parser; +use rooch_types::{ + bitcoin::ord::InscriptionID, + error::{RoochError, RoochResult}, +}; + +use crate::{ + cli_types::{CommandAction, WalletContextOptions}, + commands::bitseed::{ + operation::{AsSFT, Operation}, + sft::SFT, + }, +}; + +#[derive(Debug, Parser)] +pub struct ViewCommand { + #[arg(long, help = "The SFT inscription ID to view.")] + sft_inscription_id: InscriptionID, + + #[clap(flatten)] + pub context_options: WalletContextOptions, +} + +#[async_trait] +impl CommandAction for ViewCommand { + async fn execute(self) -> RoochResult { + let context = self.context_options.build()?; + let client = context.get_client().await?; + let ins_obj_id = self.sft_inscription_id.object_id(); + + let ins_obj = client + .rooch + .get_inscription_object(ins_obj_id.clone()) + .await? + .ok_or_else(|| { + RoochError::CommandArgumentError(format!( + "Inscription object {} not found", + ins_obj_id + )) + })?; + + let operation = Operation::from_inscription(ins_obj.value.into())?; + let sft = match operation { + Operation::Mint(mint_record) => mint_record.as_sft(), + Operation::Split(split_record) => split_record.as_sft(), + Operation::Merge(merge_record) => merge_record.as_sft(), + _ => { + return Err(RoochError::CommandArgumentError(format!( + "Inscription {} is not a valid SFT record", + self.sft_inscription_id + ))) + } + }; + + Ok(sft) + } +} diff --git a/crates/rooch/src/commands/bitseed/generator/hash.rs b/crates/rooch/src/commands/bitseed/generator/hash.rs new file mode 100644 index 0000000000..3888121757 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/generator/hash.rs @@ -0,0 +1,16 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use moveos_types::h256::H256; +use tiny_keccak::{Hasher, Sha3}; + +pub const LENGTH: usize = 32; + +//TODO use sha2 +pub fn sha3_256_of(buffer: &[u8]) -> H256 { + let mut sha3 = Sha3::v256(); + sha3.update(buffer); + let mut hash = [0u8; LENGTH]; + sha3.finalize(&mut hash); + H256(hash) +} diff --git a/crates/rooch/src/commands/bitseed/generator/mock/mod.rs b/crates/rooch/src/commands/bitseed/generator/mock/mod.rs new file mode 100644 index 0000000000..d3aeb52e07 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/generator/mock/mod.rs @@ -0,0 +1,4 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +pub mod random_amount_generator; diff --git a/crates/rooch/src/commands/bitseed/generator/mock/random_amount_generator.rs b/crates/rooch/src/commands/bitseed/generator/mock/random_amount_generator.rs new file mode 100644 index 0000000000..e9cdaee02d --- /dev/null +++ b/crates/rooch/src/commands/bitseed/generator/mock/random_amount_generator.rs @@ -0,0 +1,40 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::commands::bitseed::generator::{Generator, InscribeGenerateOutput, InscribeSeed}; +use bitcoin::Address; +use move_core_types::u256::U256; + +pub struct RandomAmountGenerator; + +impl Generator for RandomAmountGenerator { + fn inscribe_generate( + &self, + _deploy_args: &[u8], + seed: &InscribeSeed, + _recipient: &Address, + _user_input: Option, + ) -> InscribeGenerateOutput { + let hash = seed.seed(); + let min = U256::from(1u64); + let max = U256::from(100u64); + let amount = (U256::from_le_bytes(&hash.0) % (max - min) + min).unchecked_as_u64(); + InscribeGenerateOutput { + amount, + attributes: None, + content: None, + } + } + + fn inscribe_verify( + &self, + deploy_args: &[u8], + seed: &InscribeSeed, + recipient: &Address, + user_input: Option, + inscribe_output: InscribeGenerateOutput, + ) -> bool { + let output = self.inscribe_generate(deploy_args, seed, recipient, user_input); + output == inscribe_output + } +} diff --git a/crates/rooch/src/commands/bitseed/generator/mod.rs b/crates/rooch/src/commands/bitseed/generator/mod.rs new file mode 100644 index 0000000000..3ed12bc3de --- /dev/null +++ b/crates/rooch/src/commands/bitseed/generator/mod.rs @@ -0,0 +1,154 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use super::sft::Content; +use bitcoin::{hashes::Hash, Address, BlockHash}; +use moveos_types::h256::H256; +use rooch_types::bitcoin::ord::InscriptionID; +use serde::{Deserialize, Serialize}; + +pub(crate) mod hash; +pub(crate) mod mock; +pub mod wasm; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InscribeGenerateOutput { + pub amount: u64, + pub attributes: Option, + pub content: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IndexerGenerateOutput { + pub attributes: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InscribeSeed { + pub utxo: bitcoin::OutPoint, +} + +impl InscribeSeed { + pub fn new(utxo: bitcoin::OutPoint) -> Self { + Self { utxo } + } + + pub fn seed(&self) -> H256 { + let mut buffer = self.utxo.txid.as_byte_array().to_vec(); + + let vout_bytes = self.utxo.vout.to_le_bytes(); + buffer.extend_from_slice(&vout_bytes); + + hash::sha3_256_of(buffer.as_slice()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IndexerSeed { + pub block_hash: BlockHash, + pub inscription_id: InscriptionID, +} + +impl IndexerSeed { + pub fn new(block_hash: BlockHash, inscription_id: InscriptionID) -> Self { + Self { + block_hash, + inscription_id, + } + } + + pub fn seed(&self) -> H256 { + let mut buffer = self.block_hash.as_byte_array().to_vec(); + buffer.extend_from_slice(&self.inscription_id.txid.to_vec()); + buffer.extend_from_slice(&self.inscription_id.index.to_le_bytes()); + hash::sha3_256_of(buffer.as_slice()) + } +} + +pub const TICK: &str = "generator"; +pub const CONTENT_TYPE: &str = "application/wasm"; + +pub trait Generator { + fn inscribe_generate( + &self, + deploy_args: &[u8], + seed: &InscribeSeed, + recipient: &Address, + user_input: Option, + ) -> InscribeGenerateOutput; + + fn inscribe_verify( + &self, + deploy_args: &[u8], + seed: &InscribeSeed, + recipient: &Address, + user_input: Option, + inscribe_output: InscribeGenerateOutput, + ) -> bool; + + fn has_indexer_generate(&self) -> bool { + false + } + + fn indexer_generate( + &self, + _deploy_args: Vec, + _seed: &IndexerSeed, + _recipient: Address, + ) -> IndexerGenerateOutput { + IndexerGenerateOutput::default() + } +} + +pub struct StaticGenerator { + pub inscribe_output: InscribeGenerateOutput, + pub indexer_output: Option, +} + +impl StaticGenerator { + pub fn new( + inscribe_output: InscribeGenerateOutput, + indexer_output: Option, + ) -> Self { + Self { + inscribe_output, + indexer_output, + } + } +} + +impl Generator for StaticGenerator { + fn inscribe_generate( + &self, + _deploy_args: &[u8], + _seed: &InscribeSeed, + _recipient: &Address, + _user_input: Option, + ) -> InscribeGenerateOutput { + self.inscribe_output.clone() + } + + fn inscribe_verify( + &self, + _deploy_args: &[u8], + _seed: &InscribeSeed, + _recipient: &Address, + _user_input: Option, + inscribe_output: InscribeGenerateOutput, + ) -> bool { + self.inscribe_output == inscribe_output + } + + fn has_indexer_generate(&self) -> bool { + self.indexer_output.is_some() + } + + fn indexer_generate( + &self, + _deploy_args: Vec, + _seed: &IndexerSeed, + _recipient: Address, + ) -> IndexerGenerateOutput { + self.indexer_output.clone().unwrap() + } +} diff --git a/crates/rooch/src/commands/bitseed/generator/wasm/mod.rs b/crates/rooch/src/commands/bitseed/generator/wasm/mod.rs new file mode 100644 index 0000000000..03330ac8d5 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/generator/wasm/mod.rs @@ -0,0 +1,4 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +pub mod wasm_generator; diff --git a/crates/rooch/src/commands/bitseed/generator/wasm/wasm_generator.rs b/crates/rooch/src/commands/bitseed/generator/wasm/wasm_generator.rs new file mode 100644 index 0000000000..6c82b2175d --- /dev/null +++ b/crates/rooch/src/commands/bitseed/generator/wasm/wasm_generator.rs @@ -0,0 +1,657 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::commands::bitseed::generator::{Generator, InscribeGenerateOutput, InscribeSeed}; +use crate::commands::bitseed::sft; +use bitcoin::Address; +use ciborium::Value; +use serde_json; +use serde_json::{Number, Value as JSONValue}; +use std::ops::Deref; +use std::sync::{Arc, Mutex}; +use tracing::{debug, error}; +use wasmer::Value::I32; +use wasmer::*; + +#[allow(dead_code)] +#[derive(Clone)] +struct Env { + memory: Option>>, +} + +fn js_log(env: FunctionEnvMut, ptr: i32, len: i32) { + if let Some(memory_obj) = env.data().memory.clone() { + let memory = memory_obj.lock().expect("getting memory mutex failed"); + let store_ref = env.as_store_ref(); + let memory_view = memory.view(&store_ref); + + let mut buffer = vec![0u8; len as usize]; + memory_view + .read(ptr as u64, &mut buffer) + .expect("read buffer from memory failed"); + + let message = String::from_utf8_lossy(&buffer); + debug!("js_log_output: {}", message); + } +} + +fn fd_write(env: FunctionEnvMut, _fd: i32, mut iov: i32, iovcnt: i32, pnum: i32) -> i32 { + let mut written_bytes = 0; + + if let Some(memory_obj) = env.data().memory.clone() { + debug!( + "fd_write: fd:{}, iov:{}, iovcnt:{}, pnum:{}", + _fd, iov, iovcnt, pnum + ); + + let memory = memory_obj.lock().expect("getting memory mutex failed"); + let store_ref = env.as_store_ref(); + let memory_view = memory.view(&store_ref); + + let mut temp_buffer: [u8; 4] = [0; 4]; + + for _ in 0..iovcnt { + let ptr_index = iov; + let len_index = iov + 4; + + memory_view + .read(ptr_index as u64, temp_buffer.as_mut_slice()) + .expect("read data from memory view failed"); + let _ptr = u32::from_le_bytes(temp_buffer); + + memory_view + .read(len_index as u64, temp_buffer.as_mut_slice()) + .expect("read data from memory view failed"); + let len = u32::from_le_bytes(temp_buffer); + + debug!("fd_write: _ptr:{}, len:{}", _ptr, len); + + let mut buffer = vec![0u8; len as usize]; + memory_view + .read(_ptr as u64, &mut buffer) + .expect("read buffer from memory failed"); + + match _fd { + // stdout + 1 => { + use std::io::{self, Write}; + let stdout = io::stdout(); + let mut handle = stdout.lock(); + handle.write_all(&buffer).expect("write to stdout failed"); + } + // stderr + 2 => { + use std::io::{self, Write}; + let stderr = io::stderr(); + let mut handle = stderr.lock(); + handle.write_all(&buffer).expect("write to stderr failed"); + } + // Handle other file descriptors... + _ => unimplemented!(), + } + + iov += 8; + written_bytes += len as i32; + } + + let ret_index = pnum; + let ret_index_bytes: [u8; 4] = written_bytes.to_le_bytes(); + memory_view + .write(ret_index as u64, ret_index_bytes.as_slice()) + .expect("write data to memory failed"); + } + + written_bytes +} + +fn convert_i32_pair_to_i53_checked(lo: i32, hi: i32) -> i32 { + let p0 = if lo > 0 { 1 } else { 0 }; + let p1 = (hi + 0x200000) < (0x400001 - p0); + if p1 { + let (e0, _) = (hi as u32).overflowing_add_signed(429496729); + let (e1, _) = lo.overflowing_add_unsigned(e0); + e1 + } else { + 0 + } +} + +fn fd_seek( + _env: FunctionEnvMut, + _fd: i32, + offset_low: i64, + offset_high: i32, + _whence: i32, +) -> i32 { + let _offset = convert_i32_pair_to_i53_checked(offset_low as i32, offset_high); + 70 +} + +fn fd_close(_env: FunctionEnvMut, _fd: i32) -> i32 { + 0 +} + +fn proc_exit(_env: FunctionEnvMut, code: i32) { + error!("program exit with {:}", code) +} + +fn put_data_on_stack( + memory: &mut Arc>, + stack_alloc_func: &Function, + store: &mut Store, + data: &[u8], +) -> i32 { + let data_len = data.len() as i32; + let result = stack_alloc_func + .call(store, vec![I32(data_len + 1)].as_slice()) + .expect("call stackAlloc failed"); + let return_value = result + .deref() + .first() + .expect("the stackAlloc func does not have return value"); + let offset = return_value + .i32() + .expect("the return value of stackAlloc is not i32"); + + let bindings = memory.lock().expect("getting memory mutex failed"); + let memory_view = bindings.view(store); + memory_view + .write(offset as u64, data) + .expect("write memory failed"); + + offset +} + +fn get_data_from_heap(memory: &mut Arc>, store: &Store, ptr_offset: i32) -> Vec { + let bindings = memory.lock().expect("getting memory mutex failed"); + let memory_view = bindings.view(store); + let mut length_bytes: [u8; 4] = [0; 4]; + memory_view + .read(ptr_offset as u64, length_bytes.as_mut_slice()) + .expect("read length_bytes failed"); + let length = u32::from_be_bytes(length_bytes); + let mut data = vec![0; length as usize]; + memory_view + .read((ptr_offset + 4) as u64, &mut data) + .expect("read uninit failed"); + data +} + +fn create_wasm_instance(bytecode: &[u8]) -> (Instance, Store) { + let mut store = Store::default(); + let module = Module::new(&store, bytecode).unwrap(); + + let env = FunctionEnv::new(&mut store, Env { memory: None }); + + let import_object = imports! { + "wasi_snapshot_preview1" => { + "fd_write" => Function::new_typed_with_env(&mut store, &env, fd_write), + "fd_seek" => Function::new_typed_with_env(&mut store, &env, fd_seek), + "fd_close" => Function::new_typed_with_env(&mut store, &env, fd_close), + "proc_exit" => Function::new_typed_with_env(&mut store, &env, proc_exit), + }, + "env" => { + "js_log" => Function::new_typed_with_env(&mut store, &env, js_log), + }, + }; + + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); + + let memory = instance.exports.get_memory("memory").unwrap(); + env.as_mut(&mut store).memory = Some(Arc::new(Mutex::new(memory.clone()))); + + (instance, store) +} + +#[derive(Clone)] +pub struct WASMGenerator { + bytecode: Vec, +} + +impl WASMGenerator { + pub fn new(bytecode: Vec) -> Self { + Self { bytecode } + } + + fn generate_buffer_final_ptr( + &self, + deploy_args: &[u8], + seed: &InscribeSeed, + user_input: Option, + memory: &mut Arc>, + stack_alloc_func: &Function, + store: &mut Store, + ) -> i32 { + let mut attrs_buffer_vec = Vec::new(); + for byte in deploy_args.iter() { + attrs_buffer_vec.push(serde_json::Value::Number(Number::from(*byte))); + } + + let mut buffer_map = serde_json::Map::new(); + buffer_map.insert( + "attrs".to_string(), + serde_json::Value::Array(attrs_buffer_vec), + ); + + let seed = hex::encode(seed.seed()); + buffer_map.insert("seed".to_string(), serde_json::Value::String(seed)); + + if let Some(input) = user_input { + buffer_map.insert("user_input".to_string(), serde_json::Value::String(input)); + } + + let top_buffer_map = JSONValue::Object(buffer_map); + let mut top_buffer = Vec::new(); + ciborium::into_writer(&top_buffer_map, &mut top_buffer).expect("ciborium marshal failed"); + + let mut buffer_final = Vec::new(); + buffer_final.append(&mut (top_buffer.len() as u32).to_be_bytes().to_vec()); + buffer_final.append(&mut top_buffer); + + put_data_on_stack(memory, stack_alloc_func, store, buffer_final.as_slice()) + } +} + +impl Generator for WASMGenerator { + fn inscribe_generate( + &self, + deploy_args: &[u8], + seed: &InscribeSeed, + _recipient: &Address, + user_input: Option, + ) -> InscribeGenerateOutput { + let (instance, mut store) = create_wasm_instance(&self.bytecode); + let stack_alloc_func = instance.exports.get_function("stackAlloc").unwrap(); + let inscribe_generate = instance.exports.get_function("inscribe_generate").unwrap(); + + let memory_obj = instance.exports.get_memory("memory").unwrap(); + let mut memory = Arc::new(Mutex::new(memory_obj.clone())); + + let buffer_final_ptr = self.generate_buffer_final_ptr( + deploy_args, + seed, + user_input, + &mut memory, + stack_alloc_func, + &mut store, + ); + + let func_args = vec![I32(buffer_final_ptr)]; + + let calling_result = inscribe_generate + .call(&mut store, func_args.as_slice()) + .expect("call inscribe_generate failed"); + + let return_value = calling_result.deref().first().unwrap(); + let offset = return_value.i32().unwrap(); + + let data = get_data_from_heap(&mut memory, &store, offset); + + let return_value: Value = + ciborium::from_reader(data.as_slice()).expect("ciborium::from_reader failed"); + + let mut inscribe_generate_output = InscribeGenerateOutput::default(); + + for (k, v) in return_value + .as_map() + .expect("the return value from inscribe_generate is incorrect") + { + if let Some(key) = k.as_text() { + match key { + "amount" => { + let value = u128::try_from(v.as_integer().unwrap()).unwrap(); + inscribe_generate_output.amount = value as u64; + } + "attributes" => { + inscribe_generate_output.attributes = Some(v.clone()); + } + "content" => { + inscribe_generate_output.content = build_content(v.clone()); + } + _ => {} + } + } + } + + inscribe_generate_output + } + + fn inscribe_verify( + &self, + deploy_args: &[u8], + seed: &InscribeSeed, + _recipient: &Address, + user_input: Option, + inscribe_output: InscribeGenerateOutput, + ) -> bool { + let (instance, mut store) = create_wasm_instance(&self.bytecode); + let stack_alloc_func = instance.exports.get_function("stackAlloc").unwrap(); + let inscribe_verify = instance.exports.get_function("inscribe_verify").unwrap(); + + let memory_obj = instance.exports.get_memory("memory").unwrap(); + let mut memory = Arc::new(Mutex::new(memory_obj.clone())); + + let buffer_final_ptr = self.generate_buffer_final_ptr( + deploy_args, + seed, + user_input, + &mut memory, + stack_alloc_func, + &mut store, + ); + + let inscribe_output_bytes = inscribe_output_to_cbor(inscribe_output); + let inscribe_output_final_ptr = put_data_on_stack( + &mut memory, + stack_alloc_func, + &mut store, + inscribe_output_bytes.as_slice(), + ); + + let func_args = vec![I32(buffer_final_ptr), I32(inscribe_output_final_ptr)]; + + let calling_result = inscribe_verify + .call(&mut store, func_args.as_slice()) + .expect("call inscribe_verify failed"); + + let return_value = calling_result.deref().first().unwrap(); + return_value.i32().unwrap() == 1 + } +} + +fn build_content(v: ciborium::Value) -> Option { + // Check if the Value is a map + if let ciborium::Value::Map(map) = v { + // Initialize variables to store content-type and body + let mut content_type: Option = None; + let mut body: Option> = None; + + // Iterate through the map to find content-type and body + for (key, value) in map { + if let ciborium::Value::Text(key_str) = key { + match key_str.as_str() { + "content_type" => { + if let ciborium::Value::Text(ct) = value { + content_type = Some(ct); + } + } + "body" => { + if let ciborium::Value::Bytes(b) = value { + body = Some(b); + } + } + _ => {} + } + } + } + + // If both content-type and body exist, construct sft::Content + if let (Some(ct), Some(b)) = (content_type, body) { + return Some(sft::Content::new(ct, b)); + } + } + + // Return None if content-type or body is missing + None +} + +fn inscribe_output_to_cbor(inscribe_output: InscribeGenerateOutput) -> Vec { + // Create a map to hold the CBOR representation + let mut map = Vec::new(); + + // Add amount to the map + map.push(( + ciborium::Value::Text("amount".to_string()), + ciborium::Value::Integer(inscribe_output.amount.into()), + )); + + // Add attributes to the map if they exist + if let Some(attributes) = inscribe_output.attributes { + map.push((ciborium::Value::Text("attributes".to_string()), attributes)); + } + + // Add content to the map if it exists + let mut content_map = Vec::new(); + + if let Some(content) = inscribe_output.content { + content_map.push(( + ciborium::Value::Text("content_type".to_string()), + ciborium::Value::Text(content.content_type), + )); + content_map.push(( + ciborium::Value::Text("body".to_string()), + ciborium::Value::Bytes(content.body), + )); + } + + map.push(( + ciborium::Value::Text("content".to_string()), + ciborium::Value::Map(content_map), + )); + + // Serialize the map to CBOR bytes + let mut buffer = Vec::new(); + ciborium::ser::into_writer(&ciborium::Value::Map(map), &mut buffer) + .expect("Failed to serialize to CBOR"); + buffer +} + +#[cfg(test)] +mod tests { + use crate::commands::bitseed::operation::deploy_args_cbor_encode; + + use super::*; + use bitcoin::hashes::sha256d; + use bitcoin::Txid; + use bitcoin::{Address, Network}; + use sft::Content; + use std::str::FromStr; + + const CPP_GENERATOR: &[u8] = + include_bytes!("../../../../../../../generator/cpp/generator.wasm"); + const RUST_GENERATOR: &[u8] = + include_bytes!("../../../../../../../generator/rust/pkg/generator_bg.wasm"); + + #[test] + fn test_inscribe_generate_normal() { + tracing_subscriber::fmt::try_init().ok(); + + // Read WASM binary from file + let bytecode = CPP_GENERATOR.to_vec(); + let generator = WASMGenerator::new(bytecode); + + let deploy_args = + vec![r#"{"height":{"type":"range","data":{"min":1,"max":1000}}}"#.to_string()]; + let deploy_args = deploy_args_cbor_encode(deploy_args).unwrap(); + + // Block hash + // let block_hash_hex = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"; + // let block_hash_inner = sha256d::Hash::from_str(&block_hash_hex).unwrap(); + // let block_hash = BlockHash::from(block_hash_inner); + + // Txid + let txid_hex = "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"; + let txid_inner = sha256d::Hash::from_str(txid_hex).unwrap(); + let txid = Txid::from(txid_inner); + + let seed = InscribeSeed { + // block_hash, + utxo: bitcoin::OutPoint::new(txid, 0), + }; + + // Recipient + let recipient: Address = Address::from_str("32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf") + .unwrap() + .require_network(Network::Bitcoin) + .unwrap(); + + // User input + let user_input = Some("test user input".to_string()); + + let output = generator.inscribe_generate(&deploy_args, &seed, &recipient, user_input); + + // Add assertions for output + assert_eq!(output.amount, 1000); + assert!(output.attributes.is_some()); + + // Check if attributes contain expected key-value pairs + let attributes = output.attributes.unwrap(); + assert!(attributes.is_map()); + let map = attributes.as_map().unwrap(); + + let height_entry = map.iter().find(|(key, _)| key.as_text() == Some("height")); + assert!(height_entry.is_some()); + + let (_, height_value) = height_entry.unwrap(); + assert!(height_value.is_integer()); + let height = height_value.as_integer().unwrap(); + let height: i128 = height.into(); + assert!(height >= 1i128); + assert!(height <= 1000i128); + } + + #[test] + fn test_inscribe_verify() { + // Read WASM binary from file + let bytecode = CPP_GENERATOR.to_vec(); + let generator = WASMGenerator::new(bytecode); + + let deploy_args = + vec![r#"{"height":{"type":"range","data":{"min":1,"max":1000}}}"#.to_string()]; + let deploy_args = deploy_args_cbor_encode(deploy_args).unwrap(); + + // Block hash + // let block_hash_hex = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"; + // let block_hash_inner = sha256d::Hash::from_str(&block_hash_hex).unwrap(); + // let block_hash = BlockHash::from(block_hash_inner); + + // Txid + let txid_hex = "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"; + let txid_inner = sha256d::Hash::from_str(txid_hex).unwrap(); + let txid = Txid::from(txid_inner); + + let seed = InscribeSeed { + // block_hash, + utxo: bitcoin::OutPoint::new(txid, 0), + }; + + // Recipient + let recipient: Address = Address::from_str("32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf") + .unwrap() + .require_network(Network::Bitcoin) + .unwrap(); + + // User input + let user_input = Some("test user input".to_string()); + + // Generate output using inscribe_generate + let output = + generator.inscribe_generate(&deploy_args, &seed, &recipient, user_input.clone()); + + // Verify the generated output using inscribe_verify + let is_valid = + generator.inscribe_verify(&deploy_args, &seed, &recipient, user_input, output); + + // Add assertion to check if the output is valid + assert!(is_valid, "The inscribe output should be valid"); + } + + #[test] + fn test_inscribe_verify_for_rust() { + // Read WASM binary from file + let bytecode = RUST_GENERATOR.to_vec(); + let generator = WASMGenerator::new(bytecode); + + let deploy_args = + vec![r#"{"height":{"type":"range","data":{"min":1,"max":1000}}}"#.to_string()]; + let deploy_args = deploy_args_cbor_encode(deploy_args).unwrap(); + + // Block hash + // let block_hash_hex = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"; + // let block_hash_inner = sha256d::Hash::from_str(&block_hash_hex).unwrap(); + // let block_hash = BlockHash::from(block_hash_inner); + + // Txid + let txid_hex = "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"; + let txid_inner = sha256d::Hash::from_str(txid_hex).unwrap(); + let txid = Txid::from(txid_inner); + + let seed = InscribeSeed { + // block_hash, + utxo: bitcoin::OutPoint::new(txid, 0), + }; + + // Recipient + let recipient: Address = Address::from_str("32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf") + .unwrap() + .require_network(Network::Bitcoin) + .unwrap(); + + // User input + let user_input = Some("test user input".to_string()); + + // Generate output using inscribe_generate + let output = + generator.inscribe_generate(&deploy_args, &seed, &recipient, user_input.clone()); + + // Verify the generated output using inscribe_verify + let is_valid = + generator.inscribe_verify(&deploy_args, &seed, &recipient, user_input, output); + + // Add assertion to check if the output is valid + assert!(is_valid, "The inscribe output should be valid"); + } + + #[test] + fn test_inscribe_output_to_cbor() { + let attributes = vec![ + ( + ciborium::Value::Text("height".to_string()), + ciborium::Value::Integer(444.into()), + ), + ( + ciborium::Value::Text("id".to_string()), + ciborium::Value::Text("test user input".to_string()), + ), + ]; + + let output = InscribeGenerateOutput { + amount: 1, + attributes: Some(ciborium::Value::Map(attributes)), + content: Some(Content { + content_type: "text/plain".to_string(), + body: vec![104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33], + }), + }; + + let cbor_bytes = inscribe_output_to_cbor(output); + let output_hex = hex::encode(cbor_bytes); + + assert!(output_hex == "a366616d6f756e74016a61747472696275746573a2666865696768741901bc6269646f74657374207573657220696e70757467636f6e74656e74a26c636f6e74656e745f747970656a746578742f706c61696e64626f64794c68656c6c6f20776f726c6421", "The inscribe output should be valid"); + } + + #[test] + fn test_inscribe_output_to_cbor_without_body() { + let attributes = vec![ + ( + ciborium::Value::Text("height".to_string()), + ciborium::Value::Integer(444.into()), + ), + ( + ciborium::Value::Text("id".to_string()), + ciborium::Value::Text("test user input".to_string()), + ), + ]; + + let output = InscribeGenerateOutput { + amount: 1, + attributes: Some(ciborium::Value::Map(attributes)), + content: None, + }; + + let cbor_bytes = inscribe_output_to_cbor(output); + let output_hex = hex::encode(cbor_bytes); + + assert!(output_hex == "a366616d6f756e74016a61747472696275746573a2666865696768741901bc6269646f74657374207573657220696e70757467636f6e74656e74a0", "The inscribe output should be valid"); + } +} diff --git a/crates/rooch/src/commands/bitseed/inscribe.rs b/crates/rooch/src/commands/bitseed/inscribe.rs new file mode 100644 index 0000000000..a0b7134c51 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/inscribe.rs @@ -0,0 +1,1277 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use super::{ + generator::{self, Generator, InscribeSeed}, + operation::{AsSFT, DeployRecord, MergeRecord, MintRecord, Operation, SplitRecord}, + sft::{Content, SFT}, + GENERATOR_TICK, +}; +use crate::commands::{ + bitcoin::utxo_selector::UTXOSelector, + bitseed::{ + generator::{wasm::wasm_generator::WASMGenerator, CONTENT_TYPE}, + inscription::BitseedInscription, + }, +}; +use anyhow::{anyhow, bail, ensure, Result}; +use bitcoin::{ + key::{TapTweak, TweakedKeypair}, + script::PushBytesBuf, + secp256k1::Message, + transaction::Version, + EcdsaSighashType, OutPoint, +}; +use clap::Parser; +use rooch_rpc_api::jsonrpc_types::btc::{ord::InscriptionObjectView, utxo::UTXOObjectView}; +use rooch_rpc_client::wallet_context::WalletContext; +use rooch_types::{ + address::{BitcoinAddress, ParsedAddress}, + bitcoin::ord::{Inscription, InscriptionID, InscriptionRecord, SatPoint}, +}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, path::Path, str::FromStr}; +use tracing::debug; +use { + bitcoin::{ + absolute::LockTime, + blockdata::{opcodes, script}, + key::{Keypair, TweakedPublicKey}, + secp256k1::{constants::SCHNORR_SIGNATURE_SIZE, rand, All, Secp256k1, XOnlyPublicKey}, + sighash::{Prevouts, SighashCache, TapSighashType}, + taproot::{ + ControlBlock, LeafVersion, Signature, TapLeafHash, TaprootBuilder, TaprootSpendInfo, + }, + Address, Amount, FeeRate, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Witness, + }, + ciborium::Value, +}; + +const TARGET_POSTAGE: Amount = Amount::from_sat(10_000); + +#[derive(Debug, Clone, Parser)] +pub struct InscribeOptions { + /// The sender address of the transaction, if not specified, the active address will be used + #[clap(long, short = 's', default_value = "default")] + pub(crate) sender: ParsedAddress, + + /// Send inscription to , if not specified, the sender address will be used + #[arg(long)] + pub(crate) destination: Option, + + /// Use as the change address, if not specified, the sender address will be used + #[arg(long)] + pub(crate) change_address: Option, + + #[arg( + long, + help = "Inscribe . This SatPoint will be used as mint seed." + )] + pub(crate) satpoint: Option, + #[arg( + long, + help = "Use sats/vbyte for commit transaction.\nDefaults to if unset." + )] + pub(crate) commit_fee_rate: Option, + + #[arg(long, help = "Don't sign or broadcast transactions.")] + pub(crate) dry_run: bool, + #[arg(long, help = "Use fee rate of sats/vB.")] + pub(crate) fee_rate: FeeRate, + #[arg(long, alias = "nobackup", help = "Do not back up recovery key.")] + pub(crate) no_backup: bool, + #[arg( + long, + alias = "nolimit", + help = "Do not check that transactions are equal to or below the MAX_STANDARD_TX_WEIGHT of 400,000 weight units. Transactions over this limit are currently nonstandard and will not be relayed by bitcoind in its default configuration. Do not use this flag unless you understand the implications." + )] + pub(crate) no_limit: bool, + #[arg( + long, + help = "Amount of postage to include in the inscription. Default `10000sat`." + )] + pub(crate) postage: Option, +} + +impl InscribeOptions { + pub fn postage(&self) -> Amount { + self.postage.unwrap_or(TARGET_POSTAGE) + } + + pub fn commit_fee_rate(&self) -> FeeRate { + self.commit_fee_rate.unwrap_or(self.fee_rate) + } + + pub fn reveal_fee_rate(&self) -> FeeRate { + self.fee_rate + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum InscriptionOrId { + Inscription(Box), + Id(InscriptionID), +} + +#[derive(Debug, Clone)] +pub struct InscribeContext { + pub commit_tx: Transaction, + pub reveal_tx: Transaction, + pub signed_commit_tx: Option, + pub signed_reveal_tx: Option, + + pub key_pairs: Vec, + pub reveal_scripts: Vec, + pub control_blocks: Vec, + pub taproot_spend_infos: Vec, + pub commit_tx_addresses: Vec
, + + pub utxos: BTreeMap, + pub reveal_scripts_to_sign: Vec, + pub control_blocks_to_sign: Vec, + pub reveal_input_start_index: Option, + + pub total_burn_postage: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct InscribeOutput { + commit_tx: Txid, + reveal_tx: Txid, + total_fees: Amount, + inscriptions: Vec, +} + +pub struct Inscriber { + context: WalletContext, + utxo_selector: UTXOSelector, + option: InscribeOptions, + inscriptions: Vec, + inscriptions_to_burn: Vec, + satpoint: (SatPoint, UTXOObjectView), + network: bitcoin::Network, + destination: Address, + change_address: Address, +} + +impl Inscriber { + const SCHNORR_SIGNATURE_SIZE: usize = 64; + + pub async fn new(context: WalletContext, option: InscribeOptions) -> Result { + let bitcoin_network = context.get_bitcoin_network().await?; + let sender = context + .resolve_bitcoin_address(option.sender.clone()) + .await?; + let destination = match option.destination.clone() { + Some(destination) => context.resolve_bitcoin_address(destination).await?, + None => sender.clone(), + }; + let change_address = match option.change_address.clone() { + Some(change_address) => context.resolve_bitcoin_address(change_address).await?, + None => sender.clone(), + }; + + let mut utxo_selector = UTXOSelector::new( + context.get_client().await?, + sender.to_bitcoin_address(bitcoin_network)?, + Vec::new(), + false, + ) + .await?; + + let (satpoint, utxo) = match option.satpoint.clone() { + Some(satpoint) => { + let utxo_view = utxo_selector.get_utxo(&satpoint.outpoint).await?; + (satpoint, utxo_view) + } + None => { + let utxo_view = utxo_selector + .next_utxo() + .await? + .ok_or_else(|| anyhow!("No UTXO found"))?; + let outpoint = utxo_view.outpoint(); + ( + SatPoint { + outpoint, + offset: 0, + }, + utxo_view, + ) + } + }; + + Ok(Self { + context, + utxo_selector, + option, + inscriptions: Vec::new(), + inscriptions_to_burn: Vec::new(), + satpoint: (satpoint, utxo), + network: bitcoin_network.into(), + destination: destination.to_bitcoin_address(bitcoin_network)?, + change_address: change_address.to_bitcoin_address(bitcoin_network)?, + }) + } + + pub async fn with_generator

( + self, + generator_name: String, + generator_program: P, + ) -> Result + where + P: AsRef, + { + let bytecode = std::fs::read(generator_program)?; + let content = Content::new(generator::CONTENT_TYPE.to_string(), bytecode); + let attributes = Value::Map(vec![( + Value::Text("name".to_string()), + Value::Text(generator_name.clone()), + )]); + + let mint_record = MintRecord { + sft: SFT { + tick: GENERATOR_TICK.to_string(), + amount: 1, + attributes: Some(attributes), + content: Some(content), + }, + }; + + Ok(self.with_operation(Operation::Mint(mint_record))) + } + + pub async fn with_deploy( + self, + tick: String, + amount: u64, + generator: Option, + factory: Option, + repeat: u64, + deploy_args: Vec, + ) -> Result { + match (&generator, &factory) { + (Some(_), Some(_)) => bail!("generator and factory cannot be used together"), + (None, None) => bail!("generator or factory must be provided"), + _ => {} + } + let generator = match generator { + Some(generator) => { + let inscription_obj = self.get_inscription_object(generator).await?; + let bitseed_inscription = BitseedInscription::new(inscription_obj.value.into())?; + ensure!( + bitseed_inscription.tick()? == GENERATOR_TICK, + "invalid generator: {}", + generator + ); + Some(format!("/inscription/{}", generator)) + } + None => None, + }; + let deploy_record = DeployRecord { + tick, + amount, + generator, + factory, + repeat, + deploy_args, + }; + Ok(self.with_operation(Operation::Deploy(deploy_record))) + } + + pub async fn with_mint( + self, + deploy_inscription: InscriptionID, + user_input: Option, + ) -> Result { + let operation = self + .get_operation_by_inscription_id(deploy_inscription) + .await?; + let deploy_record = match operation { + Operation::Deploy(deploy_record) => deploy_record, + _ => bail!("deploy transaction must have a deploy operation"), + }; + + let generator_id = deploy_record.generator.as_ref().ok_or_else(|| { + anyhow!("The deploy record does not have a generator inscription id, can not mint on Bitcoin") + })?; + let generator = self.load_generator(generator_id).await?; + + let seed_utxo = self.satpoint.0.outpoint.clone(); + + let seed = InscribeSeed::new(seed_utxo.into()); + + let destination = self.destination.clone(); + + let output = generator.inscribe_generate( + &deploy_record.deploy_args, + &seed, + &destination, + user_input, + ); + + let sft = SFT { + tick: deploy_record.tick, + amount: output.amount, + attributes: output.attributes, + content: output.content, + }; + let mint_record = MintRecord { sft }; + + Ok(self.with_operation(Operation::Mint(mint_record))) + } + + pub async fn with_split( + self, + asset_inscription_id: InscriptionID, + amounts: Vec, + ) -> Result { + let operation = self + .get_operation_by_inscription_id(asset_inscription_id) + .await?; + let sft = match operation { + Operation::Mint(mint_record) => mint_record.as_sft(), + Operation::Split(split_record) => split_record.as_sft(), + Operation::Merge(merge_record) => merge_record.as_sft(), + _ => bail!( + "Inscription {} is not a valid SFT record", + asset_inscription_id + ), + }; + + ensure!( + sft.amount >= amounts.iter().sum::(), + "The total split amount exceeds the available SFT amount" + ); + + let mut remaining_amount = sft.amount; + let mut result = self.with_burn(asset_inscription_id).await; + + let amounts_len = amounts.len(); + + for (index, amount) in amounts.into_iter().enumerate() { + let split_sft = SFT { + tick: sft.tick.clone(), + amount, + attributes: sft.attributes.clone(), + content: sft.content.clone(), + }; + let split_record = SplitRecord { sft: split_sft }; + result = result.with_operation(Operation::Split(split_record)); + remaining_amount -= amount; + + if index == amounts_len - 1 { + let remaining_sft = SFT { + tick: sft.tick.clone(), + amount: remaining_amount, + attributes: sft.attributes.clone(), + content: sft.content.clone(), + }; + let split_record = SplitRecord { sft: remaining_sft }; + result = result.with_operation(Operation::Split(split_record)); + } + } + + Ok(result) + } + + pub async fn with_merge(self, sft_inscription_ids: Vec) -> Result { + ensure!( + sft_inscription_ids.len() > 1, + "At least two SFTs are required for merging" + ); + + let mut sft_to_merge = Vec::new(); + let mut result = self; + + for inscription_id in sft_inscription_ids { + let operation = result + .get_operation_by_inscription_id(inscription_id) + .await?; + let sft = match operation { + Operation::Mint(mint_record) => mint_record.as_sft(), + Operation::Split(split_record) => split_record.as_sft(), + Operation::Merge(merge_record) => merge_record.as_sft(), + _ => bail!("Inscription {} is not a minted SFT", inscription_id), + }; + + sft_to_merge.push(sft); + result = result.with_burn(inscription_id).await; + } + + let mut merged_sft = sft_to_merge[0].clone(); + for sft in sft_to_merge.iter().skip(1) { + ensure!( + merged_sft.tick == sft.tick, + "All SFTs must have the same tick to be merged" + ); + ensure!( + merged_sft.attributes == sft.attributes, + "All SFTs must have the same attributes to be merged" + ); + ensure!( + merged_sft.content == sft.content, + "All SFTs must have the same content to be merged" + ); + merged_sft.amount += sft.amount; + } + + let merge_record = MergeRecord { sft: merged_sft }; + result = result.with_operation(Operation::Merge(merge_record)); + + Ok(result) + } + + pub async fn with_burn(mut self, inscription_id: InscriptionID) -> Self { + self.inscriptions_to_burn.push(inscription_id); + self + } + + fn with_operation(mut self, operation: Operation) -> Self { + let inscription = operation.to_inscription(); + self.inscriptions.push(inscription); + self + } + + fn backup_recovery_key(_context: &WalletContext, kp: TweakedKeypair) -> Result<()> { + //TODO back up recovery key + + println!( + "Recovery key: {}", + hex::encode(kp.to_inner().secret_bytes()) + ); + + // let recovery_private_key = PrivateKey::new( + // recovery_key_pair.to_inner().secret_key(), + // wallet.chain().network(), + // ); + + // let bitcoin_client = wallet.bitcoin_client()?; + + // let info = bitcoin_client + // .get_descriptor_info(&format!("rawtr({})", recovery_private_key.to_wif()))?; + + // let response = bitcoin_client.import_descriptors(vec![ImportDescriptors { + // descriptor: format!("rawtr({})#{}", recovery_private_key.to_wif(), info.checksum), + // timestamp: Timestamp::Now, + // active: Some(false), + // range: None, + // next_index: None, + // internal: Some(false), + // label: Some("commit tx recovery key".to_string()), + // }])?; + + // for result in response { + // if !result.success { + // return Err(anyhow!("commit tx recovery key import failed")); + // } + // } + + Ok(()) + } + + fn calculate_fee(tx: &Transaction, utxos: &BTreeMap) -> Amount { + tx.input + .iter() + .map(|txin| utxos.get(&txin.previous_output).unwrap().value) + .sum::() + .checked_sub(tx.output.iter().map(|txout| txout.value).sum::()) + .unwrap() + } + + fn create_reveal_script_and_control_block( + inscription: &InscriptionRecord, + secp256k1: &Secp256k1, + ) -> Result<(Keypair, ScriptBuf, ControlBlock, TaprootSpendInfo)> { + let key_pair = Keypair::new(secp256k1, &mut rand::thread_rng()); + let (public_key, _parity) = XOnlyPublicKey::from_keypair(&key_pair); + + let reveal_script = inscription + .append_reveal_script_to_builder( + ScriptBuf::builder() + .push_slice(public_key.serialize()) + .push_opcode(opcodes::all::OP_CHECKSIG), + ) + .into_script(); + + let taproot_spend_info = TaprootBuilder::new() + .add_leaf(0, reveal_script.clone()) + .expect("adding leaf should work") + .finalize(secp256k1, public_key) + .expect("finalizing taproot builder should work"); + + let control_block = taproot_spend_info + .control_block(&(reveal_script.clone(), LeafVersion::TapScript)) + .expect("should compute control block"); + + Ok((key_pair, reveal_script, control_block, taproot_spend_info)) + } + + async fn select_additional_inputs( + &mut self, + ctx: &mut InscribeContext, + additional_value: Amount, + ) -> Result> { + let utxos = self.utxo_selector.select_utxos(additional_value).await?; + + let mut additional_inputs = Vec::new(); + + for utxo in utxos { + let input = TxIn { + previous_output: utxo.outpoint().into(), + script_sig: ScriptBuf::new(), + sequence: Sequence::ENABLE_RBF_NO_LOCKTIME, + witness: Witness::new(), + }; + ctx.utxos.insert(utxo.outpoint().into(), utxo.tx_output()?); + additional_inputs.push(input); + } + + Ok(additional_inputs) + } + + fn estimate_commit_tx_fee(&self, ctx: &InscribeContext) -> Amount { + let input_count = ctx.commit_tx.input.len(); + let output_count = ctx.commit_tx.output.len(); + + let mut estimated_commit_tx = Transaction { + version: Version::TWO, + lock_time: LockTime::ZERO, + input: (0..input_count) + .map(|_| TxIn { + previous_output: OutPoint::null(), + script_sig: ScriptBuf::new(), + sequence: Sequence::ENABLE_RBF_NO_LOCKTIME, + witness: Witness::from_slice(&[&[0; Self::SCHNORR_SIGNATURE_SIZE]]), + }) + .collect(), + output: (0..output_count) + .map(|_| TxOut { + value: Amount::ZERO, + script_pubkey: ScriptBuf::new(), + }) + .collect(), + }; + + for (index, output) in ctx.commit_tx.output.iter().enumerate() { + estimated_commit_tx.output[index].script_pubkey = output.script_pubkey.clone(); + } + + self.option + .commit_fee_rate() + .fee_vb(estimated_commit_tx.vsize() as u64) + .expect("fee should be valid") + } + + fn estimate_reveal_tx_fee( + &self, + ctx: &InscribeContext, + reveal_scripts: &[ScriptBuf], + control_blocks: &[ControlBlock], + ) -> Amount { + let mut reveal_tx = ctx.reveal_tx.clone(); + let reveal_input_start_index = ctx.reveal_input_start_index.unwrap_or(0); + + for (current_index, txin) in reveal_tx.input.iter_mut().enumerate() { + if current_index >= reveal_input_start_index { + let reveal_script = &reveal_scripts[current_index - reveal_input_start_index]; + let control_block = &control_blocks[current_index - reveal_input_start_index]; + + txin.witness.push( + Signature::from_slice(&[0; SCHNORR_SIGNATURE_SIZE]) + .unwrap() + .to_vec(), + ); + txin.witness.push(reveal_script); + txin.witness.push(&control_block.serialize()); + } else { + // For inputs related to inscription destruction + txin.witness.push( + Signature::from_slice(&[0; SCHNORR_SIGNATURE_SIZE]) + .unwrap() + .to_vec(), + ); + txin.witness.push([0; 33]); // Placeholder for public key + } + } + + self.option + .reveal_fee_rate() + .fee_vb(reveal_tx.vsize() as u64) + .expect("fee should be valid") + } + + fn assert_commit_transaction_balance(&self, ctx: &InscribeContext, msg: &str) { + let tx = &ctx.commit_tx; + let utxos = &ctx.utxos; + + let total_input: Amount = tx + .input + .iter() + .map(|input| utxos.get(&input.previous_output).unwrap().value) + .sum(); + + let total_output: Amount = tx.output.iter().map(|output| output.value).sum(); + + let fee = self.estimate_commit_tx_fee(ctx); + + assert_eq!(total_input, total_output + fee, "{}", msg); + } + + fn assert_reveal_transaction_balance(&self, ctx: &InscribeContext, msg: &str) { + let tx = &ctx.reveal_tx; + let utxos = &ctx.utxos; + + let total_input: Amount = tx + .input + .iter() + .map(|input| utxos.get(&input.previous_output).unwrap().value) + .sum(); + + let total_output: Amount = tx.output.iter().map(|output| output.value).sum(); + + let fee = self.estimate_reveal_tx_fee(ctx, &ctx.reveal_scripts, &ctx.control_blocks); + + assert_eq!(total_input, total_output + fee, "{}", msg); + } + + fn prepare_context(&self) -> Result { + let commit_tx = Transaction { + input: Vec::new(), + output: Vec::new(), + lock_time: LockTime::ZERO, + version: Version::TWO, + }; + + let reveal_tx = Transaction { + input: Vec::new(), + output: Vec::new(), + lock_time: LockTime::ZERO, + version: Version::TWO, + }; + + let mut utxos = BTreeMap::new(); + utxos.insert( + self.satpoint.0.outpoint.clone().into(), + self.satpoint.1.tx_output()?, + ); + + Ok(InscribeContext { + commit_tx, + reveal_tx, + signed_commit_tx: None, + signed_reveal_tx: None, + + key_pairs: Vec::new(), + reveal_scripts: Vec::new(), + control_blocks: Vec::new(), + taproot_spend_infos: Vec::new(), + commit_tx_addresses: Vec::new(), + + utxos, + reveal_scripts_to_sign: Vec::new(), + control_blocks_to_sign: Vec::new(), + reveal_input_start_index: None, + total_burn_postage: None, + }) + } + + fn build_commit(&self, ctx: &mut InscribeContext) -> Result<()> { + let secp256k1 = Secp256k1::new(); + + // set satpoint + ctx.commit_tx.input.push(TxIn { + previous_output: self.satpoint.0.outpoint.clone().into(), + script_sig: ScriptBuf::new(), + sequence: Sequence::ENABLE_RBF_NO_LOCKTIME, + witness: Witness::new(), + }); + + let dust_threshold = self.destination.script_pubkey().minimal_non_dust(); + + for inscription in &self.inscriptions { + let (key_pair, reveal_script, control_block, taproot_spend_info) = + Self::create_reveal_script_and_control_block(inscription, &secp256k1)?; + + let commit_tx_address = + Address::p2tr_tweaked(taproot_spend_info.output_key(), self.network); + + let commit_tx_output = TxOut { + script_pubkey: commit_tx_address.script_pubkey(), + value: dust_threshold, + }; + + ctx.commit_tx.output.push(commit_tx_output); + + ctx.key_pairs.push(key_pair); + ctx.reveal_scripts.push(reveal_script); + ctx.control_blocks.push(control_block); + ctx.taproot_spend_infos.push(taproot_spend_info); + ctx.commit_tx_addresses.push(commit_tx_address); + } + + Ok(()) + } + + async fn build_reveal(&self, ctx: &mut InscribeContext) -> Result<()> { + // Process the logic of inscription destruction + let mut total_burn_postage = Amount::ZERO; + + for inscription_to_burn in &self.inscriptions_to_burn { + let inscription_id = *inscription_to_burn; + let satpoint = self.get_inscription_satpoint(inscription_id).await?; + let input = TxIn { + previous_output: satpoint.outpoint(), + script_sig: ScriptBuf::new(), + sequence: Sequence::ENABLE_RBF_NO_LOCKTIME, + witness: Witness::new(), + }; + ctx.reveal_tx.input.push(input); + + let inscription_output = ctx + .utxos + .get(&satpoint.outpoint()) + .expect("inscription utxo not found"); + total_burn_postage += inscription_output.value; + } + + if !self.inscriptions_to_burn.is_empty() { + let msg = b"bitseed".to_vec(); + let msg_push_bytes = + script::PushBytesBuf::try_from(msg.clone()).expect("burn message should fit"); + + let script = ScriptBuf::new_op_return(msg_push_bytes); + let output = TxOut { + script_pubkey: script, + value: total_burn_postage, + }; + ctx.reveal_tx.output.push(output); + ctx.total_burn_postage = Some(total_burn_postage.to_btc()); + } + + // Process the logic of inscription revelation + let reveal_input_start_index = ctx.reveal_tx.input.len(); + + for (index, ((_, control_block), reveal_script)) in ctx + .commit_tx_addresses + .iter() + .zip(ctx.control_blocks.iter()) + .zip(ctx.reveal_scripts.iter()) + .enumerate() + { + // Add the commit transaction output as an input to the reveal transaction + let commit_tx_outpoint = OutPoint { + txid: ctx.commit_tx.compute_txid(), + vout: index as u32, + }; + let reveal_input = TxIn { + previous_output: commit_tx_outpoint, + script_sig: ScriptBuf::new(), + sequence: Sequence::ENABLE_RBF_NO_LOCKTIME, + witness: Witness::new(), + }; + ctx.reveal_tx.input.push(reveal_input); + + // Add the inscription output to the reveal transaction + let reveal_output = TxOut { + script_pubkey: self.destination.script_pubkey(), + value: self.option.postage(), + }; + ctx.reveal_tx.output.push(reveal_output); + + // Save the reveal script and control block for signing later + ctx.reveal_scripts_to_sign.push(reveal_script.clone()); + ctx.control_blocks_to_sign.push(control_block.clone()); + } + + // Set the commit input index in the context + ctx.reveal_input_start_index = Some(reveal_input_start_index); + + Ok(()) + } + + async fn update_fees(&mut self, ctx: &mut InscribeContext) -> Result<()> { + let dust_threshold = self.destination.script_pubkey().minimal_non_dust().to_sat(); + + let actual_reveal_fee = + self.estimate_reveal_tx_fee(ctx, &ctx.reveal_scripts, &ctx.control_blocks); + let total_new_postage = + Amount::from_sat(self.option.postage().to_sat() * self.inscriptions.len() as u64); + + let reveal_additional_fee = actual_reveal_fee + total_new_postage; + + if reveal_additional_fee > Amount::ZERO { + let mut remaining_fee = reveal_additional_fee; + + for output in ctx.commit_tx.output.iter_mut() { + remaining_fee -= output.value; + } + + // If there's still remaining fee, add it to the last output + if remaining_fee > Amount::ZERO { + let last_output = ctx + .commit_tx + .output + .last_mut() + .expect("there should be at least one output"); + last_output.value += remaining_fee; + } + } + + // Check if recharge is required + let mut commit_fee: i64 = self.estimate_commit_tx_fee(ctx).to_sat() as i64; + let mut change_value = + Self::calculate_fee(&ctx.commit_tx, &ctx.utxos).to_sat() as i64 - commit_fee; + + if change_value < 0 { + let additional_inputs = self + .select_additional_inputs(ctx, Amount::from_sat((0 - change_value) as u64)) + .await?; + for input in additional_inputs { + ctx.commit_tx.input.push(input); + } + } + + // Check if change is needed + commit_fee = self.estimate_commit_tx_fee(ctx).to_sat() as i64; + change_value = Self::calculate_fee(&ctx.commit_tx, &ctx.utxos).to_sat() as i64 - commit_fee; + + if change_value > dust_threshold as i64 { + ctx.commit_tx.output.push(TxOut { + script_pubkey: self.change_address.script_pubkey(), + value: Amount::from_sat(change_value as u64), + }); + + // Recalculate the actual commit fee, considering the impact of the change output + let new_commit_fee = self.estimate_commit_tx_fee(ctx).to_sat() as i64; + + // Adjust the change amount to compensate for the fee change + let fee_difference = new_commit_fee - commit_fee; + change_value -= fee_difference; + + if change_value <= dust_threshold as i64 { + // If the adjusted change amount is less than or equal to the dust threshold, remove the change output + ctx.commit_tx.output.pop(); + } else { + // Update the amount of the change output + ctx.commit_tx.output.last_mut().unwrap().value = + Amount::from_sat(change_value as u64); + } + } + + // Update the reveal transaction inputs to reference the new commit transaction outputs + let new_commit_txid = ctx.commit_tx.compute_txid(); + for (index, input) in ctx.reveal_tx.input.iter_mut().enumerate() { + if index >= ctx.reveal_input_start_index.unwrap() { + input.previous_output.txid = new_commit_txid; + + ctx.utxos.insert( + input.previous_output, + ctx.commit_tx.output[input.previous_output.vout as usize].clone(), + ); + } + } + + // Check commit fee + self.assert_commit_transaction_balance( + ctx, + "commit transaction input, output, and fee do not match", + ); + self.assert_reveal_transaction_balance( + ctx, + "reveal transaction input, output, and fee do not match", + ); + + Ok(()) + } + + fn sign_commit_tx(&self, ctx: &mut InscribeContext) -> Result<()> { + let commit_input_utxos = ctx + .commit_tx + .input + .iter() + .map(|tx_in| { + ctx.utxos + .get(&tx_in.previous_output) + .cloned() + .ok_or_else(|| anyhow::anyhow!("utxo {} not found", tx_in.previous_output)) + }) + .collect::>>()?; + + debug!("Commit tx before sign: {:?}", ctx.commit_tx); + ctx.signed_commit_tx = Some(sign_tx(&self.context, &ctx.commit_tx, &commit_input_utxos)?); + debug!("Commit tx after sign: {:?}", ctx.signed_commit_tx); + Ok(()) + } + + fn sign_reveal_tx(&self, ctx: &mut InscribeContext) -> Result<()> { + let reveal_input_start_index = ctx.reveal_input_start_index.unwrap(); + + let prevouts: Vec<_> = ctx + .reveal_tx + .input + .iter() + .map(|tx_in| { + ctx.utxos + .get(&tx_in.previous_output) + .cloned() + .expect("prevout not found") + }) + .collect(); + + let mut signed_reveal_tx = ctx.reveal_tx.clone(); + + // sign the reveal inscription input + debug!("Reveal tx before sign: {:?}", signed_reveal_tx); + + let mut sighash_cache = SighashCache::new(&mut signed_reveal_tx); + for (index, ((reveal_script, control_block), keypair)) in ctx + .reveal_scripts_to_sign + .iter() + .zip(ctx.control_blocks_to_sign.iter()) + .zip(ctx.key_pairs.iter()) + .enumerate() + { + let sighash = sighash_cache + .taproot_script_spend_signature_hash( + reveal_input_start_index + index, + &Prevouts::All(&prevouts), + TapLeafHash::from_script(reveal_script, LeafVersion::TapScript), + TapSighashType::Default, + ) + .expect("failed to compute sighash"); + + let secp = Secp256k1::new(); + let sig = secp.sign_schnorr(&sighash.into(), keypair); + + let witness = sighash_cache + .witness_mut(reveal_input_start_index + index) + .expect("getting mutable witness reference should work"); + + witness.push( + Signature { + signature: sig, + sighash_type: TapSighashType::Default, + } + .to_vec(), + ); + + witness.push(reveal_script); + witness.push(&control_block.serialize()); + } + + debug!("Reveal tx after reveal part sign: {:?}", signed_reveal_tx); + + //sign the burn inscription input + let signed_reveal_tx = if reveal_input_start_index > 0 { + let signed_reveal_tx = sign_tx(&self.context, &signed_reveal_tx, &prevouts)?; + debug!( + "Reveal tx after burn part sign sign: {:?}", + signed_reveal_tx + ); + signed_reveal_tx + } else { + signed_reveal_tx + }; + + ctx.signed_reveal_tx = Some(signed_reveal_tx); + Ok(()) + } + + fn sign(&self, ctx: &mut InscribeContext) -> Result<()> { + // Sign the commit transaction + self.sign_commit_tx(ctx)?; + // Sign the reveal transaction + self.sign_reveal_tx(ctx)?; + Ok(()) + } + + fn backup_keys(&self, ctx: &mut InscribeContext) -> Result<()> { + if self.option.no_backup { + return Ok(()); + } + + let secp256k1 = Secp256k1::new(); + + for ((key_pair, commit_tx_address), taproot_spend_info) in ctx + .key_pairs + .iter() + .zip(ctx.commit_tx_addresses.iter()) + .zip(ctx.taproot_spend_infos.iter()) + { + let recovery_key_pair = + key_pair.tap_tweak(&secp256k1, taproot_spend_info.merkle_root()); + let (x_only_pub_key, _parity) = recovery_key_pair.to_inner().x_only_public_key(); + assert_eq!( + Address::p2tr_tweaked( + TweakedPublicKey::dangerous_assume_tweaked(x_only_pub_key), + self.network, + ), + commit_tx_address.clone(), + "commit_tx_address invalid" + ); + + Self::backup_recovery_key(&self.context, recovery_key_pair)?; + } + + Ok(()) + } + + async fn boardcaset_tx(&self, ctx: &mut InscribeContext) -> Result { + let total_fees = Self::calculate_fee(&ctx.commit_tx, &ctx.utxos) + + Self::calculate_fee(&ctx.reveal_tx, &ctx.utxos); + + let origin_reveal_txid = ctx.reveal_tx.compute_txid(); + let reveal_input_count = ctx.reveal_scripts_to_sign.len(); + let inscriptions: Vec<_> = (0..reveal_input_count) + .map(|index| InscriptionID::new(origin_reveal_txid, index as u32)) + .map(InscriptionOrId::Id) + .collect(); + + if self.option.dry_run { + let origin_commit_txid = ctx.commit_tx.compute_txid(); + + return Ok(InscribeOutput { + commit_tx: origin_commit_txid, + reveal_tx: origin_reveal_txid, + total_fees, + inscriptions, + }); + } + + let signed_commit_tx = ctx.signed_commit_tx.as_ref().expect("commit tx not signed"); + let signed_reveal_tx = ctx.signed_reveal_tx.as_ref().expect("reveal tx not signed"); + + let commit_txid = match self + .send_raw_transaction(signed_commit_tx, None, None) + .await + { + Ok(txid) => txid, + Err(err) => return Err(anyhow!("Failed to send commit transaction: {err}")), + }; + + let reveal_txid = match self.send_raw_transaction(signed_reveal_tx, None, ctx.total_burn_postage).await { + Ok(txid) => txid, + Err(err) => { + return Err(anyhow!( + "Failed to send reveal transaction: {err}\nCommit tx {commit_txid} will be recovered once mined" + )) + } + }; + + assert_eq!( + origin_reveal_txid, reveal_txid, + "reveal txid should be equal" + ); + + Ok(InscribeOutput { + commit_tx: commit_txid, + reveal_tx: reveal_txid, + total_fees, + inscriptions, + }) + } + + pub async fn inscribe(&mut self) -> Result { + let mut ctx = self.prepare_context()?; + + self.build_commit(&mut ctx)?; + self.build_reveal(&mut ctx).await?; + self.update_fees(&mut ctx).await?; + self.sign(&mut ctx)?; + self.backup_keys(&mut ctx)?; + let output = self.boardcaset_tx(&mut ctx).await?; + Ok(output) + } + + pub async fn send_raw_transaction( + &self, + tx: &Transaction, + maxfeerate: Option, + maxburnamount: Option, + ) -> Result { + let client = self.context.get_client().await?; + let txid = client + .rooch + .broadcast_bitcoin_tx(tx, maxfeerate, maxburnamount) + .await?; + Ok(Txid::from_str(&txid)?) + } + + pub async fn get_operation_by_inscription_id( + &self, + inscription_id: InscriptionID, + ) -> Result { + let ins_obj = self.get_inscription_object(inscription_id).await?; + Operation::from_inscription(ins_obj.value.into()) + } + + async fn get_inscription_satpoint(&self, inscription_id: InscriptionID) -> Result { + let ins_obj = self.get_inscription_object(inscription_id).await?; + Ok(ins_obj.location()) + } + + async fn get_inscription_object( + &self, + inscription_id: InscriptionID, + ) -> Result { + let obj_id = inscription_id.object_id(); + let client = self.context.get_client().await?; + let ins_obj = client + .rooch + .get_inscription_object(obj_id) + .await? + .ok_or_else(|| anyhow::anyhow!("Inscription {} not found", inscription_id))?; + Ok(ins_obj) + } + + async fn load_generator(&self, generator: &str) -> Result> { + // generator: "/inscription/inscriptioin_id" + let path = generator.split('/').collect::>(); + if path.len() != 3 { + bail!("Invalid generator path: {:?}", generator); + } + let inscription_id = InscriptionID::from_str(path[2])?; + let operation = self.get_operation_by_inscription_id(inscription_id).await?; + let mint_record = operation + .as_mint() + .ok_or_else(|| anyhow!("Operation is not mint: {:?}", operation))?; + if mint_record.sft.tick != GENERATOR_TICK { + bail!("Invalid generator tick: {:?}", mint_record.sft.tick); + } + let content = mint_record + .sft + .content + .as_ref() + .ok_or_else(|| anyhow!("No content in generator mint record: {:?}", mint_record))?; + ensure!( + content.content_type == CONTENT_TYPE, + "Invalid generator content type: {:?}", + content.content_type + ); + let wasm_bytecode = &content.body; + Ok(Box::new(WASMGenerator::new(wasm_bytecode.clone()))) + } +} + +//TODO migrate this function and `bitcoin::sign_psbt` to KeyStore in the future +pub fn sign_tx( + context: &WalletContext, + unsigned_tx: &Transaction, + input_utxos: &[TxOut], +) -> Result { + let secp = Secp256k1::new(); + let mut signed_inputs: Vec<(usize, TxIn)> = Vec::with_capacity(unsigned_tx.input.len()); + let mut sighash_cache = SighashCache::new(unsigned_tx); + + for (input_index, (input, utxo)) in unsigned_tx.input.iter().zip(input_utxos.iter()).enumerate() + { + if !input.witness.is_empty() || !input.script_sig.is_empty() { + debug!("Skipping input {} as it is already signed", input_index); + continue; + } + + let script_pubkey = &utxo.script_pubkey; + let bitcoin_address = BitcoinAddress::from(script_pubkey); + + let rooch_address = bitcoin_address.to_rooch_address(); + + let keypair = context.get_key_pair(&rooch_address)?; + + let message: Message = if script_pubkey.is_p2pkh() { + sighash_cache + .legacy_signature_hash(input_index, script_pubkey, EcdsaSighashType::All.to_u32())? + .into() + } else if script_pubkey.is_p2wpkh() { + sighash_cache + .p2wpkh_signature_hash( + input_index, + script_pubkey, + utxo.value, + EcdsaSighashType::All, + )? + .into() + } else if script_pubkey.is_p2wsh() { + sighash_cache + .p2wsh_signature_hash( + input_index, + script_pubkey, + utxo.value, + EcdsaSighashType::All, + )? + .into() + } else if script_pubkey.is_p2tr() { + sighash_cache + .taproot_key_spend_signature_hash( + input_index, + &bitcoin::sighash::Prevouts::All(input_utxos), + TapSighashType::Default, + )? + .into() + } else { + return Err(anyhow::anyhow!( + "Unsupported script type for input {}", + input_index + )); + }; + + let kp = keypair.secp256k1_keypair().ok_or_else(|| { + anyhow::anyhow!("Failed to get private key for account {}", rooch_address) + })?; + + let mut signed_input = input.clone(); + + if script_pubkey.is_p2tr() { + //The taproot key spend needs to be signed with the tweaked key + let kp = Keypair::from_secret_key(&secp, &kp.secret_key()) + .tap_tweak(&secp, None) + .to_inner(); + let signature = secp.sign_schnorr(&message, &kp); + signed_input.witness = bitcoin::Witness::from_slice(&[signature.as_ref()]); + } else { + let signature = secp.sign_ecdsa(&message, &kp.secret_key()); + let mut sig_with_hashtype = signature.serialize_der().to_vec(); + sig_with_hashtype.push(EcdsaSighashType::All as u8); + + if script_pubkey.is_p2wpkh() { + let pubkey = kp.public_key(); + signed_input.witness = bitcoin::Witness::from_slice(&[ + &sig_with_hashtype, + &pubkey.serialize().to_vec(), + ]); + } else { + let pubkey = kp.public_key(); + let buf = PushBytesBuf::try_from(sig_with_hashtype)?; + signed_input.script_sig = bitcoin::Script::builder() + .push_slice(&buf) + .push_slice(pubkey.serialize()) + .into_script(); + } + } + signed_inputs.push((input_index, signed_input)); + } + + let mut signed_tx = unsigned_tx.clone(); + for (index, signed_input) in signed_inputs { + signed_tx.input[index] = signed_input; + } + + Ok(signed_tx) +} + +// #[cfg(test)] +// mod tests{ +// use super::*; + +// fn check_inscription_parse(tx: Transaction){ + +// } + +// #[test] +// fn test_generator(){ +// let wallet_context = +// let output = Inscriber::new(context, self.inscribe_options) +// .await? +// .with_generator(self.name, self.generator) +// .await? +// } +// } diff --git a/crates/rooch/src/commands/bitseed/inscription.rs b/crates/rooch/src/commands/bitseed/inscription.rs new file mode 100644 index 0000000000..311cb74acf --- /dev/null +++ b/crates/rooch/src/commands/bitseed/inscription.rs @@ -0,0 +1,212 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use super::{ + sft::Content, METADATA_AMOUNT, METADATA_ATTRIBUTES, METADATA_OP, METADATA_TICK, PROTOCOL, +}; +use anyhow::{anyhow, bail, ensure, Result}; +use ciborium::{value::Integer, Value}; +use rooch_types::bitcoin::ord::{Inscription, InscriptionID, InscriptionRecord}; + +pub struct InscriptionBuilder { + inscription_record: InscriptionRecord, + metadata: MetadataBuilder, +} + +impl Default for InscriptionBuilder { + fn default() -> Self { + Self::new() + } +} + +impl InscriptionBuilder { + pub fn new() -> Self { + let mut inscription_record = InscriptionRecord::default(); + inscription_record.set_metaprotocol(PROTOCOL.to_string()); + Self { + inscription_record, + metadata: MetadataBuilder::new(), + } + } + + pub fn op(mut self, op: String) -> Self { + self.metadata = self.metadata.add_string(METADATA_OP, op); + self + } + + pub fn tick(mut self, tick: S) -> Self { + self.metadata = self.metadata.add_string(METADATA_TICK, tick.to_string()); + self + } + + pub fn amount(mut self, amount: u64) -> Self { + self.metadata = self.metadata.add_u64(METADATA_AMOUNT, amount); + self + } + + pub fn attributes(mut self, attributes: Value) -> Self { + assert!(attributes.is_map()); + self.metadata = self.metadata.add(METADATA_ATTRIBUTES, attributes); + self + } + + pub fn content(mut self, content: Content) -> Self { + self.inscription_record + .set_content_type(content.content_type); + self.inscription_record.body = content.body; + self + } + + pub fn finish(mut self) -> InscriptionRecord { + self.inscription_record.metadata = self.metadata.finish_to_bytes(); + self.inscription_record + } +} + +pub struct MetadataBuilder { + metadata: Value, +} + +impl Default for MetadataBuilder { + fn default() -> Self { + Self::new() + } +} + +impl MetadataBuilder { + pub fn new() -> Self { + Self { + metadata: Value::Map(vec![]), + } + } + + pub fn add(mut self, key: S, value: Value) -> Self { + if let Value::Map(map) = &mut self.metadata { + map.push((Value::Text(key.to_string()), value)); + } + self + } + + pub fn add_string(self, key: S, value: String) -> Self { + self.add(key, Value::Text(value)) + } + + pub fn add_u64(self, key: S, value: u64) -> Self { + self.add(key, Value::Integer(Integer::from(value))) + } + + pub fn add_f64(self, key: S, value: f64) -> Self { + self.add(key, Value::Float(value)) + } + + pub fn add_bool(self, key: S, value: bool) -> Self { + self.add(key, Value::Bool(value)) + } + + pub fn finish(self) -> Value { + self.metadata + } + + pub fn finish_to_bytes(self) -> Vec { + let value = self.finish(); + let mut writer = vec![]; + ciborium::into_writer(&value, &mut writer).unwrap(); + writer + } +} + +pub struct BitseedInscription { + inscription: Inscription, + metadata: Value, +} + +impl BitseedInscription { + pub fn new(inscription: Inscription) -> Result { + let metaprotocol = inscription + .metaprotocol() + .ok_or_else(|| anyhow!("metaprotocol not found"))?; + ensure!(metaprotocol == PROTOCOL, "metaprotocol is not bitseed"); + let metadata = inscription.metadata(); + let metadata = if metadata.is_empty() { + bail!("Inscription {} metadata is empty", inscription.id()); + } else { + ciborium::from_reader(metadata)? + }; + Ok(Self { + inscription, + metadata, + }) + } + + pub fn id(&self) -> InscriptionID { + self.inscription.id + } + + pub fn get_metadata(&self) -> &Value { + &self.metadata + } + + pub fn get_metadata_value(&self, key: &str) -> Result { + self.get_metadata_value_opt(key) + .ok_or_else(|| anyhow!("key ({:?}) not found in metadata", key)) + } + + pub fn get_metadata_value_opt(&self, key: &str) -> Option { + let metadata = self.get_metadata(); + let kvs = metadata.as_map()?; + kvs.iter() + .find(|(k, _)| k.is_text() && k.as_text().unwrap() == key) + .map(|(_, v)| v.clone()) + } + + pub fn get_metadata_string(&self, key: &str) -> Result { + self.get_metadata_value(key)? + .as_text() + .map(|v| v.to_string()) + .ok_or_else(|| anyhow!("{} is not a string", key)) + } + + pub fn get_metadata_u64(&self, key: &str) -> Result { + let i = self + .get_metadata_value(key)? + .as_integer() + .ok_or_else(|| anyhow!("{} is not an integer", key))?; + u64::try_from(i).map_err(|_| anyhow!("{} is not a u64", key)) + } + + pub fn op(&self) -> Result { + self.get_metadata_string(METADATA_OP) + } + + pub fn tick(&self) -> Result { + self.get_metadata_string(METADATA_TICK) + } + + pub fn amount(&self) -> Result { + let amount = self + .get_metadata_value(METADATA_AMOUNT)? + .as_integer() + .ok_or_else(|| anyhow!("amount is not an integer"))?; + u64::try_from(amount).map_err(|_| anyhow!("amount is not a u64")) + } + + pub fn attributes(&self) -> Option { + self.get_metadata_value_opt(METADATA_ATTRIBUTES) + } + + pub fn get_attribute(&self, key: &str) -> Option { + self.attributes().and_then(|attributes| { + attributes.as_map().and_then(|map| { + map.iter() + .find(|(k, _)| k.is_text() && k.as_text().unwrap() == key) + .map(|(_, v)| v.clone()) + }) + }) + } + + pub fn content(&self) -> Option { + let content_type = self.inscription.content_type(); + let body = self.inscription.body(); + content_type.map(|content_type| Content::new(content_type.to_owned(), body.to_vec())) + } +} diff --git a/crates/rooch/src/commands/bitseed/mod.rs b/crates/rooch/src/commands/bitseed/mod.rs new file mode 100644 index 0000000000..580146d7b0 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/mod.rs @@ -0,0 +1,52 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::cli_types::CommandAction; +use async_trait::async_trait; +use rooch_types::error::RoochResult; + +pub mod commands; +pub mod generator; +pub mod inscribe; +pub mod inscription; +pub mod operation; +pub mod sft; + +pub const PROTOCOL: &str = "bitseed"; +pub const METADATA_OP: &str = "op"; +pub const METADATA_TICK: &str = "tick"; +pub const METADATA_AMOUNT: &str = "amount"; +pub const METADATA_ATTRIBUTES: &str = "attributes"; +pub const GENERATOR_TICK: &str = "generator"; + +/// Tool for interacting with bitseed protocol +#[derive(clap::Parser)] +pub struct Bitseed { + #[clap(subcommand)] + cmd: BitseedCommand, +} + +#[async_trait] +impl CommandAction for Bitseed { + async fn execute(self) -> RoochResult { + match self.cmd { + BitseedCommand::Generator(generator) => generator.execute_serialized().await, + BitseedCommand::Deploy(deploy) => deploy.execute_serialized().await, + BitseedCommand::Mint(mint) => mint.execute_serialized().await, + BitseedCommand::Split(split) => split.execute_serialized().await, + BitseedCommand::Merge(merge) => merge.execute_serialized().await, + BitseedCommand::View(view) => view.execute_serialized().await, + } + } +} + +#[derive(Debug, clap::Subcommand)] +#[clap(name = "bitseed")] +pub enum BitseedCommand { + Generator(commands::generator::GeneratorCommand), + Deploy(commands::deploy::DeployCommand), + Mint(commands::mint::MintCommand), + Split(commands::split::SplitCommand), + Merge(commands::merge::MergeCommand), + View(commands::view::ViewCommand), +} diff --git a/crates/rooch/src/commands/bitseed/operation.rs b/crates/rooch/src/commands/bitseed/operation.rs new file mode 100644 index 0000000000..a63c4a770a --- /dev/null +++ b/crates/rooch/src/commands/bitseed/operation.rs @@ -0,0 +1,311 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use super::{ + inscription::{BitseedInscription, InscriptionBuilder}, + sft::SFT, +}; +use anyhow::{anyhow, bail, Result}; +use ciborium::Value; +use log::debug; +use rooch_types::bitcoin::ord::{Inscription, InscriptionRecord}; +use serde::{Deserialize, Serialize}; +use serde_json; +use serde_json::Value as JSONValue; +use std::io::Cursor; + +pub trait AsSFT { + fn as_sft(&self) -> SFT; +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct DeployRecord { + pub tick: String, + // The total supply of the Inscription + pub amount: u64, + pub generator: Option, + pub factory: Option, + pub repeat: u64, + pub deploy_args: Vec, +} + +impl DeployRecord { + pub fn new_deploy_record( + tick: String, + amount: u64, + generator: Option, + factory: Option, + repeat: u64, + deploy_args: Vec, + ) -> Self { + Self { + tick, + amount, + generator, + factory, + repeat, + deploy_args, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct MintRecord { + pub sft: SFT, +} + +impl AsSFT for MintRecord { + fn as_sft(&self) -> SFT { + self.sft.clone() + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SplitRecord { + pub sft: SFT, +} + +impl AsSFT for SplitRecord { + fn as_sft(&self) -> SFT { + self.sft.clone() + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct MergeRecord { + pub sft: SFT, +} + +impl AsSFT for MergeRecord { + fn as_sft(&self) -> SFT { + self.sft.clone() + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum Operation { + Deploy(DeployRecord), + Mint(MintRecord), + Split(SplitRecord), + Merge(MergeRecord), +} + +impl Operation { + pub fn to_inscription(self) -> InscriptionRecord { + let op = self.op(); + match self { + Operation::Deploy(record) => { + let cursor = Cursor::new(record.deploy_args); + let cbor_value: Value = ciborium::from_reader(cursor).unwrap(); + + let mut att_values = vec![]; + if let Some(generator) = record.generator { + att_values.push((Value::Text("generator".to_string()), Value::Text(generator))); + } + + if let Some(factory) = record.factory { + att_values.push((Value::Text("factory".to_string()), Value::Text(factory))); + } + + att_values.push(( + Value::Text("repeat".to_string()), + Value::Integer(record.repeat.into()), + )); + debug!("inscribe deploy_args {:?} to inscription", cbor_value); + att_values.push((Value::Text("deploy_args".to_string()), cbor_value)); + + let attributes = ciborium::Value::Map(att_values); + InscriptionBuilder::new() + .op(op.clone()) + .tick(record.tick.clone()) + .amount(record.amount) + .attributes(attributes) + .finish() + } + Operation::Mint(record) => { + let mut builder = InscriptionBuilder::new() + .op(op.clone()) + .tick(record.sft.tick.clone()) + .amount(record.sft.amount); + if let Some(attributes) = record.sft.attributes { + builder = builder.attributes(attributes); + } + if let Some(content) = record.sft.content { + builder = builder.content(content) + } + builder.finish() + } + Operation::Split(record) => { + let mut builder = InscriptionBuilder::new() + .op(op.clone()) + .tick(record.sft.tick.clone()) + .amount(record.sft.amount); + if let Some(attributes) = record.sft.attributes { + builder = builder.attributes(attributes); + } + if let Some(content) = record.sft.content { + builder = builder.content(content) + } + builder.finish() + } + Operation::Merge(record) => { + let mut builder = InscriptionBuilder::new() + .op(op.clone()) + .tick(record.sft.tick.clone()) + .amount(record.sft.amount); + if let Some(attributes) = record.sft.attributes { + builder = builder.attributes(attributes); + } + if let Some(content) = record.sft.content { + builder = builder.content(content) + } + builder.finish() + } + } + } + + pub fn from_inscription(inscription: Inscription) -> Result { + let bitseed_inscription = BitseedInscription::new(inscription)?; + let op = bitseed_inscription.op()?; + let tick = bitseed_inscription.tick()?; + let amount = bitseed_inscription.amount()?; + let content = bitseed_inscription.content(); + + match op.as_ref() { + "deploy" => { + let generator = bitseed_inscription + .get_attribute("generator") + .and_then(|v| v.as_text().map(|txt| txt.to_owned())); + let factory = bitseed_inscription + .get_attribute("factory") + .and_then(|v| v.as_text().map(|txt| txt.to_owned())); + match (&generator, &factory) { + (Some(_), Some(_)) => bail!("generator and factory are mutually exclusive"), + (None, None) => bail!("missing generator or factory"), + _ => {} + } + let repeat = bitseed_inscription + .get_attribute("repeat") + .ok_or_else(|| anyhow!("missing repeat"))? + .as_integer() + .ok_or_else(|| anyhow!("repeat is not an integer"))? + .try_into()?; + let deploy_args_value = bitseed_inscription + .get_attribute("deploy_args") + .ok_or_else(|| anyhow!("missing deploy_args"))?; + + debug!( + "load deploy_args {:?} from inscription: {:?}", + deploy_args_value, + bitseed_inscription.id() + ); + + let mut deploy_args = Vec::new(); + ciborium::into_writer(&deploy_args_value, &mut deploy_args) + .expect("ciborium marshal failed"); + + Ok(Operation::Deploy(DeployRecord::new_deploy_record( + tick, + amount, + generator, + factory, + repeat, + deploy_args, + ))) + } + "mint" | "split" | "merge" => { + let attributes = bitseed_inscription.attributes(); + let sft = SFT { + tick, + amount, + attributes, + content, + }; + + let op = match op.as_ref() { + "mint" => Operation::Mint(MintRecord { sft }), + "split" => Operation::Split(SplitRecord { sft }), + "merge" => Operation::Merge(MergeRecord { sft }), + _ => unreachable!(), // We already know it's one of the three. + }; + + Ok(op) + } + _ => { + bail!("unknown op: {}", op) + } + } + } + + pub fn is_deploy(&self) -> bool { + matches!(self, Operation::Deploy(_)) + } + + pub fn as_deploy(&self) -> Option<&DeployRecord> { + match self { + Operation::Deploy(record) => Some(record), + _ => None, + } + } + + pub fn is_mint(&self) -> bool { + matches!(self, Operation::Mint(_)) + } + + pub fn as_mint(&self) -> Option<&MintRecord> { + match self { + Operation::Mint(record) => Some(record), + _ => None, + } + } + + pub fn is_split(&self) -> bool { + matches!(self, Operation::Split(_)) + } + + pub fn as_split(&self) -> Option<&SplitRecord> { + match self { + Operation::Split(record) => Some(record), + _ => None, + } + } + + pub fn is_merge(&self) -> bool { + matches!(self, Operation::Merge(_)) + } + + pub fn as_merge(&self) -> Option<&MergeRecord> { + match self { + Operation::Merge(record) => Some(record), + _ => None, + } + } + + pub fn op(&self) -> String { + match self { + Operation::Deploy(_) => "deploy".to_string(), + Operation::Mint(_) => "mint".to_string(), + Operation::Split(_) => "split".to_string(), + Operation::Merge(_) => "merge".to_string(), + } + } +} + +pub fn deploy_args_cbor_encode(deploy_args: Vec) -> Result> { + let mut mint_args_json: Vec = vec![]; + + for arg in deploy_args.iter() { + debug!("deploy arg: {}", arg); + let arg_json: JSONValue = serde_json::from_str(arg.as_str()) + .map_err(|e| anyhow!("failed to parse deploy arg: {}, arg: {}", e, arg))?; + if !arg_json.is_object() { + bail!("deploy arg must be a json object, got: {}", arg); + } + mint_args_json.push(arg_json); + } + + let mint_args_array = JSONValue::Array(mint_args_json); + let mut cbor_buffer = Vec::new(); + ciborium::into_writer(&mint_args_array, &mut cbor_buffer).expect("ciborium marshal failed"); + Ok(cbor_buffer) +} diff --git a/crates/rooch/src/commands/bitseed/sft.rs b/crates/rooch/src/commands/bitseed/sft.rs new file mode 100644 index 0000000000..ed3ccb5b17 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/sft.rs @@ -0,0 +1,93 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::commands::bitseed::operation::{MintRecord, SplitRecord}; +use anyhow::{ensure, Result}; +use ciborium::Value; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Content { + pub content_type: String, + pub body: Vec, +} + +impl Content { + pub fn new(content_type: String, body: Vec) -> Self { + Self { content_type, body } + } + + pub fn text(body: String) -> Self { + Self::new("text/plain".to_string(), body.as_bytes().to_vec()) + } + + pub fn is_text(&self) -> bool { + self.content_type == "text/plain" + } + + pub fn as_text(&self) -> Result { + ensure!(self.is_text(), "Content is not text"); + Ok(String::from_utf8(self.body.clone())?) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SFT { + pub tick: String, + pub amount: u64, + pub attributes: Option, + pub content: Option, +} + +impl SFT { + pub fn new( + tick: String, + amount: u64, + attributes: Option, + content: Option, + ) -> Self { + Self { + tick, + amount, + attributes, + content, + } + } + + pub fn split(&mut self, amount: u64) -> Result { + if amount > self.amount { + return Err(anyhow::anyhow!( + "Split amount is greater than the SFT amount" + )); + } + self.amount -= amount; + Ok(SFT::new( + self.tick.clone(), + amount, + self.attributes.clone(), + self.content.clone(), + )) + } + + pub fn merge(&mut self, sft: SFT) -> Result<()> { + if self.tick != sft.tick { + return Err(anyhow::anyhow!("SFTs have different ticks")); + } + if self.attributes != sft.attributes { + return Err(anyhow::anyhow!("SFTs have different attributes")); + } + if self.content != sft.content { + return Err(anyhow::anyhow!("SFTs have different content")); + } + self.amount += sft.amount; + Ok(()) + } + + pub fn to_mint_record(&self) -> MintRecord { + MintRecord { sft: self.clone() } + } + + pub fn to_split_record(&self) -> SplitRecord { + SplitRecord { sft: self.clone() } + } +} diff --git a/crates/rooch/src/commands/bitseed/split.rs b/crates/rooch/src/commands/bitseed/split.rs new file mode 100644 index 0000000000..6f0044c25e --- /dev/null +++ b/crates/rooch/src/commands/bitseed/split.rs @@ -0,0 +1,28 @@ +// Copyright (c) RoochNetwork +// SPDX-License-Identifier: Apache-2.0 + +use crate::commands::bitseed::inscribe::InscribeOptions; +use crate::commands::bitseed::inscribe::Inscriber; +use clap::Parser; +use rooch_types::bitcoin::ord::InscriptionID; + +#[derive(Debug, Parser)] +pub struct SplitCommand { + #[arg(long, help = "The split SFT inscription ID.")] + sft_inscription_id: InscriptionID, + + #[arg(long, help = "The split amounts.", num_args = 1..)] + amounts: Vec, + + #[clap(flatten)] + inscribe_options: InscribeOptions, +} + +// impl SplitCommand { +// pub fn run(self, wallet: Wallet) -> SubcommandResult { +// let output = Inscriber::new(wallet, self.inscribe_options)? +// .with_split(self.sft_inscription_id, self.amounts)? +// .inscribe()?; +// Ok(Box::new(output)) +// } +// } diff --git a/crates/rooch/src/commands/mod.rs b/crates/rooch/src/commands/mod.rs index dde19c7665..6bda2e9651 100644 --- a/crates/rooch/src/commands/mod.rs +++ b/crates/rooch/src/commands/mod.rs @@ -4,6 +4,7 @@ pub mod abi; pub mod account; pub mod bitcoin; +pub mod bitseed; pub mod db; pub mod dynamic_field; pub mod env; diff --git a/crates/rooch/src/lib.rs b/crates/rooch/src/lib.rs index 6f62b26c4e..5f8694c287 100644 --- a/crates/rooch/src/lib.rs +++ b/crates/rooch/src/lib.rs @@ -11,8 +11,8 @@ use clap::builder::{ }; use cli_types::CommandAction; use commands::{ - abi::ABI, account::Account, bitcoin::Bitcoin, dynamic_field::DynamicField, env::Env, - genesis::Genesis, init::Init, move_cli::MoveCli, object::ObjectCommand, + abi::ABI, account::Account, bitcoin::Bitcoin, bitseed::Bitseed, dynamic_field::DynamicField, + env::Env, genesis::Genesis, init::Init, move_cli::MoveCli, object::ObjectCommand, resource::ResourceCommand, rpc::Rpc, server::Server, session_key::SessionKey, state::StateCommand, transaction::Transaction, upgrade::Upgrade, util::Util, version::Version, }; @@ -47,6 +47,7 @@ pub enum Command { Version(Version), Account(Account), Bitcoin(Bitcoin), + Bitseed(Bitseed), Init(Init), Move(MoveCli), Server(Server), @@ -74,6 +75,7 @@ pub async fn run_cli(opt: RoochCli) -> RoochResult { Command::Version(version) => version.execute().await, Command::Account(account) => account.execute().await, Command::Bitcoin(bitcoin) => bitcoin.execute().await, + Command::Bitseed(bitseed) => bitseed.execute().await, Command::Move(move_cli) => move_cli.execute().await, Command::Server(server) => server.execute().await, Command::Init(init) => init.execute_serialized().await, diff --git a/crates/testsuite/Cargo.toml b/crates/testsuite/Cargo.toml index 72cba7ed82..0f41cfe351 100644 --- a/crates/testsuite/Cargo.toml +++ b/crates/testsuite/Cargo.toml @@ -15,7 +15,8 @@ rust-version = { workspace = true } anyhow = { workspace = true } clap = { features = ["derive"], workspace = true } jpst = { workspace = true } -serde_json = { features = ["arbitrary_precision"], workspace = true } +#do not enable the arbitrary_precision feature +serde_json = { workspace = true } tokio = { workspace = true } tracing = { workspace = true } diff --git a/crates/testsuite/features/bitseed.feature b/crates/testsuite/features/bitseed.feature index a1a2c608b6..8e49269f9d 100644 --- a/crates/testsuite/features/bitseed.feature +++ b/crates/testsuite/features/bitseed.feature @@ -7,34 +7,25 @@ Feature: Rooch CLI bitseed tests # prepare servers Given a bitcoind server for rooch_bitseed_test - Given a ord server for rooch_bitseed_test Given a server for rooch_bitseed_test # create rooch account - Then cmd: "account create" Then cmd: "account list --json" - # init wallet - Then cmd ord: "wallet create" - Then cmd ord: "wallet receive" - # mint utxos - Then cmd bitcoin-cli: "generatetoaddress 101 {{$.wallet[-1].addresses[0]}}" - Then sleep: "10" # wait ord sync and index - Then cmd ord: "wallet balance" - Then assert: "{{$.wallet[-1].total}} == 5000000000" + Then cmd bitcoin-cli: "generatetoaddress 101 {{$.account[-1].default.bitcoin_address}}" + Then sleep: "10" # wait rooch to sync # publish bitseed runner Then cmd: "move publish -p ../../examples/bitseed_runner --named-addresses rooch_examples=default --json" Then assert: "{{$.move[-1].execution_info.status.type}} == executed" # generator - Then cmd bitseed: "generator --fee-rate 1 --name random --generator /app/test-data/generator.wasm" - Then assert: "'{{$.generator[-1]}}' not_contains error" + Then cmd: "bitseed generator --fee-rate 5000 --name random --generator ../../generator/cpp/generator.wasm" + Then assert: "'{{$.bitseed[-1]}}' not_contains error" # mine a block - Then cmd ord: "wallet receive" - Then cmd bitcoin-cli: "generatetoaddress 1 {{$.wallet[-1].addresses[0]}}" + Then cmd bitcoin-cli: "generatetoaddress 1 {{$.account[-1].default.bitcoin_address}}" Then sleep: "10" # Sync bitseed @@ -42,17 +33,16 @@ Feature: Rooch CLI bitseed tests Then assert: "{{$.move[-1].execution_info.status.type}} == executed" # Check mint generator validity - Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.generator[-1].inscriptions[0].Id}} " + Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.bitseed[-1].inscriptions[0].Id}} " Then assert: "{{$.move[-1].vm_status}} == Executed" Then assert: "{{$.move[-1].return_values[0].decoded_value.value.vec[0].value.is_valid}} == true" # deploy - Then cmd bitseed: "deploy --fee-rate 1 --generator {{$.generator[-1].inscriptions[0].Id}} --tick bits --amount 210000000000 --deploy-args {"height":{"type":"range","data":{"min":1,"max":1000}}}" - Then assert: "'{{$.deploy[-1]}}' not_contains error" + Then cmd: "bitseed deploy --fee-rate 6000 --generator {{$.bitseed[-1].inscriptions[0].Id}} --tick bits --amount 210000000000 --deploy-args '{"height":{"type":"range","data":{"min":1,"max":1000}}}'" + Then assert: "'{{$.bitseed[-1]}}' not_contains error" # mine a block - Then cmd ord: "wallet receive" - Then cmd bitcoin-cli: "generatetoaddress 1 {{$.wallet[-1].addresses[0]}}" + Then cmd bitcoin-cli: "generatetoaddress 1 {{$.account[-1].default.bitcoin_address}}" Then sleep: "10" # Sync bitseed @@ -60,17 +50,16 @@ Feature: Rooch CLI bitseed tests Then assert: "{{$.move[-1].execution_info.status.type}} == executed" # Check deploy validity - Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.deploy[-1].inscriptions[0].Id}} " + Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.bitseed[-1].inscriptions[0].Id}} " Then assert: "{{$.move[-1].vm_status}} == Executed" Then assert: "{{$.move[-1].return_values[0].decoded_value.value.vec[0].value.is_valid}} == true" # mint - Then cmd bitseed: "mint --fee-rate 1 --deploy-inscription-id {{$.deploy[-1].inscriptions[0].Id}} --user-input hello_bitseed" - Then assert: "'{{$.mint[-1]}}' not_contains error" + Then cmd: "bitseed mint --fee-rate 6000 --deploy-inscription-id {{$.bitseed[-1].inscriptions[0].Id}} --user-input test" + Then assert: "'{{$.bitseed[-1]}}' not_contains error" # mine a block - Then cmd ord: "wallet receive" - Then cmd bitcoin-cli: "generatetoaddress 1 {{$.wallet[-1].addresses[0]}}" + Then cmd bitcoin-cli: "generatetoaddress 1 {{$.account[-1].default.bitcoin_address}}" Then sleep: "10" # Sync bitseed @@ -78,13 +67,12 @@ Feature: Rooch CLI bitseed tests Then assert: "{{$.move[-1].execution_info.status.type}} == executed" # Check mint bits validity - Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.mint[-1].inscriptions[0].Id}} " + Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.bitseed[-1].inscriptions[0].Id}} " Then assert: "{{$.move[-1].vm_status}} == Executed" Then assert: "{{$.move[-1].return_values[0].decoded_value.value.vec[0].value.is_valid}} == true" # release servers Then stop the server - Then stop the ord server Then stop the bitcoind server @serial @@ -94,20 +82,13 @@ Feature: Rooch CLI bitseed tests # prepare servers Given a bitcoind server for bitseed_on_rooch - Given a ord server for bitseed_on_rooch Given a server for bitseed_on_rooch Then cmd: "account list --json" - # init wallet - Then cmd ord: "wallet create" - Then cmd ord: "wallet receive" - # mint utxos - Then cmd bitcoin-cli: "generatetoaddress 101 {{$.wallet[-1].addresses[0]}}" + Then cmd bitcoin-cli: "generatetoaddress 101 {{$.account[-1].default.bitcoin_address}}" Then sleep: "10" # wait ord sync and index - Then cmd ord: "wallet balance" - Then assert: "{{$.wallet[-1].total}} == 5000000000" # publish bitseed runner Then cmd: "move publish -p ../../examples/bitseed_runner --named-addresses rooch_examples=default --json" @@ -118,12 +99,11 @@ Feature: Rooch CLI bitseed tests Then assert: "{{$.move[-1].execution_info.status.type}} == executed" # deploy - Then cmd bitseed: "deploy --fee-rate 1 --factory 0x000000000000000000000000000000000000000000000000000000000000000a::mint_get_factory::MintGetFactory --tick test --amount 210000000000" - Then assert: "'{{$.deploy[-1]}}' not_contains error" + Then cmd: "bitseed deploy --fee-rate 5000 --factory 0x000000000000000000000000000000000000000000000000000000000000000a::mint_get_factory::MintGetFactory --tick test --amount 210000000000" + Then assert: "'{{$.bitseed[-1]}}' not_contains error" # mine a block - Then cmd ord: "wallet receive" - Then cmd bitcoin-cli: "generatetoaddress 1 {{$.wallet[-1].addresses[0]}}" + Then cmd bitcoin-cli: "generatetoaddress 1 {{$.account[-1].default.bitcoin_address}}" Then sleep: "10" # Sync bitseed @@ -131,7 +111,7 @@ Feature: Rooch CLI bitseed tests Then assert: "{{$.move[-1].execution_info.status.type}} == executed" # Check deploy validity - Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.deploy[-1].inscriptions[0].Id}} " + Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.bitseed[-1].inscriptions[0].Id}} " Then assert: "{{$.move[-1].vm_status}} == Executed" Then assert: "{{$.move[-1].return_values[0].decoded_value.value.vec[0].value.is_valid}} == true" @@ -142,3 +122,7 @@ Feature: Rooch CLI bitseed tests Then cmd: "object -t 0xa::bitseed::Bitseed -o {{$.account[-1].default.address}}" Then assert: "{{$.object[-1].data[0].owner}} == {{$.account[-1].default.address}}" + # release servers + Then stop the server + Then stop the bitcoind server + diff --git a/crates/testsuite/features/multisign.feature b/crates/testsuite/features/multisign.feature index 12910e6e15..adfe73cff7 100644 --- a/crates/testsuite/features/multisign.feature +++ b/crates/testsuite/features/multisign.feature @@ -15,27 +15,10 @@ Feature: Rooch CLI multisign integration tests Then cmd: "account create-multisign -t 2 -p {{$.account[-1].account0.public_key}} -p {{$.account[-1].account1.public_key}} -p {{$.account[-1].account2.public_key}} --json" Then assert: "'{{$.account[-1]}}' not_contains error" - # Create and load a wallet - Then cmd bitcoin-cli: "createwallet \"test_wallet\"" - Then cmd bitcoin-cli: "loadwallet \"test_wallet\"" - # Prepare funds - Then cmd bitcoin-cli: "getnewaddress" - # mint btc - Then cmd bitcoin-cli: "generatetoaddress 101 {{$.getnewaddress[-1]}}" - - # Get UTXO for transaction input - Then cmd bitcoin-cli: "listunspent 1 9999999 [\"{{$.getnewaddress[-1]}}\"] true" - - # Create a Bitcoin transaction transfer to multisign account - Then cmd bitcoin-cli: "createrawtransaction [{\"txid\":\"{{$.listunspent[-1][0].txid}}\",\"vout\":{{$.listunspent[-1][0].vout}}}] {\"{{$.account[-1].multisign_bitcoin_address}}\":49.999}" - Then cmd bitcoin-cli: "signrawtransactionwithwallet {{$.createrawtransaction[-1]}}" - Then cmd: "bitcoin broadcast-tx {{$.signrawtransactionwithwallet[-1].hex}}" - Then assert: "'{{$.bitcoin[-1]}}' not_contains error" - - Then cmd bitcoin-cli: "generatetoaddress 1 {{$.getnewaddress[-1]}}" - Then sleep: "20" # wait for the transaction to be confirmed + Then cmd bitcoin-cli: "generatetoaddress 101 {{$.account[-1].multisign_bitcoin_address}}" + Then sleep: "10" # wait for the transaction to be confirmed # l1 transaction Then cmd: "bitcoin build-tx --sender {{$.account[-1].multisign_bitcoin_address}} -o {{$.account[-2].account0.bitcoin_address}}:100000000" @@ -47,7 +30,7 @@ Feature: Rooch CLI multisign integration tests Then cmd: "bitcoin broadcast-tx {{$.bitcoin[-1].path}}" Then assert: "'{{$.bitcoin[-1]}}' not_contains error" - Then cmd bitcoin-cli: "generatetoaddress 1 {{$.getnewaddress[-1]}}" + Then cmd bitcoin-cli: "generatetoaddress 1 {{$.account[-1].multisign_bitcoin_address}}" Then sleep: "10" # wait for the transaction to be confirmed Then cmd: "account balance -a {{$.account[-2].account0.address}} --json" diff --git a/crates/testsuite/tests/integration.rs b/crates/testsuite/tests/integration.rs index 4e7e59a7b1..ed83d9671c 100644 --- a/crates/testsuite/tests/integration.rs +++ b/crates/testsuite/tests/integration.rs @@ -575,7 +575,8 @@ async fn assert_output(world: &mut World, orginal_args: String) { second ), "not_contains" => assert!( - !first.contains(&second), + !first.contains(&second) + && !first.to_lowercase().contains(&second.to_lowercase()), "Assert {:?} not_contains {:?} failed", first, second diff --git a/frameworks/rooch-nursery/sources/inscribe_factory.move b/frameworks/rooch-nursery/sources/inscribe_factory.move index ad2e54b4a9..f7ffe41764 100644 --- a/frameworks/rooch-nursery/sources/inscribe_factory.move +++ b/frameworks/rooch-nursery/sources/inscribe_factory.move @@ -454,28 +454,28 @@ module rooch_nursery::inscribe_factory { // seed tx let seed_txid = types::outpoint_txid(commit_outpoint); let seed_vout = types::outpoint_vout(commit_outpoint); + // remove block hash from seed + // let seed_height_option = bitcoin::get_tx_height(seed_txid); + // if (option::is_none(&seed_height_option)) { + // return vector::empty() + // }; - let seed_height_option = bitcoin::get_tx_height(seed_txid); - if (option::is_none(&seed_height_option)) { - return vector::empty() - }; - - let seed_height = *option::borrow(&seed_height_option); + // let seed_height = *option::borrow(&seed_height_option); - let seed_block_hash_option = bitcoin::get_block_hash_by_height(seed_height); - if (option::is_none(&seed_block_hash_option)) { - return vector::empty() - }; + // let seed_block_hash_option = bitcoin::get_block_hash_by_height(seed_height); + // if (option::is_none(&seed_block_hash_option)) { + // return vector::empty() + // }; - let seed_block_hash = *option::borrow(&seed_block_hash_option); - let seed_hex = generate_seed_from_inscription_inner(seed_block_hash, seed_txid, seed_vout); + // let seed_block_hash = *option::borrow(&seed_block_hash_option); + let seed_hex = generate_seed_from_inscription_inner(seed_txid, seed_vout); seed_hex } - fun generate_seed_from_inscription_inner(block_hash: address, txid: address, vout: u32) : vector { + fun generate_seed_from_inscription_inner(txid: address, vout: u32) : vector { let buf = vector::empty(); - vector::append(&mut buf, address::to_bytes(&block_hash)); + //vector::append(&mut buf, address::to_bytes(&block_hash)); vector::append(&mut buf, address::to_bytes(&txid)); vector::append(&mut buf, bcs::to_bytes(&vout)); hash::sha3_256(buf) @@ -874,13 +874,13 @@ module rooch_nursery::inscribe_factory { #[test] fun test_generate_seed_from_inscription_inner() { - let block_hash = address::from_bytes(x"89753cc1cdc61a89d49d5b267ab8353d4e984e08cda587f54e813add2b6d207c"); let txid = address::from_bytes(x"1a49883e4248bd8b2e423af8157a1795cd457ece0eb4d1f453266874dc1da262"); let vout = 1; - let seed = generate_seed_from_inscription_inner(block_hash, txid, vout); + let seed = generate_seed_from_inscription_inner(txid, vout); let hex_seed = hex::encode(seed); - assert!(hex_seed == b"1700b4e1d726ef40b2832eb1d5f91fd88d36ddf79eb235789c9b417c997279bc", 1); + //std::debug::print(&hex_seed); + assert!(hex_seed == x"65343932653661643734373265393439656634663039623735613761643934323237363566373035353161363732633739353963316133333665363437396634", 1); } diff --git a/generator/cpp/Makefile b/generator/cpp/Makefile new file mode 100644 index 0000000000..b652535faf --- /dev/null +++ b/generator/cpp/Makefile @@ -0,0 +1,38 @@ +# Makefile for building the generator.cpp into WebAssembly using Emscripten + +# Define the compiler to be the Emscripten C++ Compiler +CXX = emcc + +# Define the source files +SRC = generator.cpp + +# Define the output targets +TARGET = generator.wasm +TARGET_JS = generator.js + +# Compiler flags +# -O3 for optimization, --no-entry to indicate no main() function +# EXPORTED_FUNCTIONS to list the functions you want to call from JavaScript +# ALLOW_MEMORY_GROWTH to allow the memory to grow at runtime if needed +CXXFLAGS = -g0 -Oz -flto -fno-rtti -fno-exceptions --no-entry \ + -s STANDALONE_WASM=1 \ + -s WASM=1 \ + -s WARN_ON_UNDEFINED_SYMBOLS=0 \ + -s EXPORTED_FUNCTIONS='["_inscribe_generate", "_inscribe_verify"]' \ + -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE='["stringToUTF8"]' \ + -s EXPORTED_RUNTIME_METHODS='["cwrap"]' + +# Define the build rule +.PHONY: all build +all: build + +build: $(TARGET) + +$(TARGET): $(SRC) + $(CXX) $(CXXFLAGS) $(SRC) -o $(TARGET_JS) + +# Define the clean rule +.PHONY: clean +clean: + rm -f $(TARGET) $(TARGET_JS) + diff --git a/generator/cpp/generator.cpp b/generator/cpp/generator.cpp new file mode 100644 index 0000000000..02b87c4625 --- /dev/null +++ b/generator/cpp/generator.cpp @@ -0,0 +1,132 @@ +#include +#include "nlohmann/json.hpp" + +using json = nlohmann::json; + +#ifdef __cplusplus +extern "C"{ +#endif + +uint32_t hash_str_uint32(const std::string& str) { + + uint32_t hash = 0x811c9dc5; + uint32_t prime = 0x1000193; + + for(int i = 0; i < str.size(); ++i) { + uint8_t value = str[i]; + hash = hash ^ value; + hash *= prime; + } + + return hash; +} + +uint32_t get_data_length(const char *buf) { + char data_len_buf[4]; + data_len_buf[3] = buf[0]; + data_len_buf[2] = buf[1]; + data_len_buf[1] = buf[2]; + data_len_buf[0] = buf[3]; + uint32_t data_len; + memcpy(&data_len, data_len_buf, 4); + return data_len; +} + +char * int_to_bytes(uint32_t n) { + char* bytes = (char *)malloc(4); + + bytes[0] = (n >> 24) & 0xFF; + bytes[1] = (n >> 16) & 0xFF; + bytes[2] = (n >> 8) & 0xFF; + bytes[3] = n & 0xFF; + + return bytes; +} + +EMSCRIPTEN_KEEPALIVE const char * inscribe_generate(const char* buffer) { + printf("inscribe_generate_start\n"); + + uint32_t buffer_length = get_data_length(buffer); + printf("buffer_length: %d\n", buffer_length); + + std::vector buffer_vec; + buffer_vec.insert(buffer_vec.end(), buffer + 4, buffer + 4 + buffer_length); + json json_object_top = json::from_cbor(buffer_vec.begin(), buffer_vec.end()); + + json json_output; + + std::string seed; + json_object_top["seed"].get_to(seed); + printf("seed: %s\n", seed.c_str()); + + std::string user_input; + json_object_top["user_input"].get_to(user_input); + printf("user_input: %s\n", user_input.c_str()); + + std::vector attrs_buffer; + json_object_top["attrs"].get_to(attrs_buffer); + + json attrs_object = json::from_cbor(attrs_buffer.begin(), attrs_buffer.end()); + uint32_t hash_value = hash_str_uint32(seed + user_input); + + if ((!attrs_object.empty()) && (attrs_object.is_array())) { + for (json::iterator it = attrs_object.begin(); it != attrs_object.end(); ++it) { + json attr = *it; + if (attr.is_object()) { + for (json::iterator it_inner = attr.begin(); it_inner != attr.end(); ++it_inner) { + json attr_value = it_inner.value(); + if (attr_value.is_object()) { + std::string attr_key = it_inner.key(); + if ((attr_value.contains("data")) && (attr_value.contains("type"))) { + std::string attr_type = attr_value["type"]; + if (attr_type == "range") { + json attr_data = attr_value["data"]; + uint32_t range_min = attr_data["min"]; + uint32_t range_max = attr_data["max"]; + uint32_t random_value = range_min + (hash_value % (range_max - range_min + 1)); + json_output.emplace("id", user_input); + json_output.emplace(attr_key, random_value); + } + } + } + } + } + } + } + + json content(json::value_t::object); + json top_json_output; + top_json_output.emplace("amount", 1000); + top_json_output.emplace("attributes", json_output); + top_json_output.emplace("content", content); + + std::vector dump = json::to_cbor(top_json_output); + size_t dump_len = dump.size(); + char * length_bytes = int_to_bytes((uint32_t)dump_len); + char * output = (char *)dump.data(); + char * buffer_output = (char *)malloc(sizeof(char) * dump_len + 4); + memcpy(buffer_output, length_bytes, 4); + memcpy(buffer_output + 4, output, dump_len); + free(length_bytes); + + printf("inscribe_generate_end\n"); + + return buffer_output; +} + +EMSCRIPTEN_KEEPALIVE bool inscribe_verify(const char* buffer, const char* inscribe_output_buffer) { + const char *inscribe_output = inscribe_generate(buffer); + uint32_t output_len = get_data_length(inscribe_output); + bool result = memcmp(inscribe_output+4, inscribe_output_buffer, output_len) == 0; + free((void*)inscribe_output); // Free the dynamically allocated memory + return result; +} + +EMSCRIPTEN_KEEPALIVE const char * indexer_generate(const char* buffer) { + char seed[] = ""; + return inscribe_generate(buffer); +} + +#ifdef __cplusplus +} +#endif diff --git a/generator/cpp/generator.js b/generator/cpp/generator.js new file mode 100644 index 0000000000..a4b5cd6c04 --- /dev/null +++ b/generator/cpp/generator.js @@ -0,0 +1 @@ +var Module=typeof Module!="undefined"?Module:{};var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(ENVIRONMENT_IS_WORKER){scriptDirectory=nodePath.dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=(filename,binary)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);return fs.readFileSync(filename,binary?undefined:"utf8")};readBinary=filename=>{var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}return ret};readAsync=(filename,onload,onerror,binary=true)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);fs.readFile(filename,binary?undefined:"utf8",(err,data)=>{if(err)onerror(err);else onload(binary?data.buffer:data)})};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);if(typeof module!="undefined"){module["exports"]=Module}process.on("uncaughtException",ex=>{if(ex!=="unwind"&&!(ex instanceof ExitStatus)&&!(ex.context instanceof ExitStatus)){throw ex}});quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var dataURIPrefix="data:application/octet-stream;base64,";var isDataURI=filename=>filename.startsWith(dataURIPrefix);var isFileURI=filename=>filename.startsWith("file://");var wasmBinaryFile;wasmBinaryFile="generator.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(binaryFile){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"&&!isFileURI(binaryFile)){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{if(!response["ok"]){throw`failed to load wasm binary file at '${binaryFile}'`}return response["arrayBuffer"]()}).catch(()=>getBinarySync(binaryFile))}else if(readAsync){return new Promise((resolve,reject)=>{readAsync(binaryFile,response=>resolve(new Uint8Array(response)),reject)})}}return Promise.resolve().then(()=>getBinarySync(binaryFile))}function instantiateArrayBuffer(binaryFile,imports,receiver){return getBinaryPromise(binaryFile).then(binary=>WebAssembly.instantiate(binary,imports)).then(receiver,reason=>{err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)})}function instantiateAsync(binary,binaryFile,imports,callback){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{var result=WebAssembly.instantiateStreaming(response,imports);return result.then(callback,function(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(binaryFile,imports,callback)})})}return instantiateArrayBuffer(binaryFile,imports,callback)}function createWasm(){var info={"env":wasmImports,"wasi_snapshot_preview1":wasmImports};function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["memory"];updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err(`Module.instantiateWasm callback failed with error: ${e}`);return false}}instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult);return{}}function ExitStatus(status){this.name="ExitStatus";this.message=`Program terminated with exit(${status})`;this.status=status}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var noExitRuntime=Module["noExitRuntime"]||true;var _fd_close=fd=>52;var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);return 70}var printCharBuffers=[null,[],[]];var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;var UTF8ArrayToString=(heapOrArray,idx,maxBytesToRead)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var SYSCALLS={varargs:undefined,get(){var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret},getp(){return SYSCALLS.get()},getStr(ptr){var ret=UTF8ToString(ptr);return ret}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j>2]=num;return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};function _stringToUTF8(){abort("missing function: stringToUTF8")}_stringToUTF8.stub=true;var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={"string":str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},"array":arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var wasmImports={fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,proc_exit:_proc_exit};var wasmExports=createWasm();var _inscribe_generate=Module["_inscribe_generate"]=a0=>(_inscribe_generate=Module["_inscribe_generate"]=wasmExports["inscribe_generate"])(a0);var _inscribe_verify=Module["_inscribe_verify"]=(a0,a1)=>(_inscribe_verify=Module["_inscribe_verify"]=wasmExports["inscribe_verify"])(a0,a1);var _indexer_generate=Module["_indexer_generate"]=a0=>(_indexer_generate=Module["_indexer_generate"]=wasmExports["indexer_generate"])(a0);var __initialize=Module["__initialize"]=()=>(__initialize=Module["__initialize"]=wasmExports["_initialize"])();var stackSave=()=>(stackSave=wasmExports["stackSave"])();var stackRestore=a0=>(stackRestore=wasmExports["stackRestore"])(a0);var stackAlloc=a0=>(stackAlloc=wasmExports["stackAlloc"])(a0);Module["cwrap"]=cwrap;var calledRun;var mainArgs=undefined;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function callMain(args=[]){var entryFunction=__initialize;mainArgs=[thisProgram].concat(args);try{entryFunction();var ret=0;exitJS(ret,true);return ret}catch(e){return handleException(e)}}function run(args=arguments_){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(shouldRunNow)callMain(args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=true;if(Module["noInitialRun"])shouldRunNow=false;run(); diff --git a/generator/cpp/generator.wasm b/generator/cpp/generator.wasm new file mode 100644 index 0000000000000000000000000000000000000000..3ead3cebb8589faa33f9ac82a907313a85e4e9fe GIT binary patch literal 46257 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 Wqv9A=^PavqjUvY(NNH8YTK_KvB;$Ml literal 0 HcmV?d00001 diff --git a/generator/cpp/nlohmann/json.hpp b/generator/cpp/nlohmann/json.hpp new file mode 100644 index 0000000000..a858728c4c --- /dev/null +++ b/generator/cpp/nlohmann/json.hpp @@ -0,0 +1,24766 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 3 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 3 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // nullptr_t +#include // exception +#if JSON_DIAGNOSTICS + #include // accumulate +#endif +#include // runtime_error +#include // to_string +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + + +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-FileCopyrightText: 2016-2021 Evan Nemerson +// SPDX-License-Identifier: MIT + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions (except those affecting ABI) +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// #include + + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifndef JSON_HAS_STATIC_RTTI + #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 + #define JSON_HAS_STATIC_RTTI 1 + #else + #define JSON_HAS_STATIC_RTTI 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType, \ + class CustomBaseClass> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1); + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +// inspired from https://stackoverflow.com/a/26745591 +// allows to call any std function as if (e.g. with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 +#endif + +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != StringType::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +template +inline StringType escape(StringType s) +{ + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +template +static void unescape(StringType& s) +{ + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // size_t + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static JSON_INLINE_VARIABLE constexpr T value{}; +}; + +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif + +template +inline constexpr std::array make_array(Args&& ... args) +{ + return std::array {{static_cast(std::forward(args))...}}; +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval +#include // tuple +#include // char_traits + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // random_access_iterator_tag + +// #include + +// #include + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); + +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); + +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector + + // #include + + + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN + + /*! + @brief default JSONSerializer template argument + + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; + + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector, // cppcheck-suppress syntaxError + class CustomBaseClass = void> + class basic_json; + + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; + + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; + + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; + + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; + + NLOHMANN_JSON_NAMESPACE_END + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +NLOHMANN_JSON_NAMESPACE_BEGIN +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ + +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; + +///////////////// +// char_traits // +///////////////// + +// Primary template of char_traits calls std char_traits +template +struct char_traits : std::char_traits +{}; + +// Explicitly define char traits for unsigned char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = unsigned char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(EOF); + } +}; + +// Explicitly define char traits for signed char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = signed char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(EOF); + } +}; + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + + static constexpr auto value = + conjunction < + is_constructible, + is_detected_exact>::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& + is_complete_type < + detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template