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/.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/Cargo.lock b/Cargo.lock index dfb4c9afa7..fce60843f7 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", @@ -9190,7 +9339,9 @@ dependencies = [ "bcs", "bitcoin 0.32.2", "bitcoin-move", + "bitcoincore-rpc", "chrono", + "ciborium", "clap 4.5.17", "codespan-reporting", "csv", @@ -9262,11 +9413,13 @@ dependencies = [ "smt", "tempfile", "termcolor", + "tiny-keccak", "tokio", "tracing", "tracing-subscriber", "vergen-git2", "vergen-pretty", + "wasmer", "xorf", "xxhash-rust", ] @@ -9855,6 +10008,7 @@ dependencies = [ "anyhow", "bcs", "bitcoin 0.32.2", + "bitcoincore-rpc", "futures", "hex", "jsonrpsee 0.23.2", @@ -9989,7 +10143,7 @@ dependencies = [ "bs58 0.5.1", "chacha20poly1305", "clap 4.5.17", - "derive_more", + "derive_more 0.99.18", "enum_dispatch", "ethers", "eyre", @@ -10367,7 +10521,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 +10813,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..c192d7a19f 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 = [ @@ -67,6 +68,10 @@ default-members = [ "crates/rooch-oracle" ] +exclude = [ + "generator/rust", +] + # All workspace members should inherit these keys # for package declarations. [workspace.package] @@ -200,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-benchmarks/README.md b/crates/rooch-benchmarks/README.md index 72cf13b2db..8234eeb5c8 100644 --- a/crates/rooch-benchmarks/README.md +++ b/crates/rooch-benchmarks/README.md @@ -70,7 +70,7 @@ in `target/criterion///profile` dir. e.g., profiling `bench_tx_exec` for 3.1 seconds: ```shell -cargo bench --bench bench_tx_exec -- --profile-time=3.1 +cargo bench --bench bench_tx_exec -- --profile-time=3 ``` for PPROF_OUT output location: @@ -98,7 +98,8 @@ Coming soon... ### How to prepare the Bitcoin blocks -Run the benchmark with Bitcoin RPC config, it will download the blocks from Bitcoin network and save them in `target/btc_blocks` dir. +Run the benchmark with Bitcoin RPC config, it will download the blocks from Bitcoin network and save them in +`target/btc_blocks` dir. ```shell ROOCH_BENCH_TX_TYPE=btc_tx ROOCH_BENCH_BTC_RPC_URL=http://localhost:8332 ROOCH_BENCH_BTC_RPC_USERNAME=YourBTCUser ROOCH_BENCH_BTC_RPC_PASSWORD=YourBTCPass cargo bench -p rooch-benchmarks --bench bench_tx_exec 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( 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-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/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-api/src/jsonrpc_types/state_view.rs b/crates/rooch-rpc-api/src/jsonrpc_types/state_view.rs index 2faf1a3d96..a28bb127f8 100644 --- a/crates/rooch-rpc-api/src/jsonrpc_types/state_view.rs +++ b/crates/rooch-rpc-api/src/jsonrpc_types/state_view.rs @@ -504,7 +504,9 @@ fn parse_changed_objects( let mut deleted_objs = vec![]; for obj_change in changes { let metadata = obj_change.metadata.clone(); - debug_assert!(obj_change.value.is_some() || !obj_change.fields.is_empty()); + //TODO fixme + //https://github.com/rooch-network/rooch/issues/2657 + //debug_assert!(obj_change.value.is_some() || !obj_change.fields.is_empty()); match obj_change.value { Some(OpView::New(_)) => new_objs.push(metadata), Some(OpView::Modify(_)) => modified_objs.push(metadata), 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..cd88721504 --- /dev/null +++ b/crates/rooch/src/commands/bitseed/inscribe.rs @@ -0,0 +1,1283 @@ +// 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; +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 burn_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, + utxos: BTreeMap, + 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, + ) + } + }; + + let mut utxos = BTreeMap::new(); + utxos.insert(satpoint.outpoint.clone().into(), utxo.tx_output()?); + + Ok(Self { + context, + utxo_selector, + option, + inscriptions: Vec::new(), + inscriptions_to_burn: Vec::new(), + satpoint, + utxos, + 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.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" + ); + //TODO enable the attributes check + // 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) -> Result { + let inscription_obj = self.get_inscription_object(inscription_id).await?; + let outpoint = inscription_obj.location().outpoint.clone(); + let utxo_obj = self.utxo_selector.get_utxo(&outpoint).await?; + self.inscriptions_to_burn.push(inscription_id); + self.utxos.insert(outpoint.into(), utxo_obj.tx_output()?); + Ok(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 burn_input_start_index = ctx.burn_input_start_index.unwrap_or(0); + + for (current_index, txin) in reveal_tx.input.iter_mut().enumerate() { + if current_index < burn_input_start_index { + let reveal_script = &reveal_scripts[current_index]; + let control_block = &control_blocks[current_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, + }; + + 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: self.utxos.clone(), + reveal_scripts_to_sign: Vec::new(), + control_blocks_to_sign: Vec::new(), + burn_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.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 revelation + + 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 + let burn_input_start_index = ctx.reveal_tx.input.len(); + ctx.burn_input_start_index = Some(burn_input_start_index); + + // Process the logic of inscription destruction + // The ordinals protocol require the inscribe input should be first input, + // So we need to put the burn input after the reveal input. + 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()); + } + + 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.burn_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 burn_input_start_index = ctx.burn_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( + 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(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 burn_input_start_index < signed_reveal_tx.input.len() { + 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/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..8ed1cdb417 100644 --- a/crates/testsuite/features/bitseed.feature +++ b/crates/testsuite/features/bitseed.feature @@ -7,84 +7,93 @@ 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" - - # 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" + Then cmd bitcoin-cli: "generatetoaddress 101 {{$.account[-1].default.bitcoin_address}}" + Then sleep: "10" # wait rooch to sync # 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 - Then cmd: "move run --function default::bitseed_runner::run --json" + # process bitseed inscription event + Then cmd: "move run --function 0xa::inscribe_factory::process_bitseed_event --args u64:10 --json" 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 - Then cmd: "move run --function default::bitseed_runner::run --json" + Then cmd: "move run --function 0xa::inscribe_factory::process_bitseed_event --args u64:10 --json" 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" + # mint 1 + 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" + + Then cmd bitcoin-cli: "generatetoaddress 1 {{$.account[-1].default.bitcoin_address}}" + Then sleep: "5" + + # mint 2 + Then cmd: "bitseed mint --fee-rate 7000 --deploy-inscription-id {{$.bitseed[-2].inscriptions[0].Id}} --user-input test2" + 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 - Then cmd: "move run --function default::bitseed_runner::run --json" + Then cmd: "move run --function 0xa::inscribe_factory::process_bitseed_event --args u64:10 --json" 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" + + Then cmd: "move view --function 0x4::ord::view_validity --args string:{{$.bitseed[-2].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" + + Then cmd: "bitseed merge --fee-rate 6000 --sft-inscription-ids {{$.bitseed[-1].inscriptions[0].Id}} --sft-inscription-ids {{$.bitseed[-2].inscriptions[0].Id}}" + Then assert: "'{{$.bitseed[-1]}}' not_contains error" + + # mine a block + Then cmd bitcoin-cli: "generatetoaddress 1 {{$.account[-1].default.bitcoin_address}}" + Then sleep: "10" + + Then cmd: "move run --function 0xa::inscribe_factory::process_bitseed_event --args u64:10 --json" + Then assert: "{{$.move[-1].execution_info.status.type}} == executed" + + 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,44 +103,32 @@ 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 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" - Then assert: "{{$.move[-1].execution_info.status.type}} == executed" + Then cmd bitcoin-cli: "generatetoaddress 101 {{$.account[-1].default.bitcoin_address}}" + Then sleep: "10" # wait ord sync and index # Sync bitseed - Then cmd: "move run --function default::bitseed_runner::run --json" + Then cmd: "move run --function 0xa::inscribe_factory::process_bitseed_event --args u64:10 --json" 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 - Then cmd: "move run --function default::bitseed_runner::run --json" + Then cmd: "move run --function 0xa::inscribe_factory::process_bitseed_event --args u64:10 --json" 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 +139,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/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); + } +} diff --git a/examples/bitseed_runner/Move.toml b/examples/bitseed_runner/Move.toml deleted file mode 100644 index 943fa51ecd..0000000000 --- a/examples/bitseed_runner/Move.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "bitseed_runner" -version = "0.0.1" - -[dependencies] -MoveosStdlib = { local = "../../frameworks/moveos-stdlib" } -BitcoinMove = { local = "../../frameworks/bitcoin-move" } -RoochNursery = { local = "../../frameworks/rooch-nursery" } - -[addresses] -rooch_examples = "_" -moveos_std = "0x2" -rooch_framework = "0x3" -bitcoin_move = "0x4" -rooch_nursery = "0xa" - -[dev-addresses] -rooch_examples = "0x42" diff --git a/examples/bitseed_runner/readme.md b/examples/bitseed_runner/readme.md deleted file mode 100644 index 370bf7b173..0000000000 --- a/examples/bitseed_runner/readme.md +++ /dev/null @@ -1,7 +0,0 @@ -**A full workflow example:** - -1. add fixtures/config.yml to the ROOCH_CONFIG environment variable -2. Start a local server: -``` - rooch server start -``` diff --git a/examples/bitseed_runner/sources/bitseed.move b/examples/bitseed_runner/sources/bitseed.move deleted file mode 100644 index e10adde74d..0000000000 --- a/examples/bitseed_runner/sources/bitseed.move +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) RoochNetwork -// SPDX-License-Identifier: Apache-2.0 - -module rooch_examples::bitseed_runner { - - use std::option; - use moveos_std::object::{Self, Object}; - use moveos_std::event_queue::{Self, Subscriber}; - use bitcoin_move::ord::{Self, Inscription}; - use rooch_nursery::inscribe_factory; - use rooch_nursery::bitseed; - - struct BitseedRunnerStore has key { - subscriber: Object>, - } - - fun init() { - let subscriber = event_queue::subscribe(bitseed::metaprotocol()); - let store = BitseedRunnerStore { - subscriber, - }; - let store_obj = object::new_named_object(store); - object::to_shared(store_obj); - } - - public entry fun run() { - let object_id = object::named_object_id(); - let bitseed_runner_store = object::borrow_mut_object_shared(object_id); - let runner = object::borrow_mut(bitseed_runner_store); - - let event_opt = event_queue::consume(&mut runner.subscriber); - - if (option::is_some(&event_opt)){ - let event = option::destroy_some(event_opt); - let (_metaprotocol, _sequence_number, inscription_obj_id, event_type) = ord::unpack_inscription_event(event); - - let inscription_obj = object::borrow_object(inscription_obj_id); - let inscription = object::borrow(inscription_obj); - if (event_type == ord::inscription_event_type_new()){ - inscribe_factory::process_inscription(inscription); - }else { - //TODO handle burn event. - std::debug::print(&event); - }; - }; - } -} diff --git a/examples/bitseed_runner/web/README.md b/examples/bitseed_runner/web/README.md deleted file mode 100644 index 84b4cc3988..0000000000 --- a/examples/bitseed_runner/web/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Counter Web Example - -Please visit the following path to view the Counter Web Example project: - -- `sdk/typescript/examples/bitseed_runner` diff --git a/frameworks/bitcoin-move/doc/ord.md b/frameworks/bitcoin-move/doc/ord.md index af7a955755..271981db1e 100644 --- a/frameworks/bitcoin-move/doc/ord.md +++ b/frameworks/bitcoin-move/doc/ord.md @@ -99,6 +99,8 @@ - [Function `is_metaprotocol_register`](#0x4_ord_is_metaprotocol_register) - [Function `seal_metaprotocol_validity`](#0x4_ord_seal_metaprotocol_validity) - [Function `add_metaprotocol_attachment`](#0x4_ord_add_metaprotocol_attachment) +- [Function `remove_metaprotocol_attachment`](#0x4_ord_remove_metaprotocol_attachment) +- [Function `exists_metaprotocol_attachment`](#0x4_ord_exists_metaprotocol_attachment) - [Function `exists_metaprotocol_validity`](#0x4_ord_exists_metaprotocol_validity) - [Function `borrow_metaprotocol_validity`](#0x4_ord_borrow_metaprotocol_validity) - [Function `metaprotocol_validity_protocol_match`](#0x4_ord_metaprotocol_validity_protocol_match) @@ -1395,6 +1397,29 @@ Seal the metaprotocol validity for the given inscription_id. + + +## Function `remove_metaprotocol_attachment` + + + +

#[private_generics(#[T])]
+public fun remove_metaprotocol_attachment<T>(inscription_id: ord::InscriptionID): object::Object<T>
+
+ + + + + +## Function `exists_metaprotocol_attachment` + + + +
public fun exists_metaprotocol_attachment<T>(inscription_id: ord::InscriptionID): bool
+
+ + + ## Function `exists_metaprotocol_validity` diff --git a/frameworks/bitcoin-move/sources/ord.move b/frameworks/bitcoin-move/sources/ord.move index 58c84ee882..15437bdf7f 100644 --- a/frameworks/bitcoin-move/sources/ord.move +++ b/frameworks/bitcoin-move/sources/ord.move @@ -350,7 +350,9 @@ module bitcoin_move::ord { event_type: InscriptionEventTypeBurn, }); }; - object::to_frozen(inscription_obj); + //Transfer the burned inscription to system address @bitcoin_move + //We do not freeze the inscription, because the Inscription maybe include the metaprotocol attachment + object::transfer_extend(inscription_obj, @bitcoin_move); }else{ object::transfer_extend(inscription_obj, to); }; @@ -783,6 +785,32 @@ module bitcoin_move::ord { object::add_field(inscription_obj, protocol_type, attachment); } + #[private_generics(T)] + public fun remove_metaprotocol_attachment(inscription_id: InscriptionID) : Object { + let inscription_object_id = derive_inscription_id(inscription_id); + let inscription_obj = object::borrow_mut_object_extend(inscription_object_id); + let protocol_type = type_info::type_name(); + assert!(metaprotocol_protocol_match(inscription_obj, protocol_type), ErrorMetaprotocolProtocolMismatch); + object::remove_field(inscription_obj, protocol_type) + } + + public fun exists_metaprotocol_attachment(inscription_id: InscriptionID): bool { + let inscription_object_id = derive_inscription_id(inscription_id); + let exists = object::exists_object_with_type(inscription_object_id); + if (!exists) { + return false + }; + + let inscription_obj = object::borrow_object(inscription_object_id); + let protocol_type = type_info::type_name(); + if(metaprotocol_protocol_match(inscription_obj, protocol_type)){ + object::contains_field(inscription_obj, protocol_type) + }else{ + false + } + } + + /// Returns true if Inscription `object` contains metaprotocol validity public fun exists_metaprotocol_validity(inscription_id: InscriptionID): bool { let inscription_object_id = derive_inscription_id(inscription_id); diff --git a/frameworks/moveos-stdlib/doc/json.md b/frameworks/moveos-stdlib/doc/json.md index 7f0953e7f7..f185139708 100644 --- a/frameworks/moveos-stdlib/doc/json.md +++ b/frameworks/moveos-stdlib/doc/json.md @@ -9,6 +9,7 @@ - [Function `from_json`](#0x2_json_from_json) - [Function `from_json_option`](#0x2_json_from_json_option) - [Function `to_map`](#0x2_json_to_map) +- [Function `to_json`](#0x2_json_to_json)
use 0x1::option;
@@ -82,3 +83,15 @@ If the field type is primitive type, it will be parsed to String, array or objec
 
 
public fun to_map(json_str: vector<u8>): simple_map::SimpleMap<string::String, string::String>
 
+ + + + + +## Function `to_json` + +Serialize a value of type T to JSON string bytes. + + +
public fun to_json<T>(value: &T): vector<u8>
+
diff --git a/frameworks/moveos-stdlib/sources/json.move b/frameworks/moveos-stdlib/sources/json.move index 5c406b1745..5332beaad7 100644 --- a/frameworks/moveos-stdlib/sources/json.move +++ b/frameworks/moveos-stdlib/sources/json.move @@ -40,7 +40,13 @@ module moveos_std::json{ option::destroy_some(opt_result) } + /// Serialize a value of type T to JSON string bytes. + public fun to_json(value: &T): vector { + native_to_json(value) + } + native fun native_from_json(json_str: vector): Option; + native fun native_to_json(value: &T): vector; #[test_only] use std::vector; @@ -116,4 +122,139 @@ module moveos_std::json{ let obj = from_json_option(invalid_json); assert!(option::is_none(&obj), 1); } + + #[test] + fun test_to_json_basic_types() { + // Test u8 + let u8_value = 255u8; + let u8_json = to_json(&u8_value); + assert!(string::utf8(u8_json) == string::utf8(b"255"), 1); + + // Test u64 + let u64_value = 18446744073709551615u64; + let u64_json = to_json(&u64_value); + assert!(string::utf8(u64_json) == string::utf8(b"18446744073709551615"), 2); + + // Test u128 + let u128_value = 340282366920938463463374607431768211455u128; + let u128_json = to_json(&u128_value); + assert!(string::utf8(u128_json) == string::utf8(b"\"340282366920938463463374607431768211455\""), 3); + + // Test address + let address_value = @0x42; + let address_json = to_json(&address_value); + assert!(string::utf8(address_json) == string::utf8(b"\"0x42\""), 4); + + // Test String + let string_value = string::utf8(b"rooch.network"); + let string_json = to_json(&string_value); + assert!(string::utf8(string_json) == string::utf8(b"\"rooch.network\""), 5); + + // Test vector + let bytes_value = vector::empty(); + vector::push_back(&mut bytes_value, 1u8); + vector::push_back(&mut bytes_value, 2u8); + vector::push_back(&mut bytes_value, 3u8); + let bytes_json = to_json(&bytes_value); + assert!(string::utf8(bytes_json) == string::utf8(b"[1,2,3]"), 6); + } + + #[test_only] + struct InnerStruct has copy, drop { + inner_value: u64 + } + + #[test_only] + struct OuterStruct has copy, drop { + outer_value: u64, + inner_struct: InnerStruct + } + + #[test_only] + struct SimpleStruct has copy, drop { + value: u64 + } + + #[test] + fun test_to_json_composite_types() { + let inner_struct = InnerStruct { inner_value: 42 }; + let outer_struct = OuterStruct { outer_value: 100, inner_struct: inner_struct }; + let outer_json = to_json(&outer_struct); + assert!(string::utf8(outer_json) == string::utf8(b"{\"outer_value\":100,\"inner_struct\":{\"inner_value\":42}}"), 1); + + // Test array of structs + let struct_array = vector::empty(); + vector::push_back(&mut struct_array, SimpleStruct { value: 1 }); + vector::push_back(&mut struct_array, SimpleStruct { value: 2 }); + vector::push_back(&mut struct_array, SimpleStruct { value: 3 }); + let array_json = to_json(&struct_array); + assert!(string::utf8(array_json) == string::utf8(b"[{\"value\":1},{\"value\":2},{\"value\":3}]"), 2); + } + + #[test_only] + struct StructWithEmptyString has copy, drop { + value: u64, + empty_string: String + } + + #[test] + fun test_to_json_boundary_conditions() { + // Test empty array + let empty_array = vector::empty(); + let empty_array_json = to_json(&empty_array); + assert!(string::utf8(empty_array_json) == string::utf8(b"[]"), 1); + + // Test struct with empty string + let empty_string_struct = StructWithEmptyString { + value: 0, + empty_string: string::utf8(b"") + }; + let empty_string_json = to_json(&empty_string_struct); + assert!(string::utf8(empty_string_json) == string::utf8(b"{\"value\":0,\"empty_string\":\"\"}"), 2); + } + + #[test] + fun test_to_json_boolean_and_null() { + // Test boolean values + let bool_true = true; + let bool_true_json = to_json(&bool_true); + assert!(string::utf8(bool_true_json) == string::utf8(b"true"), 1); + + let bool_false = false; + let bool_false_json = to_json(&bool_false); + assert!(string::utf8(bool_false_json) == string::utf8(b"false"), 2); + + // Test null value + let null_value = option::none(); + let null_json = to_json(&null_value); + assert!(string::utf8(null_json) == string::utf8(b"null"), 3); + } + + #[test] + fun test_to_json_composite_all() { + let inner = Inner { value: 100 }; + let inner_array = vector::empty(); + vector::push_back(&mut inner_array, Inner { value: 101 }); + + let test_obj = Test { + balance: 170141183460469231731687303715884105728u128, + utf8_string: string::utf8(b"rooch.network"), + age: 30u8, + inner: inner, + bytes: vector::empty(), + inner_array: inner_array, + account: @0x42, + }; + + let json_str = to_json(&test_obj); + + let map = to_map(json_str); + assert!(simple_map::borrow(&map, &string::utf8(b"balance")) == &string::utf8(b"170141183460469231731687303715884105728"), 1); + assert!(simple_map::borrow(&map, &string::utf8(b"utf8_string")) == &string::utf8(b"rooch.network"), 2); + assert!(simple_map::borrow(&map, &string::utf8(b"age")) == &string::utf8(b"30"), 3); + assert!(simple_map::borrow(&map, &string::utf8(b"inner")) == &string::utf8(b"{\"value\":100}"), 4); + assert!(simple_map::borrow(&map, &string::utf8(b"bytes")) == &string::utf8(b"[]"), 5); + assert!(simple_map::borrow(&map, &string::utf8(b"inner_array")) == &string::utf8(b"[{\"value\":101}]"), 6); + assert!(simple_map::borrow(&map, &string::utf8(b"account")) == &string::utf8(b"0x42"), 7); + } } \ No newline at end of file diff --git a/frameworks/moveos-stdlib/src/natives/moveos_stdlib/json.rs b/frameworks/moveos-stdlib/src/natives/moveos_stdlib/json.rs index 53222c03c8..4aa33548c0 100644 --- a/frameworks/moveos-stdlib/src/natives/moveos_stdlib/json.rs +++ b/frameworks/moveos-stdlib/src/natives/moveos_stdlib/json.rs @@ -1,36 +1,48 @@ // Copyright (c) RoochNetwork // SPDX-License-Identifier: Apache-2.0 -use crate::natives::helpers::{make_module_natives, make_native}; +use std::collections::VecDeque; +use std::str::FromStr; + use anyhow::Result; use log::debug; +use primitive_types::U128 as PrimitiveU128; +use primitive_types::U256 as PrimitiveU256; +use serde_json; +use serde_json::Value as JsonValue; +use smallvec::smallvec; + use move_binary_format::errors::{PartialVMError, PartialVMResult}; use move_core_types::account_address::AccountAddress; +use move_core_types::gas_algebra::{InternalGas, InternalGasPerByte, NumBytes}; +use move_core_types::identifier::Identifier; +use move_core_types::language_storage::StructTag; use move_core_types::language_storage::TypeTag; use move_core_types::u256::U256; -use move_core_types::value::MoveStructLayout; +use move_core_types::value::MoveStruct; +use move_core_types::value::MoveValue; +use move_core_types::value::{MoveFieldLayout, MoveStructLayout, MoveTypeLayout}; use move_core_types::vm_status::StatusCode; -use move_core_types::{ - gas_algebra::{InternalGas, InternalGasPerByte, NumBytes}, - value::MoveTypeLayout, -}; + use move_vm_runtime::native_functions::{NativeContext, NativeFunction}; + use move_vm_types::{ loaded_data::runtime_types::Type, natives::function::NativeResult, pop_arg, - values::{Struct, Value, Vector}, + values::{values_impl::Reference, Struct, Value, Vector}, }; + use moveos_types::addresses::MOVE_STD_ADDRESS; use moveos_types::move_std::string::MoveString; use moveos_types::moveos_std::simple_map::{Element, SimpleMap}; use moveos_types::state::{MoveStructType, MoveType}; -use serde_json; -use smallvec::smallvec; -use std::collections::VecDeque; -use std::str::FromStr; + +use crate::natives::helpers::{make_module_natives, make_native}; const E_TYPE_NOT_MATCH: u64 = 1; +const STATUS_CODE_FAILED_TO_SERIALIZE_VALUE: u64 = 2; +const E_JSON_SERIALIZATION_FAILURE: u64 = 3; fn parse_struct_value_from_bytes( layout: &MoveStructLayout, @@ -38,13 +50,13 @@ fn parse_struct_value_from_bytes( context: &NativeContext, ) -> Result { let json_str = std::str::from_utf8(&bytes)?; - let json_obj: serde_json::Value = serde_json::from_str(json_str)?; + let json_obj: JsonValue = serde_json::from_str(json_str)?; parse_struct_value_from_json(layout, &json_obj, context) } fn parse_struct_value_from_json( layout: &MoveStructLayout, - json_value: &serde_json::Value, + json_value: &JsonValue, context: &NativeContext, ) -> Result { if let MoveStructLayout::WithTypes { @@ -103,7 +115,7 @@ fn parse_struct_value_from_json( } fn parse_move_value_from_json( layout: &MoveTypeLayout, - json_value: &serde_json::Value, + json_value: &JsonValue, context: &NativeContext, ) -> Result { match layout { @@ -189,16 +201,16 @@ fn parse_move_value_from_json( } } -fn json_obj_to_key_value_pairs(json_obj: &serde_json::Value) -> Result> { - if let serde_json::Value::Object(obj) = json_obj { +fn json_obj_to_key_value_pairs(json_obj: &JsonValue) -> Result> { + if let JsonValue::Object(obj) = json_obj { let mut key_value_pairs = Vec::new(); for (key, value) in obj.iter() { let key = key.to_string(); let value = match value { - serde_json::Value::String(s) => s.to_string(), - serde_json::Value::Number(n) => n.to_string(), - serde_json::Value::Bool(b) => b.to_string(), - serde_json::Value::Null => "null".to_string(), + JsonValue::String(s) => s.to_string(), + JsonValue::Number(n) => n.to_string(), + JsonValue::Bool(b) => b.to_string(), + JsonValue::Null => "null".to_string(), //convert array and object to string value => value.to_string(), }; @@ -281,6 +293,325 @@ fn native_from_json( } } +#[derive(Debug, Clone)] +pub struct ToBytesGasParametersOption { + pub base: Option, + pub per_byte_in_str: Option, +} + +impl ToBytesGasParametersOption { + pub fn zeros() -> Self { + Self { + base: Some(0.into()), + per_byte_in_str: Some(0.into()), + } + } +} + +impl ToBytesGasParametersOption { + pub fn is_empty(&self) -> bool { + self.base.is_none() || self.per_byte_in_str.is_none() + } +} + +fn serialize_move_value_to_json(layout: &MoveTypeLayout, value: &MoveValue) -> Result { + use MoveTypeLayout as L; + + let json_value = match (layout, value) { + (L::Struct(layout), MoveValue::Struct(struct_)) => { + serialize_move_struct_to_json(layout, struct_)? + } + (L::Bool, MoveValue::Bool(b)) => JsonValue::Bool(*b), + (L::U8, MoveValue::U8(b)) => JsonValue::Number((*b).into()), + (L::U16, MoveValue::U16(b)) => JsonValue::Number((*b).into()), + (L::U32, MoveValue::U32(b)) => JsonValue::Number((*b).into()), + (L::U64, MoveValue::U64(b)) => JsonValue::Number((*b).into()), + (L::U128, MoveValue::U128(i)) => { + let slice = i.to_le_bytes(); + let value = PrimitiveU128::from_little_endian(&slice); + JsonValue::String(value.to_string()) + } + (L::U256, MoveValue::U256(i)) => { + let slice = i.to_le_bytes(); + let value = PrimitiveU256::from_little_endian(&slice); + JsonValue::String(value.to_string()) + } + (L::Address, MoveValue::Address(addr)) => JsonValue::String(addr.to_hex_literal()), + (L::Signer, MoveValue::Signer(_a)) => { + return Err(anyhow::anyhow!("Do not support Signer type")) + } + (L::Vector(vec_layout), MoveValue::Vector(vec)) => { + let layout = vec_layout.as_ref(); + + if let L::U8 = layout { + let mut json_vec = Vec::new(); + + for item in vec.iter() { + if let MoveValue::U8(b) = item { + json_vec.push(JsonValue::Number((*b).into())); + } + } + + JsonValue::Array(json_vec) + } else { + let mut json_vec = Vec::new(); + + for item in vec.iter() { + let json_value = serialize_move_value_to_json(layout, item)?; + json_vec.push(json_value); + } + + JsonValue::Array(json_vec) + } + } + _ => { + return Err(anyhow::anyhow!( + "Invalid combination of MoveStructLayout and MoveStruct" + )) + } + }; + + Ok(json_value) +} + +fn serialize_move_struct_to_json( + layout: &MoveStructLayout, + struct_: &MoveStruct, +) -> Result { + use MoveStructLayout as L; + + let value = match (layout, struct_) { + (L::Runtime(layouts), MoveStruct::Runtime(s)) => { + let mut json_array = Vec::new(); + for (layout, v) in layouts.iter().zip(s) { + let json_value = serialize_move_value_to_json(layout, v)?; + json_array.push(json_value); + } + JsonValue::Array(json_array) + } + (L::WithFields(layout_fields), MoveStruct::WithFields(value_fields)) => { + serialize_move_fields_to_json(layout_fields, value_fields)? + } + ( + L::WithTypes { + type_: struct_type, + fields: layout_fields, + }, + MoveStruct::WithTypes { + type_: _, + fields: value_fields, + }, + ) => { + if struct_type.is_ascii_string(&MOVE_STD_ADDRESS) + || struct_type.is_std_string(&MOVE_STD_ADDRESS) + { + let bytes_field = value_fields + .first() + .ok_or_else(|| anyhow::anyhow!("Invalid bytes field"))?; + + match &bytes_field.1 { + MoveValue::Vector(vec) => { + let bytes = MoveValue::vec_to_vec_u8(vec.clone())?; + let string = String::from_utf8(bytes) + .map_err(|_| anyhow::anyhow!("Invalid utf8 String"))?; + JsonValue::String(string) + } + _ => return Err(anyhow::anyhow!("Invalid string")), + } + } else if is_std_option(struct_type, &MOVE_STD_ADDRESS) { + let vec_layout = layout_fields + .first() + .ok_or_else(|| anyhow::anyhow!("Invalid std option layout"))?; + let vec_field = value_fields + .first() + .ok_or_else(|| anyhow::anyhow!("Invalid std option field"))?; + + match (&vec_layout.layout, &vec_field.1) { + (MoveTypeLayout::Vector(vec_layout), MoveValue::Vector(vec)) => { + let item_layout = vec_layout.as_ref(); + + if !vec.is_empty() { + serialize_move_value_to_json(item_layout, vec.first().unwrap())? + } else { + JsonValue::Null + } + } + _ => return Err(anyhow::anyhow!("Invalid std option")), + } + } else if struct_type == &SimpleMap::>::struct_tag() { + let data_field = value_fields + .iter() + .find(|(name, _)| name.as_str() == "data") + .ok_or_else(|| anyhow::anyhow!("Missing data field in SimpleMap"))?; + + let data_vector = match &data_field.1 { + MoveValue::Vector(vec) => vec, + _ => return Err(anyhow::anyhow!("Invalid data field in SimpleMap")), + }; + + let key_value_pairs = data_vector + .iter() + .map(|element| { + let struct_ = match element { + MoveValue::Struct(s) => s, + _ => return Err(anyhow::anyhow!("Invalid element in SimpleMap data")), + }; + + let fields = match struct_ { + MoveStruct::WithTypes { + type_: _, + fields: value_fields, + } => value_fields, + _ => return Err(anyhow::anyhow!("Invalid element in SimpleMap data")), + }; + + let key = match &fields[0].1 { + MoveValue::Struct(struct_) => { + let value_fields = match struct_ { + MoveStruct::WithTypes { + type_: _, + fields: value_fields, + } => value_fields, + _ => { + return Err(anyhow::anyhow!( + "Invalid element in SimpleMap data" + )) + } + }; + + let bytes_field = value_fields + .first() + .ok_or_else(|| anyhow::anyhow!("Invalid bytes field"))?; + + match bytes_field.1.clone() { + MoveValue::Vector(vec) => { + let bytes = MoveValue::vec_to_vec_u8(vec)?; + String::from_utf8(bytes) + .map_err(|_| anyhow::anyhow!("Invalid utf8 String"))? + } + _ => return Err(anyhow::anyhow!("Invalid std string")), + } + } + _ => return Err(anyhow::anyhow!("Invalid key in SimpleMap")), + }; + + let json_value = match &fields[1].1 { + MoveValue::Vector(vec) => { + let bytes = MoveValue::vec_to_vec_u8(vec.clone())?; + let json_value: JsonValue = serde_json::from_slice(&bytes) + .map_err(|_| { + anyhow::anyhow!("Invalid JSON value in SimpleMap") + })?; + json_value + } + _ => return Err(anyhow::anyhow!("Invalid value in SimpleMap")), + }; + + Ok((key, json_value)) + }) + .collect::>>()?; + + JsonValue::Object(key_value_pairs.into_iter().collect()) + } else { + serialize_move_fields_to_json(layout_fields, value_fields)? + } + } + _ => { + debug!( + "Invalid combination of MoveStructLayout and MoveStruct, layout:{:?}, struct:{:?}", + layout, struct_ + ); + + return Err(anyhow::anyhow!( + "Invalid combination of MoveStructLayout and MoveStruct" + )); + } + }; + + Ok(value) +} + +fn is_std_option(struct_tag: &StructTag, move_std_addr: &AccountAddress) -> bool { + struct_tag.address == *move_std_addr + && struct_tag.module.as_str().eq("option") + && struct_tag.name.as_str().eq("Option") +} + +fn serialize_move_fields_to_json( + layout_fields: &[MoveFieldLayout], + value_fields: &Vec<(Identifier, MoveValue)>, +) -> Result { + let mut fields = serde_json::Map::new(); + + for (field_layout, (name, value)) in layout_fields.iter().zip(value_fields) { + let json_value = serialize_move_value_to_json(&field_layout.layout, value)?; + fields.insert(name.clone().into_string(), json_value); + } + + Ok(JsonValue::Object(fields)) +} + +#[inline] +fn native_to_json( + gas_params: &ToBytesGasParametersOption, + context: &mut NativeContext, + mut ty_args: Vec, + mut args: VecDeque, +) -> PartialVMResult { + debug_assert_eq!(ty_args.len(), 1); + debug_assert_eq!(args.len(), 1); + + let gas_base = gas_params.base.expect("base gas is missing"); + let per_byte_in_str = gas_params + .per_byte_in_str + .expect("per byte in str gas is missing"); + + let mut cost = gas_base; + + // pop type and value + let ref_to_val = pop_arg!(args, Reference); + let arg_type = ty_args.pop().unwrap(); + + // get type layout + let layout = match context.type_to_type_layout(&arg_type)? { + Some(layout) => layout, + None => { + return Ok(NativeResult::err(cost, E_JSON_SERIALIZATION_FAILURE)); + } + }; + + let move_val = ref_to_val.read_ref()?.as_move_value(&layout); + + let annotated_layout = match context.type_to_fully_annotated_layout(&arg_type)? { + Some(layout) => layout, + None => { + return Ok(NativeResult::err(cost, E_JSON_SERIALIZATION_FAILURE)); + } + }; + + let annotated_move_val = move_val.decorate(&annotated_layout); + + match serialize_move_value_to_json(&annotated_layout, &annotated_move_val) { + Ok(json_value) => { + let json_string = json_value.to_string(); + cost += per_byte_in_str * NumBytes::new(json_string.len() as u64); + + Ok(NativeResult::ok( + cost, + smallvec![Value::vector_u8(json_string.into_bytes())], + )) + } + Err(e) => { + debug!("Failed to serialize value: {:?}", e); + + Ok(NativeResult::err( + cost, + STATUS_CODE_FAILED_TO_SERIALIZE_VALUE, + )) + } + } +} + /*************************************************************************************************** * module **************************************************************************************************/ @@ -288,21 +619,31 @@ fn native_from_json( #[derive(Debug, Clone)] pub struct GasParameters { pub from_bytes: FromBytesGasParameters, + pub to_bytes: ToBytesGasParametersOption, } impl GasParameters { pub fn zeros() -> Self { Self { from_bytes: FromBytesGasParameters::zeros(), + to_bytes: ToBytesGasParametersOption::zeros(), } } } pub fn make_all(gas_params: GasParameters) -> impl Iterator { - let natives = [( + let mut natives = [( "native_from_json", make_native(gas_params.from_bytes, native_from_json), - )]; + )] + .to_vec(); + + if !gas_params.to_bytes.is_empty() { + natives.push(( + "native_to_json", + make_native(gas_params.to_bytes, native_to_json), + )); + } make_module_natives(natives) } diff --git a/frameworks/rooch-framework/src/natives/gas_parameter/json.rs b/frameworks/rooch-framework/src/natives/gas_parameter/json.rs index 6680c58635..1a36d913e2 100644 --- a/frameworks/rooch-framework/src/natives/gas_parameter/json.rs +++ b/frameworks/rooch-framework/src/natives/gas_parameter/json.rs @@ -7,4 +7,6 @@ use moveos_stdlib::natives::moveos_stdlib::json::GasParameters; crate::natives::gas_parameter::native::define_gas_parameters_for_natives!(GasParameters, "json", [ [.from_bytes.base, "from_bytes.base", 1000 * MUL], [.from_bytes.per_byte_in_str, "from_bytes.per_byte_in_str", 20 * MUL], + [.to_bytes.base, optional "to_bytes.base", 1000 * MUL], + [.to_bytes.per_byte_in_str, optional "to_bytes.per_byte_in_str", 20 * MUL], ]); diff --git a/frameworks/rooch-nursery/doc/bitseed.md b/frameworks/rooch-nursery/doc/bitseed.md index 13452dfd67..bb05a0c56a 100644 --- a/frameworks/rooch-nursery/doc/bitseed.md +++ b/frameworks/rooch-nursery/doc/bitseed.md @@ -7,15 +7,26 @@ - [Resource `Bitseed`](#0xa_bitseed_Bitseed) - [Constants](#@Constants_0) -- [Function `metaprotocol`](#0xa_bitseed_metaprotocol) +- [Function `default_metaprotocol`](#0xa_bitseed_default_metaprotocol) - [Function `new`](#0xa_bitseed_new) - [Function `is_same_type`](#0xa_bitseed_is_same_type) - [Function `is_mergeable`](#0xa_bitseed_is_mergeable) - [Function `merge`](#0xa_bitseed_merge) - [Function `is_splitable`](#0xa_bitseed_is_splitable) - [Function `split`](#0xa_bitseed_split) +- [Function `burn`](#0xa_bitseed_burn) +- [Function `metaprotocol`](#0xa_bitseed_metaprotocol) +- [Function `amount`](#0xa_bitseed_amount) +- [Function `tick`](#0xa_bitseed_tick) +- [Function `bid`](#0xa_bitseed_bid) +- [Function `content_type`](#0xa_bitseed_content_type) +- [Function `body`](#0xa_bitseed_body) +- [Function `attributes`](#0xa_bitseed_attributes) +- [Function `content_attributes_hash`](#0xa_bitseed_content_attributes_hash) - [Function `seal_metaprotocol_validity`](#0xa_bitseed_seal_metaprotocol_validity) - [Function `add_metaprotocol_attachment`](#0xa_bitseed_add_metaprotocol_attachment) +- [Function `exists_metaprotocol_attachment`](#0xa_bitseed_exists_metaprotocol_attachment) +- [Function `remove_metaprotocol_attachment`](#0xa_bitseed_remove_metaprotocol_attachment)
use 0x1::option;
@@ -108,13 +119,13 @@ Bitseed is a SFT asset type.
 
 
 
-
+
 
-## Function `metaprotocol`
+## Function `default_metaprotocol`
 
 
 
-
public fun metaprotocol(): string::String
+
public fun default_metaprotocol(): string::String
 
@@ -189,6 +200,105 @@ Split the bitseed and return the new bitseed. + + +## Function `burn` + + + +
public(friend) fun burn(bitseed_obj: object::Object<bitseed::Bitseed>): u64
+
+ + + + + +## Function `metaprotocol` + + + +
public fun metaprotocol(bitseed: &bitseed::Bitseed): string::String
+
+ + + + + +## Function `amount` + + + +
public fun amount(bitseed: &bitseed::Bitseed): u64
+
+ + + + + +## Function `tick` + + + +
public fun tick(bitseed: &bitseed::Bitseed): string::String
+
+ + + + + +## Function `bid` + + + +
public fun bid(bitseed: &bitseed::Bitseed): address
+
+ + + + + +## Function `content_type` + + + +
public fun content_type(bitseed: &bitseed::Bitseed): &option::Option<string::String>
+
+ + + + + +## Function `body` + + + +
public fun body(bitseed: &bitseed::Bitseed): &vector<u8>
+
+ + + + + +## Function `attributes` + + + +
public fun attributes(bitseed: &bitseed::Bitseed): &simple_map::SimpleMap<string::String, copyable_any::Any>
+
+ + + + + +## Function `content_attributes_hash` + + + +
public fun content_attributes_hash(bitseed: &bitseed::Bitseed): address
+
+ + + ## Function `seal_metaprotocol_validity` @@ -208,3 +318,25 @@ Split the bitseed and return the new bitseed.
public(friend) fun add_metaprotocol_attachment(inscription_id: ord::InscriptionID, attachment: object::Object<bitseed::Bitseed>)
 
+ + + + + +## Function `exists_metaprotocol_attachment` + + + +
public(friend) fun exists_metaprotocol_attachment(inscription_id: ord::InscriptionID): bool
+
+ + + + + +## Function `remove_metaprotocol_attachment` + + + +
public(friend) fun remove_metaprotocol_attachment(inscription_id: ord::InscriptionID): object::Object<bitseed::Bitseed>
+
diff --git a/frameworks/rooch-nursery/doc/genesis.md b/frameworks/rooch-nursery/doc/genesis.md index 632393918a..d3ac12a9d8 100644 --- a/frameworks/rooch-nursery/doc/genesis.md +++ b/frameworks/rooch-nursery/doc/genesis.md @@ -10,6 +10,7 @@
use 0xa::ethereum;
+use 0xa::inscribe_factory;
 use 0xa::tick_info;
 
diff --git a/frameworks/rooch-nursery/doc/inscribe_factory.md b/frameworks/rooch-nursery/doc/inscribe_factory.md index dce0a7d107..8e6dec718f 100644 --- a/frameworks/rooch-nursery/doc/inscribe_factory.md +++ b/frameworks/rooch-nursery/doc/inscribe_factory.md @@ -6,13 +6,16 @@ Bitseed inscribe inscription factory +- [Struct `MergeState`](#0xa_inscribe_factory_MergeState) +- [Resource `BitseedEventStore`](#0xa_inscribe_factory_BitseedEventStore) - [Struct `InscribeGenerateArgs`](#0xa_inscribe_factory_InscribeGenerateArgs) - [Struct `InscribeGenerateOutput`](#0xa_inscribe_factory_InscribeGenerateOutput) - [Constants](#@Constants_0) +- [Function `genesis_init`](#0xa_inscribe_factory_genesis_init) - [Function `bitseed_deploy_key`](#0xa_inscribe_factory_bitseed_deploy_key) - [Function `bitseed_mint_key`](#0xa_inscribe_factory_bitseed_mint_key) - [Function `inscribe_verify`](#0xa_inscribe_factory_inscribe_verify) -- [Function `process_inscription`](#0xa_inscribe_factory_process_inscription) +- [Function `process_bitseed_event`](#0xa_inscribe_factory_process_bitseed_event)
use 0x1::bcs;
@@ -21,6 +24,7 @@ Bitseed inscribe inscription factory
 use 0x1::vector;
 use 0x2::address;
 use 0x2::cbor;
+use 0x2::event_queue;
 use 0x2::hash;
 use 0x2::hex;
 use 0x2::object;
@@ -37,6 +41,28 @@ Bitseed inscribe inscription factory
 
 
 
+
+
+## Struct `MergeState`
+
+
+
+
struct MergeState has store
+
+ + + + + +## Resource `BitseedEventStore` + + + +
struct BitseedEventStore has key
+
+ + + ## Struct `InscribeGenerateArgs` @@ -92,6 +118,17 @@ Bitseed inscribe inscription factory + + +## Function `genesis_init` + + + +
public(friend) fun genesis_init()
+
+ + + ## Function `bitseed_deploy_key` @@ -125,11 +162,11 @@ Bitseed inscribe inscription factory - + -## Function `process_inscription` +## Function `process_bitseed_event` -
public fun process_inscription(inscription: &ord::Inscription)
+
public entry fun process_bitseed_event(batch_size: u64)
 
diff --git a/frameworks/rooch-nursery/doc/tick_info.md b/frameworks/rooch-nursery/doc/tick_info.md index e1d716ae5c..cf93187743 100644 --- a/frameworks/rooch-nursery/doc/tick_info.md +++ b/frameworks/rooch-nursery/doc/tick_info.md @@ -13,6 +13,7 @@ - [Function `borrow_tick_info`](#0xa_tick_info_borrow_tick_info) - [Function `deploy_tick`](#0xa_tick_info_deploy_tick) - [Function `mint`](#0xa_tick_info_mint) +- [Function `burn`](#0xa_tick_info_burn) - [Function `mint_on_bitcoin`](#0xa_tick_info_mint_on_bitcoin) - [Function `metaprotocol`](#0xa_tick_info_metaprotocol) - [Function `tick`](#0xa_tick_info_tick) @@ -178,6 +179,17 @@ Check if the tick is deployed. + + +## Function `burn` + + + +
public fun burn(bitseed_obj: object::Object<bitseed::Bitseed>)
+
+ + + ## Function `mint_on_bitcoin` diff --git a/frameworks/rooch-nursery/sources/bitseed.move b/frameworks/rooch-nursery/sources/bitseed.move index 42dec83c0b..b570f0464e 100644 --- a/frameworks/rooch-nursery/sources/bitseed.move +++ b/frameworks/rooch-nursery/sources/bitseed.move @@ -49,7 +49,7 @@ module rooch_nursery::bitseed { content_attributes_hash: address, } - public fun metaprotocol(): String{ + public fun default_metaprotocol(): String{ string::utf8(METAPROTOCOL) } @@ -133,6 +133,49 @@ module rooch_nursery::bitseed { split_bitseed } + public(friend) fun burn(bitseed_obj: Object) : u64{ + let bitseed = object::remove(bitseed_obj); + let amount = bitseed.amount; + drop(bitseed); + amount + } + + // ==================== Get functions ==================== // + + public fun metaprotocol(bitseed: &Bitseed): String { + bitseed.metaprotocol + } + + public fun amount(bitseed: &Bitseed): u64 { + bitseed.amount + } + + public fun tick(bitseed: &Bitseed): String { + bitseed.tick + } + + public fun bid(bitseed: &Bitseed): address { + bitseed.bid + } + + public fun content_type(bitseed: &Bitseed): &Option { + &bitseed.content_type + } + + public fun body(bitseed: &Bitseed): &vector { + &bitseed.body + } + + public fun attributes(bitseed: &Bitseed): &SimpleMap { + &bitseed.attributes + } + + public fun content_attributes_hash(bitseed: &Bitseed): address { + bitseed.content_attributes_hash + } + + // ========= Metaprotocol delegate function ========= // + public(friend) fun seal_metaprotocol_validity(inscription_id: InscriptionID, is_valid: bool, invalid_reason: Option){ ord::seal_metaprotocol_validity(inscription_id, is_valid, invalid_reason) } @@ -141,6 +184,14 @@ module rooch_nursery::bitseed { ord::add_metaprotocol_attachment(inscription_id, attachment) } + public(friend) fun exists_metaprotocol_attachment(inscription_id: InscriptionID): bool{ + ord::exists_metaprotocol_attachment(inscription_id) + } + + public(friend) fun remove_metaprotocol_attachment(inscription_id: InscriptionID): Object{ + ord::remove_metaprotocol_attachment(inscription_id) + } + fun drop(bitseed: Bitseed) { let Bitseed { metaprotocol:_, diff --git a/frameworks/rooch-nursery/sources/genesis.move b/frameworks/rooch-nursery/sources/genesis.move index 72f2fbacc3..35ec9e578a 100644 --- a/frameworks/rooch-nursery/sources/genesis.move +++ b/frameworks/rooch-nursery/sources/genesis.move @@ -4,6 +4,7 @@ module rooch_nursery::genesis { use rooch_nursery::ethereum; use rooch_nursery::tick_info; + use rooch_nursery::inscribe_factory; const ErrorInvalidChainId: u64 = 1; @@ -13,6 +14,7 @@ module rooch_nursery::genesis { fun init(genesis_account: &signer){ ethereum::genesis_init(genesis_account); tick_info::genesis_init(); + inscribe_factory::genesis_init(); } #[test_only] diff --git a/frameworks/rooch-nursery/sources/inscribe_factory.move b/frameworks/rooch-nursery/sources/inscribe_factory.move index ad2e54b4a9..aa68ef886c 100644 --- a/frameworks/rooch-nursery/sources/inscribe_factory.move +++ b/frameworks/rooch-nursery/sources/inscribe_factory.move @@ -9,24 +9,51 @@ module rooch_nursery::inscribe_factory { use moveos_std::address; use moveos_std::hash; use moveos_std::hex; - use moveos_std::object::Object; + use moveos_std::object::{Self, Object}; use moveos_std::string_utils; use moveos_std::simple_map::{Self, SimpleMap}; - use rooch_nursery::wasm; + use moveos_std::result::{Self, Result, err_str, ok, is_err, as_err}; use moveos_std::cbor; + use moveos_std::event_queue::{Self, Subscriber}; use bitcoin_move::types; - use bitcoin_move::ord::{Self, Inscription}; + use bitcoin_move::ord::{Self, Inscription, InscriptionID}; use bitcoin_move::bitcoin; use rooch_nursery::bitseed::{Self, Bitseed}; use rooch_nursery::tick_info; - use moveos_std::result::{Self, Result, err_str, ok, is_err, as_err}; + use rooch_nursery::wasm; + + friend rooch_nursery::genesis; + const BIT_SEED_DEPLOY: vector = b"bitseed_deploy"; const BIT_SEED_MINT: vector = b"bitseed_mint"; const BIT_SEED_GENERATOR_TICK: vector = b"generator"; + struct MergeState has store { + inscription_id: InscriptionID, + merge_amount: u64, + txid: address, + burned_inscriptions: vector, + bitseeds: vector>, + } + + struct BitseedEventStore has key { + subscriber: Object>, + merge_state: Option, + } + + public(friend) fun genesis_init() { + let subscriber = event_queue::subscribe(bitseed::default_metaprotocol()); + let store = BitseedEventStore { + subscriber, + merge_state: option::none(), + }; + let store_obj = object::new_named_object(store); + object::to_shared(store_obj); + } + public fun bitseed_deploy_key(): vector { BIT_SEED_DEPLOY } @@ -37,7 +64,7 @@ module rooch_nursery::inscribe_factory { fun is_bitseed(inscription: &Inscription) : bool { let metaprotocol = ord::metaprotocol(inscription); - option::is_some(&metaprotocol) && option::borrow(&metaprotocol) == &bitseed::metaprotocol() + option::is_some(&metaprotocol) && option::borrow(&metaprotocol) == &bitseed::default_metaprotocol() } fun get_SFT_op(metadata: &SimpleMap>) : Option { @@ -259,7 +286,7 @@ module rooch_nursery::inscribe_factory { let deploy_args = get_SFT_bytes_attribute(&attributes, b"deploy_args"); - tick_info::deploy_tick(bitseed::metaprotocol(), tick, inscription_id_option, factory_option, max, repeat, has_user_input, deploy_args); + tick_info::deploy_tick(bitseed::default_metaprotocol(), tick, inscription_id_option, factory_option, max, repeat, has_user_input, deploy_args); (true, option::none()) } @@ -274,11 +301,11 @@ module rooch_nursery::inscribe_factory { let attributes = get_SFT_attributes(metadata); let amount = get_SFT_amount(metadata); - if (!tick_info::is_deployed(bitseed::metaprotocol(), tick)) { + if (!tick_info::is_deployed(bitseed::default_metaprotocol(), tick)) { return err_str(b"the tick is not deployed") }; - let tick_info = tick_info::borrow_tick_info(bitseed::metaprotocol(), tick); + let tick_info = tick_info::borrow_tick_info(bitseed::default_metaprotocol(), tick); let has_user_input = tick_info::has_user_input(tick_info); let deploy_args = option::destroy_with_default(tick_info::deploy_args(tick_info), vector::empty()); @@ -317,11 +344,29 @@ module rooch_nursery::inscribe_factory { return result::err(option::destroy_with_default(reason, utf8(b"inscribe verify fail"))) }; }; - let bitseed_result = tick_info::mint_on_bitcoin(bitseed::metaprotocol(), tick, amount); + let bitseed_result = tick_info::mint_on_bitcoin(bitseed::default_metaprotocol(), tick, amount); bitseed_result } + fun merge_bitseed(bitseeds: vector>): Result, vector>> { + if (vector::length(&bitseeds) == 0){ + return result::err(bitseeds) + }; + let bitseed = vector::pop_back(&mut bitseeds); + while(vector::length(&bitseeds) > 0){ + let bitseed_to_merge = vector::pop_back(&mut bitseeds); + if(!bitseed::is_mergeable(&bitseed, &bitseed_to_merge)){ + vector::push_back(&mut bitseeds, bitseed_to_merge); + vector::push_back(&mut bitseeds, bitseed); + return result::err(bitseeds) + }; + bitseed::merge(&mut bitseed, bitseed_to_merge); + }; + vector::destroy_empty(bitseeds); + ok(bitseed) + } + public fun inscribe_verify(wasm_bytes: vector, deploy_args: vector, seed: vector, user_input: String, metadata: &SimpleMap>, content_type: Option, body: vector): (bool, Option) { @@ -454,40 +499,86 @@ 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) } // ==== Process Bitseed Entry ==== // - public fun process_inscription(inscription: &Inscription) { - let txid = ord::txid(inscription); - let index = ord::index(inscription); - let inscription_id = ord::new_inscription_id(txid, index); - if (is_bitseed(inscription)) { + public entry fun process_bitseed_event(batch_size: u64) { + let store_obj_id = object::named_object_id(); + let event_store_obj = object::borrow_mut_object_shared(store_obj_id); + let event_store = object::borrow_mut(event_store_obj); + let count = 0; + while (count < batch_size) { + let event_opt = event_queue::consume(&mut event_store.subscriber); + + if (option::is_some(&event_opt)){ + let event = option::destroy_some(event_opt); + let (_metaprotocol, _sequence_number, inscription_obj_id, event_type) = ord::unpack_inscription_event(event); + + let inscription_obj = object::borrow_object(inscription_obj_id); + let inscription = object::borrow(inscription_obj); + if (event_type == ord::inscription_event_type_new()){ + if(option::is_some(&event_store.merge_state)){ + let merge_state = option::extract(&mut event_store.merge_state); + finish_merge(merge_state); + }; + process_inscription(inscription, event_store); + }else { + let inscription_id = *ord::id(inscription); + let location = ord::location(inscription); + let outpoint = ord::satpoint_outpoint(location); + let txid = types::outpoint_txid(outpoint); + if(option::is_some(&event_store.merge_state)) { + let merge_state = option::extract(&mut event_store.merge_state); + if(txid == merge_state.txid){ + vector::push_back(&mut merge_state.burned_inscriptions, inscription_id); + if(bitseed::exists_metaprotocol_attachment(inscription_id)){ + let bitseed_obj = bitseed::remove_metaprotocol_attachment(inscription_id); + vector::push_back(&mut merge_state.bitseeds, bitseed_obj); + }; + }; + if (can_finish_merge(&merge_state)) { + finish_merge(merge_state); + }else{ + option::fill(&mut event_store.merge_state, merge_state); + }; + }; + }; + }else{ + break + }; + count = count + 1; + }; + } + + fun process_inscription(inscription: &Inscription, event_store: &mut BitseedEventStore) { + if (is_bitseed(inscription)) { + let inscription_id = *ord::id(inscription); let metadata_bytes = ord::metadata(inscription); let metadata = cbor::to_map(metadata_bytes); @@ -529,15 +620,68 @@ module rooch_nursery::inscribe_factory { } else if (option::borrow(&op) == &string::utf8(b"split")) { bitseed::seal_metaprotocol_validity(inscription_id, true, option::none()); } else if (option::borrow(&op) == &string::utf8(b"merge")) { - bitseed::seal_metaprotocol_validity(inscription_id, true, option::none()); + let location = ord::location(inscription); + let outpoint = ord::satpoint_outpoint(location); + let txid = types::outpoint_txid(outpoint); + let merge_state = MergeState{ + inscription_id, + merge_amount: get_SFT_amount(&metadata), + txid: txid, + burned_inscriptions: vector::empty(), + bitseeds: vector::empty(), + }; + option::fill(&mut event_store.merge_state, merge_state); } else { bitseed::seal_metaprotocol_validity(inscription_id, false, option::some(string::utf8(b"invalid op"))); } } else { bitseed::seal_metaprotocol_validity(inscription_id, false, option::some(string::utf8(b"op not found"))); }; + }; + } + + fun can_finish_merge(merge_state: &MergeState) : bool { + let len = vector::length(&merge_state.bitseeds); + let index = 0; + let total_amount = 0; + while(index < len){ + let bitseed_obj = vector::borrow(&merge_state.bitseeds, index); + total_amount = total_amount + bitseed::amount(object::borrow(bitseed_obj)); + index = index + 1; + }; + total_amount >= merge_state.merge_amount + } - } + fun finish_merge(merge_state: MergeState){ + let MergeState{inscription_id, merge_amount, txid:_, burned_inscriptions:_, bitseeds} = merge_state; + + let merge_result = merge_bitseed(bitseeds); + let (o,e) = result::unpack(merge_result); + if(option::is_some(&o)){ + option::destroy_none(e); + let bitseed_obj = option::destroy_some(o); + let real_amount = bitseed::amount(object::borrow(&bitseed_obj)); + if (merge_amount == real_amount) { + bitseed::add_metaprotocol_attachment(inscription_id, bitseed_obj); + bitseed::seal_metaprotocol_validity(inscription_id, true, option::none()); + }else if (merge_amount < real_amount) { + let split_amount = real_amount - merge_amount; + let redundant_bitseed = bitseed::split(&mut bitseed_obj, split_amount); + tick_info::burn(redundant_bitseed); + bitseed::add_metaprotocol_attachment(inscription_id, bitseed_obj); + bitseed::seal_metaprotocol_validity(inscription_id, true, option::none()); + }else{ + tick_info::burn(bitseed_obj); + bitseed::seal_metaprotocol_validity(inscription_id, false, option::some(string::utf8(b"merge amount not match"))); + }; + }else{ + option::destroy_none(o); + let bitseeds = option::destroy_some(e); + vector::for_each(bitseeds, |bitseed_obj|{ + tick_info::burn(bitseed_obj); + }); + bitseed::seal_metaprotocol_validity(inscription_id, false, option::some(string::utf8(b"merge fail"))); + }; } #[test_only] @@ -545,7 +689,7 @@ module rooch_nursery::inscribe_factory { #[test(genesis_account=@0x4)] fun test_is_valid_bitseed_deploy_ok(genesis_account: &signer){ - let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::metaprotocol()); + let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::default_metaprotocol()); bitseed::seal_metaprotocol_validity(test_inscription_id, true, option::none()); let metadata_bytes = x"a4626f70666465706c6f79647469636b646d6f766566616d6f756e74016a61747472696275746573a16967656e657261746f72784f2f696e736372697074696f6e2f373764666332666535393834313962303036343163323936313831613936636631363934333639376635373334383062303233623737636365383261646132316930"; @@ -649,7 +793,7 @@ module rooch_nursery::inscribe_factory { #[test(genesis_account=@0x4)] fun test_is_valid_bitseed_deploy_fail_for_inscription_metaprotocol_validity_not_exists(genesis_account: &signer){ - let (_test_address, _test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::metaprotocol()); + let (_test_address, _test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::default_metaprotocol()); let metadata_bytes = x"a4626f70666465706c6f79647469636b646d6f766566616d6f756e74016a61747472696275746573a16967656e657261746f72784f2f696e736372697074696f6e2f373764666332666535393834313962303036343163323936313831613936636631363934333639376635373334383062303233623737636365383261646132316930"; let metadata = cbor::to_map(metadata_bytes); @@ -676,7 +820,7 @@ module rooch_nursery::inscribe_factory { #[test(genesis_account=@0x4)] fun test_is_valid_bitseed_deploy_fail_for_inscription_metaprotocol_validity_not_valid(genesis_account: &signer){ - let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::metaprotocol()); + let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::default_metaprotocol()); bitseed::seal_metaprotocol_validity(test_inscription_id, false, option::none()); let metadata_bytes = x"a4626f70666465706c6f79647469636b646d6f766566616d6f756e74016a61747472696275746573a16967656e657261746f72784f2f696e736372697074696f6e2f373764666332666535393834313962303036343163323936313831613936636631363934333639376635373334383062303233623737636365383261646132316930"; @@ -692,7 +836,7 @@ module rooch_nursery::inscribe_factory { fun test_deploy_tick_ok(genesis_account: &signer){ tick_info::init_for_testing(); - let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::metaprotocol()); + let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::default_metaprotocol()); bitseed::seal_metaprotocol_validity(test_inscription_id, true, option::none()); let metadata_bytes = x"a4626f70666465706c6f79647469636b646d6f766566616d6f756e74016a61747472696275746573a16967656e657261746f72784f2f696e736372697074696f6e2f373764666332666535393834313962303036343163323936313831613936636631363934333639376635373334383062303233623737636365383261646132316930"; @@ -703,9 +847,9 @@ module rooch_nursery::inscribe_factory { assert!(ok, 1); assert!(option::is_none(&reason), 1); - assert!(tick_info::is_deployed(bitseed::metaprotocol(), string::utf8(b"move")), 2); + assert!(tick_info::is_deployed(bitseed::default_metaprotocol(), string::utf8(b"move")), 2); - let tick_info = tick_info::borrow_tick_info(bitseed::metaprotocol(), string::utf8(b"move")); + let tick_info = tick_info::borrow_tick_info(bitseed::default_metaprotocol(), string::utf8(b"move")); // check tick let tick = tick_info::tick(tick_info); @@ -747,7 +891,7 @@ module rooch_nursery::inscribe_factory { fun test_is_valid_bitseed_mint_fail_with_tick_not_deploy(genesis_account: &signer){ tick_info::init_for_testing(); - let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::metaprotocol()); + let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::default_metaprotocol()); bitseed::seal_metaprotocol_validity(test_inscription_id, true, option::none()); let metadata_bytes = x"a4626f70666465706c6f79647469636b646d6f766566616d6f756e74016a61747472696275746573a16967656e657261746f72784f2f696e736372697074696f6e2f373764666332666535393834313962303036343163323936313831613936636631363934333639376635373334383062303233623737636365383261646132316930"; @@ -766,7 +910,7 @@ module rooch_nursery::inscribe_factory { fun test_is_valid_bitseed_mint_fail_with_maximum_supply_exceeded(genesis_account: &signer){ tick_info::init_for_testing(); - let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::metaprotocol()); + let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::default_metaprotocol()); bitseed::seal_metaprotocol_validity(test_inscription_id, true, option::none()); let metadata_bytes = x"a4626f70666465706c6f79647469636b646d6f766566616d6f756e74016a61747472696275746573a16967656e657261746f72784f2f696e736372697074696f6e2f373764666332666535393834313962303036343163323936313831613936636631363934333639376635373334383062303233623737636365383261646132316930"; @@ -800,7 +944,7 @@ module rooch_nursery::inscribe_factory { fun test_is_valid_bitseed_mint_fail_with_user_input_is_required(genesis_account: &signer){ tick_info::init_for_testing(); - let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::metaprotocol()); + let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::default_metaprotocol()); bitseed::seal_metaprotocol_validity(test_inscription_id, true, option::none()); let metadata_bytes = x"a4626f70666465706c6f79647469636b646d6f766566616d6f756e741927106a61747472696275746573a466726570656174056967656e657261746f72784f2f696e736372697074696f6e2f3737646663326665353938343139623030363431633239363138316139366366313639343336393766353733343830623032336237376363653832616461323169306e6861735f757365725f696e707574f56b6465706c6f795f617267738178377b22686569676874223a7b2274797065223a2272616e6765222c2264617461223a7b226d696e223a312c226d6178223a313030307d7d7d"; @@ -833,7 +977,7 @@ module rooch_nursery::inscribe_factory { features::init_and_enable_all_features_for_test(); tick_info::init_for_testing(); - let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::metaprotocol()); + let (_test_address, test_inscription_id) = ord::setup_inscription_for_test(genesis_account, bitseed::default_metaprotocol()); bitseed::seal_metaprotocol_validity(test_inscription_id, true, option::none()); let metadata_bytes = x"a4626f70666465706c6f79647469636b646d6f766566616d6f756e741927106a61747472696275746573a466726570656174056967656e657261746f72784f2f696e736372697074696f6e2f3737646663326665353938343139623030363431633239363138316139366366313639343336393766353733343830623032336237376363653832616461323169306e6861735f757365725f696e707574f56b6465706c6f795f617267738178377b22686569676874223a7b2274797065223a2272616e6765222c2264617461223a7b226d696e223a312c226d6178223a313030307d7d7d"; @@ -874,13 +1018,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/frameworks/rooch-nursery/sources/tick_info.move b/frameworks/rooch-nursery/sources/tick_info.move index f70176a237..dc285d7307 100644 --- a/frameworks/rooch-nursery/sources/tick_info.move +++ b/frameworks/rooch-nursery/sources/tick_info.move @@ -63,9 +63,9 @@ module rooch_nursery::tick_info { //u64max let max = 18_446_744_073_709_551_615u64; - deploy_tick(bitseed::metaprotocol(), tick, option::none(), option::none(), max, repeat, has_user_input, option::none()); + deploy_tick(bitseed::default_metaprotocol(), tick, option::none(), option::none(), max, repeat, has_user_input, option::none()); let module_signer = moveos_std::signer::module_signer(); - ord::register_metaprotocol_via_system(&module_signer, bitseed::metaprotocol()); + ord::register_metaprotocol_via_system(&module_signer, bitseed::default_metaprotocol()); } /// Check if the tick is deployed. @@ -162,6 +162,15 @@ module rooch_nursery::tick_info { bitseed } + public fun burn(bitseed_obj: Object){ + let bitseed = object::borrow(&bitseed_obj); + let metaprotocol = bitseed::metaprotocol(bitseed); + let tick = bitseed::tick(bitseed); + let tick_info = borrow_mut_tick_info(metaprotocol, tick); + let amount = bitseed::burn(bitseed_obj); + tick_info.supply = tick_info.supply - amount; + } + public(friend) fun mint_on_bitcoin(metaprotocol: String, tick: String, amount: u64) : Result,String>{ let tick = string_utils::to_lower_case(&tick); let tick_info = borrow_mut_tick_info(metaprotocol, tick); 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 0000000000..3ead3cebb8 Binary files /dev/null and b/generator/cpp/generator.wasm differ 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