diff --git a/.config/nextest.toml b/.config/nextest.toml index 4c0844adc6..8dbbaba6ec 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -16,6 +16,14 @@ status-level = "slow" [test-groups] slashing = { max-threads = 1 } +# Bedrock proves every transaction it funds, so a runner's cores go to the nodes: the binaries +# with the most tests take turns at them. +bedrock-heavy = { max-threads = 2 } + [[profile.default.overrides]] filter = 'binary(slashing) + test(/^any_program::/) + test(/^system_upgrade::/)' test-group = 'slashing' + +[[profile.default.overrides]] +filter = 'binary(sequencer_ffi) + binary(wallet_ffi_non_generic_transfers)' +test-group = 'bedrock-heavy' diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 7c3d0bf8c6..9cf4f4a42d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -85,6 +85,7 @@ /lez/sequencer/core/ @schouhy @erhant @arjentix /lez/sequencer/genesis/ @schouhy @erhant @arjentix /lez/sequencer/bridge/ @schouhy @erhant @arjentix +/lez/vault_circuit/ @erhant /lez/sequencer/service/ @arjentix @schouhy @erhant /lez/mempool/ @arjentix @erhant diff --git a/Cargo.lock b/Cargo.lock index d72032be8a..daa0a98205 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -258,6 +258,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ark-bls12-381" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3df4dcc01ff89867cd86b0da835f23c3f02738353aaee7dde7495af71363b8d5" +dependencies = [ + "ark-ec", + "ark-ff", + "ark-serialize", + "ark-std", +] + [[package]] name = "ark-bn254" version = "0.5.0" @@ -289,6 +301,7 @@ dependencies = [ "digest 0.10.7", "fnv", "merlin", + "rayon", "sha2 0.10.9", ] @@ -321,9 +334,23 @@ dependencies = [ "num-bigint 0.4.6", "num-integer", "num-traits", + "rayon", "zeroize", ] +[[package]] +name = "ark-ed-on-bn254" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "962e24e25cbdcaabe619c281a62bccc885f778b188129d6a02875c2671666219" +dependencies = [ + "ark-bn254", + "ark-ec", + "ark-ff", + "ark-r1cs-std", + "ark-std", +] + [[package]] name = "ark-ff" version = "0.5.0" @@ -341,6 +368,7 @@ dependencies = [ "num-bigint 0.4.6", "num-traits", "paste", + "rayon", "zeroize", ] @@ -380,6 +408,7 @@ dependencies = [ "ark-relations", "ark-serialize", "ark-std", + "rayon", ] [[package]] @@ -395,6 +424,7 @@ dependencies = [ "educe 0.6.0", "fnv", "hashbrown 0.15.5", + "rayon", ] [[package]] @@ -437,6 +467,7 @@ dependencies = [ "arrayvec", "digest 0.10.7", "num-bigint 0.4.6", + "rayon", ] [[package]] @@ -470,6 +501,7 @@ checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a" dependencies = [ "num-traits", "rand 0.8.6", + "rayon", ] [[package]] @@ -1109,7 +1141,7 @@ dependencies = [ [[package]] name = "blockchain-test-logos" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "anyhow", "async-trait", @@ -1125,9 +1157,11 @@ dependencies = [ "logos-blockchain-common-http-client", "logos-blockchain-config", "logos-blockchain-core", + "logos-blockchain-groth16", "logos-blockchain-http-api-common", "logos-blockchain-key-management-system-service", "logos-blockchain-libp2p", + "logos-blockchain-mmr", "logos-blockchain-network-service", "logos-blockchain-node", "logos-blockchain-sdp-service", @@ -1156,7 +1190,7 @@ dependencies = [ [[package]] name = "blockchain-test-support" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "hex", "logos-blockchain-binary-codec", @@ -1575,6 +1609,7 @@ dependencies = [ "anyhow", "async-trait", "borsh", + "bridge_core", "clock_core", "common", "fee_core", @@ -1585,6 +1620,7 @@ dependencies = [ "logos-blockchain-zone-sdk", "program_loader_core", "programs", + "sequencer_bridge", "sequencer_stake_core", "serde", "serde_json", @@ -1596,6 +1632,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tracing", + "vault_circuit", ] [[package]] @@ -2661,7 +2698,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccc2776f0c61eca1ca32528f85548abd1a4be8fb53d1b21c013e4f18da1e7090" dependencies = [ "data-encoding", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] @@ -5058,6 +5095,7 @@ dependencies = [ "borsh", "bridge_core", "bridge_lock_core", + "chain_state", "common", "core_ffi", "cross_zone", @@ -5098,6 +5136,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber 0.3.23", + "vault_circuit", "wallet", "wrapped_token_core", ] @@ -5201,6 +5240,7 @@ name = "jf-poseidon2" version = "0.2.0" source = "git+https://github.com/EspressoSystems/jellyfish.git?rev=8d80230358e900f8d63765a937f63f4978ca1daa#8d80230358e900f8d63765a937f63f4978ca1daa" dependencies = [ + "ark-bls12-381", "ark-bn254", "ark-ff", "ark-std", @@ -7065,17 +7105,17 @@ dependencies = [ [[package]] name = "logos-blockchain-api-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "futures", "logos-blockchain-binary-codec", "logos-blockchain-blend-service", "logos-blockchain-chain-broadcast-service", - "logos-blockchain-chain-leader-service", "logos-blockchain-chain-service", "logos-blockchain-core", "logos-blockchain-key-management-system-keys", + "logos-blockchain-kv-store", "logos-blockchain-ledger", "logos-blockchain-libp2p", "logos-blockchain-log-targets", @@ -7085,7 +7125,6 @@ dependencies = [ "logos-blockchain-storage-service", "logos-blockchain-time-service", "logos-blockchain-tx-service", - "logos-blockchain-wallet-service", "overwatch", "serde", "thiserror 2.0.18", @@ -7098,7 +7137,7 @@ dependencies = [ [[package]] name = "logos-blockchain-binary-codec" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "bincode", "bytes", @@ -7114,7 +7153,7 @@ dependencies = [ [[package]] name = "logos-blockchain-binary-codec-macros" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "hex", "proc-macro2", @@ -7125,7 +7164,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-blend-crypto", "logos-blockchain-blend-membership", @@ -7140,7 +7179,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-crypto" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "blake2", "logos-blockchain-groth16", @@ -7155,7 +7194,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-membership" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-key-management-system-keys", "multiaddr 0.18.2", @@ -7166,7 +7205,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-message" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "blake2", "educe 0.7.6", @@ -7193,7 +7232,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-network" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "either", "futures", @@ -7214,7 +7253,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-primitives" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "futures", "tokio", @@ -7223,7 +7262,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-proofs" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "ed25519-dalek 2.2.0", "generic-array 1.4.3", @@ -7245,7 +7284,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-provers" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "educe 0.7.6", @@ -7269,7 +7308,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-scheduling" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "fork_stream", "futures", @@ -7290,7 +7329,7 @@ dependencies = [ [[package]] name = "logos-blockchain-blend-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "futures", @@ -7331,7 +7370,7 @@ dependencies = [ [[package]] name = "logos-blockchain-chain-broadcast-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "educe 0.7.6", @@ -7346,7 +7385,7 @@ dependencies = [ [[package]] name = "logos-blockchain-chain-leader-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "futures", @@ -7359,6 +7398,7 @@ dependencies = [ "logos-blockchain-key-management-system-service", "logos-blockchain-ledger", "logos-blockchain-log-targets", + "logos-blockchain-pol", "logos-blockchain-services-utils", "logos-blockchain-storage-service", "logos-blockchain-time-service", @@ -7367,7 +7407,6 @@ dependencies = [ "logos-blockchain-utils", "logos-blockchain-wallet-service", "overwatch", - "rand 0.8.6", "serde", "thiserror 2.0.18", "tokio", @@ -7379,7 +7418,7 @@ dependencies = [ [[package]] name = "logos-blockchain-chain-network-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "backon", @@ -7413,7 +7452,7 @@ dependencies = [ [[package]] name = "logos-blockchain-chain-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "bytes", @@ -7425,7 +7464,7 @@ dependencies = [ "logos-blockchain-cryptarchia-engine", "logos-blockchain-cryptarchia-sync", "logos-blockchain-groth16", - "logos-blockchain-key-management-system-keys", + "logos-blockchain-kv-store", "logos-blockchain-ledger", "logos-blockchain-log-targets", "logos-blockchain-network-service", @@ -7447,8 +7486,8 @@ dependencies = [ [[package]] name = "logos-blockchain-circuits-build" -version = "0.5.7" -source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.5.7#ebf7ddf5b5b625ef4ea7c803171c670beebd05ef" +version = "0.7.3" +source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.7.3#6ac94979fef0dfb74d909c8422d5a999e3190eef" dependencies = [ "dirs", "fd-lock", @@ -7459,16 +7498,16 @@ dependencies = [ [[package]] name = "logos-blockchain-circuits-common" -version = "0.5.7" -source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.5.7#ebf7ddf5b5b625ef4ea7c803171c670beebd05ef" +version = "0.7.3" +source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.7.3#6ac94979fef0dfb74d909c8422d5a999e3190eef" dependencies = [ "logos-blockchain-circuits-types", ] [[package]] -name = "logos-blockchain-circuits-poc-sys" -version = "0.5.7" -source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.5.7#ebf7ddf5b5b625ef4ea7c803171c670beebd05ef" +name = "logos-blockchain-circuits-pol-sys" +version = "0.7.3" +source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.7.3#6ac94979fef0dfb74d909c8422d5a999e3190eef" dependencies = [ "logos-blockchain-circuits-build", "logos-blockchain-circuits-common", @@ -7476,9 +7515,9 @@ dependencies = [ ] [[package]] -name = "logos-blockchain-circuits-pol-sys" -version = "0.5.7" -source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.5.7#ebf7ddf5b5b625ef4ea7c803171c670beebd05ef" +name = "logos-blockchain-circuits-poq-sys" +version = "0.7.3" +source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.7.3#6ac94979fef0dfb74d909c8422d5a999e3190eef" dependencies = [ "logos-blockchain-circuits-build", "logos-blockchain-circuits-common", @@ -7486,9 +7525,9 @@ dependencies = [ ] [[package]] -name = "logos-blockchain-circuits-poq-sys" -version = "0.5.7" -source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.5.7#ebf7ddf5b5b625ef4ea7c803171c670beebd05ef" +name = "logos-blockchain-circuits-program-spend-sys" +version = "0.7.3" +source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.7.3#6ac94979fef0dfb74d909c8422d5a999e3190eef" dependencies = [ "logos-blockchain-circuits-build", "logos-blockchain-circuits-common", @@ -7498,15 +7537,15 @@ dependencies = [ [[package]] name = "logos-blockchain-circuits-prover" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "rust-rapidsnark", ] [[package]] -name = "logos-blockchain-circuits-signature-sys" -version = "0.5.7" -source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.5.7#ebf7ddf5b5b625ef4ea7c803171c670beebd05ef" +name = "logos-blockchain-circuits-transfer-sys" +version = "0.7.3" +source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.7.3#6ac94979fef0dfb74d909c8422d5a999e3190eef" dependencies = [ "logos-blockchain-circuits-build", "logos-blockchain-circuits-common", @@ -7515,8 +7554,8 @@ dependencies = [ [[package]] name = "logos-blockchain-circuits-types" -version = "0.5.7" -source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.5.7#ebf7ddf5b5b625ef4ea7c803171c670beebd05ef" +version = "0.7.3" +source = "git+https://github.com/logos-blockchain/logos-blockchain-circuits.git?tag=v0.7.3#6ac94979fef0dfb74d909c8422d5a999e3190eef" dependencies = [ "bytes", "libc", @@ -7525,7 +7564,7 @@ dependencies = [ [[package]] name = "logos-blockchain-common-http-client" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "futures", "hex", @@ -7551,14 +7590,14 @@ dependencies = [ [[package]] name = "logos-blockchain-config" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "hex", "logos-blockchain-binary-codec", "logos-blockchain-core", - "logos-blockchain-cryptarchia-engine", "logos-blockchain-groth16", "logos-blockchain-key-management-system-service", + "logos-blockchain-ledger", "logos-blockchain-libp2p", "logos-blockchain-node", "logos-blockchain-sdp-service", @@ -7573,7 +7612,7 @@ dependencies = [ [[package]] name = "logos-blockchain-core" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "ark-ff", "bincode", @@ -7583,17 +7622,20 @@ dependencies = [ "logos-blockchain-binary-codec", "logos-blockchain-blend-proofs", "logos-blockchain-cryptarchia-engine", + "logos-blockchain-dynamic-merkle", "logos-blockchain-groth16", + "logos-blockchain-imt", "logos-blockchain-key-management-system-keys", + "logos-blockchain-kv-store", "logos-blockchain-log-targets", "logos-blockchain-mmr", - "logos-blockchain-poc", "logos-blockchain-pol", "logos-blockchain-poseidon2", + "logos-blockchain-program-spend", "logos-blockchain-time", "logos-blockchain-utils", "logos-blockchain-utxotree", - "logos-blockchain-zksign", + "logos-blockchain-zktransfer", "multiaddr 0.18.2", "num-bigint 0.4.6", "rpds", @@ -7608,7 +7650,7 @@ dependencies = [ [[package]] name = "logos-blockchain-cryptarchia-engine" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-log-targets", "logos-blockchain-pol", @@ -7624,7 +7666,7 @@ dependencies = [ [[package]] name = "logos-blockchain-cryptarchia-sync" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "bytes", "educe 0.7.6", @@ -7647,7 +7689,7 @@ dependencies = [ [[package]] name = "logos-blockchain-dynamic-merkle" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "serde", ] @@ -7655,7 +7697,7 @@ dependencies = [ [[package]] name = "logos-blockchain-groth16" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "ark-bn254", "ark-ec", @@ -7676,10 +7718,11 @@ dependencies = [ [[package]] name = "logos-blockchain-http-api-common" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "axum 0.8.9", "logos-blockchain-core", + "logos-blockchain-groth16", "logos-blockchain-key-management-system-keys", "logos-blockchain-log-targets", "logos-blockchain-tracing", @@ -7694,10 +7737,26 @@ dependencies = [ "validator", ] +[[package]] +name = "logos-blockchain-imt" +version = "0.0.0" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" +dependencies = [ + "ark-ff", + "logos-blockchain-dynamic-merkle", + "logos-blockchain-groth16", + "logos-blockchain-kv-store", + "logos-blockchain-poseidon2", + "logos-blockchain-utxotree", + "rpds", + "serde", + "thiserror 2.0.18", +] + [[package]] name = "logos-blockchain-key-management-system-keys" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "arbitrary-int", "async-trait", @@ -7705,21 +7764,18 @@ dependencies = [ "blake2", "bytes", "ed25519-dalek 2.2.0", - "generic-array 1.4.3", "hex", "logos-blockchain-binary-codec", "logos-blockchain-groth16", "logos-blockchain-key-management-system-macros", - "logos-blockchain-log-targets", "logos-blockchain-poseidon2", "logos-blockchain-utils", - "logos-blockchain-zksign", + "logos-blockchain-zktransfer", "num-bigint 0.4.6", "rand_core 0.6.4", "serde", "subtle", "thiserror 2.0.18", - "tracing", "utoipa", "x25519-dalek", "zeroize", @@ -7728,7 +7784,7 @@ dependencies = [ [[package]] name = "logos-blockchain-key-management-system-macros" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "proc-macro2", "quote", @@ -7738,7 +7794,7 @@ dependencies = [ [[package]] name = "logos-blockchain-key-management-system-operators" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "logos-blockchain-blend-proofs", @@ -7746,9 +7802,9 @@ dependencies = [ "logos-blockchain-groth16", "logos-blockchain-key-management-system-keys", "logos-blockchain-log-targets", + "logos-blockchain-pol", "logos-blockchain-poseidon2", "logos-blockchain-utils", - "logos-blockchain-utxotree", "tokio", "tracing", ] @@ -7756,7 +7812,7 @@ dependencies = [ [[package]] name = "logos-blockchain-key-management-system-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "logos-blockchain-key-management-system-keys", @@ -7771,10 +7827,20 @@ dependencies = [ "tracing", ] +[[package]] +name = "logos-blockchain-kv-store" +version = "0.0.0" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" +dependencies = [ + "bytes", + "rocksdb", + "thiserror 2.0.18", +] + [[package]] name = "logos-blockchain-ledger" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "educe 0.7.6", "logos-blockchain-binary-codec", @@ -7784,18 +7850,18 @@ dependencies = [ "logos-blockchain-core", "logos-blockchain-cryptarchia-engine", "logos-blockchain-groth16", + "logos-blockchain-imt", "logos-blockchain-key-management-system-keys", + "logos-blockchain-kv-store", "logos-blockchain-log-targets", "logos-blockchain-mmr", "logos-blockchain-pol", "logos-blockchain-time", "logos-blockchain-utils", - "logos-blockchain-utxotree", "num-bigint 0.4.6", "rand 0.8.6", "rpds", "serde", - "serde_arrays", "thiserror 2.0.18", "tracing", ] @@ -7803,7 +7869,7 @@ dependencies = [ [[package]] name = "logos-blockchain-libp2p" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "backon", @@ -7834,7 +7900,7 @@ dependencies = [ [[package]] name = "logos-blockchain-log-targets" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-log-targets-macros", ] @@ -7842,28 +7908,17 @@ dependencies = [ [[package]] name = "logos-blockchain-log-targets-macros" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "proc-macro2", "quote", "syn 2.0.117", ] -[[package]] -name = "logos-blockchain-merkle-tree" -version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" -dependencies = [ - "logos-blockchain-dynamic-merkle", - "rpds", - "serde", - "thiserror 2.0.18", -] - [[package]] name = "logos-blockchain-mmr" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "ark-ff", "logos-blockchain-groth16", @@ -7877,7 +7932,7 @@ dependencies = [ [[package]] name = "logos-blockchain-network-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "educe 0.7.6", @@ -7904,7 +7959,7 @@ dependencies = [ [[package]] name = "logos-blockchain-node" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "axum 0.8.9", @@ -7928,6 +7983,7 @@ dependencies = [ "logos-blockchain-groth16", "logos-blockchain-http-api-common", "logos-blockchain-key-management-system-service", + "logos-blockchain-kv-store", "logos-blockchain-ledger", "logos-blockchain-libp2p", "logos-blockchain-log-targets", @@ -7969,27 +8025,10 @@ dependencies = [ "validator", ] -[[package]] -name = "logos-blockchain-poc" -version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" -dependencies = [ - "logos-blockchain-circuits-poc-sys", - "logos-blockchain-circuits-prover", - "logos-blockchain-circuits-types", - "logos-blockchain-groth16", - "logos-blockchain-log-targets", - "logos-blockchain-proofs-error", - "num-bigint 0.4.6", - "serde", - "serde_json", - "tracing", -] - [[package]] name = "logos-blockchain-pol" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "astro-float", "logos-blockchain-circuits-pol-sys", @@ -8003,13 +8042,14 @@ dependencies = [ "num-traits", "serde", "serde_json", + "serde_with", "tracing", ] [[package]] name = "logos-blockchain-poq" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-circuits-poq-sys", "logos-blockchain-circuits-prover", @@ -8021,13 +8061,14 @@ dependencies = [ "num-bigint 0.4.6", "serde", "serde_json", + "serde_with", "tracing", ] [[package]] name = "logos-blockchain-poseidon2" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "ark-bn254", "ark-ff", @@ -8038,7 +8079,7 @@ dependencies = [ [[package]] name = "logos-blockchain-pow-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "futures", @@ -8056,7 +8097,7 @@ dependencies = [ "logos-blockchain-time-service", "logos-blockchain-utils", "logos-blockchain-wallet-service", - "logos-blockchain-zksign", + "logos-blockchain-zktransfer", "overwatch", "rand 0.8.6", "rayon", @@ -8067,10 +8108,29 @@ dependencies = [ "tracing", ] +[[package]] +name = "logos-blockchain-program-spend" +version = "0.0.0" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" +dependencies = [ + "logos-blockchain-circuits-program-spend-sys", + "logos-blockchain-circuits-prover", + "logos-blockchain-circuits-types", + "logos-blockchain-groth16", + "logos-blockchain-log-targets", + "logos-blockchain-proofs-error", + "logos-blockchain-zktransfer", + "serde", + "serde_json", + "serde_with", + "thiserror 2.0.18", + "tracing", +] + [[package]] name = "logos-blockchain-proofs-error" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-circuits-types", "logos-blockchain-groth16", @@ -8081,7 +8141,7 @@ dependencies = [ [[package]] name = "logos-blockchain-sdp-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "logos-blockchain-chain-service", @@ -8104,7 +8164,7 @@ dependencies = [ [[package]] name = "logos-blockchain-services-utils" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "bytes", @@ -8114,13 +8174,14 @@ dependencies = [ "overwatch", "serde", "thiserror 2.0.18", + "tokio", "tracing", ] [[package]] name = "logos-blockchain-storage-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "bytes", @@ -8143,7 +8204,7 @@ dependencies = [ [[package]] name = "logos-blockchain-system-sig-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-ctrlc", "async-trait", @@ -8155,7 +8216,7 @@ dependencies = [ [[package]] name = "logos-blockchain-time" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-binary-codec", "logos-blockchain-utils", @@ -8168,7 +8229,7 @@ dependencies = [ [[package]] name = "logos-blockchain-time-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "futures", @@ -8191,7 +8252,7 @@ dependencies = [ [[package]] name = "logos-blockchain-tracing" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "flate2", "logos-blockchain-log-targets", @@ -8218,7 +8279,7 @@ dependencies = [ [[package]] name = "logos-blockchain-tracing-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "logos-blockchain-log-targets", @@ -8236,7 +8297,7 @@ dependencies = [ [[package]] name = "logos-blockchain-tx-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "futures", @@ -8266,7 +8327,7 @@ dependencies = [ [[package]] name = "logos-blockchain-utils" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "const-hex", @@ -8290,20 +8351,17 @@ dependencies = [ [[package]] name = "logos-blockchain-utxotree" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "ark-ff", "logos-blockchain-dynamic-merkle", - "logos-blockchain-merkle-tree", "logos-blockchain-poseidon2", - "rpds", - "serde", ] [[package]] name = "logos-blockchain-version" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "serde", "utoipa", @@ -8312,16 +8370,16 @@ dependencies = [ [[package]] name = "logos-blockchain-wallet" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-core", "logos-blockchain-cryptarchia-engine", + "logos-blockchain-groth16", "logos-blockchain-key-management-system-keys", - "logos-blockchain-ledger", "logos-blockchain-log-targets", "logos-blockchain-mmr", "logos-blockchain-utils", - "num-bigint 0.4.6", + "logos-blockchain-zktransfer", "rpds", "serde", "thiserror 2.0.18", @@ -8331,7 +8389,7 @@ dependencies = [ [[package]] name = "logos-blockchain-wallet-service" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "async-trait", "bytes", @@ -8353,7 +8411,9 @@ dependencies = [ "logos-blockchain-utils", "logos-blockchain-wallet", "overwatch", + "rand 0.8.6", "serde", + "strum_macros 0.27.2", "thiserror 2.0.18", "tokio", "tokio-stream", @@ -8361,21 +8421,19 @@ dependencies = [ ] [[package]] -name = "logos-blockchain-zksign" +name = "logos-blockchain-zktransfer" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=a159f8c155df68d7e2f045a418ae737de246354e#a159f8c155df68d7e2f045a418ae737de246354e" +source = "git+https://github.com/logos-blockchain/logos-blockchain.git?rev=767cf967b23b471869a7cae4cb5a6fa54f9389ac#767cf967b23b471869a7cae4cb5a6fa54f9389ac" dependencies = [ "logos-blockchain-circuits-prover", - "logos-blockchain-circuits-signature-sys", + "logos-blockchain-circuits-transfer-sys", "logos-blockchain-circuits-types", "logos-blockchain-groth16", "logos-blockchain-log-targets", - "logos-blockchain-poseidon2", "logos-blockchain-proofs-error", - "num-bigint 0.4.6", "serde", - "serde-big-array", "serde_json", + "serde_with", "thiserror 2.0.18", "tracing", ] @@ -8383,8 +8441,9 @@ dependencies = [ [[package]] name = "logos-blockchain-zone-sdk" version = "0.0.0" -source = "git+https://github.com/logos-blockchain/logos-zone-sdk.git?rev=1b5073a10caaa63cbbd825bd4397f2f1fb48b33a#1b5073a10caaa63cbbd825bd4397f2f1fb48b33a" +source = "git+https://github.com/logos-blockchain/logos-zone-sdk.git?rev=1f95999f474d2fae12a8ad4e3afd218678fb4799#1f95999f474d2fae12a8ad4e3afd218678fb4799" dependencies = [ + "ark-ff", "async-trait", "blockchain-test-logos", "futures", @@ -8396,8 +8455,10 @@ dependencies = [ "logos-blockchain-http-api-common", "logos-blockchain-key-management-system-service", "logos-blockchain-log-targets", + "logos-blockchain-mmr", + "logos-blockchain-program-spend", "logos-blockchain-time", - "rand 0.8.6", + "logos-blockchain-wallet", "reqwest 0.12.28", "rpds", "serde", @@ -9618,7 +9679,7 @@ dependencies = [ [[package]] name = "overwatch" version = "0.2.0" -source = "git+https://github.com/logos-co/Overwatch?rev=fc71a844886f9fb8f382ecfadcebff455e33474b#fc71a844886f9fb8f382ecfadcebff455e33474b" +source = "git+https://github.com/logos-co/Overwatch.git?rev=f25266fb32b3c0651fdc7c368db8d66a544dcf68#f25266fb32b3c0651fdc7c368db8d66a544dcf68" dependencies = [ "async-trait", "futures", @@ -9633,7 +9694,7 @@ dependencies = [ [[package]] name = "overwatch-derive" version = "0.2.0" -source = "git+https://github.com/logos-co/Overwatch?rev=fc71a844886f9fb8f382ecfadcebff455e33474b#fc71a844886f9fb8f382ecfadcebff455e33474b" +source = "git+https://github.com/logos-co/Overwatch.git?rev=f25266fb32b3c0651fdc7c368db8d66a544dcf68#f25266fb32b3c0651fdc7c368db8d66a544dcf68" dependencies = [ "convert_case 0.8.0", "manyhow", @@ -11982,12 +12043,16 @@ version = "0.1.0" dependencies = [ "anyhow", "borsh", + "bridge_core", "chain_state", "common", "futures", "glob", "kameo", "kameo_actors", + "lee", + "logos-blockchain-core", + "logos-blockchain-program-spend", "logos-blockchain-zone-sdk", "mockall", "rand 0.8.6", @@ -11999,6 +12064,7 @@ dependencies = [ "tokio", "tracing", "url", + "vault_circuit", ] [[package]] @@ -12047,7 +12113,6 @@ dependencies = [ "libp2p 0.57.1", "logos-blockchain-zone-sdk", "mempool", - "num-bigint 0.4.6", "ping_core", "program_loader_core", "programs", @@ -12089,7 +12154,6 @@ version = "0.1.0" dependencies = [ "anyhow", "borsh", - "bridge_core", "bytesize", "chain_state", "common", @@ -12360,15 +12424,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "serde-big-array" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11fc7cc2c76d73e0f27ee52abbd64eec84d46f370c88371120433196934e4b7f" -dependencies = [ - "serde", -] - [[package]] name = "serde-value" version = "0.7.0" @@ -12379,15 +12434,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_arrays" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94a16b99c5ea4fe3daccd14853ad260ec00ea043b2708d1fd1da3106dcd8d9df" -dependencies = [ - "serde", -] - [[package]] name = "serde_core" version = "1.0.228" @@ -13319,7 +13365,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.2", "once_cell", "rustix", "windows-sys 0.61.2", @@ -14678,6 +14724,28 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "vault_circuit" +version = "0.1.0" +dependencies = [ + "ark-bn254", + "ark-ec", + "ark-ed-on-bn254", + "ark-ff", + "ark-groth16", + "ark-r1cs-std", + "ark-relations", + "jf-poseidon2", + "logos-blockchain-core", + "logos-blockchain-groth16", + "logos-blockchain-key-management-system-keys", + "logos-blockchain-poseidon2", + "rand 0.8.6", + "rand_chacha 0.3.1", + "sha2 0.10.9", + "tracing", +] + [[package]] name = "vcpkg" version = "0.2.15" diff --git a/Cargo.toml b/Cargo.toml index 3716126c9e..8e42f03d76 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,7 @@ members = [ "lez/programs/ping_receiver", "lez/programs/sequencer_stake", "lez/cross_zone", + "lez/vault_circuit", "lez/core_ffi", "test_guest_core", @@ -146,6 +147,7 @@ wrapped_token_core = { path = "lez/programs/wrapped_token/core" } ping_core = { path = "lez/programs/ping_core" } sequencer_stake_core = { path = "lez/programs/sequencer_stake/core" } cross_zone = { path = "lez/cross_zone" } +vault_circuit = { path = "lez/vault_circuit" } build_utils = { path = "build_utils" } test_guest_core = { path = "test_guest_core" } test_methods = { path = "lee/state_machine/test_methods" } @@ -232,6 +234,11 @@ tempfile = "3.14.0" light-poseidon = "0.3.0" ark-bn254 = "0.5.0" ark-ff = "0.5.0" +ark-ec = "0.5.0" +ark-ed-on-bn254 = { version = "0.5.0", features = ["r1cs"] } +ark-groth16 = "0.5.0" +ark-r1cs-std = "0.5.0" +ark-relations = "0.5.0" tiny-keccak = { version = "2.0.2", features = ["keccak"] } base64 = "0.22.1" bip39 = "2.2.0" @@ -251,7 +258,18 @@ async-stream = "0.3.6" strum = { version = "0.28.0", features = ["derive"] } mockall = "0.15.0" -logos-blockchain-zone-sdk = { git = "https://github.com/logos-blockchain/logos-zone-sdk.git", rev = "1b5073a10caaa63cbbd825bd4397f2f1fb48b33a" } +# FIXME: WIP branch for PUTXOs +logos-blockchain-zone-sdk = { git = "https://github.com/logos-blockchain/logos-zone-sdk.git", rev = "1f95999f474d2fae12a8ad4e3afd218678fb4799" } + +# Bedrock's hash and Groth16 verifier, for the vault circuit. Keep on the node revision zone-sdk pins. +logos-blockchain-poseidon2 = { git = "https://github.com/logos-blockchain/logos-blockchain.git", rev = "767cf967b23b471869a7cae4cb5a6fa54f9389ac" } +logos-blockchain-groth16 = { git = "https://github.com/logos-blockchain/logos-blockchain.git", rev = "767cf967b23b471869a7cae4cb5a6fa54f9389ac" } +logos-blockchain-core = { git = "https://github.com/logos-blockchain/logos-blockchain.git", rev = "767cf967b23b471869a7cae4cb5a6fa54f9389ac" } +logos-blockchain-key-management-system-keys = { git = "https://github.com/logos-blockchain/logos-blockchain.git", rev = "767cf967b23b471869a7cae4cb5a6fa54f9389ac" } +logos-blockchain-program-spend = { git = "https://github.com/logos-blockchain/logos-blockchain.git", rev = "767cf967b23b471869a7cae4cb5a6fa54f9389ac" } +jf-poseidon2 = { git = "https://github.com/EspressoSystems/jellyfish.git", rev = "8d80230358e900f8d63765a937f63f4978ca1daa", features = [ + "bn254", +] } keycard-rs = { git = "https://github.com/keycard-tech/keycard-rs", rev = "9535a657ba04b1e6916de51777e22b4837c1a84d" } @@ -260,6 +278,7 @@ rocksdb = { version = "0.24.0", default-features = false, features = [ "bindgen-runtime", ] } rand = { version = "0.8.5", features = ["std", "std_rng", "getrandom"] } +rand_chacha = "0.3.1" pcsc = "2" k256 = { version = "0.13.3", features = [ "ecdsa-core", diff --git a/Justfile b/Justfile index 686acaed65..9ce4826629 100644 --- a/Justfile +++ b/Justfile @@ -6,7 +6,7 @@ default: # ---- Configuration ---- ARTIFACTS := "artifacts" # Funded key of the local Bedrock node, `funding_pk` in bedrock/node-config.yaml. -BEDROCK_FUNDING_PUBLIC_KEY := "2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26" +BEDROCK_FUNDING_PUBLIC_KEY := "756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903" # On macOS the integration-test binary links pyo3 against the CommandLineTools # Python framework with no embedded rpath, so it needs this to launch. Empty on @@ -104,6 +104,11 @@ run-bedrock *args: resolve-bedrock-node: @bash bedrock/tools/resolve_bedrock_node_in_docker.sh +# Regenerate bedrock/deployment-settings*.yaml (genesis included) from bedrock/genesis/. +regenerate-bedrock-settings: + @just resolve-bedrock-node + @bash bedrock/tools/regenerate_deployment_settings.sh + resolve-host-bedrock-node: @python3 bedrock/tools/resolve_bedrock_node.py \ --target-platform host \ diff --git a/README.md b/README.md index 683065b0e0..465c4f773e 100644 --- a/README.md +++ b/README.md @@ -160,7 +160,7 @@ The sequencer and logos blockchain node can be run locally: - `RUST_LOG=info cargo run -p indexer_service lez/indexer/service/configs/debug/indexer_config.json` 3. On another terminal go to the `logos-blockchain/logos-execution-zone` repo and run the sequencer: - - `cargo run -p sequencer_service -- setup lez/sequencer/service/sequencer_home --config lez/sequencer/service/networks/local.json --funding-public-key 2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26 --create-channel` (once; the key is the local Bedrock node's funded key) + - `cargo run -p sequencer_service -- setup lez/sequencer/service/sequencer_home --config lez/sequencer/service/networks/local.json --funding-public-key 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 --create-channel` (once; the key is the local Bedrock node's funded key) - `RUST_LOG=info cargo run -p sequencer_service -- start lez/sequencer/service/sequencer_home` 4. (To run the explorer): on another terminal go to `logos-blockchain/logos-execution-zone/lez/explorer_service` and run the following: - `cargo install cargo-leptos` diff --git a/artifacts/lez/programs/bridge.bin b/artifacts/lez/programs/bridge.bin index d857bdfb7a..d01ef5d788 100644 Binary files a/artifacts/lez/programs/bridge.bin and b/artifacts/lez/programs/bridge.bin differ diff --git a/bedrock/README.md b/bedrock/README.md index 47ebf417bb..dfdc261488 100644 --- a/bedrock/README.md +++ b/bedrock/README.md @@ -73,3 +73,17 @@ The scripts folder contains the existing configuration entrypoints: ```bash curl -O https://raw.githubusercontent.com/logos-blockchain/logos-blockchain/master/tests/kzgrs/kzgrs_test_params ``` + +## Deployment settings + +`deployment-settings.yaml` and its slow-finality variant are generated, genesis +block included, from the inputs in `genesis/` by the genesis tool of the +resolved Logos revision. Edit the inputs, not the output, then run: + +```bash +just regenerate-bedrock-settings +``` + +The public keys in `genesis/` and `node-config.yaml` are derived from the secret +keys in `node-config.yaml`, so they change when the node changes its key +derivation. diff --git a/bedrock/deployment-settings-slow-finality.yaml b/bedrock/deployment-settings-slow-finality.yaml index 90cd417934..9efc0dc4d2 100644 --- a/bedrock/deployment-settings-slow-finality.yaml +++ b/bedrock/deployment-settings-slow-finality.yaml @@ -9,7 +9,9 @@ eras: core: scheduler: cover: - message_frequency_per_round: 1.0 + message_frequency_per_round: + numerator: 1 + denominator: 1 replication_factor: 0 delayer: maximum_release_delay_in_rounds: 1 @@ -29,13 +31,12 @@ eras: numerator: 1 denominator: 2 learning_rate: 0.5 - # At most ⌊0.6 × security_param⌋ blocks. uncle_reference_window_in_block: 1 max_uncles: 4 max_transactions: 1024 - # The most bytes a block's transactions may take, 2 MiB. An inscription or a - # deposit's metadata may take seven eighths of it. max_transactions_size: 2097152 + root_window: 1024 + channel_withdraw_delay: 86400 pow_config: blend: base_difficulty: 19 @@ -50,19 +51,16 @@ eras: target_claims_per_block: 100 rate_num: 0 rate_den: 1 - target_claim_per_block: 1 pow_share: 0 share_den: 100 slot_window: 100 sdp_config: service_params: - inactivity_period: 2 - epoch: 0 min_stake: threshold: 1 - timestamp: 0 execution_market: - max_gas_per_block: 3193460 + max_gas_per_block: 3137798 fee_adjustment_rate: numerator: 1 denominator: 8 @@ -77,173 +75,103 @@ eras: numerator: 1 denominator: 2 block_rewards: - stake_target: 3000000000 - emission_factor_scale: 120000000 - fee_average_numerator: 10512 - max_emission_per_block: - numerator: 62500 - denominator: 657 + max_emission_rate: + numerator: 1 + denominator: 100 + min_emission_rate: + numerator: 0 + denominator: 1 + stake_target: + numerator: 3 + denominator: 10 + pooled_fees_target: + numerator: 1 + denominator: 1 + stake_deviation_weight: + numerator: 1 + denominator: 4 + pooled_fees_weight: + numerator: 1 + denominator: 1 + pooled_fees_window: 120 blend_share: numerator: 6 denominator: 10 gas_profile: - transfer: 590 - channel_config: 56 - channel_inscribe: 56 - channel_deposit: 590 - channel_withdraw: 56 - channel_transfer: 56 - sdp_declare: 646 - sdp_withdraw: 590 - sdp_active: 590 - leader_claim: 580 - claim_pow_reward: 1 + transfer: 10 + program_register: 15114 + channel_config: 24 + channel_inscribe: 26 + channel_deposit: 26 + channel_withdraw: 33 + sdp_declare: 1693 + sdp_withdraw: 0 + sdp_active: 15117 + claim_pow_reward: 1506 + kilobyte: 30 + note_set: 8961 + proof: 4177 + root: 2332 + buffered: 60 + nullifier: 1758 + commitment: 58 + signature: 557 + user_step: 28 + program_deposit: 144 + program_step: 13528 + opening: 470 time: slot_duration_in_seconds: 4 genesis_block: header: slot: 0 parent_block: '0000000000000000000000000000000000000000000000000000000000000000' - body_root: '4f745b070df8b8ac5876e4cbd4caadd6e6e73b0c57546ce2e8870e9f89e36b63' + body_root: 2a0e1e129499444510b964a134d35a3e0d73c9fdcb40dec79f11b769133d59b6 proof_of_leadership: proof: '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' entropy_contribution: '0000000000000000000000000000000000000000000000000000000000000000' - leader_key: '0000000000000000000000000000000000000000000000000000000000000000' - voucher_cm: '0000000000000000000000000000000000000000000000000000000000000000' - signature: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + reward_commitment: '0000000000000000000000000000000000000000000000000000000000000000' + reward_value: 0 uncle_headers: [] transactions: - mantle_tx: fork_digest: '0000000000000000000000000000000000000000000000000000000000000000' ops: - - opcode: 0 - payload: - inputs: [] - outputs: - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 100000 - pk: '6b2bcd3029fba573cff0c332dc4de7430faf5e261383d693d8dbb5b97665660a' - - value: 1000000000000 - pk: ed266e6e887b9b97059dc1aa1b7b2e19b934291753c6336a163fe4ebaa28e717 - - value: 18446744073709551615 - pk: c2a6a4a0981d5bdcf8ddeb8d7934fd8c5510efeb1053f613b45871670b6f7b19 - opcode: 17 payload: channel_id: '0000000000000000000000000000000000000000000000000000000000000000' - inscription: '05302e322e3123766c6a2d2ddf918544bca603c5a291c7dd1b902d6769ff4b00021506780e075c06051a00ca9a3b0000000001000000c2a6a4a0981d5bdcf8ddeb8d7934fd8c5510efeb1053f613b45871670b6f7b19' + inscription: 0f6c657a2d6c6f63616c2f302e312e3000b955692d2ddf918544bca603c5a291c7dd1b902d6769ff4b00021506780e075c06051a0000e8890423c78a0000c52ebca2b100000064a7b3b6e00d00ca9a3b0000000000ca9a3b00000000 parent: '0000000000000000000000000000000000000000000000000000000000000000' signer: '0000000000000000000000000000000000000000000000000000000000000000' + mini_blocks: [] + - opcode: 17 + payload: + channel_id: '0000000000000000000000000000000000000000000000000000000000000000' + inscription: 320080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300dbbc36e86c41c8532fb08594e9179fe0cdeb801a819c2538d0bdd5c1b172822400b625ee56b4867b756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + parent: ce8270a5a1db1f42ffb93dfc07229952bcd54ee0e9bc037cc2e2c301632dfe41 + signer: '0000000000000000000000000000000000000000000000000000000000000000' + mini_blocks: [] - opcode: 32 payload: service_type: BN locators: - /ip4/65.109.51.37/udp/3400/quic-v1 - provider_id: '59c662860b737f4e2515599adb3434856db8070b373a449ff66955ad3da6b473' - zk_id: '6b2bcd3029fba573cff0c332dc4de7430faf5e261383d693d8dbb5b97665660a' - service_note_id: '67e2ec02c536a82f0eb80800fcfb8f2d66c5423d57cd081dfb0f237234f6ac26' + provider_id: 59c662860b737f4e2515599adb3434856db8070b373a449ff66955ad3da6b473 + zk_id: 6a800ed77f1c55fd8b3af1bd0c4b9bd000e404e7ebb5c13864d026ab90b50a1b + note_pk: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + note_stake_pk: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + inputs: [] + commitment_merkle_root: 32f165b759eb971b6cf2e21c586558d1391b20942166a6a0d7a598058b18ad1d + amount: 1000000000 ops_proofs: - - !ZkSig - pi_a: '0000000000000000000000000000000000000000000000000000000000000000' - pi_b: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' - pi_c: '0000000000000000000000000000000000000000000000000000000000000000' - - !Ed25519Sig '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + - !ChannelInscribe + signature: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + step_proofs: [] + - !ChannelInscribe + signature: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + step_proofs: [] - !ZkAndEd25519Sigs - zk_sig: + zk_proof: pi_a: '0000000000000000000000000000000000000000000000000000000000000000' pi_b: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' pi_c: '0000000000000000000000000000000000000000000000000000000000000000' diff --git a/bedrock/deployment-settings.yaml b/bedrock/deployment-settings.yaml index cd30076e25..c0177ce6c1 100644 --- a/bedrock/deployment-settings.yaml +++ b/bedrock/deployment-settings.yaml @@ -9,7 +9,9 @@ eras: core: scheduler: cover: - message_frequency_per_round: 1.0 + message_frequency_per_round: + numerator: 1 + denominator: 1 replication_factor: 0 delayer: maximum_release_delay_in_rounds: 1 @@ -29,13 +31,12 @@ eras: numerator: 1 denominator: 2 learning_rate: 0.5 - # At most ⌊0.6 × security_param⌋ blocks. uncle_reference_window_in_block: 1 max_uncles: 4 max_transactions: 1024 - # The most bytes a block's transactions may take, 2 MiB. An inscription or a - # deposit's metadata may take seven eighths of it. max_transactions_size: 2097152 + root_window: 1024 + channel_withdraw_delay: 86400 pow_config: blend: base_difficulty: 19 @@ -50,19 +51,16 @@ eras: target_claims_per_block: 100 rate_num: 0 rate_den: 1 - target_claim_per_block: 1 pow_share: 0 share_den: 100 slot_window: 100 sdp_config: service_params: - inactivity_period: 2 - epoch: 0 min_stake: threshold: 1 - timestamp: 0 execution_market: - max_gas_per_block: 3193460 + max_gas_per_block: 3137798 fee_adjustment_rate: numerator: 1 denominator: 8 @@ -77,173 +75,103 @@ eras: numerator: 1 denominator: 2 block_rewards: - stake_target: 3000000000 - emission_factor_scale: 120000000 - fee_average_numerator: 10512 - max_emission_per_block: - numerator: 62500 - denominator: 657 + max_emission_rate: + numerator: 1 + denominator: 100 + min_emission_rate: + numerator: 0 + denominator: 1 + stake_target: + numerator: 3 + denominator: 10 + pooled_fees_target: + numerator: 1 + denominator: 1 + stake_deviation_weight: + numerator: 1 + denominator: 4 + pooled_fees_weight: + numerator: 1 + denominator: 1 + pooled_fees_window: 120 blend_share: numerator: 6 denominator: 10 gas_profile: - transfer: 590 - channel_config: 56 - channel_inscribe: 56 - channel_deposit: 590 - channel_withdraw: 56 - channel_transfer: 56 - sdp_declare: 646 - sdp_withdraw: 590 - sdp_active: 590 - leader_claim: 580 - claim_pow_reward: 1 + transfer: 10 + program_register: 15114 + channel_config: 24 + channel_inscribe: 26 + channel_deposit: 26 + channel_withdraw: 33 + sdp_declare: 1693 + sdp_withdraw: 0 + sdp_active: 15117 + claim_pow_reward: 1506 + kilobyte: 30 + note_set: 8961 + proof: 4177 + root: 2332 + buffered: 60 + nullifier: 1758 + commitment: 58 + signature: 557 + user_step: 28 + program_deposit: 144 + program_step: 13528 + opening: 470 time: slot_duration_in_seconds: 4 genesis_block: header: slot: 0 parent_block: '0000000000000000000000000000000000000000000000000000000000000000' - body_root: '4f745b070df8b8ac5876e4cbd4caadd6e6e73b0c57546ce2e8870e9f89e36b63' + body_root: 2a0e1e129499444510b964a134d35a3e0d73c9fdcb40dec79f11b769133d59b6 proof_of_leadership: proof: '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' entropy_contribution: '0000000000000000000000000000000000000000000000000000000000000000' - leader_key: '0000000000000000000000000000000000000000000000000000000000000000' - voucher_cm: '0000000000000000000000000000000000000000000000000000000000000000' - signature: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + reward_commitment: '0000000000000000000000000000000000000000000000000000000000000000' + reward_value: 0 uncle_headers: [] transactions: - mantle_tx: fork_digest: '0000000000000000000000000000000000000000000000000000000000000000' ops: - - opcode: 0 - payload: - inputs: [] - outputs: - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 1000000 - pk: '2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26' - - value: 100000 - pk: '6b2bcd3029fba573cff0c332dc4de7430faf5e261383d693d8dbb5b97665660a' - - value: 1000000000000 - pk: ed266e6e887b9b97059dc1aa1b7b2e19b934291753c6336a163fe4ebaa28e717 - - value: 18446744073709551615 - pk: c2a6a4a0981d5bdcf8ddeb8d7934fd8c5510efeb1053f613b45871670b6f7b19 - opcode: 17 payload: channel_id: '0000000000000000000000000000000000000000000000000000000000000000' - inscription: '05302e322e3123766c6a2d2ddf918544bca603c5a291c7dd1b902d6769ff4b00021506780e075c06051a00ca9a3b0000000001000000c2a6a4a0981d5bdcf8ddeb8d7934fd8c5510efeb1053f613b45871670b6f7b19' + inscription: 0f6c657a2d6c6f63616c2f302e312e3000b955692d2ddf918544bca603c5a291c7dd1b902d6769ff4b00021506780e075c06051a0000e8890423c78a0000c52ebca2b100000064a7b3b6e00d00ca9a3b0000000000ca9a3b00000000 parent: '0000000000000000000000000000000000000000000000000000000000000000' signer: '0000000000000000000000000000000000000000000000000000000000000000' + mini_blocks: [] + - opcode: 17 + payload: + channel_id: '0000000000000000000000000000000000000000000000000000000000000000' + inscription: 320080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c9030080c6a47e8d0300dbbc36e86c41c8532fb08594e9179fe0cdeb801a819c2538d0bdd5c1b172822400b625ee56b4867b756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + parent: ce8270a5a1db1f42ffb93dfc07229952bcd54ee0e9bc037cc2e2c301632dfe41 + signer: '0000000000000000000000000000000000000000000000000000000000000000' + mini_blocks: [] - opcode: 32 payload: service_type: BN locators: - /ip4/65.109.51.37/udp/3400/quic-v1 - provider_id: '59c662860b737f4e2515599adb3434856db8070b373a449ff66955ad3da6b473' - zk_id: '6b2bcd3029fba573cff0c332dc4de7430faf5e261383d693d8dbb5b97665660a' - service_note_id: '67e2ec02c536a82f0eb80800fcfb8f2d66c5423d57cd081dfb0f237234f6ac26' + provider_id: 59c662860b737f4e2515599adb3434856db8070b373a449ff66955ad3da6b473 + zk_id: 6a800ed77f1c55fd8b3af1bd0c4b9bd000e404e7ebb5c13864d026ab90b50a1b + note_pk: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + note_stake_pk: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + inputs: [] + commitment_merkle_root: 32f165b759eb971b6cf2e21c586558d1391b20942166a6a0d7a598058b18ad1d + amount: 1000000000 ops_proofs: - - !ZkSig - pi_a: '0000000000000000000000000000000000000000000000000000000000000000' - pi_b: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' - pi_c: '0000000000000000000000000000000000000000000000000000000000000000' - - !Ed25519Sig '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + - !ChannelInscribe + signature: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + step_proofs: [] + - !ChannelInscribe + signature: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + step_proofs: [] - !ZkAndEd25519Sigs - zk_sig: + zk_proof: pi_a: '0000000000000000000000000000000000000000000000000000000000000000' pi_b: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' pi_c: '0000000000000000000000000000000000000000000000000000000000000000' diff --git a/bedrock/genesis/era-template.yaml b/bedrock/genesis/era-template.yaml new file mode 100644 index 0000000000..ff1f92aa8f --- /dev/null +++ b/bedrock/genesis/era-template.yaml @@ -0,0 +1,129 @@ +0: !V1 + blend: + common: + num_blend_layers: 1 + minimum_network_size: 30 + network_absorption_in_rounds: 2 + data_replication_factor: 1 + core: + scheduler: + cover: + message_frequency_per_round: + numerator: 1 + denominator: 1 + replication_factor: 0 + delayer: + maximum_release_delay_in_rounds: 1 + target_peering_degree: 4 + verification_rate_per_second: 156 + edge_node_send_deadline_in_rounds: 1 + core_handshake_deadline_in_rounds: 2 + expected_deliveries_per_observation_window: 60 + activity_threshold_sensitivity: 1 + cryptarchia: + epoch_config: + epoch_stake_distribution_stabilization: 3 + epoch_period_nonce_buffer: 3 + epoch_period_nonce_stabilization: 4 + security_param: 3 + slot_activation_coeff: + numerator: 1 + denominator: 2 + learning_rate: 0.5 + # At most ⌊0.6 × security_param⌋ blocks. + uncle_reference_window_in_block: 1 + max_uncles: 4 + max_transactions: 1024 + # The most bytes a block's transactions may take, 2 MiB. An inscription or a + # deposit's metadata may take seven eighths of it. + max_transactions_size: 2097152 + # ROOT_WINDOW: how many blocks a commitment root stays referenceable once a + # block supersedes it, kept by the root whatever window a later era sets. + root_window: 1024 + # WITHDRAW_DELAY: the slots between a channel withdrawal and its release. + channel_withdraw_delay: 86400 + pow_config: + blend: + base_difficulty: 19 + target_transactions_per_block: 512 + max_step: 2 + damping_num: 1 + damping_den_offset: 1 + reward: + minimum_difficulty: 19 + ema_smoothing_factor: 9 + ema_smoothing_precision: 10 + target_claims_per_block: 100 + rate_num: 0 + rate_den: 1 + pow_share: 0 + share_den: 100 + slot_window: 100 + sdp_config: + service_params: + - inactivity_period: 2 + min_stake: + threshold: 1 + execution_market: + max_gas_per_block: 3137798 + fee_adjustment_rate: + numerator: 1 + denominator: 8 + ema_smoothing_factor: + numerator: 9 + denominator: 10 + storage_market: + max_adjustment_factor: + numerator: 1 + denominator: 8 + ema_smoothing_factor: + numerator: 1 + denominator: 2 + block_rewards: + max_emission_rate: + numerator: 1 + denominator: 100 + min_emission_rate: + numerator: 0 + denominator: 1 + stake_target: + numerator: 3 + denominator: 10 + pooled_fees_target: + numerator: 1 + denominator: 1 + stake_deviation_weight: + numerator: 1 + denominator: 4 + pooled_fees_weight: + numerator: 1 + denominator: 1 + pooled_fees_window: 120 + blend_share: + numerator: 6 + denominator: 10 + gas_profile: + transfer: 10 + program_register: 15114 + channel_config: 24 + channel_inscribe: 26 + channel_deposit: 26 + channel_withdraw: 33 + sdp_declare: 1693 + sdp_withdraw: 0 + sdp_active: 15117 + claim_pow_reward: 1506 + kilobyte: 30 + note_set: 8961 + proof: 4177 + root: 2332 + buffered: 60 + nullifier: 1758 + commitment: 58 + signature: 557 + user_step: 28 + program_deposit: 144 + program_step: 13528 + opening: 470 + time: + slot_duration_in_seconds: 4 diff --git a/bedrock/genesis/inscribe.yaml b/bedrock/genesis/inscribe.yaml new file mode 100644 index 0000000000..d7269f309c --- /dev/null +++ b/bedrock/genesis/inscribe.yaml @@ -0,0 +1,10 @@ +entropy_sources: + - "0000000000000000000000000000000000000000000000000000000000000001" +chain_id: "lez-local/0.1.0" +genesis_time: "2026-01-01T00:00:00Z" +# The node's test-chain defaults. +max_supply: 10000000000000000000 +pow_reward_pool: 50000000000000000 +rewards_reserve: 1000000000000000000 +storage_gas_price: 1000000000 +execution_gas_price: 1000000000 diff --git a/bedrock/genesis/providers.yaml b/bedrock/genesis/providers.yaml new file mode 100644 index 0000000000..a249734d5a --- /dev/null +++ b/bedrock/genesis/providers.yaml @@ -0,0 +1,8 @@ +- provider_id: 59c662860b737f4e2515599adb3434856db8070b373a449ff66955ad3da6b473 + zk_id: 6a800ed77f1c55fd8b3af1bd0c4b9bd000e404e7ebb5c13864d026ab90b50a1b + note_pk: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + note_stake_pk: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + locators: + - /ip4/65.109.51.37/udp/3400/quic-v1 + service_type: BN + amount: 1000000000 diff --git a/bedrock/genesis/stakeholders.yaml b/bedrock/genesis/stakeholders.yaml new file mode 100644 index 0000000000..5d3e1b84b6 --- /dev/null +++ b/bedrock/genesis/stakeholders.yaml @@ -0,0 +1,101 @@ +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 1000000000000000 +- zk_id: dbbc36e86c41c8532fb08594e9179fe0cdeb801a819c2538d0bdd5c1b1728224 + stake: 1000000000000000 +# The rest of the maximum supply, which the genesis block must hold in full. +- zk_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 + stake: 8900999999000000000 diff --git a/bedrock/node-config.yaml b/bedrock/node-config.yaml index 22bcdd958d..4ec7d020c6 100644 --- a/bedrock/node-config.yaml +++ b/bedrock/node-config.yaml @@ -17,22 +17,22 @@ cryptarchia: max_discovered_peers_to_try_download: 16 leader: wallet: - funding_pk: "2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26" + funding_pk: "756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903" sdp: wallet: - funding_pk: ed266e6e887b9b97059dc1aa1b7b2e19b934291753c6336a163fe4ebaa28e717 + funding_pk: dbbc36e86c41c8532fb08594e9179fe0cdeb801a819c2538d0bdd5c1b1728224 kms: backend: keys: - 2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26: !Zk 6c645cd4636d9c4c36a37a9aeabcaa3300000000000000000000000000000000 + 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903: !Zk 6c645cd4636d9c4c36a37a9aeabcaa3300000000000000000000000000000000 64249c75c2cb813578b75d05b215fc95f67cea5862fff047228183f22e63460e: !Zk 83c851cf4436e8d2fdac33d56d2b235f66431be97e2a20bf241d431713dc720f - ed266e6e887b9b97059dc1aa1b7b2e19b934291753c6336a163fe4ebaa28e717: !Zk 7364705cd4636d9c4c36a37a9aeabcaa00000000000000000000000000000000 + dbbc36e86c41c8532fb08594e9179fe0cdeb801a819c2538d0bdd5c1b1728224: !Zk 7364705cd4636d9c4c36a37a9aeabcaa00000000000000000000000000000000 86c8519f00178e9eb1fe5f4247e4bed77d4c9f6da2fb10e8a1fdd7ba6bc79fa0: !Ed25519 5cd4636d9c4c36a37a9aeabcaa332c3ec796226af0af48a0b2e70167205af749 wallet: known_keys: - 2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26: "2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26" - ed266e6e887b9b97059dc1aa1b7b2e19b934291753c6336a163fe4ebaa28e717: "ed266e6e887b9b97059dc1aa1b7b2e19b934291753c6336a163fe4ebaa28e717" - voucher_master_key_id: 2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26 + 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903: "756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903" + dbbc36e86c41c8532fb08594e9179fe0cdeb801a819c2538d0bdd5c1b1728224: "dbbc36e86c41c8532fb08594e9179fe0cdeb801a819c2538d0bdd5c1b1728224" + voucher_master_key_id: 756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903 pow: auto_claim: diff --git a/bedrock/tools/regenerate_deployment_settings.sh b/bedrock/tools/regenerate_deployment_settings.sh new file mode 100755 index 0000000000..0ea8ec2e04 --- /dev/null +++ b/bedrock/tools/regenerate_deployment_settings.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Regenerates bedrock/deployment-settings*.yaml from bedrock/genesis/ with the genesis tool of the +# Cargo-resolved Logos revision. Run `just resolve-bedrock-node` first: it builds the image and +# fetches the checkout used here. + +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo_root" + +image="${BEDROCK_RESOLVER_IMAGE:-lez-bedrock-resolver:local}" +revision="$(python3 -c 'import json; print(json.load(open("bedrock/.resolved/metadata.json"))["resolved_sha"])')" +cargo_home="${CARGO_HOME:-$HOME/.cargo}" +checkout="$(find "$cargo_home/git/checkouts" -maxdepth 2 -type d -path "*/logos-blockchain-*/${revision:0:7}" | head -n 1)" +[ -n "$checkout" ] || { echo "No Cargo checkout of Logos revision $revision" >&2; exit 1; } +target="$repo_root/target/bedrock-node" + +in_docker() { + docker run --rm \ + --user "$(id -u):$(id -g)" \ + --volume "$repo_root:$repo_root" \ + --volume "$cargo_home/registry:/cargo/registry" \ + --volume "$cargo_home/git:/cargo/git" \ + --env CARGO_HOME=/cargo \ + --env HOME=/tmp/lez-bedrock-resolver-home \ + --env CARGO_TARGET_DIR="$target" \ + --env RUSTFLAGS=-A\ single-use-lifetimes \ + "$@" +} + +in_docker --workdir "/cargo/git/checkouts/${checkout#"$cargo_home/git/checkouts/"}" "$image" \ + cargo build --locked --release -p logos-blockchain-tools --bin logos-blockchain-tools-genesis + +settings="$(mktemp)" +in_docker --workdir "$repo_root/bedrock" "$image" \ + "$target/release/logos-blockchain-tools-genesis" ceremony \ + --inscription-params genesis/inscribe.yaml \ + --stake-holders genesis/stakeholders.yaml \ + --providers genesis/providers.yaml \ + --template genesis/era-template.yaml >"$settings" + +mv "$settings" bedrock/deployment-settings.yaml +sed 's/security_param: 3$/security_param: 10/' bedrock/deployment-settings.yaml \ + >bedrock/deployment-settings-slow-finality.yaml +echo "Regenerated bedrock/deployment-settings.yaml and its slow-finality variant" diff --git a/docker-compose.yml b/docker-compose.yml index 114770c458..79e0dda608 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,7 +28,7 @@ x-sequencer: &sequencer x-sequencer-environment: &sequencer_environment SEQUENCER_CONFIG: /etc/sequencer_service/sequencer_config.json SEQUENCER_CHANNEL_SIGNING_KEY_FILE: /run/secrets/channel_signing_key - SEQUENCER_FUNDING_PUBLIC_KEY: ${LEZ_COMPOSE_FUNDING_PUBLIC_KEY:-2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26} + SEQUENCER_FUNDING_PUBLIC_KEY: ${LEZ_COMPOSE_FUNDING_PUBLIC_KEY:-756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903} SEQUENCER_BEDROCK_NODE_URL: ${LEZ_COMPOSE_SEQUENCER_BEDROCK_NODE_URL:-http://logos-blockchain-node-0:18080} # Traces go to Alloy, which runs with `--profile monitoring`. Without it, a sequencer warns once # that it cannot export, and drops them. Empty turns exporting off. diff --git a/integration_tests/Cargo.toml b/integration_tests/Cargo.toml index 3386032243..db86b743a2 100644 --- a/integration_tests/Cargo.toml +++ b/integration_tests/Cargo.toml @@ -20,6 +20,8 @@ common.workspace = true key_protocol.workspace = true serde_json.workspace = true bridge_core.workspace = true +chain_state.workspace = true +vault_circuit.workspace = true ping_core.workspace = true cross_zone.workspace = true cross_zone_outbox_core.workspace = true diff --git a/integration_tests/src/testing_framework/apps/bedrock.rs b/integration_tests/src/testing_framework/apps/bedrock.rs index 3df4a48a1a..204a21e844 100644 --- a/integration_tests/src/testing_framework/apps/bedrock.rs +++ b/integration_tests/src/testing_framework/apps/bedrock.rs @@ -15,6 +15,10 @@ use num_bigint::BigUint; use tempfile::TempDir; use tokio::time::{sleep, timeout}; +/// The node funds a transaction from at most four notes, at a gas price of 1e9. Same value as +/// the notes of `bedrock/genesis/stakeholders.yaml`. +const FUNDING_NOTE_VALUE: u64 = 1_000_000_000_000_000; + /// A TF-managed Logos blockchain cluster used as LEZ's Bedrock layer. /// /// Logos owns node configuration generation through [`TopologyConfig`] and @@ -258,7 +262,7 @@ fn lez_funding_account() -> WalletAccount { fn lez_funding_wallet() -> WalletConfig { WalletConfig::new( std::iter::repeat_with(|| WalletAccount { - value: 50_000_000, + value: FUNDING_NOTE_VALUE, ..lez_funding_account() }) .take(20) @@ -269,7 +273,7 @@ fn lez_funding_wallet() -> WalletConfig { fn committee_funding_wallet() -> WalletConfig { WalletConfig::new( std::iter::repeat_with(|| WalletAccount { - value: 1_000_000, + value: FUNDING_NOTE_VALUE, ..lez_funding_account() }) .take(20) diff --git a/integration_tests/tests/bridge.rs b/integration_tests/tests/bridge.rs index 610834a948..43288c174d 100644 --- a/integration_tests/tests/bridge.rs +++ b/integration_tests/tests/bridge.rs @@ -8,12 +8,13 @@ use std::{ time::Duration, }; -use anyhow::{Context as _, ensure}; +use anyhow::{Context as _, bail, ensure}; use bridge_core::{DepositMetadata, DepositRecipient}; +use chain_state::vault::VAULT_PROGRAM; use common::transaction::LeeTransaction; -use futures::StreamExt as _; use integration_tests::{ - TIME_TO_WAIT_FOR_BLOCK_SECONDS, TestContext, no_seal, utils::account_balance, + TIME_TO_WAIT_FOR_BLOCK_SECONDS, TestContext, no_seal, + utils::{account_balance, get_account, wait_for_indexer_to_catch_up, wait_until}, }; use lee::{ AccountId, Actor, PrivateKey, PublicAccountEvidence, PublicKey, @@ -23,32 +24,167 @@ use lee::{ use lee_core::{RootCall, execution_state::TransactionEntry}; use logos_blockchain_zone_sdk::{ CommonHttpClient, + binary_codec::canonical::BinaryEncode as _, core::mantle::{ - Note, Value, + Value, gas::GasCost, - ledger::{Inputs, NoteId, Utxo}, - ops::{OpId as _, OpRef, channel::deposit::DepositOp}, + ops::channel::{deposit::Metadata, inscribe::Step}, }, http_api_common::{ - bodies::{ - channel::{ChannelDepositRequestBody, ChannelDepositResponseBody}, - wallet::transfer_funds::WalletTransferFundsRequestBody, + bodies::channel::{ + ChannelDepositRequestBody, ChannelDepositResponseBody, ChannelStepRequestBody, + ProgramDepositBody, }, paths::CHANNEL_DEPOSIT, }, - node_types::ApiBlock, + node_types::Inscription, }; -use sequencer_service_rpc::RpcClient as _; -use test_fixtures::{ - MultiZoneTestContextBuilder, ZoneTestContextBuilder, - config::{ - MultiNodeTestContextConfig, SequencerPartialConfig, UrlProtocol, addr_to_url, - bedrock_channel_id, bedrock_funding_key, - }, +use sequencer_service_rpc::{HexBytes, RpcClient as _}; +use test_fixtures::config::{ + CHANNEL_SIGNING_KEY, UrlProtocol, addr_to_url, bedrock_channel_id, bedrock_funding_key, }; use tokio::test; +use vault_circuit::{Committee, Deposit, SigningKey}; + +/// The indexer's reads, apart from the sequencer's methods of the same names. +mod indexed { + use anyhow::Context as _; + use indexer_service_rpc::RpcClient as _; + use integration_tests::TestContext; + use lee::AccountId; + + pub async fn account( + ctx: &TestContext, + account_id: AccountId, + ) -> anyhow::Result> { + ctx.indexer_client() + .get_account(account_id.into()) + .await + .context("Failed to read the account from the indexer") + } +} + +/// Has the Bedrock test node's wallet pay `amount` into the zone's channel and deposit it to the +/// vault for `recipient`. Returns the deposit as the sequencer takes it: the step, then its proof. +async fn program_deposit( + ctx: &TestContext, + recipient: PublicKey, + amount: u64, +) -> anyhow::Result> { + let node = CommonHttpClient::new(None); + let bedrock_url = addr_to_url(UrlProtocol::Http, ctx.bedrock_addr())?; + let holder = bedrock_funding_key(); + + let _: ChannelDepositResponseBody = node + .post( + bedrock_url.join(CHANNEL_DEPOSIT.trim_start_matches('/'))?, + &ChannelDepositRequestBody { + tip: None, + channel_id: bedrock_channel_id(), + amount, + holder_public_key: holder, + metadata: Metadata::default(), + change_public_key: holder, + funding_public_keys: vec![holder], + max_tx_fee: GasCost::new(Value::MAX), + }, + ) + .await + .context("Failed to pay into the channel")?; + + let recipient = DepositRecipient::Identified(PublicAccountEvidence::Key(recipient)); + // The vault of the one sequencer of the test. + let committee = Committee { + threshold: 1, + signers: vec![SigningKey::from_channel_seed(&CHANNEL_SIGNING_KEY).public_key()], + }; + let intent = Deposit { + value: amount, + recipient: Deposit::recipient_element(recipient.account_id().value()), + } + .intent(committee.id()); + let inscription = Inscription::try_new(borsh::to_vec(&DepositMetadata { recipient })?, 128) + .ok() + .context("The recipient does not fit the deposit's inscription")?; + + // The wallet proves the step once it holds the channel note. + let request = || ChannelStepRequestBody { + tip: None, + channel_id: bedrock_channel_id(), + appended: Vec::new(), + payments: Vec::new(), + program_deposit: Some(ProgramDepositBody { + program_id: *VAULT_PROGRAM, + value: amount, + intent, + }), + inscription: inscription.clone(), + change_public_key: holder, + holder_public_keys: vec![holder], + }; + let mut attempts = 0_u32; + let step = loop { + match node.channel_step(bedrock_url.clone(), request()).await { + Ok(step) => break step, + Err(err) if attempts >= 120 => { + return Err(err).context("The wallet never proved the deposit step"); + } + Err(_) => { + attempts = attempts.saturating_add(1); + tokio::time::sleep(Duration::from_millis(500)).await; + } + } + }; + let Step::ProgramDeposit(deposit) = step.step else { + bail!("The node answered with a step that is no program deposit"); + }; + + let mut bytes = Vec::new(); + deposit.encode_into(&mut bytes); + step.proof.encode_into(&mut bytes); + Ok(bytes) +} + +#[test] +async fn a_vault_deposit_is_minted_exactly_once() -> anyhow::Result<()> { + let ctx = TestContext::new().await?; + let recipient = PublicKey::new_from_private_key(&PrivateKey::new_os_random()); + let recipient_id = AccountId::from(&recipient); + let amount = 1_000_u64; + + let deposit = program_deposit(&ctx, recipient, amount).await?; + ctx.sequencer_client() + .submit_program_deposit(HexBytes(deposit.clone())) + .await + .context("The sequencer refused the deposit")?; + + wait_until("the deposit to credit its recipient", || async { + Ok(account_balance(&ctx, recipient_id).await? >= u128::from(amount)) + }) + .await?; + ensure!( + ctx.sequencer_client() + .submit_program_deposit(HexBytes(deposit)) + .await + .is_err(), + "A minted deposit was admitted again" + ); -const TIME_TO_FINALIZE_DEPOSIT_EVENT_ON_BEDROCK: Duration = Duration::from_mins(2); + // The indexer applies the block only if it finds the deposit in the block's inscription. + wait_for_indexer_to_catch_up(&ctx).await?; + tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + ensure!( + account_balance(&ctx, recipient_id).await? == u128::from(amount), + "The deposit credited its recipient more than once" + ); + let indexed = indexed::account(&ctx, recipient_id).await?; + ensure!( + indexed == Some(get_account(&ctx, recipient_id).await?.into()), + "The indexer and the sequencer disagree on the recipient: {indexed:?}" + ); + + Ok(()) +} #[test] async fn public_bridge_deposit_invocation_is_dropped() -> anyhow::Result<()> { @@ -253,459 +389,4 @@ async fn private_bridge_deposit_invocation_is_dropped() -> anyhow::Result<()> { Ok(()) } -/// Deposits `amount` from the Bedrock test node's wallet into the zone's -/// channel for `recipient` and returns the channel note the deposit re-creates. -async fn submit_bedrock_deposit( - ctx: &TestContext, - recipient: PublicKey, - amount: u64, -) -> anyhow::Result { - let node = CommonHttpClient::new(None); - let bedrock_url = addr_to_url(UrlProtocol::Http, ctx.bedrock_addr())?; - let funding_key = bedrock_funding_key(); - - let exact_note = async || -> anyhow::Result<_> { - let balance = node - .get_wallet_balance(bedrock_url.clone(), funding_key, None) - .await - .context("Failed to query the Bedrock wallet balance")?; - Ok(balance - .notes - .iter() - .find_map(|(note_id, value)| (*value == amount).then_some(*note_id))) - }; - - let mut note_id = exact_note().await?; - if note_id.is_none() { - node.transfer_funds( - bedrock_url.clone(), - WalletTransferFundsRequestBody { - tip: None, - change_public_key: funding_key, - funding_public_keys: vec![funding_key], - recipient_public_key: funding_key, - amount, - }, - ) - .await - .context("Failed to split off a note of the deposit amount")?; - for _ in 0..240 { - tokio::time::sleep(Duration::from_millis(500)).await; - note_id = exact_note().await?; - if note_id.is_some() { - break; - } - } - } - let note_id = note_id.context("The Bedrock wallet never held a note of the deposit amount")?; - - // Bounded per era now; a recipient is far under any era's limit. - let metadata = - logos_blockchain_zone_sdk::core::mantle::ops::channel::deposit::Metadata::new_unchecked( - borsh::to_vec(&DepositMetadata { - recipient: DepositRecipient::Identified(PublicAccountEvidence::Key(recipient)), - })?, - ); - let deposit = DepositOp { - channel_id: bedrock_channel_id(), - inputs: Inputs::new(note_id), - metadata, - }; - let deposited_note = Utxo::new(deposit.op_id(), 0, Note::new(amount, funding_key)).id(); - let _: ChannelDepositResponseBody = node - .post( - bedrock_url.join(CHANNEL_DEPOSIT.trim_start_matches('/'))?, - &ChannelDepositRequestBody { - tip: None, - deposit, - change_public_key: funding_key, - funding_public_keys: vec![funding_key], - max_tx_fee: GasCost::new(Value::MAX), - }, - ) - .await - .context("Failed to submit the Bedrock deposit")?; - - Ok(deposited_note) -} - -/// Whether `block` carries a channel inscription bundled with a transfer that -/// spends `note`, which only a block pinned on that deposited note does. -fn pins_note(block: &ApiBlock, note: NoteId) -> bool { - let channel_id = bedrock_channel_id(); - block.transactions.iter().any(|tx| { - tx.op_refs_iter().any(|op| { - matches!(op, OpRef::ChannelInscribe(inscribe) if inscribe.channel_id == channel_id) - }) && tx.op_refs_iter().any(|op| { - matches!( - op, - OpRef::ChannelTransfer(transfer) - if transfer.channel_id == channel_id - && transfer.inputs.iter().any(|input| *input == note) - ) - }) - }) -} - -/// A deposit the sequencer sees before its finality is minted in a block -/// published together with a transfer that spends the deposit's channel note, -/// and its finalization does not mint it again. Finality is slowed so the -/// deposit cannot finalize before the first turn and mint unpinned instead. -#[test] -async fn a_bedrock_deposit_seen_before_finality_is_minted_in_a_block_pinned_on_it_and_only_once() --> anyhow::Result<()> { - let ctx = MultiZoneTestContextBuilder::default() - .with_zone( - ZoneTestContextBuilder::new(MultiNodeTestContextConfig::default()) - .with_sequencer_partial_config(SequencerPartialConfig { - // Covers the storage price doubling at the devnet's first epoch rotations. - priority_fee_percent: 150, - ..SequencerPartialConfig::default() - }), - ) - .with_bedrock_settings("deployment-settings-slow-finality.yaml") - .build() - .await?; - let recipient = PublicKey::new_from_private_key(&PrivateKey::new_os_random()); - let recipient_id = AccountId::from(&recipient); - let amount = 1_u64; - - // Subscribed before the deposit, so no block after it is missed. - let blocks = CommonHttpClient::new(None) - .get_blocks_stream(addr_to_url(UrlProtocol::Http, ctx.bedrock_addr())?) - .await - .context("Failed to subscribe to Bedrock blocks")?; - let mut blocks = std::pin::pin!(blocks); - let deposited_note = submit_bedrock_deposit(&ctx, recipient, amount).await?; - - let pinned_at = tokio::time::timeout(TIME_TO_FINALIZE_DEPOSIT_EVENT_ON_BEDROCK, async { - while let Some(event) = blocks.next().await { - if pins_note(&event.block, deposited_note) { - return anyhow::Ok(u64::from(event.block.header.slot)); - } - } - anyhow::bail!("The Bedrock block stream ended") - }) - .await - .context("No block was published pinned on the deposit")??; - - tokio::time::timeout(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS), async { - while account_balance(&ctx, recipient_id).await? != u128::from(amount) { - tokio::time::sleep(Duration::from_millis(500)).await; - } - anyhow::Ok(()) - }) - .await - .context("The pinned block did not credit the deposit")??; - - tokio::time::timeout(TIME_TO_FINALIZE_DEPOSIT_EVENT_ON_BEDROCK, async { - while let Some(event) = blocks.next().await { - if u64::from(event.lib_slot) >= pinned_at { - return anyhow::Ok(()); - } - } - anyhow::bail!("The Bedrock block stream ended") - }) - .await - .context("The deposit never became final")??; - // Time for the sequencer to see the deposit final and produce on it. - tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS).saturating_mul(2)).await; - - ensure!( - account_balance(&ctx, recipient_id).await? == u128::from(amount), - "The finalized deposit credited the recipient again" - ); - - Ok(()) -} - -/// A deposit credits its recipient exactly once, whether it is minted pinned -/// before its finality or from its store record after. -#[test] -async fn a_bedrock_deposit_is_minted_exactly_once() -> anyhow::Result<()> { - let ctx = TestContext::new().await?; - let recipient = PublicKey::new_from_private_key(&PrivateKey::new_os_random()); - let recipient_id = AccountId::from(&recipient); - let amount = 1_u64; - - submit_bedrock_deposit(&ctx, recipient, amount).await?; - - tokio::time::timeout(TIME_TO_FINALIZE_DEPOSIT_EVENT_ON_BEDROCK, async { - while account_balance(&ctx, recipient_id).await? < u128::from(amount) { - tokio::time::sleep(Duration::from_millis(500)).await; - } - anyhow::Ok(()) - }) - .await - .context("The deposit never credited the recipient")??; - ensure!( - account_balance(&ctx, recipient_id).await? == u128::from(amount), - "The deposit credited the recipient more than once" - ); - - let client = CommonHttpClient::new(None); - let bedrock_url = addr_to_url(UrlProtocol::Http, ctx.bedrock_addr())?; - let credited_slot = u64::from( - client - .consensus_info(bedrock_url.clone()) - .await - .context("Failed to read consensus info")? - .cryptarchia_info - .slot, - ); - tokio::time::timeout(TIME_TO_FINALIZE_DEPOSIT_EVENT_ON_BEDROCK, async { - loop { - let info = client.consensus_info(bedrock_url.clone()).await?; - if u64::from(info.cryptarchia_info.lib_slot) >= credited_slot { - return anyhow::Ok(()); - } - tokio::time::sleep(Duration::from_millis(500)).await; - } - }) - .await - .context("The deposit never became final")??; - tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS).saturating_mul(2)).await; - - ensure!( - account_balance(&ctx, recipient_id).await? == u128::from(amount), - "The deposit credited the recipient more than once" - ); - - Ok(()) -} - -// TODO(withdrawals): the vault program is deleted — deposits credit recipients -// directly now, so this helper has no target account; rework when withdrawals -// are re-enabled. -// async fn wait_for_vault_balance( -// ctx: &TestContext, -// vault_id: AccountId, -// expected_balance: u128, -// ) -> anyhow::Result<()> { -// let timeout = TIME_TO_FINALIZE_DEPOSIT_EVENT_ON_BEDROCK -// + Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS); -// tokio::time::timeout(timeout, async { -// loop { -// let balance = account_balance(ctx, vault_id).await?; -// if balance == expected_balance { -// return Ok(()); -// } -// tokio::time::sleep(Duration::from_millis(500)).await; -// } -// }) -// .await -// .with_context(|| { -// format!("Timed out waiting for vault {vault_id} balance to reach {expected_balance}") -// })? -// } - -// TODO(withdrawals): predates the vault deletion — the deposit leg now credits -// the recipient directly and `Claim` no longer exists, so the claim step must -// go, not just be uncommented. -// /// Test deposit and withdraw round trip. -// /// -// /// Implemented as one test instead of two separate tests for deposit and withdraw, because the -// /// withdraw test depends on the deposit to set up the necessary state (funds in vault) for -// testing /// withdraw functionality. -// #[test] -// async fn bedrock_deposit_claim_and_withdraw_round_trip_succeeds() -> anyhow::Result<()> { -// let mut ctx = TestContext::new().await?; - -// let bedrock_account_pk = "2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26"; -// let recipient_id = ctx.existing_public_accounts()[0]; -// let amount = 1_u64; -// let vault_program_id = programs::vault_account_id(); -// let recipient_vault_id = vault_core::compute_vault_account_id(vault_program_id, -// recipient_id); - -// let vault_balance_before = account_balance(&ctx, recipient_vault_id).await?; -// let recipient_balance_before = account_balance(&ctx, recipient_id).await?; - -// // Submit deposit to Bedrock -// submit_bedrock_deposit(ctx.bedrock_addr(), bedrock_account_pk, recipient_id, amount) -// .await -// .context("Failed to submit Bedrock deposit for round-trip setup")?; - -// // Wait for vault to receive the deposit (minted from bridge to vault) -// wait_for_vault_balance( -// &ctx, -// recipient_vault_id, -// vault_balance_before + u128::from(amount), -// ) -// .await?; - -// // Now claim funds from vault back to recipient -// let nonces = ctx -// .wallet() -// .get_accounts_nonces(&[recipient_id]) -// .await -// .context("Failed to get nonce for vault claim")?; - -// let signing_key = ctx -// .wallet() -// .storage() -// .key_chain() -// .pub_account_signing_key(recipient_id) -// .with_context(|| format!("Missing signing key for account {recipient_id}"))?; - -// let claim_message = public_transaction::Message::try_new( -// vault_program_id, -// vec![recipient_id, recipient_vault_id], -// nonces, -// vault_core::Instruction::Claim { -// amount: u128::from(amount), -// }, -// ) -// .context("Failed to build vault claim message")?; - -// let claim_witness_set = -// public_transaction::WitnessSet::for_message(&claim_message, &[signing_key]); -// let claim_tx = LeeTransaction::Public(lee::PublicTransaction::new( -// claim_message, -// claim_witness_set, -// )); - -// let claim_hash = ctx.sequencer_client().send_transaction(claim_tx).await?; - -// tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; - -// let claim_on_chain = ctx.sequencer_client().get_transaction(claim_hash).await?; -// let vault_balance_after_claim = account_balance(&ctx, recipient_vault_id).await?; -// let recipient_balance_after_claim = account_balance(&ctx, recipient_id).await?; - -// assert!( -// claim_on_chain.is_some(), -// "Vault claim transaction must be included on-chain" -// ); -// assert_eq!( -// vault_balance_after_claim, vault_balance_before, -// "Vault balance should return to initial state after claim" -// ); -// assert_eq!( -// recipient_balance_after_claim, -// recipient_balance_before + u128::from(amount), -// "Recipient balance should increase by claimed amount" -// ); - -// // The indexer must replay the deposit and claim blocks and reach the same -// // state as the sequencer — including the bridge system account the deposit -// // modifies, which is the case the hot fix unblocks. -// wait_for_indexer_to_catch_up(&ctx).await?; -// let bridge_account_id = system_accounts::bridge_account_id(); -// for account_id in [recipient_id, recipient_vault_id, bridge_account_id] { -// let indexer_account = indexer_service_rpc::RpcClient::get_account( -// // `deref` is needed for correct trait resolution -// // of the async `get_account` method on `RpcClient` -// ctx.indexer_client().deref(), -// account_id.into(), -// ) -// .await?; -// let sequencer_account = get_account(&ctx, account_id).await?; -// assert_eq!( -// indexer_account, -// sequencer_account.into(), -// "Indexer and sequencer diverged for account {account_id} after deposit" -// ); -// } - -// // Withdraw back to Bedrock and wait for finalized withdraw event. -// let sender_id = recipient_id; - -// let observer = create_zone_indexer_observer(ctx.bedrock_addr())?; -// let observe_fut = -// wait_for_finalized_withdraw_op(&observer, ctx.bedrock_addr(), amount, -// bedrock_account_pk); - -// let withdraw_fut = execute_subcommand( -// ctx.wallet_mut(), -// Command::Bridge(BridgeSubcommand::Withdraw { -// from: public_mention(sender_id), -// amount, -// bedrock_account_pk: bedrock_account_pk.to_owned(), -// }), -// ); - -// let (observe_result, withdraw_result) = tokio::join!(observe_fut, withdraw_fut); - -// withdraw_result.context("Failed to execute wallet bridge withdraw command")?; - -// observe_result -// .context("Failed while waiting for finalized withdraw event from zone indexer")?; - -// // Sleep to observe sequencer log about validated withdraw event -// tokio::time::sleep(Duration::from_secs(1)).await; - -// Ok(()) -// } - -// fn create_zone_indexer_observer( -// bedrock_addr: std::net::SocketAddr, -// ) -> anyhow::Result> { -// let bedrock_url = integration_tests::config::addr_to_url( -// integration_tests::config::UrlProtocol::Http, -// bedrock_addr, -// ) -// .context("Failed to convert Bedrock addr to URL for zone indexer observer")?; - -// let node = NodeHttpClient::new(CommonHttpClient::new(None), bedrock_url); - -// Ok(ZoneIndexer::new( -// integration_tests::config::bedrock_channel_id(), -// node, -// )) -// } - -// /// Waits for a finalized withdraw that pays `expected_amount` to `receiver_pk`. -// /// -// /// A withdraw op releases channel-owned notes and carries nothing but their -// /// ids — the value and recipient live in the note itself. A released note keeps -// /// its id, value and public key, so the pairing is checked on the receiver's -// /// Bedrock wallet: one of the released notes must land there with the expected -// /// value. -// async fn wait_for_finalized_withdraw_op( -// observer: &ZoneIndexer, -// bedrock_addr: std::net::SocketAddr, -// expected_amount: u64, -// receiver_pk: &str, -// ) -> anyhow::Result<()> { -// let timeout = TIME_TO_FINALIZE_DEPOSIT_EVENT_ON_BEDROCK -// + Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS); - -// tokio::time::timeout(timeout, async { -// // The wallet can trail the channel event, so released notes accumulate -// // across polls instead of being checked once when first observed. -// let mut released_notes = HashSet::new(); - -// loop { -// let stream = observer -// .follow() -// .await -// .context("Failed to read zone indexer message batch")?; -// let mut stream = std::pin::pin!(stream); - -// while let Some(message) = stream.next().await { -// tracing::info!(?message, "Observed zone message"); - -// if let ZoneMessage::Withdraw(withdraw) = message { -// released_notes.extend(withdraw.inputs.iter().copied()); -// } -// } - -// if !released_notes.is_empty() { -// let balance = bedrock_wallet_balance(bedrock_addr, receiver_pk).await?; -// if released_notes -// .iter() -// .any(|note_id| balance.notes.get(note_id) == Some(&expected_amount)) -// { -// return Ok(()); -// } -// } - -// tokio::time::sleep(Duration::from_millis(500)).await; -// } -// }) -// .await -// .with_context(|| { -// format!("Timed out waiting for finalized withdraw message with amount {expected_amount}") -// })? -// } +// TODO: Bedrock deposit and withdraw tests return with the vault program. diff --git a/lez/chain_state/Cargo.toml b/lez/chain_state/Cargo.toml index 4db13bce12..bb2957c139 100644 --- a/lez/chain_state/Cargo.toml +++ b/lez/chain_state/Cargo.toml @@ -13,6 +13,9 @@ fee_core.workspace = true lee.workspace = true lee_core = { workspace = true, features = ["host"] } programs.workspace = true +sequencer_bridge.workspace = true +bridge_core = { workspace = true, features = ["host"] } +vault_circuit.workspace = true sequencer_stake_core.workspace = true system_accounts.workspace = true logos-blockchain-zone-sdk.workspace = true diff --git a/lez/chain_state/src/classify.rs b/lez/chain_state/src/classify.rs index 1cd4f05660..2bcb26326a 100644 --- a/lez/chain_state/src/classify.rs +++ b/lez/chain_state/src/classify.rs @@ -213,7 +213,7 @@ pub fn classify(tx: &LeeTransaction, is_genesis: bool) -> Result = LazyLock::new(|| derive_program_id(&vault_key())); + +/// What the zone mints for a deposit the vault took in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VaultMint { + /// The first nullifier of the deposit. Bedrock spends a note once, so no other deposit + /// shares it. + pub id: [u8; 32], + /// Read from the deposit's inscription, a borsh [`DepositMetadata`]. + pub recipient: DepositRecipient, + pub amount: BridgeAmount, +} + +impl VaultMint { + /// `None` for a deposit that names no recipient or spends no note. + #[must_use] + pub fn of(deposit: &ProgramDeposit) -> Option { + let recipient = DepositMetadata::try_from_slice(deposit.inscription.as_ref()) + .ok()? + .recipient; + let nullifier = deposit.inputs.iter().next()?; + Some(Self { + id: fr_to_bytes(&nullifier.0), + recipient, + amount: deposit.value, + }) + } + + /// The transaction a block mints it with, byte for byte. + #[must_use] + pub fn transaction(&self) -> Option { + deposit_tx( + self.id, + &Credited::Public(self.recipient.evidence()), + self.amount, + ) + .ok() + .map(LeeTransaction::Public) + } +} + +/// The key the vault program is registered under. +#[must_use] +pub fn vault_key() -> ProgramVerificationKey { + ProgramVerificationKey::try_from_bytes(vault_circuit::DEMO_VERIFICATION_KEY) + .expect("the vault key is a valid program key") +} + +/// Whether `block` mints exactly the deposits the vault took in with the inscription carrying +/// it, in their order. Genesis mints its supply with no deposit behind it. +#[must_use] +pub fn mints_backed(block: &Block, steps: &InscriptionSteps) -> bool { + let mut taken = Vec::new(); + for mini_block in steps.mini_blocks.iter() { + for step in mini_block.iter() { + let Step::ProgramDeposit(deposit) = step else { + continue; + }; + if deposit.program_id != *VAULT_PROGRAM { + continue; + } + let Some(mint) = VaultMint::of(deposit).and_then(|mint| mint.transaction()) else { + return false; + }; + taken.push(mint); + } + } + if block.header.block_id == GENESIS_BLOCK_ID { + return taken.is_empty(); + } + block + .body + .transactions + .iter() + .filter(|tx| is_bridge_deposit(tx)) + .eq(&taken) +} + +fn is_bridge_deposit(tx: &LeeTransaction) -> bool { + tx.public_call().is_some_and(|(to, message)| { + to.program_account_id == programs::bridge_account_id() + && matches!( + borsh::from_slice(message), + Ok(bridge_core::Message::Deposit { .. }) + ) + }) +} + +#[cfg(test)] +mod tests { + use common::test_utils::produce_dummy_block; + use logos_blockchain_zone_sdk::{ + core::mantle::{ + notes::{NoteNullifier, OutputCommitments}, + ops::channel::inscribe::{MiniBlock, MiniBlocks}, + }, + groth16::Fr, + node_types::Inscription, + }; + + use super::*; + + fn deposit(program_id: ProgramId, nullifier: u64, value: u64) -> ProgramDeposit { + let metadata = DepositMetadata { + recipient: DepositRecipient::Identified(lee::PublicAccountEvidence::Pda { + program: lee::AccountId::new([7; 32]), + seed: bridge_core::deposit_receipt_seed([9; 32]), + }), + }; + ProgramDeposit { + program_id, + inputs: [NoteNullifier(Fr::from(nullifier))].into(), + outputs: OutputCommitments::default(), + commitment_merkle_root: Fr::from(0_u64), + value, + intent: Fr::from(0_u64), + inscription: Inscription::try_new(borsh::to_vec(&metadata).unwrap(), 128).unwrap(), + } + } + + fn steps(deposits: &[ProgramDeposit]) -> InscriptionSteps { + let mini_blocks = MiniBlock::try_from( + deposits + .iter() + .cloned() + .map(Step::ProgramDeposit) + .collect::>(), + ) + .map_or_else(|_| MiniBlocks::default(), |block| [block].into()); + InscriptionSteps { + mini_blocks, + ..InscriptionSteps::default() + } + } + + fn block(mints: &[&ProgramDeposit]) -> Block { + let txs = mints + .iter() + .map(|deposit| VaultMint::of(deposit).unwrap().transaction().unwrap()) + .collect(); + produce_dummy_block(2, None, txs) + } + + #[test] + fn a_block_mints_exactly_the_deposits_of_its_inscription() { + let first = deposit(*VAULT_PROGRAM, 1, 10); + let second = deposit(*VAULT_PROGRAM, 2, 20); + let both = steps(&[first.clone(), second.clone()]); + + assert!(mints_backed(&block(&[&first, &second]), &both)); + assert!(mints_backed(&block(&[]), &steps(&[]))); + + // A mint with no deposit behind it, a deposit left unminted, another amount, another + // order. + assert!(!mints_backed(&block(&[&first]), &steps(&[]))); + assert!(!mints_backed(&block(&[&first]), &both)); + assert!(!mints_backed( + &block(&[&deposit(*VAULT_PROGRAM, 1, 11), &second]), + &both + )); + assert!(!mints_backed(&block(&[&second, &first]), &both)); + } + + #[test] + fn a_deposit_to_another_program_backs_no_mint() { + let other = deposit(Fr::from(5_u64), 1, 10); + + assert!(mints_backed( + &block(&[]), + &steps(std::slice::from_ref(&other)) + )); + assert!(!mints_backed(&block(&[&other]), &steps(&[other]))); + } + + #[test] + fn genesis_mints_unbacked() { + let minted = deposit(*VAULT_PROGRAM, 1, 10); + let genesis = produce_dummy_block( + GENESIS_BLOCK_ID, + None, + vec![VaultMint::of(&minted).unwrap().transaction().unwrap()], + ); + + assert!(mints_backed(&genesis, &steps(&[]))); + } +} diff --git a/lez/chain_state/src/zone_indexer.rs b/lez/chain_state/src/zone_indexer.rs index a50141f39f..d41d807654 100644 --- a/lez/chain_state/src/zone_indexer.rs +++ b/lez/chain_state/src/zone_indexer.rs @@ -293,6 +293,7 @@ mod tests { id: MsgId::root(), data: Inscription::new_unchecked(vec![tag]), signer: UnverifiedEd25519PublicKey::from_bytes(&[0; 32]).expect("valid key"), + steps: logos_blockchain_zone_sdk::InscriptionSteps::default(), }) } diff --git a/lez/common/src/transaction.rs b/lez/common/src/transaction.rs index bc000eb14f..a2c1812a33 100644 --- a/lez/common/src/transaction.rs +++ b/lez/common/src/transaction.rs @@ -685,9 +685,8 @@ fn validate_no_inbox_state_modification( /// Whether `pre` became `post` by a pure native balance increase: nonce and /// every other shard unchanged. /// -/// The only change a user transaction may make to the bridge escrow (legit -/// deposits debit it, but they are sequencer-injected) or, for a private -/// transaction, to the fee inbox. +/// The only change a user transaction may make to the bridge escrow (only +/// genesis deposits debit it) or, for a private transaction, to the fee inbox. #[must_use] fn native_balance_only_increased(pre: &lee::Account, post: &lee::Account) -> bool { fn non_native( diff --git a/lez/configs/docker-all-in-one/devnet/sequencer_config.json b/lez/configs/docker-all-in-one/devnet/sequencer_config.json index 1c5ab457f3..c71ad05dc0 100644 --- a/lez/configs/docker-all-in-one/devnet/sequencer_config.json +++ b/lez/configs/docker-all-in-one/devnet/sequencer_config.json @@ -57,8 +57,8 @@ 132, 121 ], - "ownership_public_key": "76d462a4242a2dfd73535dc608e3258986edd5f0b4e13ed09360c1c1e1d79016", - "stake_signature": "d928bf3964f623ce1966eef3f7d4dc6d89c2cbfe4c898ca4315996864d5866b8081166d7ccf65dfad8fd88a026cd58d704638dbd2b164335dcb463c04c075715" + "ownership_public_key": "9f7cd3f5a113bbd7508ef7666a93f5971a713b277d442724b179f219ce7d6cb2", + "stake_signature": "13025cf54169175b6471bc149d3d2cb7aac90224b6a84962a5a37a39703d0f1aaf47f32bb15cb97bc8f7fdbf018b27d97f00bd99904379993d68809f2ddedd01" } }, { @@ -97,8 +97,8 @@ 42, 251 ], - "ownership_public_key": "734c990c6e18e2787c6d302097b6e624f979c035fa27e9d07b2375d64057f6ba", - "stake_signature": "7764de1b449a724c8ba6c6e082ec738a62be320ffe95c353a0f8b2ac7d2d8689fb80da73c23213a26555314b29fac66112c028ce48e18e22a240b135290b658d" + "ownership_public_key": "5ee575ac5123fe6ee7d050ab18b8bab6b968dbddcc6be74b1f970799edb649bd", + "stake_signature": "24547eea66ce70aefaf0b76a8aa67e0ad0f692c1580cd73f9574610b3721c30786fb97638362172ac89ac9477450d932b62fd8275d3275b1b93df451859b9d30" } }, { @@ -137,8 +137,8 @@ 113, 209 ], - "ownership_public_key": "1e88684905306c8867818142d79622cb648f5e0a48f979608adffff6cf2e441f", - "stake_signature": "e34acf0055f7207fc757fedfc1f6dab07b8a0863223e38afd99132e9192275cad60d0697db7be9c240ab96416adc456223de9c207245837c58eff2a8e3ecf6c6" + "ownership_public_key": "e66f5edc6718244925f40f427211ff51bff96e04e70983fb81c0fdc3a0972d84", + "stake_signature": "2ec40393f31169d5b6c816e6dd9626fd579a4446a7366c817473e7dbf4b5d8b66e086d8c6bc3521f1603747e618e9981e2efa01ee9064273a8425744ff2e7cea" } }, { @@ -177,8 +177,8 @@ 17, 10 ], - "ownership_public_key": "44cb48cc1cbbdb3cf2e566d22a54412a821c115c6a3d65f0f2c7e1db82cdbca9", - "stake_signature": "279cf5a7818a267113568d85b05d25d5c46bb27a93d0d6d29a523c9f2ddf986e8d6e75c65a0089998312433e92602aa021d3f863c9995753e3b67637b4c41a9d" + "ownership_public_key": "13f110498c8758ab700747ffedcd542566b199e7465938b592801251691bc209", + "stake_signature": "b0fce6cecb14a53d447becfae638518463f02b21fb1d268dc375d96c6be48b076d6b87a6855b728ec2100e45c7461a872abb37a34c7e4d3a2096d31f40f6f58c" } }, { diff --git a/lez/indexer/core/src/block_store.rs b/lez/indexer/core/src/block_store.rs index 1364cac70b..64b258c93c 100644 --- a/lez/indexer/core/src/block_store.rs +++ b/lez/indexer/core/src/block_store.rs @@ -1794,24 +1794,29 @@ mod accept_tests { .await .expect("accept genesis"); - // A system-shaped bridge deposit (empty witness set, so fee-exempt by + // A system-shaped inbox dispatch (empty witness set, so fee-exempt by // classification) whose execution fails: the guest rejects the bogus - // accounts → StateTransition → retryable. A charged overdraft no - // longer works here: it reverts-with-fee inside a valid block. - let bogus_deposit = { + // accounts → StateTransition → retryable. A charged overdraft does + // not work here: it reverts-with-fee inside a valid block. + let bogus_dispatch = { let to = Actor::new( lee::AccountId::new([1_u8; 32]), - programs::bridge_account_id(), + programs::cross_zone_inbox_account_id(), ); let message = lee::public_transaction::Message::try_new( to, vec![to], std::collections::BTreeMap::new(), - bridge_core::Message::Deposit { - l1_deposit_op_id: [7_u8; 32], - recipient_id: lee::AccountId::new([3_u8; 32]), - amount: 5, - }, + cross_zone_inbox_core::Message::Dispatch(cross_zone_inbox_core::CrossZoneMessage { + src_zone: [7_u8; 32], + src_block_id: 1, + src_block_hash: [0_u8; 32], + src_tx_index: 0, + src_account_id: lee::AccountId::new([2_u8; 32]), + target_account_id: lee::AccountId::new([3_u8; 32]), + payload: Vec::new(), + l1_inclusion_witness: None, + }), ) .expect("valid message"); common::transaction::LeeTransaction::Public(lee::PublicTransaction::new( @@ -1819,7 +1824,7 @@ mod accept_tests { lee::public_transaction::WitnessSet::from_raw_parts(vec![]), )) }; - let block = produce_dummy_block(2, Some(genesis.header.hash), vec![bogus_deposit]); + let block = produce_dummy_block(2, Some(genesis.header.hash), vec![bogus_dispatch]); let outcome = store.accept_block(&block, Slot::from(0)).await.unwrap(); assert!(matches!( diff --git a/lez/indexer/core/src/cross_zone_verifier.rs b/lez/indexer/core/src/cross_zone_verifier.rs index 0a2c4cc7d7..48590235f5 100644 --- a/lez/indexer/core/src/cross_zone_verifier.rs +++ b/lez/indexer/core/src/cross_zone_verifier.rs @@ -1548,6 +1548,7 @@ mod tests { id: MsgId::from([0; 32]), data: Inscription::new_unchecked(data), signer: UnverifiedEd25519PublicKey::from_bytes(&[0; 32]).expect("valid key"), + steps: logos_blockchain_zone_sdk::InscriptionSteps::default(), }), Slot::from(slot), ) diff --git a/lez/indexer/core/src/lib.rs b/lez/indexer/core/src/lib.rs index 4a89ac99fc..9396cc5c22 100644 --- a/lez/indexer/core/src/lib.rs +++ b/lez/indexer/core/src/lib.rs @@ -461,7 +461,17 @@ impl IndexerCore { ZoneMessage::Deposit(_) | ZoneMessage::Withdraw(_) => continue, }; - let block: Block = match borsh::from_slice(&zone_block.data) { + let block: Block = match borsh::from_slice(&zone_block.data).and_then( + |block| { + if chain_state::vault::mints_backed(&block, &zone_block.steps) { + Ok(block) + } else { + Err(std::io::Error::other( + "the block's mints differ from the vault's deposits", + )) + } + }, + ) { Ok(b) => b, Err(error) => { // The stall must be durable before the cursor moves. diff --git a/lez/programs/bridge/core/src/event.rs b/lez/programs/bridge/core/src/event.rs index 800658b68d..aca6978c8f 100644 --- a/lez/programs/bridge/core/src/event.rs +++ b/lez/programs/bridge/core/src/event.rs @@ -24,8 +24,6 @@ impl Deposit { } } -// The bridge emitter for this event is disabled; withdrawals panic today, so no -// Withdraw event is ever produced. #[derive(Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)] pub struct Withdraw { pub sender_id: AccountId, diff --git a/lez/programs/bridge/core/src/lib.rs b/lez/programs/bridge/core/src/lib.rs index a3e9aba066..b73d3dbf4f 100644 --- a/lez/programs/bridge/core/src/lib.rs +++ b/lez/programs/bridge/core/src/lib.rs @@ -34,10 +34,10 @@ pub enum Message { amount: BridgeAmount, }, - /// Transfers native tokens from a user account to the bridge PDA account. + /// Transfers native tokens from the signing account to the bridge PDA account. /// - /// `bedrock_account_pk` is consumed by the Sequencer and is not used by the Bridge program - /// logic. + /// Sent to the signer's own actor of this program. `bedrock_account_pk` is the L1 key the + /// sequencer pays out to; the program does not read it. Withdraw { amount: BridgeAmount, bedrock_account_pk: [u8; 32], diff --git a/lez/programs/bridge/src/main.rs b/lez/programs/bridge/src/main.rs index 63a2e9c7cb..3ae92ff793 100644 --- a/lez/programs/bridge/src/main.rs +++ b/lez/programs/bridge/src/main.rs @@ -1,6 +1,7 @@ -use bridge_core::Message; +use bridge_core::{BridgeAmount, Message}; use lee_core::{ - native_token::custody_transfer, + account::{AccountId, Actor}, + native_token::{self, custody_transfer}, program::{ProgramEvent, ReceiveInput, Response}, }; @@ -15,15 +16,25 @@ fn handle_message(input: &ReceiveInput, message: Message) -> Response { "Bridge cannot be invoked through chain calls" ); - let Message::Deposit { - l1_deposit_op_id, - recipient_id, - amount, - } = message - else { - panic!("Withdraws are disabled in the current version of LEZ"); - }; + match message { + Message::Deposit { + l1_deposit_op_id, + recipient_id, + amount, + } => deposit(input, l1_deposit_op_id, recipient_id, amount), + Message::Withdraw { + amount, + bedrock_account_pk, + } => withdraw(input, amount, bedrock_account_pk), + } +} +fn deposit( + input: &ReceiveInput, + l1_deposit_op_id: [u8; 32], + recipient_id: AccountId, + amount: BridgeAmount, +) -> Response { let bridge = input.receiver.program_account_id; // The receipt actor state is the L1-deposit replay guard, so it must be the one this op id // derives. @@ -55,12 +66,35 @@ fn handle_message(input: &ReceiveInput, message: Message) -> Response { }) } +/// Returns `amount` from the signing account to bridge custody. +/// The event is what the sequencer pays out on L1. +fn withdraw(input: &ReceiveInput, amount: BridgeAmount, bedrock_account_pk: [u8; 32]) -> Response { + assert!(input.is_authorized, "must sign for the withdrawing account"); + assert!(amount > 0, "a withdrawal moves a nonzero amount"); + + let sender_id = input.receiver.account_id; + Response::keep_state() + .send_sync( + Actor::native_balance(sender_id), + &native_token::Message::Transfer { + to: bridge_core::compute_bridge_account_id(input.receiver.program_account_id), + amount: u128::from(amount), + }, + ) + .event(ProgramEvent { + selector: bridge_core::event::Withdraw::SELECTOR, + data: bridge_core::event::Withdraw { + sender_id, + amount, + bedrock_account_pk, + } + .to_bytes(), + }) +} + #[cfg(test)] mod tests { - use lee_core::{ - account::{AccountId, Actor, ActorState}, - program::Transition, - }; + use lee_core::{account::ActorState, program::Transition}; use super::*; @@ -130,4 +164,51 @@ mod tests { fn a_deposit_from_another_program_is_refused() { let _transition = run(Some(AccountId::new([5; 32])), &[]); } + + fn run_withdraw(is_authorized: bool, amount: BridgeAmount) -> Transition { + let message = || Message::Withdraw { + amount, + bedrock_account_pk: [4; 32], + }; + let input = ReceiveInput { + receiver: Actor::new(RECIPIENT, BRIDGE), + from: None, + is_authorized, + pre_state: ActorState::empty(), + message: borsh::to_vec(&message()).unwrap(), + }; + handle_message(&input, message()).into_transition(input) + } + + #[test] + fn a_withdrawal_returns_the_amount_to_custody_and_names_the_payout() { + let transition = run_withdraw(true, 5); + + assert_eq!(transition.response.post_state, None); + assert_eq!(transition.response.sync_messages.len(), 1); + assert_eq!( + transition.response.sync_messages[0].to, + Actor::native_balance(RECIPIENT) + ); + assert_eq!( + bridge_core::event::Withdraw::from_bytes(&transition.response.events[0].data).unwrap(), + bridge_core::event::Withdraw { + sender_id: RECIPIENT, + amount: 5, + bedrock_account_pk: [4; 32], + } + ); + } + + #[test] + #[should_panic(expected = "must sign for the withdrawing account")] + fn a_withdrawal_nobody_signed_is_refused() { + let _transition = run_withdraw(false, 5); + } + + #[test] + #[should_panic(expected = "a withdrawal moves a nonzero amount")] + fn an_empty_withdrawal_is_refused() { + let _transition = run_withdraw(true, 0); + } } diff --git a/lez/programs/src/lib.rs b/lez/programs/src/lib.rs index 67ab72ebe5..783d1127a1 100644 --- a/lez/programs/src/lib.rs +++ b/lez/programs/src/lib.rs @@ -1371,6 +1371,56 @@ mod inner { )); } + #[test] + fn bridge_withdraw_returns_the_amount_to_custody_and_emits_the_payout() { + let signer = lee::PrivateKey::try_new([0x44; 32]).unwrap(); + let sender_id = AccountId::from(&lee::PublicKey::new_from_private_key(&signer)); + let custody = bridge_core::compute_bridge_account_id(bridge_account_id()); + let mut state = V03State::new() + .with_public_accounts([ + (custody, Account::default()), + (sender_id, Account::funded(9)), + ]) + .with_programs_at([(bridge_account_id(), bridge(), true)]); + + let root = Actor::new(sender_id, bridge_account_id()); + let message = public_transaction::Message::try_new( + root, + [ + root, + Actor::native_balance(sender_id), + Actor::native_balance(custody), + ], + std::collections::BTreeMap::from([(sender_id, lee_core::account::Nonce(0))]), + bridge_core::Message::Withdraw { + amount: 4, + bedrock_account_pk: [6; 32], + }, + ) + .unwrap(); + let witness_set = public_transaction::WitnessSet::for_message(&message, &[&signer]); + let tx = PublicTransaction::new(message, witness_set); + let events = state.transition_from_public_transaction(&tx, 1, 0).unwrap(); + + assert_eq!(events.len(), 1); + assert_eq!( + bridge_core::event::Withdraw::from_bytes(&events[0].event.data).unwrap(), + bridge_core::event::Withdraw { + sender_id, + amount: 4, + bedrock_account_pk: [6; 32], + } + ); + assert_eq!( + state.get_account_by_id(sender_id).data, + Account::funded(5).data + ); + assert_eq!( + state.get_account_by_id(custody).data, + Account::funded(4).data + ); + } + #[test] fn builtin_constructors_carry_their_ids_and_elfs() { let bridge_program = bridge(); diff --git a/lez/sequencer/actors/bedrock/Cargo.toml b/lez/sequencer/actors/bedrock/Cargo.toml index 4a7ae343ac..507fcaf3b4 100644 --- a/lez/sequencer/actors/bedrock/Cargo.toml +++ b/lez/sequencer/actors/bedrock/Cargo.toml @@ -9,7 +9,16 @@ workspace = true [features] # Adds actor implementation using kameo_actors. -actor = ["dep:kameo_actors", "dep:tokio", "dep:borsh", "dep:url", "dep:tracing"] +actor = [ + "dep:kameo_actors", + "dep:tokio", + "dep:borsh", + "dep:url", + "dep:tracing", + "dep:vault_circuit", + "dep:bridge_core", + "dep:rand", +] # Adds mock actor implementation. mock = ["sequencer_actors_common/mock", "dep:mockall"] test-utils = [] @@ -28,13 +37,18 @@ thiserror.workspace = true anyhow.workspace = true futures.workspace = true kameo_actors = { workspace = true, optional = true } -tokio = { workspace = true, features = ["time"], optional = true } +tokio = { workspace = true, features = ["time", "rt"], optional = true } borsh = { workspace = true, optional = true } url = { workspace = true, optional = true } tracing = { workspace = true, optional = true } mockall = { workspace = true, optional = true } +vault_circuit = { workspace = true, optional = true } +bridge_core = { workspace = true, features = ["host"], optional = true } +rand = { workspace = true, optional = true } [dev-dependencies] -rand.workspace = true +logos-blockchain-program-spend.workspace = true +lee.workspace = true +logos-blockchain-core = { workspace = true, features = ["test-utils"] } glob.workspace = true tokio = { workspace = true, features = ["macros", "test-util"] } diff --git a/lez/sequencer/actors/bedrock/src/actor.rs b/lez/sequencer/actors/bedrock/src/actor.rs index 7b0e085862..55b0485afe 100644 --- a/lez/sequencer/actors/bedrock/src/actor.rs +++ b/lez/sequencer/actors/bedrock/src/actor.rs @@ -1,5 +1,5 @@ use std::{ - collections::{BTreeSet, HashMap, HashSet}, + collections::{BTreeSet, HashMap}, num::NonZero, time::Duration, }; @@ -22,8 +22,7 @@ use logos_blockchain_zone_sdk::{ CommonHttpClient, adapter::{Node as _, NodeHttpClient}, common_http_client::BasicAuthCredentials, - core::mantle::NoteId, - sequencer::{InscriptionInfo, PendingTx}, + sequencer::InscriptionInfo, }; use sequencer_storage_actor::{ StorageActorTrait, @@ -39,13 +38,13 @@ use crate::{ actor::finality::{BlockSummary, ConfigIndex, L1Reader}, error::Error, protocol::{ - AccreditedKeys, ChangeChannelConfig, ChannelEvent, ChannelId, ChannelReadStream, - ChannelSeq, CheckChannelExists, CheckIsOurTurn, CreateChannel, DeserializeOp as _, - Ed25519PublicKey, FilterFinallyAbsent, FollowChannel, GetAccreditedKeys, GetChannelNotes, - GetChannelTipMessageId, GetChannelTipSlot, HeaderId, InitializeChannelPublisher, - LiveChannelConfig, MsgId, PrepareConfig, PreparePin, PreparedConfig, PreparedPin, - PublishBlock, PublishOutcome, PublishPin, ReadChannel, SequencerCheckpoint, SequencerKey, - Slot, UnverifiedEd25519PublicKey, + AccreditedKeys, AdmitDeposit, ChangeChannelConfig, ChannelEvent, ChannelId, + ChannelReadStream, ChannelSeq, CheckChannelExists, CheckIsOurTurn, CreateChannel, + DeserializeOp as _, Ed25519PublicKey, FilterFinallyAbsent, FollowChannel, + GetAccreditedKeys, GetChannelTipMessageId, GetChannelTipSlot, HeaderId, + InitializeChannelPublisher, LiveChannelConfig, MsgId, PrepareConfig, PreparedConfig, + PublishBlock, PublishOutcome, ReadChannel, SequencerCheckpoint, SequencerKey, Slot, + UnverifiedEd25519PublicKey, VaultMint, }, }; @@ -54,6 +53,7 @@ mod node_stream; mod publisher; #[cfg(test)] mod tests; +pub mod vault; /// Time one [`FilterFinallyAbsent`] may hold the actor; the blocks and configs it read are kept. const FILTER_FINALLY_ABSENT_BUDGET: Duration = Duration::from_secs(10); @@ -81,10 +81,6 @@ pub struct Args { /// - If the channel is followed with [`FollowChannel`]: /// - `channel//finalized_block`: for /// [`ChannelEventKind::FinalizedBlock`](crate::protocol::ChannelEventKind::FinalizedBlock). -/// - `channel//finalized_deposit`: for -/// [`ChannelEventKind::FinalizedDeposit`](crate::protocol::ChannelEventKind::FinalizedDeposit). -/// - `channel//finalized_withdrawal`: for -/// [`ChannelEventKind::FinalizedWithdrawal`](crate::protocol::ChannelEventKind::FinalizedWithdrawal). /// - `channel//finalized_up_to`: for /// [`ChannelEventKind::FinalizedUpTo`](crate::protocol::ChannelEventKind::FinalizedUpTo). /// - If publisher was initialized with [`InitializeChannelPublisher`]: @@ -94,8 +90,6 @@ pub struct Args { /// [`PublisherEvent::Turn`](crate::protocol::PublisherEvent::Turn) /// - `channel//publisher/config`: for /// [`PublisherEvent::Config`](crate::protocol::PublisherEvent::Config) -/// - `channel//publisher/deposits`: for -/// [`PublisherEvent::Deposits`](crate::protocol::PublisherEvent::Deposits) pub struct BedrockActor { channel_id: ChannelId, backfill_batch_slots: NonZero, @@ -198,6 +192,10 @@ impl Actor for BedrockActor { )] loop { select! { + // Channel events first, so the ones a publish queued while it was funded are + // handed on before the next publish. This alone does not keep zone-sdk moving + // under back-to-back publishes: `Publisher::fund_ops` polls it for that. + biased; Some(Some(item)) = OptionFuture::from(self.node_stream.as_mut().map(node_stream::NodeStream::next_item)) => { let item = item?; let span = info_span!("bedrock_event", otel.name = item.span_name()); @@ -317,20 +315,13 @@ impl Message for BedrockActor { keys, channel_params, configuration_threshold, - transfer_threshold, }: CreateChannel, _ctx: &mut Context, ) -> Self::Reply { self.assert_channel_id(channel_id); self.publisher()? - .create_channel( - genesis, - keys, - channel_params, - configuration_threshold, - transfer_threshold, - ) + .create_channel(genesis, keys, channel_params, configuration_threshold) .await } } @@ -343,62 +334,20 @@ impl Message for BedrockActor { PublishBlock { channel_id, block, - withdrawals, parent, expected_seq, + bridge, }: PublishBlock, _ctx: &mut Context, ) -> Self::Reply { self.assert_channel_id(channel_id); self.publisher()? - .publish_block(block, withdrawals, parent, expected_seq) - .await - } -} - -impl Message for BedrockActor { - type Reply = Result; - - async fn handle( - &mut self, - PreparePin { - channel_id, - block, - parent, - notes, - expected_seq, - }: PreparePin, - _ctx: &mut Context, - ) -> Self::Reply { - self.assert_channel_id(channel_id); - - self.publisher()? - .prepare_pin(block, parent, ¬es, expected_seq) + .publish_block(block, parent, expected_seq, bridge) .await } } -impl Message for BedrockActor { - type Reply = Result; - - async fn handle( - &mut self, - PublishPin { - channel_id, - prepared, - signatures, - expected_seq, - }: PublishPin, - _ctx: &mut Context, - ) -> Self::Reply { - self.assert_channel_id(channel_id); - - self.publisher()? - .publish_pin(prepared, signatures, expected_seq) - } -} - impl Message for BedrockActor { type Reply = Result; @@ -410,7 +359,6 @@ impl Message for BedrockActor { posting_timeframe, posting_timeout, configuration_threshold, - transfer_threshold, }: PrepareConfig, _ctx: &mut Context, ) -> Self::Reply { @@ -422,7 +370,6 @@ impl Message for BedrockActor { posting_timeframe, posting_timeout, configuration_threshold, - transfer_threshold, ) .await } @@ -480,6 +427,23 @@ impl Message for BedrockActor { } } +impl Message for BedrockActor { + type Reply = Result; + + async fn handle( + &mut self, + AdmitDeposit { + channel_id, + deposit, + }: AdmitDeposit, + _ctx: &mut Context, + ) -> Self::Reply { + self.assert_channel_id(channel_id); + + self.publisher()?.admit_deposit(&deposit) + } +} + impl Message for BedrockActor { type Reply = Result>; @@ -506,20 +470,6 @@ impl Message for BedrockActor { } } -impl Message for BedrockActor { - type Reply = Result>; - - async fn handle( - &mut self, - GetChannelNotes { channel_id }: GetChannelNotes, - _ctx: &mut Context, - ) -> Self::Reply { - self.assert_channel_id(channel_id); - - Ok(self.publisher()?.channel_notes()) - } -} - impl Message for BedrockActor { type Reply = Result>; @@ -759,7 +709,6 @@ impl TryFrom<&logos_blockchain_zone_sdk::node_types::ChannelState> for LiveChann keys: verified_keys(&state.accredited_keys)?, config_tip: state.config_tip_hash, required_signatures: state.configuration_threshold, - transfer_threshold: state.transfer_threshold, posting_timeframe: state.posting_timeframe.clone().into(), posting_timeout: state.posting_timeout.clone().into(), }) @@ -789,19 +738,6 @@ fn block_from_inscription(inscription: &InscriptionInfo) -> Option { .ok() } -/// Channel notes the withdraws bundled with a published tx release; empty for a -/// plain inscription. See [`PublishOutcome::released_notes`]. -fn released_notes(tx: &PendingTx) -> Vec { - match tx { - PendingTx::Inscription(_) | PendingTx::PinDeposit(_) => Vec::new(), - PendingTx::AtomicWithdraw(bundle) => bundle - .withdraws - .iter() - .flat_map(|withdraw| withdraw.op.inputs.iter().copied()) - .collect(), - } -} - fn verified_keys(keys: &[UnverifiedEd25519PublicKey]) -> Result> { keys.iter() .map(|key| { diff --git a/lez/sequencer/actors/bedrock/src/actor/node_stream.rs b/lez/sequencer/actors/bedrock/src/actor/node_stream.rs index bd51e53340..9fde209bd3 100644 --- a/lez/sequencer/actors/bedrock/src/actor/node_stream.rs +++ b/lez/sequencer/actors/bedrock/src/actor/node_stream.rs @@ -9,10 +9,8 @@ use futures::{Stream, StreamExt as _, TryStreamExt as _}; use kameo::actor::ActorRef; use kameo_actors::broker::Broker; use logos_blockchain_zone_sdk::{ - Deposit, Withdraw, adapter::{Node as _, NodeHttpClient}, common_http_client::ProcessedBlockEvent, - core::mantle::ops::channel::withdraw::ChannelWithdrawOp, }; use sequencer_actors_common::SendErrorExt as _; use sequencer_storage_actor::protocol::ZoneAnchorRecord; @@ -22,8 +20,8 @@ use crate::{ Result, error::Error, protocol::{ - BlockData, BoxStream, ChannelEvent, ChannelEventKind, ChannelId, DepositInfo, - Ed25519PublicKey, FinalizedBlock, FinalizedUpTo, Slot, WithdrawInfo, ZoneMessage, + BlockData, BoxStream, ChannelEvent, ChannelEventKind, ChannelId, Ed25519PublicKey, + FinalizedBlock, FinalizedUpTo, Slot, ZoneMessage, }, }; @@ -66,8 +64,7 @@ pub struct NodeStream { impl NodeStream { /// Starts reading at the slot of the stored `anchor`, or at genesis without one. The anchor - /// block is read again, so a warm start can check it against the store, along with the deposits - /// and withdrawals following it, which may not have been persisted. + /// block is read again, so a warm start can check it against the store. pub async fn new( node: TimeoutNode, channel_id: ChannelId, @@ -194,8 +191,10 @@ impl NodeStream { match msg { ZoneMessage::Block(zone_block) => { let block = match borsh::from_slice::(&zone_block.data) { - Ok(block) => BlockData::Block(block), - Err(_) => BlockData::Undecodable(zone_block.data.into()), + Ok(block) if chain_state::vault::mints_backed(&block, &zone_block.steps) => { + BlockData::Block(block) + } + Ok(_) | Err(_) => BlockData::Undecodable(zone_block.data.into()), }; self.publish( @@ -209,22 +208,8 @@ impl NodeStream { ) .await } - ZoneMessage::Deposit(deposit) => { - let deposit = deposit_info(deposit, self.channel_id); - self.publish( - "finalized_deposit", - ChannelEventKind::FinalizedDeposit(Arc::new(deposit)), - ) - .await - } - ZoneMessage::Withdraw(withdraw) => { - let withdraw = withdraw_info(withdraw, self.channel_id); - self.publish( - "finalized_withdrawal", - ChannelEventKind::FinalizedWithdrawal(Arc::new(withdraw)), - ) - .await - } + // Deposits and withdrawals move their holders' own notes. + ZoneMessage::Deposit(_) | ZoneMessage::Withdraw(_) => Ok(()), } } @@ -300,38 +285,6 @@ where } } -/// The deposit `deposit` reports on `channel_id`, as the publisher reports it. -fn deposit_info(deposit: Deposit, channel_id: ChannelId) -> DepositInfo { - let Deposit { - tx_hash, - op_id, - inputs, - notes, - amount, - metadata, - } = deposit; - DepositInfo { - tx_hash, - op_id, - channel_id, - inputs, - notes, - amount, - metadata, - } -} - -/// The withdrawal `withdraw` reports on `channel_id`, as the publisher reports it. -fn withdraw_info(withdraw: Withdraw, channel_id: ChannelId) -> WithdrawInfo { - WithdrawInfo { - tx_hash: withdraw.tx_hash, - op: ChannelWithdrawOp { - channel_id, - inputs: withdraw.inputs, - }, - } -} - #[cfg(test)] mod tests { use common::{HashType, block::HashableBlockData}; @@ -365,9 +318,7 @@ mod tests { let published = match msg.event { ChannelEventKind::FinalizedBlock(finalized) => Published::Block(finalized.msg_id), ChannelEventKind::FinalizedUpTo(up_to) => Published::UpTo(up_to), - ChannelEventKind::FinalizedDeposit(_) - | ChannelEventKind::FinalizedWithdrawal(_) - | ChannelEventKind::Publisher(_) => return, + ChannelEventKind::Publisher(_) => return, }; self.0.send(published).expect("the test is listening"); } @@ -416,6 +367,7 @@ mod tests { signer: Ed25519Key::from_bytes(&[3; 32]) .public_key() .into_unverified(), + steps: logos_blockchain_zone_sdk::InscriptionSteps::default(), }), Slot::from(slot), ) diff --git a/lez/sequencer/actors/bedrock/src/actor/publisher.rs b/lez/sequencer/actors/bedrock/src/actor/publisher.rs index d6f69432b4..255286035a 100644 --- a/lez/sequencer/actors/bedrock/src/actor/publisher.rs +++ b/lez/sequencer/actors/bedrock/src/actor/publisher.rs @@ -1,11 +1,11 @@ use std::{ - collections::{BTreeSet, HashMap, HashSet}, + collections::{BTreeSet, VecDeque}, num::NonZero, sync::Arc, time::Duration, }; -use anyhow::{Context as _, anyhow}; +use anyhow::Context as _; use chain_state::timeout_node::TimeoutNode; use common::block::Block; use kameo::actor::ActorRef; @@ -14,43 +14,48 @@ use logos_blockchain_zone_sdk::{ adapter::{Node as _, NodeHttpClient}, core::{ mantle::{ - Note, Op, OpProof, SignedOps, + Op, OpProof, SignedOps, channel::{SlotTimeframe, SlotTimeout}, gas::GasCost, - ledger::{Inputs, Outputs}, - ops::channel::{ - VerifiedChannelKeys, channel_transfer::ChannelTransferOp, config::ChannelConfigOp, - inscribe::InscriptionOp, + ops::{ + ChannelInscribeProof, NoOpProof, + channel::{ + VerifiedChannelKeys, + config::ChannelConfigOp, + inscribe::{InscriptionOp, MiniBlocks}, + }, + program::ProgramRegisterOp, }, traits::Hashable as _, transactions::{MantleTxBuilder, OpProofs}, }, proofs::channel_multi_sig_proof::ChannelMultiSigProof, }, - node_types::{Inscription, WalletFundRequestBody, WalletFundResponseBody}, + node_types::{Inscription, StepProof, WalletFundRequestBody, WalletFundResponseBody}, sequencer::{ ChannelUpdate as SdkChannelUpdate, ChannelUpdateTx, Event, FinalizedOp, FinalizedTx, - FundingConfig, InscriptionInfo, SequencerConfig, WithdrawInputs, ZoneSequencer, + FundingConfig, InscriptionInfo, SequencerConfig, ZoneSequencer, }, }; use sequencer_actors_common::SendErrorExt as _; use sequencer_storage_actor::protocol::ZoneCheckpointRecord; -use tracing::info; +use tracing::{debug, info}; +use vault_circuit::{Committee, PublicInputs, SigningKey}; use crate::{ Result, actor::{ block_from_inscription, finality::{self, ConfigIndex}, - released_notes, verified_keys, + vault::{VAULT_PROGRAM, VaultDeposit, VaultNote, VaultStep, vault_key}, + verified_keys, }, error::Error, protocol::{ - ChannelEntry, ChannelEvent, ChannelEventKind, ChannelId, ChannelParams, ChannelSeq, - ChannelUpdate, DeserializeOp as _, Ed25519Key, Ed25519PublicKey, IndexedSignature, - IndexedSignatures, LiveChannelConfig, MsgId, NoteId, Ops, PreparedConfig, PreparedPin, - PublishOutcome, PublisherEvent, SequencerCheckpoint, Slot, ViewChange, WithdrawArg, - ZkPublicKey, + BridgeMoves, ChannelEntry, ChannelEvent, ChannelEventKind, ChannelId, ChannelParams, + ChannelSeq, ChannelUpdate, DeserializeOp as _, Ed25519Key, Ed25519PublicKey, + IndexedSignatures, LiveChannelConfig, MsgId, Ops, PreparedConfig, PublishOutcome, + PublisherEvent, SequencerCheckpoint, Slot, VaultMint, ViewChange, ZkPublicKey, }, }; @@ -77,6 +82,10 @@ pub struct Publisher { /// History finalized up to this slot was replayed by the consumer, so it is left out. replayed_up_to: Option, broker_ref: ActorRef>, + /// Events zone-sdk raised while a publish waited on the node, in order. + backlog: VecDeque, + /// Whether this publisher has registered the vault program. + vault_registered: bool, } impl Publisher { @@ -124,8 +133,6 @@ impl Publisher { backfill_batch_slots: backfill_batch_slots.get(), ..SequencerConfig::new(FundingConfig { funding_pk, - // Withdraw change goes back to the funding key. - change_pk: None, max_tx_fee: GasCost::new(logos_blockchain_zone_sdk::core::mantle::Value::MAX), priority_fee_percent, }) @@ -149,6 +156,8 @@ impl Publisher { seq, replayed_up_to, broker_ref, + backlog: VecDeque::new(), + vault_registered: false, }; // Wait for cold-start backfill to complete before returning so callers @@ -164,6 +173,9 @@ impl Publisher { /// The next zone-sdk event. Cancel safe, unlike [`Self::on_event`]. pub async fn next_event(&mut self) -> Event { + if let Some(event) = self.backlog.pop_front() { + return event; + } self.sequencer.next_event().await } @@ -175,7 +187,8 @@ impl Publisher { checkpoint, channel_update, finalized, - deposits: observed_deposits, + // A plain channel deposit stays under its holder's key and mints nothing. + observed: _, } => { let config_keys = finalized.iter().flat_map(|item| { item.ops.iter().filter_map(|op| { @@ -190,11 +203,6 @@ impl Publisher { }) }); config_index.extend_final(config_keys, checkpoint.lib_slot.into_inner()); - // Apart from the update: they carry no checkpoint and move no channel sequence. - if !observed_deposits.is_empty() { - self.publish("deposits", PublisherEvent::Deposits(observed_deposits)) - .await?; - } self.on_blocks_processed(checkpoint, channel_update, finalized) .await?; self.publish_live_config().await @@ -254,8 +262,6 @@ impl Publisher { }; let mut finalized_entries = Vec::new(); - let mut deposits = Vec::new(); - let mut withdrawals = Vec::new(); let mut undecodable = Vec::new(); let mut finalized_signers = Vec::new(); for (slot, op) in finalized @@ -281,13 +287,12 @@ impl Publisher { } finalized_entries.push(entry); } - FinalizedOp::Deposit(deposit) => deposits.push(deposit), - FinalizedOp::Withdraw(withdraw) => { - withdrawals.push(withdraw); - } - // Neither carries a block or an - // author the LEZ chain models. - FinalizedOp::Config(_) | FinalizedOp::ChannelTransfer(_) => {} + // None carries a block or an author the LEZ chain models; deposits and + // withdrawals move their holders' own notes. + FinalizedOp::Deposit(_) + | FinalizedOp::Withdraw(_) + | FinalizedOp::Config(_) + | FinalizedOp::ProgramRegister(_) => {} } } @@ -299,8 +304,6 @@ impl Publisher { seq, view, finalized: finalized_entries, - deposits, - withdrawals, undecodable, finalized_signers, })), @@ -355,7 +358,6 @@ impl Publisher { keys: Vec, channel_params: ChannelParams, configuration_threshold: NonZero, - transfer_threshold: NonZero, ) -> Result { let own_key = self.channel_signing_key.public_key(); if keys.first() != Some(&own_key) { @@ -371,7 +373,6 @@ impl Publisher { keys, &channel_params, configuration_threshold, - transfer_threshold, )?; let inscription = block_inscription(&self.node, &genesis).await?; @@ -381,11 +382,16 @@ impl Publisher { inscription, parent: MsgId::root(), signer: own_key.into_unverified(), + mini_blocks: MiniBlocks::default(), }; let msg_id = inscribe_op.id(); + // Registering a program already registered has no effect, so every zone can do it. let funded = self .fund_ops([ + Op::ProgramRegister(ProgramRegisterOp { + verification_key: vault_key(), + }), Op::ChannelConfig(config_op), Op::ChannelInscribe(inscribe_op), ]) @@ -396,10 +402,15 @@ impl Publisher { .channel_signing_key .sign_payload(mantle_tx.hash().as_signing_bytes().as_ref()); - let mut op_proofs = OpProofs::from([OpProof::ChannelMultiSigProof(genesis_config_proof())]); - op_proofs - .try_push(OpProof::Ed25519Sig(signature)) - .map_err(|err| Error::TooManyOperationProofs(err.into()))?; + let mut op_proofs = OpProofs::from([OpProof::None(NoOpProof)]); + for proof in [ + OpProof::ChannelMultiSigProof(genesis_config_proof()), + OpProof::ChannelInscribe(ChannelInscribeProof::without_steps(signature)), + ] { + op_proofs + .try_push(proof) + .map_err(|err| Error::TooManyOperationProofs(err.into()))?; + } if let Some(transfer_proof) = funded.transfer_proof { op_proofs .try_push(transfer_proof) @@ -408,7 +419,8 @@ impl Publisher { info!( accredited_keys = key_count, - "Creating the channel, genesis block bundled" + vault_program = %*VAULT_PROGRAM, + "Creating the channel, genesis block and vault program registration bundled" ); let tx = SignedOps::from_parts(mantle_tx, op_proofs)?; @@ -418,45 +430,53 @@ impl Publisher { pub async fn publish_block( &mut self, block: Block, - withdrawals: Vec, parent: Option, expected_seq: Option, + bridge: BridgeMoves, ) -> Result { self.check_seq(expected_seq)?; let inscription = block_inscription(&self.node, &block).await?; let data_byte_size = inscription.len(); let published = if let Some(parent) = parent { - if !withdrawals.is_empty() { - return Err(Error::CannotPublishBlockOnParentWithWithdrawals); - } - - let inscribe_op = self.inscription_op(inscription, parent); + let (inscribe_op, step_proofs) = if bridge.is_empty() { + (self.inscription_op(inscription, parent), Vec::new()) + } else { + self.vault_inscription(inscription, parent, &bridge).await? + }; let msg_id = inscribe_op.id(); let funded = self.fund_ops([Op::ChannelInscribe(inscribe_op)]).await?; - - self.sign_and_submit(funded.funded_tx, msg_id, parent, funded.transfer_proof) + self.check_backlog(expected_seq)?; + + self.sign_and_submit( + funded.funded_tx, + msg_id, + parent, + step_proofs, + funded.transfer_proof, + ) + } else if !bridge.is_empty() { + Err(Error::InvalidVaultStep( + "a block moving funds through the bridge names its parent", + )) } else { - let (result, checkpoint) = if withdrawals.is_empty() { - self.sequencer - .handle() - .publish(inscription) - .await - .map_err(|err| Error::SubmitSignedTransactionFailed(err.into()))? - } else { - self.sequencer - .handle() - .publish_atomic_withdraw(inscription, withdrawals, WithdrawInputs::Auto) - .await - .map_err(|err| Error::PublishAtomicWithdrawFailed(err.into()))? - }; + // The first block of a channel zone-sdk creates: the vault needs its program too. + if !self.vault_registered { + self.register_vault().await?; + self.vault_registered = true; + } + let (result, checkpoint) = self + .sequencer + .handle() + .publish(inscription) + .await + .map_err(|err| Error::SubmitSignedTransactionFailed(err.into()))?; Ok(PublishOutcome { this_msg: result.tx.inscription().this_msg, parent: result.tx.inscription().parent_msg, checkpoint, seq: self.next_seq(), - released_notes: released_notes(&result.tx), }) }; if published.is_ok() { @@ -469,85 +489,12 @@ impl Publisher { published } - pub async fn prepare_pin( - &mut self, - block: Block, - parent: MsgId, - notes: &[NoteId], - expected_seq: Option, - ) -> Result { - self.check_seq(expected_seq)?; - let inscription = block_inscription(&self.node, &block).await?; - let block_size = inscription.len(); - let inscribe_op = self.inscription_op(inscription, parent); - let msg_id = inscribe_op.id(); - let transfer = self.deposit_pin_transfer(notes)?; - let funded = self - .fund_ops([ - Op::ChannelInscribe(inscribe_op), - Op::ChannelTransfer(transfer), - ]) - .await?; - - Ok(PreparedPin { - tx: funded.funded_tx, - msg_id, - parent, - fee_proof: funded.transfer_proof, - block_id: block.header.block_id, - block_size, - }) - } - - pub fn publish_pin( - &mut self, - prepared: PreparedPin, - signatures: Vec, - expected_seq: Option, - ) -> Result { - self.check_seq(expected_seq)?; - let PreparedPin { - tx, - msg_id, - parent, - fee_proof, - block_id, - block_size, - } = prepared; - let signatures = IndexedSignatures::try_from_iter(signatures.into_iter().map(Into::into)) - .map_err(|err| Error::ChannelMultiSigProofAssemblyFailed(err.into()))?; - let transfer_proof = OpProof::ChannelMultiSigProof(ChannelMultiSigProof::new(signatures)); - - let published = self.sign_and_submit( - tx, - msg_id, - parent, - std::iter::once(transfer_proof).chain(fee_proof), - ); - if published.is_ok() { - info!(block_id, size_bytes = block_size, "Published block"); - } - published - } - - /// The channel's notes on the current L1 branch, finalized or not. - pub fn channel_notes(&self) -> HashSet { - let wallet = self.sequencer.channel_wallet(); - wallet - .finalized - .into_iter() - .chain(wallet.unfinalized) - .map(|note| note.note_id) - .collect() - } - pub async fn prepare_config( &mut self, keys: Vec, posting_timeframe: u32, posting_timeout: u32, configuration_threshold: NonZero, - transfer_threshold: NonZero, ) -> Result { let keys = VerifiedChannelKeys::try_from(keys) .map_err(|err| Error::InvalidChannelKeyList(err.into()))?; @@ -560,7 +507,6 @@ impl Publisher { SlotTimeframe::from(posting_timeframe), SlotTimeout::from(posting_timeout), configuration_threshold.get(), - transfer_threshold.get(), ) .await?; let accredited_keys = verified_keys(&prepared.accredited_keys)?; @@ -603,7 +549,6 @@ impl Publisher { parent: result.tx.inscription().parent_msg, checkpoint, seq: self.next_seq(), - released_notes: released_notes(&result.tx), }) } @@ -627,7 +572,6 @@ impl Publisher { parent, checkpoint, seq: self.next_seq(), - released_notes: released_notes(&result.tx), }) } @@ -645,6 +589,211 @@ impl Publisher { Ok(()) } + /// Registers the vault program on Bedrock. Registering a program already registered has no + /// effect, so every zone can do it. + async fn register_vault(&mut self) -> Result<()> { + let funded = self + .fund_ops([Op::ProgramRegister(ProgramRegisterOp { + verification_key: vault_key(), + })]) + .await?; + let mut op_proofs = OpProofs::from([OpProof::None(NoOpProof)]); + if let Some(transfer_proof) = funded.transfer_proof { + op_proofs + .try_push(transfer_proof) + .map_err(|err| Error::TooManyOperationProofs(err.into()))?; + } + let tx = SignedOps::from_parts(funded.funded_tx, op_proofs)?; + self.node + .post_transaction(tx) + .await + .map_err(|err| Error::NodeRequestFailed(err.into()))?; + info!(vault_program = %*VAULT_PROGRAM, "Registered the vault program"); + Ok(()) + } + + /// Checks a deposit its holder submitted for this channel's vault. + pub fn admit_deposit(&self, deposit: &[u8]) -> Result { + let committee = Self::committee(&self.vault_signing_key()); + let admitted = VaultDeposit::admit(deposit, &self.channel_id, &committee)?; + VaultMint::of(&admitted.deposit).ok_or(Error::InvalidVaultDeposit("it spends no note")) + } + + fn vault_signing_key(&self) -> SigningKey { + SigningKey::from_channel_seed(self.channel_signing_key.clone().into_unsecured().as_bytes()) + } + + // FIXME: the committee is this sequencer alone until the sequencer set shares one. + fn committee(signing_key: &SigningKey) -> Committee { + Committee { + threshold: 1, + signers: vec![signing_key.public_key()], + } + } + + /// The inscription of `data` on `parent` carrying the vault's program step for `bridge`, + /// with the proofs of its steps. + async fn vault_inscription( + &mut self, + data: Inscription, + parent: MsgId, + bridge: &BridgeMoves, + ) -> Result<(InscriptionOp, Vec)> { + let signing_key = self.vault_signing_key(); + let committee = Self::committee(&signing_key); + let deposits = bridge + .deposits + .iter() + .map(|deposit| VaultDeposit::admit(deposit, &self.channel_id, &committee)) + .collect::>>()?; + let payouts: Vec<_> = bridge + .payouts + .iter() + .map(|(value, key)| (*value, ZkPublicKey::new(PublicInputs::op_id_element(key)))) + .collect(); + let vault = VaultStep { + inputs: self.vault_inputs(&committee, &deposits, &payouts)?, + committee, + deposits, + payouts, + }; + + let inscription = self + .sequencer + .handle() + .prepare_program_inscription(data, vec![vault.mini_block()?]) + .map_err(|err| Error::VaultStepRefused(err.into()))?; + // zone-sdk chains on its own publish tip, the caller on the view it applied. + if inscription.op.parent != parent { + return Err(Error::InvalidVaultStep( + "its inscription is not on the parent the block was built on", + )); + } + let draft = inscription + .program_steps() + .next() + .cloned() + .ok_or(Error::InvalidVaultStep( + "its inscription has no program step", + ))?; + let signature = signing_key.sign(&VaultStep::public_inputs(&draft)); + + // Proving takes seconds: off the actor's thread, and with zone-sdk still followed. + let started = std::time::Instant::now(); + let proving = + tokio::task::spawn_blocking(move || vault.prove(&draft, vec![Some(signature)])); + let proofs = self + .following(proving) + .await + .map_err(|err| Error::VaultProofFailed(err.into()))??; + debug!(elapsed = ?started.elapsed(), "Proved the vault step"); + let step_proofs = inscription + .step_proofs(vec![proofs]) + .map_err(|err| Error::VaultStepRefused(err.into()))?; + Ok((inscription.op, step_proofs)) + } + + /// The spendable vault notes of `committee` a step consumes to pay `payouts`, the largest + /// first. A step that pays nothing out consumes none. + fn vault_inputs( + &mut self, + committee: &Committee, + deposits: &[VaultDeposit], + payouts: &[(u64, ZkPublicKey)], + ) -> Result> { + let overflows = Error::InvalidVaultStep("the value it moves overflows"); + let Some(owed) = payouts + .iter() + .try_fold(0_u64, |owed, (value, _)| owed.checked_add(*value)) + else { + return Err(overflows); + }; + let Some(mut held) = deposits.iter().try_fold(0_u64, |held, deposit| { + held.checked_add(deposit.deposit.value) + }) else { + return Err(overflows); + }; + + let committee = committee.id(); + let view = self.sequencer.handle().program_notes(); + let mut spendable: Vec<_> = view + .finalized + .iter() + .chain(&view.unfinalized) + .filter(|note| note.program == *VAULT_PROGRAM && note.opening.data == committee) + .collect(); + spendable.sort_unstable_by_key(|note| std::cmp::Reverse(note.opening.value)); + + let mut inputs = Vec::new(); + for note in spendable { + if held >= owed || inputs.len() == vault_circuit::MAX_INPUTS { + break; + } + held = held.saturating_add(note.opening.value); + inputs.push(VaultNote { + commitment: note.commitment, + opening: note.opening, + }); + } + if held < owed { + return Err(Error::InvalidVaultStep( + "its spendable notes do not cover its payouts", + )); + } + Ok(inputs) + } + + /// Awaits `task` with zone-sdk still followed: the events it raises meanwhile are queued + /// for [`Self::next_event`]. + #[expect( + clippy::integer_division_remainder_used, + reason = "Generated by select! macro, can't be easily rewritten to avoid this lint" + )] + async fn following(&mut self, task: impl Future) -> T { + tokio::pin!(task); + loop { + tokio::select! { + biased; + done = &mut task => break done, + event = self.sequencer.next_event() => self.backlog.push_back(event), + } + } + } + + /// Refuses a publish when the channel moved while the node funded it. The queued events + /// reach the consumer after the publish would, with checkpoints taken before it, so the + /// block has to be rebuilt on the view they leave. + fn check_backlog(&self, expected_seq: Option) -> Result<()> { + let current = self + .backlog + .iter() + .filter(|event| self.moves_channel(event)) + .fold(self.seq, |seq, _| seq.next()); + if current == self.seq { + return Ok(()); + } + Err(Error::ChannelMoved { + provided: expected_seq.unwrap_or(self.seq), + current, + }) + } + + /// Whether [`Self::on_blocks_processed`] will hand `event` on under a new channel sequence. + fn moves_channel(&self, event: &Event) -> bool { + let Event::BlocksProcessed { + channel_update, + finalized, + .. + } = event + else { + return false; + }; + !matches!(channel_update, SdkChannelUpdate::Extension { adopted } if adopted.is_empty()) + || finalized + .iter() + .any(|tx| self.replayed_up_to.is_none_or(|up_to| tx.l1_slot > up_to)) + } + /// This node's inscription of `inscription` chained on `parent`. fn inscription_op(&self, inscription: Inscription, parent: MsgId) -> InscriptionOp { InscriptionOp { @@ -652,6 +801,7 @@ impl Publisher { inscription, parent, signer: self.channel_signing_key.public_key().into_unverified(), + mini_blocks: MiniBlocks::default(), } } @@ -662,12 +812,16 @@ impl Publisher { tx: Ops, msg_id: MsgId, parent: MsgId, + step_proofs: Vec, proofs: impl IntoIterator, ) -> Result { let signature = self .channel_signing_key .sign_payload(tx.hash().as_signing_bytes().as_ref()); - let mut op_proofs = OpProofs::from([OpProof::Ed25519Sig(signature)]); + let mut op_proofs = OpProofs::from([OpProof::ChannelInscribe(ChannelInscribeProof::new( + signature, + step_proofs, + ))]); for proof in proofs { op_proofs .try_push(proof) @@ -678,35 +832,6 @@ impl Publisher { self.submit_tx(tx, msg_id, parent) } - /// A transfer spending each of `notes` and re-creating it unchanged, so the - /// tx carrying it is valid only on a branch holding all of them. - fn deposit_pin_transfer(&self, notes: &[NoteId]) -> Result { - let wallet = self.sequencer.channel_wallet(); - let channel_notes: HashMap = wallet - .finalized - .iter() - .chain(&wallet.unfinalized) - .map(|note| (note.note_id, Note::new(note.value, note.pk))) - .collect(); - let outputs = notes - .iter() - .map(|id| { - channel_notes - .get(id) - .copied() - .ok_or(Error::DepositNoteNotOnBranch(*id)) - }) - .collect::>>()?; - - Ok(ChannelTransferOp { - channel_id: self.channel_id, - inputs: Inputs::try_new(notes.to_vec()) - .map_err(|err| Error::DepositPinAssemblyFailed(anyhow!("{err:?}")))?, - outputs: Outputs::try_new(outputs) - .map_err(|err| Error::DepositPinAssemblyFailed(anyhow!("{err:?}")))?, - }) - } - /// Bumps the channel sequence and hands back the new one. const fn next_seq(&mut self) -> ChannelSeq { self.seq = self.seq.next(); @@ -718,10 +843,6 @@ impl Publisher { /// /// A timed-out call can leave the node's wallet holding its funding-note /// reservation until `pending_note_expiry_blocks` releases it. - #[expect( - clippy::needless_pass_by_ref_mut, - reason = "Helps to make returned future Send" - )] async fn fund_ops( &mut self, ops: impl IntoIterator, @@ -729,16 +850,20 @@ impl Publisher { let tx_builder = MantleTxBuilder::new() .extend_ops(ops) .map_err(|err| Error::TooManyOperationProofs(err.into()))?; + let request = WalletFundRequestBody { + tip: None, + tx_builder, + change_public_key: self.funding_pk, + funding_public_keys: vec![self.funding_pk], + max_tx_fee: GasCost::new(logos_blockchain_zone_sdk::core::mantle::Value::MAX), + priority_fee_percent: self.priority_fee_percent, + }; - self.node - .fund_tx(WalletFundRequestBody { - tip: None, - tx_builder, - change_public_key: self.funding_pk, - funding_public_keys: vec![self.funding_pk], - max_tx_fee: GasCost::new(logos_blockchain_zone_sdk::core::mantle::Value::MAX), - priority_fee_percent: self.priority_fee_percent, - }) + // The node proves the fee transfer, which can take longer than a block interval. zone-sdk + // keeps following the channel meanwhile: publishing back to back would otherwise leave it + // no time to, and the channel view would freeze. + let node = self.node.clone(); + self.following(async move { node.fund_tx(request).await }) .await .context("Failed to fund channel transaction") .map_err(Error::NodeRequestFailed) @@ -751,7 +876,6 @@ pub(super) fn genesis_config_op( keys: VerifiedChannelKeys, channel_params: &ChannelParams, configuration_threshold: NonZero, - transfer_threshold: NonZero, ) -> Result { ChannelConfigOp::new( channel_id, @@ -761,7 +885,6 @@ pub(super) fn genesis_config_op( SlotTimeframe::from(channel_params.posting_timeframe), SlotTimeout::from(channel_params.posting_timeout), configuration_threshold, - transfer_threshold, ) .map_err(|err| Error::InvalidChannelConfig(err.into())) } @@ -821,7 +944,9 @@ fn channel_entry(inscription: &InscriptionInfo, final_slot: Option) -> Chan let block = if >::as_ref(&inscription.payload).is_empty() { None } else { + // A block minting anything but the vault's deposits is no block of this chain. block_from_inscription(inscription) + .filter(|block| chain_state::vault::mints_backed(block, &inscription.steps)) }; ChannelEntry { msg: inscription.this_msg, @@ -838,8 +963,6 @@ fn channel_entry(inscription: &InscriptionInfo, final_slot: Option) -> Chan pub(super) fn channel_entries(tx: &ChannelUpdateTx, channel_id: ChannelId) -> Vec { match tx { ChannelUpdateTx::Inscription(info) => vec![channel_entry(info, None)], - ChannelUpdateTx::AtomicWithdraw(bundle) => vec![channel_entry(&bundle.inscription, None)], - ChannelUpdateTx::PinDeposit(bundle) => vec![channel_entry(&bundle.inscription, None)], ChannelUpdateTx::Config(_) => Vec::new(), ChannelUpdateTx::Custom(signed_tx) => { logos_blockchain_zone_sdk::sequencer::channel_inscriptions(signed_tx, channel_id) diff --git a/lez/sequencer/actors/bedrock/src/actor/tests.rs b/lez/sequencer/actors/bedrock/src/actor/tests.rs index b6aa4d75a3..d98ea1b945 100644 --- a/lez/sequencer/actors/bedrock/src/actor/tests.rs +++ b/lez/sequencer/actors/bedrock/src/actor/tests.rs @@ -12,11 +12,11 @@ use logos_blockchain_zone_sdk::{ channel::Channels, ledger::{VerifiableOperation as _, verification_mode::StandardMode}, ops::{ - Op, OpProof, SignedOperation, + ChannelInscribeProof, Op, OpProof, SignedOperation, channel::{ ChannelId, MsgId, VerifiedChannelKeys, config::ChannelConfigValidationContext, - inscribe::{Inscription, InscriptionOp}, + inscribe::{Inscription, InscriptionOp, MiniBlocks}, }, }, transactions::{ @@ -46,14 +46,17 @@ fn inscribing_tx(channel: ChannelId, block: &Block) -> SignedOps::MIN, - NonZero::::MIN, ) - .expect("a one-key channel with thresholds of one is valid"); + .expect("a one-key channel with a threshold of one is valid"); let tx_hash_view = TxHashView::new(TxHash::from([7; 32])); let signed = SignedOperation::<_, Unverified, StandardMode>::new(op, genesis_config_proof()) diff --git a/lez/sequencer/actors/bedrock/src/actor/vault.rs b/lez/sequencer/actors/bedrock/src/actor/vault.rs new file mode 100644 index 0000000000..15aaf04c8f --- /dev/null +++ b/lez/sequencer/actors/bedrock/src/actor/vault.rs @@ -0,0 +1,849 @@ +//! The vault's program step of an inscription: what it asks zone-sdk to build and the proof of +//! the vault's own rule. + +use borsh::BorshDeserialize as _; +use bridge_core::{DepositMetadata, DepositRecipient}; +pub use chain_state::vault::{VAULT_PROGRAM, vault_key}; +use logos_blockchain_zone_sdk::{ + binary_codec::canonical::BinaryDecode as _, + core::mantle::{ + batch::{DeferrableProof as _, DeferredProofs}, + notes::NoteCommitment, + ops::{ + ProgramProof, StepProof, ZkProgramSpendProof, ZkTransferProof, + channel::{ + ChannelId, + inscribe::Step, + program_step::{ProgramDeposit, program_deposit_id}, + }, + zk_transfer::defer_zk_transfer, + }, + }, + groth16::{Fr, fr_to_bytes}, + key_management_system_service::keys::{PK0, ZkPublicKey}, + node_types::{Inscription, ProgramNoteOpening, Value}, + sequencer::{ + MiniBlockSpec, ProgramOutput, ProgramStepDraft, ProgramStepSpec, StepSpec, UserOutput, + prove_program_step, + }, +}; +use vault_circuit::{ + Committee, Deposit, InputNote, MAX_DEPOSITS, MAX_INPUTS, MAX_OUTPUTS, OutputNote, PublicInputs, + Signature, VaultCircuit, +}; + +use crate::{Result, error::Error}; + +/// The most bytes the inscription of a deposit holds: a borsh [`DepositMetadata`] fits. +pub const MAX_DEPOSIT_INSCRIPTION: u32 = 128; + +/// A program deposit the vault consumes, as its holder submitted it. +#[derive(Clone, Debug)] +pub struct VaultDeposit { + pub deposit: ProgramDeposit, + /// The holder's proof of the deposit. + pub proof: ZkTransferProof, + /// Whom the zone credits: the opening of the deposit's intent, read from its inscription. + pub recipient: DepositRecipient, +} + +impl VaultDeposit { + /// Admits a deposit to the vault of `committee` on `channel`. `bytes` holds the step, then + /// its proof, in Bedrock's encoding; the step's inscription is a borsh [`DepositMetadata`]. + /// + /// Bedrock still decides whether the notes it spends exist and its root is recent. + pub fn admit(bytes: &[u8], channel: &ChannelId, committee: &Committee) -> Result { + let (rest, deposit) = ProgramDeposit::decode(bytes, &(MAX_DEPOSIT_INSCRIPTION, ())) + .map_err(|_err| Error::InvalidVaultDeposit("its step does not decode"))?; + let proof = ZkTransferProof::decode_all(rest, &()) + .map_err(|_err| Error::InvalidVaultDeposit("its proof does not decode"))?; + let recipient = DepositMetadata::try_from_slice(deposit.inscription.as_ref()) + .map_err(|_err| Error::InvalidVaultDeposit("its inscription names no recipient"))? + .recipient; + + if deposit.program_id != *VAULT_PROGRAM { + return Err(Error::InvalidVaultDeposit("it pays another program")); + } + if deposit.value == 0 { + return Err(Error::InvalidVaultDeposit("it pays nothing")); + } + // Bedrock refuses the whole inscription over a note spent twice. + if deposit.inputs.iter().enumerate().any(|(at, input)| { + deposit + .inputs + .iter() + .take(at) + .any(|earlier| earlier == input) + }) { + return Err(Error::InvalidVaultDeposit("it spends a note twice")); + } + if deposit.inputs.is_empty() { + return Err(Error::InvalidVaultDeposit("it spends no note")); + } + let intent = Deposit { + value: deposit.value, + recipient: recipient_element(&recipient), + } + .intent(committee.id()); + if deposit.intent != intent { + return Err(Error::InvalidVaultDeposit( + "its intent names another committee or recipient", + )); + } + // A deposit sits in the first mini-block, where its root is the one its holder proved + // against. + defer_zk_transfer( + &proof, + deposit.inputs.iter(), + deposit.outputs.iter(), + deposit.value, + deposit.commitment_merkle_root, + program_deposit_id(channel, &deposit), + ) + .ok() + .and_then(|transfer| { + let mut batch = DeferredProofs::new(); + transfer.defer_into(&mut batch); + batch.verify().ok() + }) + .ok_or(Error::InvalidVaultDeposit("its proof does not verify"))?; + + Ok(Self { + deposit, + proof, + recipient, + }) + } + + /// The id the zone mints the deposit under. Bedrock spends a note once, so no other deposit + /// shares its first nullifier. + #[must_use] + pub fn id(&self) -> Option<[u8; 32]> { + let nullifier = self.deposit.inputs.iter().next()?; + Some(fr_to_bytes(&nullifier.0)) + } +} + +/// A vault note a step may consume, as zone-sdk tracks it. +#[derive(Clone, Debug)] +pub struct VaultNote { + pub commitment: NoteCommitment, + pub opening: ProgramNoteOpening, +} + +/// What the vault does in one inscription: it takes the deposits in, pays the payouts and keeps +/// the rest in one note. zone-sdk builds the step and its spend; the vault's own proof is ours. +#[derive(Clone, Debug)] +pub struct VaultStep { + pub committee: Committee, + /// The vault notes consumed, among the ones zone-sdk lists as spendable. + pub inputs: Vec, + /// In the order of their mini-block. + pub deposits: Vec, + /// The value and payee of each payout. + pub payouts: Vec<(Value, ZkPublicKey)>, +} + +impl VaultStep { + /// The mini-block of the step for zone-sdk to build: the deposits, then the vault's program + /// step. + pub fn mini_block(&self) -> Result { + let committee = self.committee.id(); + if self + .inputs + .iter() + .any(|note| note.opening.data != committee) + { + return Err(Error::InvalidVaultStep( + "it consumes a note that is not its vault's", + )); + } + let kept = self.kept_value()?; + // The spend's own limits are zone-sdk's to check. + if self.deposits.len() > MAX_DEPOSITS { + return Err(Error::InvalidVaultStep( + "it takes in more deposits than a step holds", + )); + } + + let deposits = self.deposits.iter().map(|deposit| StepSpec::Holder { + step: Step::ProgramDeposit(deposit.deposit.clone()), + proof: StepProof::ZkTransfer(deposit.proof), + }); + let program = StepSpec::Program(ProgramStepSpec { + program_id: *VAULT_PROGRAM, + inputs: self.inputs.iter().map(|note| note.commitment).collect(), + program_outputs: (kept > 0) + .then(|| ProgramOutput { + value: kept, + stake_public_key: ZkPublicKey::zero(), + data: committee, + }) + .into_iter() + .collect(), + outputs: self + .payouts + .iter() + .map(|(value, public_key)| UserOutput { + public_key: *public_key, + value: *value, + }) + .collect(), + inscription: Inscription::default(), + }); + Ok(deposits.chain([program]).collect()) + } + + /// What a committee member signs to authorize the step zone-sdk built as `draft`. + #[must_use] + pub const fn public_inputs(draft: &ProgramStepDraft) -> PublicInputs { + let [program_step_id, program_deposits_hash, op_id] = draft.program_inputs; + PublicInputs { + program_step_id, + program_deposits_hash, + op_id, + } + } + + /// The spend and program proofs of the step zone-sdk built as `draft`, for + /// `ProgramInscription::step_proofs`. `signatures` holds one slot per committee member. + /// Takes seconds of CPU. + pub fn prove( + &self, + draft: &ProgramStepDraft, + signatures: Vec>, + ) -> Result<(ZkProgramSpendProof, ProgramProof)> { + let public = Self::public_inputs(draft); + let signatures = self.threshold_of(&public, signatures)?; + + let inputs: Vec<_> = self + .inputs + .iter() + .map(|note| InputNote { + value: note.opening.value, + nonce: note.opening.nonce, + public_key: *PK0.as_fr(), + stake_public_key: *note.opening.stake_public_key.as_fr(), + data: note.opening.data, + }) + .collect(); + let outputs: Vec<_> = draft + .outputs + .iter() + .map(|note| OutputNote { + value: note.value, + nonce: note.nonce, + public_key: *note.public_key.as_fr(), + stake_public_key: *note.stake_public_key.as_fr(), + program: note.program, + data: note.data, + }) + .collect(); + let step = vault_circuit::Step { + inputs: std::array::from_fn(|slot| inputs.get(slot).copied()), + outputs: std::array::from_fn(|slot| outputs.get(slot).copied()), + }; + if inputs.len() > MAX_INPUTS + || outputs.len() > MAX_OUTPUTS + || step.id() != public.program_step_id + { + return Err(Error::InvalidVaultStep( + "the step built is not the one it describes", + )); + } + + let circuit = VaultCircuit { + committee: self.committee.clone(), + step, + deposits: self + .deposits + .iter() + .map(|deposit| Deposit { + value: deposit.deposit.value, + recipient: recipient_element(&deposit.recipient), + }) + .collect(), + public, + signatures: signatures.clone(), + successor: self.committee.clone(), + successor_signatures: signatures, + }; + let program_proof = vault_circuit::prove( + vault_circuit::demo_proving_key(), + circuit, + &mut rand::rngs::OsRng, + ) + .map_err(|err| Error::VaultProofFailed(err.into()))?; + let spend_proof = + prove_program_step(draft).map_err(|err| Error::VaultProofFailed(err.into()))?; + + Ok((spend_proof, ProgramProof::new(program_proof))) + } + + /// The valid ones among `signatures`, cut down to the committee's threshold: the circuit + /// takes exactly that many. + fn threshold_of( + &self, + public: &PublicInputs, + signatures: Vec>, + ) -> Result>> { + let mut missing = self.committee.threshold; + let kept = self + .committee + .signers + .iter() + .zip(signatures) + .map(|(signer, signature)| { + let signature = + signature.filter(|signed| missing > 0 && signed.verify(signer, public))?; + missing = missing.saturating_sub(1); + Some(signature) + }) + .collect(); + if missing > 0 { + return Err(Error::InvalidVaultStep("its committee has not signed it")); + } + Ok(kept) + } + + /// What stays in the vault: the notes consumed and the deposits, less the payouts. + fn kept_value(&self) -> Result { + let held = self + .deposits + .iter() + .map(|deposit| deposit.deposit.value) + .chain(self.inputs.iter().map(|note| note.opening.value)) + .try_fold(0, |held: Value, value| held.checked_add(value)) + .ok_or(Error::InvalidVaultStep("the value it moves overflows"))?; + self.payouts + .iter() + .try_fold(held, |kept, (value, _)| kept.checked_sub(*value)) + .ok_or(Error::InvalidVaultStep("it pays out more than it holds")) + } +} + +/// The recipient as a deposit's intent commits to it. +fn recipient_element(recipient: &DepositRecipient) -> Fr { + Deposit::recipient_element(recipient.account_id().value()) +} + +#[cfg(test)] +mod tests { + use logos_blockchain_core::mantle::ops::transfer::test_utils::prove_transfer; + use logos_blockchain_program_spend::{ + ZkProgramSpendChainInputsData, ZkProgramSpendInputNoteData, ZkProgramSpendOutputNoteData, + ZkProgramSpendWalletInputsData, ZkProgramSpendWitnessInputsData, + }; + use logos_blockchain_zone_sdk::{ + Slot, + binary_codec::canonical::BinaryEncode as _, + core::mantle::{ + channel::Channels, + ledger::{VerifiableOperation as _, verification_mode::StandardMode}, + note_set::{CommitmentMmr, NoteSets, TxNoteState}, + notes::{NoteNullifier, derive_note_nullifier}, + ops::{ + ChannelInscribeProof, ProgramStepProof, SignedOperation, + channel::{ + MsgId, UnverifiedChannelKeys, + inscribe::{ + InscriptionOp, InscriptionPreverificationContext, + InscriptionValidationContext, + }, + program_step::ProgramStep, + }, + }, + programs::{Programs, RegisteredProgram, SpendInputFields, SpendOutputFields}, + transactions::{ + hash::{TxHash, TxHashView}, + states::Unverified, + }, + }, + key_management_system_service::keys::{Ed25519Key, ZkKey}, + node_types::{ + InputNullifiers, MerklePath, Note, OpId as _, OutputCommitments, + derive_program_output_nonce, program_deposits_hash, program_step_id, + }, + }; + use vault_circuit::SigningKey; + + use super::*; + + const SEED: [u8; 32] = [15; 32]; + + fn channel() -> ChannelId { + ChannelId::from([14; 32]) + } + + fn committee() -> Committee { + Committee { + threshold: 1, + signers: vec![SigningKey::from_channel_seed(&SEED).public_key()], + } + } + + /// The inscription of `vault` and the draft of its program step, built the way zone-sdk + /// builds them: `held` are the notes `vault` consumes with their paths to `root`. + #[expect( + clippy::arithmetic_side_effects, + reason = "an addition in the field does not overflow" + )] + fn built( + vault: &VaultStep, + held: &[(Note, MerklePath)], + root: Fr, + ) -> (InscriptionOp, ProgramStepDraft) { + let mut mini_block = vault.mini_block().unwrap(); + let Some(StepSpec::Program(spec)) = mini_block.pop() else { + panic!("the mini-block ends with the vault's step"); + }; + let deposits: Vec<_> = vault + .deposits + .iter() + .map(|deposit| &deposit.deposit) + .collect(); + let index = mini_block.len(); + let parent = MsgId::root(); + + let nullifier_key = ZkKey::zero().nullifier_key(); + let nullifiers: Vec<_> = held + .iter() + .map(|(note, _)| derive_note_nullifier(¬e.commitment(), &nullifier_key)) + .collect(); + let first_input = nullifiers.first().copied().unwrap_or_else(|| { + NoteNullifier( + PublicInputs::op_id_element(&parent.into()) + + Fr::from(u64::try_from(index).unwrap()), + ) + }); + let program_notes: Vec<_> = spec + .program_outputs + .iter() + .enumerate() + .map(|(at, output)| ProgramNoteOpening { + value: output.value, + nonce: derive_program_output_nonce(&first_input, at, output.value, &PK0), + stake_public_key: output.stake_public_key, + data: output.data, + }) + .collect(); + let outputs: Vec = program_notes + .iter() + .map(|opening| opening.note(spec.program_id)) + .chain( + spec.outputs + .iter() + .zip(program_notes.len()..) + .map(|(output, at)| { + Note::new( + output.value, + derive_program_output_nonce( + &first_input, + at, + output.value, + &output.public_key, + ), + output.public_key, + ) + }), + ) + .collect(); + + let input_fields = std::array::from_fn(|slot| { + held.get(slot) + .map_or_else(SpendInputFields::inactive, |(note, _)| SpendInputFields { + active: true, + value: note.value, + nonce: note.nonce, + public_key: note.public_key, + stake_public_key: note.stake_public_key, + data: note.data, + }) + }); + let output_fields = std::array::from_fn(|slot| { + outputs + .get(slot) + .map_or_else(SpendOutputFields::inactive, SpendOutputFields::of) + }); + let step = ProgramStep { + program_id: spec.program_id, + inputs: InputNullifiers::try_from_iter(nullifiers).unwrap(), + program_outputs: OutputCommitments::try_from_iter( + outputs + .iter() + .take(program_notes.len()) + .map(Note::commitment), + ) + .unwrap(), + outputs: OutputCommitments::try_from_iter( + outputs + .iter() + .skip(program_notes.len()) + .map(Note::commitment), + ) + .unwrap(), + commitment_merkle_root: root, + program_step_id: program_step_id(&input_fields, &output_fields), + inscription: spec.inscription, + }; + let step_id = step.program_step_id; + + let steps = vault + .deposits + .iter() + .map(|deposit| Step::ProgramDeposit(deposit.deposit.clone())) + .chain([Step::Program(step)]) + .collect::>(); + let op = InscriptionOp { + channel_id: channel(), + inscription: Inscription::default(), + parent, + signer: Ed25519Key::from_bytes(&SEED).public_key().into_unverified(), + mini_blocks: [steps.try_into().unwrap()].into(), + }; + let op_id = PublicInputs::op_id_element(&op.op_id()); + + let witness = ZkProgramSpendWitnessInputsData { + wallet: ZkProgramSpendWalletInputsData { + inputs: std::array::from_fn(|slot| { + held.get(slot).map_or_else( + ZkProgramSpendInputNoteData::inactive, + |(note, path)| ZkProgramSpendInputNoteData { + stake_public_key: *note.stake_public_key.as_fr(), + nonce: note.nonce, + value: note.value, + data: note.data, + path_and_selectors: std::array::from_fn(|level| { + path.path_and_selectors(level).into() + }), + }, + ) + }), + outputs: std::array::from_fn(|slot| { + outputs + .get(slot) + .map_or_else(ZkProgramSpendOutputNoteData::inactive, |note| { + ZkProgramSpendOutputNoteData { + public_key: *note.public_key.as_fr(), + stake_public_key: *note.stake_public_key.as_fr(), + nonce: note.nonce, + value: note.value, + program: note.program, + data: note.data, + } + }) + }), + }, + chain: ZkProgramSpendChainInputsData { + inputs_active: std::array::from_fn(|slot| slot < held.len()), + outputs_active: std::array::from_fn(|slot| slot < outputs.len()), + outputs_of_program: std::array::from_fn(|slot| slot < program_notes.len()), + // No step before this one leaves a note: the deposits have no change. + tx_commitment_root: root, + program_id: spec.program_id, + paid_value: deposits.iter().map(|deposit| deposit.value).sum(), + msg: op_id, + }, + }; + let draft = ProgramStepDraft { + index, + witness: Box::new(witness), + program_notes, + outputs, + program_inputs: [step_id, program_deposits_hash(&deposits), op_id], + }; + (op, draft) + } + + /// Runs Bedrock's checks of the inscription carrying `vault`, on a channel whose note set + /// holds `notes`: `held` are the ones `vault` consumes. + fn bedrock_accepts( + vault: &VaultStep, + held: &[(Note, MerklePath)], + root: Fr, + notes: &[NoteCommitment], + ) { + let sequencer = Ed25519Key::from_bytes(&SEED); + let keys = UnverifiedChannelKeys::from(sequencer.public_key().into_unverified()); + let (channels, note_sets) = + Channels::new().create_channel(channel(), Slot::from(0), keys, NoteSets::new()); + let set = note_sets + .channel(&channel()) + .unwrap() + .clone() + .execute_adding(notes) + .unwrap(); + let note_sets = note_sets.update_channel(set).end_block(1, 1024).unwrap(); + let programs = Programs::new() + .register(RegisteredProgram::new(vault_key()).unwrap()) + .0; + + let (op, draft) = built(vault, held, root); + let signature = + SigningKey::from_channel_seed(&SEED).sign(&VaultStep::public_inputs(&draft)); + let (spend_proof, program_proof) = vault.prove(&draft, vec![Some(signature)]).unwrap(); + let proofs = vault + .deposits + .iter() + .map(|deposit| StepProof::ZkTransfer(deposit.proof)) + .chain([StepProof::ProgramStep(ProgramStepProof { + spend_proof, + program_proof, + program_notes: draft.program_notes, + })]) + .collect(); + + let tx_hash_view = TxHashView::new(TxHash::from([9; 32])); + let inscribe_proof = ChannelInscribeProof::new( + sequencer.sign_payload(tx_hash_view.as_bytes().as_ref()), + proofs, + ); + let deferred = SignedOperation::<_, Unverified, StandardMode>::new(op, inscribe_proof) + .into_preverified(&InscriptionPreverificationContext { + tx_hash_view: &tx_hash_view, + }) + .expect("the inscription is well formed") + .verify(&InscriptionValidationContext { + channels: &channels, + note_sets: ¬e_sets, + tx_notes: &TxNoteState::new(), + programs: &programs, + block_slot: Slot::from(0), + block_number: 2, + }) + .expect("the steps fit the channel's notes"); + let mut batch = DeferredProofs::new(); + deferred.defer_into(&mut batch); + batch.verify().expect("the proofs of the steps verify"); + } + + /// A vault note of `committee` worth 100, alone in its note set: with its path and root. + fn held_note(data: Fr) -> (Note, MerklePath, Fr) { + let held = Note { + value: 100, + nonce: Fr::from(21_u64), + public_key: *PK0, + stake_public_key: ZkPublicKey::zero(), + program: *VAULT_PROGRAM, + data, + }; + let (mmr, path) = CommitmentMmr::new() + .push_with_paths(held.commitment(), &mut []) + .unwrap(); + (held, path, mmr.frontier_root()) + } + + fn vault_note(note: &Note) -> VaultNote { + VaultNote { + commitment: note.commitment(), + opening: ProgramNoteOpening { + value: note.value, + nonce: note.nonce, + stake_public_key: note.stake_public_key, + data: note.data, + }, + } + } + + fn recipient() -> DepositRecipient { + DepositRecipient::Identified(lee::PublicAccountEvidence::Pda { + program: lee::AccountId::new([4; 32]), + seed: bridge_core::PdaSeed::new([6; 32]), + }) + } + + /// A deposit of a note worth 1000 to the vault of `committee`, with the note and the root + /// of the set holding it alone. + fn deposit(committee: &Committee) -> (VaultDeposit, Note, Fr) { + deposit_of(committee, Fr::from(11_u64)) + } + + /// [`deposit`], of the holder's note with `nonce`. + fn deposit_of(committee: &Committee, nonce: Fr) -> (VaultDeposit, Note, Fr) { + let holder = Fr::from(1_u64); + let note = Note::new(1_000, nonce, ZkKey::new(holder).to_public_key()); + let (mmr, path) = CommitmentMmr::new() + .push_with_paths(note.commitment(), &mut []) + .unwrap(); + let root = mmr.frontier_root(); + let metadata = DepositMetadata { + recipient: recipient(), + }; + let nullifier = + derive_note_nullifier(¬e.commitment(), &ZkKey::new(holder).nullifier_key()); + let deposit = ProgramDeposit { + program_id: *VAULT_PROGRAM, + inputs: [nullifier].into(), + outputs: OutputCommitments::default(), + commitment_merkle_root: root, + value: 1_000, + intent: Deposit { + value: 1_000, + recipient: recipient_element(&recipient()), + } + .intent(committee.id()), + inscription: Inscription::try_new( + borsh::to_vec(&metadata).unwrap(), + MAX_DEPOSIT_INSCRIPTION, + ) + .unwrap(), + }; + let proof = prove_transfer( + &[(note, holder, path)], + &[], + root, + program_deposit_id(&channel(), &deposit), + ); + let deposit = VaultDeposit { + deposit, + proof: ZkTransferProof::new(proof), + recipient: recipient(), + }; + (deposit, note, root) + } + + fn submitted(deposit: &VaultDeposit) -> Vec { + let mut bytes = Vec::new(); + deposit.deposit.encode_into(&mut bytes); + deposit.proof.encode_into(&mut bytes); + bytes + } + + #[test] + fn bedrock_accepts_a_deposit_into_an_empty_vault() { + let (deposit, note, root) = deposit(&committee()); + let vault = VaultStep { + committee: committee(), + inputs: vec![], + deposits: vec![deposit], + payouts: vec![], + }; + + bedrock_accepts(&vault, &[], root, &[note.commitment()]); + } + + #[test] + fn a_submitted_deposit_is_admitted_with_its_recipient() { + let (deposit, _, _) = deposit(&committee()); + + let admitted = VaultDeposit::admit(&submitted(&deposit), &channel(), &committee()).unwrap(); + + assert_eq!(admitted.recipient, recipient()); + assert_eq!(admitted.deposit, deposit.deposit); + assert_eq!( + admitted.id(), + Some(fr_to_bytes( + &deposit.deposit.inputs.iter().next().unwrap().0 + )) + ); + } + + #[test] + fn a_deposit_spending_a_note_twice_is_refused() { + let (mut deposit, _, _) = deposit(&committee()); + let nullifier = *deposit.deposit.inputs.iter().next().unwrap(); + deposit.deposit.inputs = [nullifier, nullifier].into(); + + assert!(matches!( + VaultDeposit::admit(&submitted(&deposit), &channel(), &committee()), + Err(Error::InvalidVaultDeposit("it spends a note twice")) + )); + } + + #[test] + fn a_step_its_committee_has_not_signed_is_not_proven() { + let (deposit, _, root) = deposit(&committee()); + let vault = VaultStep { + committee: committee(), + inputs: vec![], + deposits: vec![deposit], + payouts: vec![], + }; + let (_, draft) = built(&vault, &[], root); + let stranger = SigningKey::from_channel_seed(&[16; 32]); + let signature = stranger.sign(&VaultStep::public_inputs(&draft)); + + for signatures in [vec![], vec![None], vec![Some(signature)]] { + assert!(matches!( + vault.prove(&draft, signatures), + Err(Error::InvalidVaultStep("its committee has not signed it")) + )); + } + } + + #[test] + fn a_step_consuming_a_note_of_another_committee_is_refused() { + let (held, _, _) = held_note(Fr::from(3_u64)); + let vault = VaultStep { + committee: committee(), + inputs: vec![vault_note(&held)], + deposits: vec![], + payouts: vec![], + }; + + assert!(matches!( + vault.mini_block(), + Err(Error::InvalidVaultStep( + "it consumes a note that is not its vault's" + )) + )); + } + + #[test] + fn a_deposit_to_another_committee_is_refused() { + let other = Committee { + threshold: 1, + signers: vec![SigningKey::from_channel_seed(&[16; 32]).public_key()], + }; + let (deposit, _, _) = deposit(&other); + + assert!(matches!( + VaultDeposit::admit(&submitted(&deposit), &channel(), &committee()), + Err(Error::InvalidVaultDeposit( + "its intent names another committee or recipient" + )) + )); + } + + #[test] + fn a_deposit_whose_proof_covers_another_channel_is_refused() { + let (deposit, _, _) = deposit(&committee()); + + assert!(matches!( + VaultDeposit::admit( + &submitted(&deposit), + &ChannelId::from([13; 32]), + &committee() + ), + Err(Error::InvalidVaultDeposit("its proof does not verify")) + )); + } + + #[test] + fn bedrock_accepts_a_payout_from_a_vault_note() { + let (held, path, root) = held_note(committee().id()); + let vault = VaultStep { + committee: committee(), + inputs: vec![vault_note(&held)], + deposits: vec![], + payouts: vec![(30, ZkKey::new(Fr::from(5_u64)).to_public_key())], + }; + + bedrock_accepts(&vault, &[(held, path)], root, &[held.commitment()]); + } + + #[test] + fn a_step_paying_out_more_than_it_holds_is_refused() { + let vault = VaultStep { + committee: committee(), + inputs: vec![], + deposits: vec![], + payouts: vec![(1, ZkKey::new(Fr::from(5_u64)).to_public_key())], + }; + + assert!(matches!( + vault.mini_block(), + Err(Error::InvalidVaultStep("it pays out more than it holds")) + )); + } +} diff --git a/lez/sequencer/actors/bedrock/src/error.rs b/lez/sequencer/actors/bedrock/src/error.rs index 9b8bdcdd59..b25ff66ef5 100644 --- a/lez/sequencer/actors/bedrock/src/error.rs +++ b/lez/sequencer/actors/bedrock/src/error.rs @@ -84,19 +84,6 @@ pub enum Error { #[error("Failed to submit signed transaction")] SubmitSignedTransactionFailed(#[source] anyhow::Error), - #[error("Failed to publish atomic withdraw transaction")] - PublishAtomicWithdrawFailed(#[source] anyhow::Error), - - // TODO: Not a technical limitation, but rather a complexity of dealing with zone sdk - #[error("Cannot publish block on parent with withdrawals")] - CannotPublishBlockOnParentWithWithdrawals, - - #[error("Deposited note {0:?} is not a channel note on the current branch")] - DepositNoteNotOnBranch(logos_blockchain_zone_sdk::core::mantle::NoteId), - - #[error("Failed to assemble the deposit pin transfer")] - DepositPinAssemblyFailed(#[source] anyhow::Error), - #[error( "Tried to publish block which was built on channel sequence {provided} but the channel is at {current}" )] @@ -105,6 +92,18 @@ pub enum Error { current: ChannelSeq, }, + #[error("Invalid vault deposit: {0}")] + InvalidVaultDeposit(&'static str), + + #[error("Invalid vault step: {0}")] + InvalidVaultStep(&'static str), + + #[error("zone-sdk refused the vault step")] + VaultStepRefused(#[source] anyhow::Error), + + #[error("Failed to prove the vault step")] + VaultProofFailed(#[source] anyhow::Error), + #[error("Zone-sdk error")] ZoneSdkError(#[from] logos_blockchain_zone_sdk::sequencer::Error), } diff --git a/lez/sequencer/actors/bedrock/src/mock.rs b/lez/sequencer/actors/bedrock/src/mock.rs index 39a61b34b7..d192a01929 100644 --- a/lez/sequencer/actors/bedrock/src/mock.rs +++ b/lez/sequencer/actors/bedrock/src/mock.rs @@ -3,7 +3,7 @@ reason = "`handle*` prefix is used for convenience with `Message` trait" )] -use std::collections::{BTreeSet, HashSet}; +use std::collections::BTreeSet; use kameo::{ Actor, @@ -18,11 +18,11 @@ use crate::{ BedrockActorTrait, Result, error::Error, protocol::{ - AccreditedKeys, ChangeChannelConfig, ChannelId, ChannelReadStream, ChannelSeq, - CheckChannelExists, CheckIsOurTurn, CreateChannel, FilterFinallyAbsent, FollowChannel, - GetAccreditedKeys, GetChannelNotes, GetChannelTipMessageId, GetChannelTipSlot, - InitializeChannelPublisher, MsgId, NoteId, PrepareConfig, PreparePin, PreparedConfig, - PreparedPin, PublishBlock, PublishOutcome, PublishPin, ReadChannel, SequencerKey, Slot, + AccreditedKeys, AdmitDeposit, ChangeChannelConfig, ChannelId, ChannelReadStream, + ChannelSeq, CheckChannelExists, CheckIsOurTurn, CreateChannel, FilterFinallyAbsent, + FollowChannel, GetAccreditedKeys, GetChannelTipMessageId, GetChannelTipSlot, + InitializeChannelPublisher, MsgId, PrepareConfig, PreparedConfig, PublishBlock, + PublishOutcome, ReadChannel, SequencerKey, Slot, VaultMint, }, }; @@ -86,18 +86,6 @@ mockall::mock! { ctx: &mut Context> ) -> Result; - pub fn handle_prepare_pin( - &mut self, - msg: PreparePin, - ctx: &mut Context> - ) -> Result; - - pub fn handle_publish_pin( - &mut self, - msg: PublishPin, - ctx: &mut Context> - ) -> Result; - pub fn handle_prepare_config( &mut self, msg: PrepareConfig, @@ -122,18 +110,18 @@ mockall::mock! { ctx: &mut Context> ) -> Result; + pub fn handle_admit_deposit( + &mut self, + msg: AdmitDeposit, + ctx: &mut Context> + ) -> Result; + pub fn handle_get_accredited_keys( &mut self, msg: GetAccreditedKeys, ctx: &mut Context>> ) -> Result>; - pub fn handle_get_channel_notes( - &mut self, - msg: GetChannelNotes, - ctx: &mut Context>> - ) -> Result>; - pub fn handle_get_channel_tip_slot( &mut self, msg: GetChannelTipSlot, @@ -247,30 +235,6 @@ impl Message for MockBedrockActor { } } -impl Message for MockBedrockActor { - type Reply = Result; - - async fn handle( - &mut self, - msg: PreparePin, - ctx: &mut Context, - ) -> Self::Reply { - self.handle_prepare_pin(msg, ctx) - } -} - -impl Message for MockBedrockActor { - type Reply = Result; - - async fn handle( - &mut self, - msg: PublishPin, - ctx: &mut Context, - ) -> Self::Reply { - self.handle_publish_pin(msg, ctx) - } -} - impl Message for MockBedrockActor { type Reply = Result; @@ -307,39 +271,39 @@ impl Message for MockBedrockActor { } } -impl Message for MockBedrockActor { - type Reply = Result; +impl Message for MockBedrockActor { + type Reply = Result; async fn handle( &mut self, - msg: CheckIsOurTurn, + msg: AdmitDeposit, ctx: &mut Context, ) -> Self::Reply { - self.handle_check_is_our_turn(msg, ctx) + self.handle_admit_deposit(msg, ctx) } } -impl Message for MockBedrockActor { - type Reply = Result>; +impl Message for MockBedrockActor { + type Reply = Result; async fn handle( &mut self, - msg: GetAccreditedKeys, + msg: CheckIsOurTurn, ctx: &mut Context, ) -> Self::Reply { - self.handle_get_accredited_keys(msg, ctx) + self.handle_check_is_our_turn(msg, ctx) } } -impl Message for MockBedrockActor { - type Reply = Result>; +impl Message for MockBedrockActor { + type Reply = Result>; async fn handle( &mut self, - msg: GetChannelNotes, + msg: GetAccreditedKeys, ctx: &mut Context, ) -> Self::Reply { - self.handle_get_channel_notes(msg, ctx) + self.handle_get_accredited_keys(msg, ctx) } } diff --git a/lez/sequencer/actors/bedrock/src/mock/canned_channel.rs b/lez/sequencer/actors/bedrock/src/mock/canned_channel.rs index f6939376fb..f1ce39d3b2 100644 --- a/lez/sequencer/actors/bedrock/src/mock/canned_channel.rs +++ b/lez/sequencer/actors/bedrock/src/mock/canned_channel.rs @@ -1,13 +1,12 @@ //! A [`MockBedrockActor`] serving a canned channel. use std::{ - collections::{BTreeSet, HashMap, HashSet}, + collections::BTreeSet, sync::{Arc, Mutex, MutexGuard}, }; use anyhow::anyhow; use common::block::Block; -use logos_blockchain_zone_sdk::core::mantle::ledger::{Inputs, NoteId, Utxo}; use sequencer_storage_actor::protocol::ZoneAnchorRecord; use super::MockBedrockActor; @@ -16,9 +15,8 @@ use crate::{ error::Error, protocol::{ AccreditedKeys, ChannelReadStream, ChannelSeq, CreateChannel, FilterFinallyAbsent, - HeaderId, InitializeChannelPublisher, MsgId, PreparePin, PreparedPin, PublishBlock, - PublishOutcome, PublishPin, ReadChannel, SequencerCheckpoint, SequencerKey, Slot, - WithdrawArg, ZoneMessage, + HeaderId, InitializeChannelPublisher, MsgId, PublishBlock, PublishOutcome, ReadChannel, + SequencerCheckpoint, SequencerKey, Slot, VaultMint, ZoneMessage, }, }; @@ -39,14 +37,6 @@ pub struct CannedChannel { pub failed_tip_slot_reads: u32, /// Fails every publish. pub publish_fails: bool, - /// Fails every pin before it is funded. - pub prepare_pin_fails: bool, - /// Fails every pin once it is signed. - pub publish_pin_fails: bool, - /// Channel notes on the current branch, the ones a publish may pin. - pub channel_notes: HashSet, - /// The deposit notes each publish pinned, in publish order. - pub pins: Arc>>>, /// Keys whose removal config is reported not yet final; every other key's is. pub pending_removals: BTreeSet, /// Channel sequence the last publish left the channel at. @@ -56,6 +46,10 @@ pub struct CannedChannel { /// [`FollowChannel::anchor`](crate::protocol::FollowChannel::anchor) of every follow, in /// order. pub follows: Vec>, + /// The deposits the vault admits, by the bytes submitted; it refuses any other. + pub admitted: Vec<(Vec, VaultMint)>, + /// The deposits of every publish, in order. + pub taken_in: Vec>, } impl CannedChannel { @@ -117,6 +111,20 @@ impl SharedChannel { }); mock.expect_handle_check_is_our_turn() .returning(|_msg, _ctx| Ok(true)); + mock.expect_handle_admit_deposit().returning({ + let channel = self.clone(); + move |msg, _ctx| { + channel + .lock() + .admitted + .iter() + .find(|(deposit, _)| *deposit == msg.deposit) + .map(|(_, mint)| mint.clone()) + .ok_or(Error::InvalidVaultDeposit( + "the canned vault does not know it", + )) + } + }); mock.expect_handle_get_channel_tip_slot().returning({ let channel = self.clone(); move |_msg, _ctx| { @@ -145,10 +153,6 @@ impl SharedChannel { }); mock.expect_handle_change_channel_config() .returning(|_msg, _ctx| Ok(())); - mock.expect_handle_get_channel_notes().returning({ - let channel = self.clone(); - move |_msg, _ctx| Ok(channel.lock().channel_notes.clone()) - }); mock.expect_handle_filter_finally_absent().returning({ let channel = self.clone(); move |FilterFinallyAbsent { keys, .. }, _ctx| { @@ -175,81 +179,20 @@ impl SharedChannel { }); mock.expect_handle_create_channel().returning({ let channel = self.clone(); - move |CreateChannel { genesis, .. }, _ctx| channel.land(&genesis, None, Vec::new()) + move |CreateChannel { genesis, .. }, _ctx| channel.land(&genesis, None) }); mock.expect_handle_publish_block().returning({ let channel = self.clone(); move |PublishBlock { - channel_id: _, - block, - withdrawals, - parent, - expected_seq: _, - }, - _ctx| { - let outcome = channel.publish(&block, parent, mock_released_notes(&withdrawals))?; - channel.record_pin(Vec::new()); - Ok(outcome) - } - }); - let prepared = Arc::new(Mutex::new(HashMap::new())); - mock.expect_handle_prepare_pin().returning({ - let channel = self.clone(); - let prepared = Arc::clone(&prepared); - move |PreparePin { channel_id: _, block, parent, - notes, - expected_seq: _, - }, - _ctx| { - let (prepare_pin_fails, channel_notes) = { - let channel = channel.lock(); - (channel.prepare_pin_fails, channel.channel_notes.clone()) - }; - if prepare_pin_fails { - return Err(Error::DepositPinAssemblyFailed(anyhow!( - "Canned pin failure for block {}", - block.header.block_id - ))); - } - if let Some(missing) = notes.iter().find(|note| !channel_notes.contains(note)) { - return Err(Error::DepositNoteNotOnBranch(*missing)); - } - // Bedrock's own bound on the transfer's inputs. - Inputs::try_new(notes.clone()) - .map_err(|err| Error::DepositPinAssemblyFailed(anyhow!("{err:?}")))?; - let msg_id = mock_msg_of(&block); - prepared - .lock() - .expect("prepared pins lock poisoned") - .insert(msg_id, (block, notes)); - Ok(PreparedPin::mocked(msg_id, parent)) - } - }); - mock.expect_handle_publish_pin().returning({ - let channel = self.clone(); - move |PublishPin { - channel_id: _, - prepared: pin, - signatures: _, expected_seq: _, + bridge, }, _ctx| { - let (block, notes) = prepared - .lock() - .expect("prepared pins lock poisoned") - .remove(&pin.msg_id()) - .expect("only a prepared pin is published"); - if channel.lock().publish_pin_fails { - return Err(Error::SubmitSignedTransactionFailed(anyhow!( - "Canned pin publish failure for block {}", - block.header.block_id - ))); - } - let outcome = channel.publish(&block, Some(pin.parent()), Vec::new())?; - channel.record_pin(notes); + let outcome = channel.publish(&block, parent)?; + channel.lock().taken_in.extend(bridge.deposits); Ok(outcome) } }); @@ -258,12 +201,7 @@ impl SharedChannel { /// Lands `block` unless it is chained on an entry that is no longer the tip, as L1 refuses /// it. - fn publish( - &self, - block: &Block, - parent: Option, - released_notes: Vec, - ) -> Result { + fn publish(&self, block: &Block, parent: Option) -> Result { let current = self.lock().tip; if let Some(parent) = parent && current.is_some_and(|current| current != parent) @@ -273,23 +211,12 @@ impl SharedChannel { block.header.block_id ))); } - self.land(block, parent, released_notes) - } - - /// Records the deposit notes a landed publish pinned. - fn record_pin(&self, notes: Vec) { - let pins = Arc::clone(&self.lock().pins); - pins.lock().expect("pins lock poisoned").push(notes); + self.land(block, parent) } /// Moves the channel tip to `block`, inscribed on `parent` or else on the tip, and reports /// what its publish produced. - fn land( - &self, - block: &Block, - parent: Option, - released_notes: Vec, - ) -> Result { + fn land(&self, block: &Block, parent: Option) -> Result { let mut channel = self.lock(); if channel.publish_fails { return Err(Error::SubmitSignedTransactionFailed(anyhow!( @@ -308,7 +235,6 @@ impl SharedChannel { parent, checkpoint: checkpoint_at(this_msg), seq: ChannelSeq::mocked(channel.seq), - released_notes, }) } @@ -334,9 +260,9 @@ pub fn checkpoint_at(tip: MsgId) -> SequencerCheckpoint { pending_txs: Vec::new(), lib: HeaderId::from([0; 32]), lib_slot: Slot::from(0), - channel_notes: Vec::new(), finalized_config: MsgId::root(), funding: Vec::new(), + program_notes: None, } } @@ -350,16 +276,3 @@ fn history_after(messages: &[(ZoneMessage, Slot)], after: Option) -> Chann .collect(); Box::pin(futures::stream::iter(messages)) } - -/// The notes the mock reports as released by `withdrawals`. -/// -/// Zone-sdk picks the actual channel notes to release, so the mock invents one -/// per requested output, derived from the output itself so a test can -/// recompute the reconciliation keys of a block it produced. -fn mock_released_notes(withdrawals: &[WithdrawArg]) -> Vec { - withdrawals - .iter() - .flat_map(|withdraw| withdraw.outputs.into_iter().enumerate()) - .map(|(output_index, note)| Utxo::new([0; 32], output_index, *note).id()) - .collect() -} diff --git a/lez/sequencer/actors/bedrock/src/protocol.rs b/lez/sequencer/actors/bedrock/src/protocol.rs index e34adf079f..50538bc048 100644 --- a/lez/sequencer/actors/bedrock/src/protocol.rs +++ b/lez/sequencer/actors/bedrock/src/protocol.rs @@ -1,21 +1,20 @@ use std::{collections::BTreeSet, num::NonZero, sync::Arc, time::Duration}; -pub use chain_state::ChannelEntry; +pub use chain_state::{ChannelEntry, vault::VaultMint}; use common::block::Block; use kameo::Reply; +use logos_blockchain_zone_sdk::sequencer::PreparedChannelConfig; pub use logos_blockchain_zone_sdk::{ Slot, UnverifiedEd25519PublicKey, ZoneMessage, adapter::BoxStream, binary_codec::bincode::{DeserializeOp, SerializeOp}, - core::mantle::{NoteId, transactions::Ops}, + core::mantle::transactions::Ops, key_management_system_service::keys::{Ed25519Key, Ed25519PublicKey, ZkPublicKey}, node_types::{ChannelId, HeaderId, MsgId}, sequencer::{ - DepositInfo, IndexedSignature, IndexedSignatures, SequencerCheckpoint as Checkpoint, - SequencerCheckpoint, WithdrawArg, WithdrawInfo, + IndexedSignature, IndexedSignatures, SequencerCheckpoint as Checkpoint, SequencerCheckpoint, }, }; -use logos_blockchain_zone_sdk::{core::mantle::OpProof, sequencer::PreparedChannelConfig}; pub use sequencer_stake_core::{ChannelParams, SequencerKey}; use sharding_pool_actor::ShardingKey; @@ -89,15 +88,7 @@ pub enum ChannelEventKind { /// `channel//finalized_block` topic. FinalizedBlock(Arc), - /// A deposit that has been finalized on chain since configured `stream_from` arriving to - /// `channel//finalized_deposit` topic. - FinalizedDeposit(Arc), - - /// A withdrawal that has been finalized on chain since configured `stream_from` arriving to - /// `channel//finalized_withdrawal` topic. - FinalizedWithdrawal(Arc), - - /// Every finalized block, deposit and withdrawal up to a slot has been published, arriving to + /// Every finalized block up to a slot has been published, arriving to /// `channel//finalized_up_to` topic. Comes after the events it covers, also when /// the slots it covers hold none. FinalizedUpTo(FinalizedUpTo), @@ -160,11 +151,6 @@ pub enum PublisherEvent { /// Message arriving to `channel//publisher/config` topic. Config(LiveChannelConfig), - - /// Deposits seen in L1 blocks before finality, arriving to - /// `channel//publisher/deposits` topic. Observations, not view: a reorg can drop - /// one or deliver it again. - Deposits(Vec), } /// Everything one channel update carries. @@ -181,10 +167,6 @@ pub struct ChannelUpdate { pub view: ViewChange, /// Message-lineage entries whose L1 block reached finality, in channel order. pub finalized: Vec, - /// Finalized Bedrock deposit events, to record and mint on L2. - pub deposits: Vec, - /// Finalized Bedrock withdraw events, to reconcile against local intents. - pub withdrawals: Vec, /// Finalized inscriptions that are not blocks, with the key that signed each. pub undecodable: Vec<(MsgId, Ed25519PublicKey)>, /// The key that signed each finalized entry carrying a block. @@ -200,8 +182,6 @@ pub struct LiveChannelConfig { pub config_tip: MsgId, /// Signatures Bedrock demands of the next config op, exactly. pub required_signatures: u16, - /// Signatures Bedrock demands of a channel transfer, exactly. - pub transfer_threshold: u16, /// Slots one sequencer's posting turn lasts. pub posting_timeframe: u32, /// Idle slots after which Bedrock passes a turn on. @@ -262,7 +242,6 @@ pub struct CreateChannel { pub keys: Vec, pub channel_params: ChannelParams, pub configuration_threshold: NonZero, - pub transfer_threshold: NonZero, } impl ShardingKey for CreateChannel { @@ -278,7 +257,6 @@ impl ShardingKey for CreateChannel { pub struct PublishBlock { pub channel_id: ChannelId, pub block: Block, - pub withdrawals: Vec, /// Parent message ID to inscribe the block on. /// If [`None`] then the block is inscribed on top of channel tip. pub parent: Option, @@ -288,112 +266,29 @@ pub struct PublishBlock { /// /// [`None`] will omit the check. pub expected_seq: Option, + /// What the block moves through the bridge. The inscription carries the vault's program + /// step for it. + pub bridge: BridgeMoves, } -impl ShardingKey for PublishBlock { - type Key = ChannelId; - - fn sharding_key(&self) -> Self::Key { - self.channel_id - } +/// What a block moves between Bedrock and the zone. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BridgeMoves { + /// The program deposits the block mints from, each as its holder submitted it: the step, + /// then its proof, in Bedrock's encoding. + pub deposits: Vec>, + /// The amount and Bedrock key of each withdrawal the block burns. + pub payouts: Vec<(u64, [u8; 32])>, } -/// Funds `block` chained on `parent` and bundled with a transfer re-creating -/// `notes` unchanged, so it lands only where they exist; submits nothing. -#[derive(Debug, Clone)] -pub struct PreparePin { - pub channel_id: ChannelId, - pub block: Block, - pub parent: MsgId, - /// Deposited channel notes the block mints from. - pub notes: Vec, - /// As in [`PublishBlock::expected_seq`]. - pub expected_seq: Option, -} - -/// A funded pinned block, short of the signatures its transfer needs. -#[derive(Debug, Clone)] -pub struct PreparedPin { - pub(crate) tx: Ops, - pub(crate) msg_id: MsgId, - pub(crate) parent: MsgId, - /// Proof of the fee transfer the wallet appended, if it appended one. - #[cfg_attr( - not(feature = "actor"), - expect(dead_code, reason = "Only the actor publishes a pin") - )] - pub(crate) fee_proof: Option, - /// Id of the pinned block, for the publish log. - #[cfg_attr( - not(feature = "actor"), - expect(dead_code, reason = "Only the actor publishes a pin") - )] - pub(crate) block_id: u64, - /// Encoded size of the pinned block in bytes, for the publish log. - #[cfg_attr( - not(feature = "actor"), - expect(dead_code, reason = "Only the actor publishes a pin") - )] - pub(crate) block_size: usize, -} - -impl ShardingKey for PreparePin { - type Key = ChannelId; - - fn sharding_key(&self) -> Self::Key { - self.channel_id - } -} - -impl PreparedPin { - /// The transaction the transfer's signers sign. - #[must_use] - pub const fn tx(&self) -> &Ops { - &self.tx - } - - #[must_use] - pub const fn msg_id(&self) -> MsgId { - self.msg_id - } - +impl BridgeMoves { #[must_use] - pub const fn parent(&self) -> MsgId { - self.parent + pub const fn is_empty(&self) -> bool { + self.deposits.is_empty() && self.payouts.is_empty() } - - /// A pin conjured outside the actor, for a mocked channel to serve. - #[cfg(feature = "mock")] - #[must_use] - pub fn mocked(msg_id: MsgId, parent: MsgId) -> Self { - Self { - tx: Ops::new( - logos_blockchain_zone_sdk::core::era::ForkDigest::new([0; 32]), - logos_blockchain_zone_sdk::core::mantle::transactions::TxList::new_unchecked( - Vec::new(), - ), - ), - msg_id, - parent, - fee_proof: None, - block_id: 0, - block_size: 0, - } - } -} - -/// Publishes a prepared pin with exactly the channel's transfer threshold of -/// signatures. -#[derive(Debug, Clone)] -pub struct PublishPin { - pub channel_id: ChannelId, - pub prepared: PreparedPin, - pub signatures: Vec, - /// As in [`PublishBlock::expected_seq`]. - pub expected_seq: Option, } -impl ShardingKey for PublishPin { +impl ShardingKey for PublishBlock { type Key = ChannelId; fn sharding_key(&self) -> Self::Key { @@ -412,9 +307,6 @@ pub struct PublishOutcome { pub checkpoint: Checkpoint, /// The channel sequence this publish leaves the actor at. pub seq: ChannelSeq, - /// Channel notes the bundled withdrawals release, empty for a plain - /// publish. - pub released_notes: Vec, } /// Fund a channel config moving the channel to the config described here, ready to be signed. @@ -427,7 +319,6 @@ pub struct PrepareConfig { pub posting_timeout: u32, /// Signatures the *next* config will have to carry, not this one. pub configuration_threshold: NonZero, - pub transfer_threshold: NonZero, } impl ShardingKey for PrepareConfig { @@ -512,6 +403,22 @@ impl ShardingKey for CheckChannelExists { } } +/// Checks a program deposit as its holder submitted it, the step and then its proof in Bedrock's +/// encoding, and answers with what the zone mints once the vault takes it in. +#[derive(Debug, Clone)] +pub struct AdmitDeposit { + pub channel_id: ChannelId, + pub deposit: Vec, +} + +impl ShardingKey for AdmitDeposit { + type Key = ChannelId; + + fn sharding_key(&self) -> Self::Key { + self.channel_id + } +} + /// Whether this sequencer is currently authorized to write to the channel. /// /// Prefer subscribing to `channel//turn` topic instead of polling this. @@ -567,20 +474,6 @@ impl AccreditedKeys { } } -/// The channel's notes on the current L1 branch, finalized or not. -#[derive(Debug, Clone)] -pub struct GetChannelNotes { - pub channel_id: ChannelId, -} - -impl ShardingKey for GetChannelNotes { - type Key = ChannelId; - - fn sharding_key(&self) -> Self::Key { - self.channel_id - } -} - /// Get current channel frontier slot on the connected chain. #[derive(Debug, Clone)] pub struct GetChannelTipSlot { diff --git a/lez/sequencer/actors/bedrock/src/trait.rs b/lez/sequencer/actors/bedrock/src/trait.rs index ab2eeb9d5d..8446e5531e 100644 --- a/lez/sequencer/actors/bedrock/src/trait.rs +++ b/lez/sequencer/actors/bedrock/src/trait.rs @@ -1,4 +1,4 @@ -use std::collections::{BTreeSet, HashSet}; +use std::collections::BTreeSet; use kameo::{Actor, message::Message}; @@ -6,11 +6,11 @@ use crate::{ Result, error::Error, protocol::{ - AccreditedKeys, ChangeChannelConfig, ChannelReadStream, ChannelSeq, CheckChannelExists, - CheckIsOurTurn, CreateChannel, FilterFinallyAbsent, FollowChannel, GetAccreditedKeys, - GetChannelNotes, GetChannelTipMessageId, GetChannelTipSlot, InitializeChannelPublisher, - MsgId, NoteId, PrepareConfig, PreparePin, PreparedConfig, PreparedPin, PublishBlock, - PublishOutcome, PublishPin, ReadChannel, SequencerKey, Slot, + AccreditedKeys, AdmitDeposit, ChangeChannelConfig, ChannelReadStream, ChannelSeq, + CheckChannelExists, CheckIsOurTurn, CreateChannel, FilterFinallyAbsent, FollowChannel, + GetAccreditedKeys, GetChannelTipMessageId, GetChannelTipSlot, InitializeChannelPublisher, + MsgId, PrepareConfig, PreparedConfig, PublishBlock, PublishOutcome, ReadChannel, + SequencerKey, Slot, VaultMint, }, }; @@ -20,14 +20,12 @@ pub trait BedrockActorTrait: + Message>> + Message> + Message> - + Message> - + Message> + Message> + Message> + Message> + + Message> + Message> + Message>> - + Message>> + Message>> + Message>> + Message> diff --git a/lez/sequencer/actors/channel_signing/src/actor.rs b/lez/sequencer/actors/channel_signing/src/actor.rs index 26ef0bd443..902898095a 100644 --- a/lez/sequencer/actors/channel_signing/src/actor.rs +++ b/lez/sequencer/actors/channel_signing/src/actor.rs @@ -1,20 +1,14 @@ -use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::collections::BTreeMap; use kameo::{ Actor, actor::{ActorRef, WeakRecipient}, message::{Context, Message}, - reply::{DelegatedReply, ReplySender}, }; use logos_blockchain_zone_sdk::{ core::{ mantle::{ - NoteId, - ledger::Note, - ops::{ - Op, - channel::{ChannelId, config::ChannelConfigOp}, - }, + ops::{Op, channel::config::ChannelConfigOp}, traits::Hashable as _, transactions::Ops, }, @@ -28,9 +22,8 @@ use tracing::{debug, warn}; use crate::{ error::Error, protocol::{ - Action, BlockDeposits, ChannelView, ConfigTarget, Draft, FinalMints, FundedTx, - ObservedDeposits, Propose, Reset, SetPublisher, SetSubmitter, SignPin, Signature, - Submission, SubmitConfig, Wire, + Action, ChannelView, ConfigTarget, Draft, FundedTx, Propose, Reset, SetPublisher, + SetSubmitter, Signature, Submission, SubmitConfig, Wire, }, }; @@ -38,22 +31,9 @@ use crate::{ /// /// A rotation where several nodes fund rivals puts one draft and one signature /// per peer per rival on the topic, so the inbound burst grows with the square -/// of the committee, and a pinned block adds one draft and a signature per -/// peer; `try_send` drops past this, which costs one turn or one pin. +/// of the committee; `try_send` drops past this, which costs one turn. pub const MAILBOX_CAPACITY: usize = 256; -/// Peers' pins held for deposits this node has not observed yet; the oldest -/// goes past this. -const PARKED_PINS: usize = 8; - -/// What to do with a peer's draft. -enum Verdict { - Sign, - /// A pin of a deposit this node has not observed yet. - Park, - Refuse, -} - /// A draft this node funded and is collecting signatures for. struct OwnDraft { target: ConfigTarget, @@ -65,33 +45,14 @@ struct OwnDraft { submission_sent: bool, } -/// A pin this node funded, waiting on its transfer signatures. -struct OwnPin { - tx_hash: [u8; 32], - /// Signatures by accredited-key index, so the choice below is ordered. - signatures: BTreeMap, - reply: ReplySender>>, -} - pub struct ChannelSigningActor { signing_key: Ed25519Key, own_key: Ed25519PublicKey, - /// The channel a pin must inscribe and transfer on. - channel_id: ChannelId, - block_deposits: BlockDeposits, - /// Notes of the deposits seen on L1 and not yet minted in a final block, - /// with the deposit each belongs to. - deposit_notes: HashMap, - /// Peers' pins of deposits this node has not observed yet, checked again as - /// deposits arrive. - parked: VecDeque, /// The live channel and the committee it should have, as of the last turn. view: Option, /// Our own draft. Not persisted: a signature is only good for one funded /// transaction, and a restart funds a different one. draft: Option, - /// Our own pin, for as long as its producer waits on it. - pin: Option, // TODO: Use messages instead of tokio's primitives. publisher: Option>, /// Sent the draft once it has its signatures. @@ -100,23 +61,14 @@ pub struct ChannelSigningActor { impl ChannelSigningActor { #[must_use] - pub fn new( - signing_key: Ed25519Key, - channel_id: ChannelId, - block_deposits: BlockDeposits, - ) -> Self { + pub fn new(signing_key: Ed25519Key) -> Self { let own_key = signing_key.public_key(); Self { signing_key, own_key, - channel_id, - block_deposits, - deposit_notes: HashMap::new(), - parked: VecDeque::new(), view: None, draft: None, - pin: None, publisher: None, submitter: None, } @@ -205,103 +157,21 @@ impl ChannelSigningActor { })) } - /// Whether a transaction is only a peer's block pinned on deposits it - /// mints: one block inscribed by another live accredited key, one transfer - /// re-creating unchanged notes of those deposits, and the fee. - fn check_pin(&self, tx: &Ops, live_keys: &[Ed25519PublicKey]) -> Verdict { - let mut inscription = None; - let mut transfer = None; - let mut funded = false; - for op in tx { - let first = match op { - // Our co-signature would also be the proof of an inscription - // signed as us, putting in our name a block we never built. - Op::ChannelInscribe(op) - if op.channel_id == self.channel_id - && op.signer != self.own_key.into_unverified() - && live_keys - .iter() - .any(|key| key.into_unverified() == op.signer) => - { - inscription.replace(op).is_none() - } - Op::ChannelTransfer(op) if op.channel_id == self.channel_id => { - transfer.replace(op).is_none() - } - // The fee the proposer's wallet added. - Op::Transfer(_) => !std::mem::replace(&mut funded, true), - // Nothing else may share a transaction our signatures cover. - Op::ChannelInscribe(_) - | Op::ChannelTransfer(_) - | Op::ChannelConfig(_) - | Op::ChannelDeposit(_) - | Op::ChannelWithdraw(_) - | Op::SDPDeclare(_) - | Op::SDPWithdraw(_) - | Op::SDPActive(_) - | Op::LeaderClaim(_) - | Op::ClaimPowReward(_) => return Verdict::Refuse, - }; - if !first { - return Verdict::Refuse; - } - } - let (Some(inscription), Some(transfer)) = (inscription, transfer) else { - return Verdict::Refuse; - }; - let Some(minted) = (self.block_deposits)(&inscription.inscription) else { - return Verdict::Refuse; - }; - if transfer.inputs.is_empty() || transfer.inputs.len() != transfer.outputs.len() { - return Verdict::Refuse; - } - - let mut verdict = Verdict::Sign; - for (input, output) in transfer.inputs.iter().zip(transfer.outputs.iter()) { - match self.deposit_notes.get(input) { - // Bedrock checks the balance but not the keys, and a note's key - // holds its stake, so each output must be its input exactly. - Some((op_id, note)) if note == output && minted.contains(op_id) => {} - Some(_) => return Verdict::Refuse, - None => verdict = Verdict::Park, - } - } - - verdict - } - /// A peer's draft, from gossip or from a direct send. - fn on_peer_draft(&mut self, msg: Draft) { + fn on_peer_draft(&self, msg: &Draft) { let Some(view) = &self.view else { return; }; // A peer is trusted for its signature, never for the op: sign a config // only if this node derived it from finalized state for itself. - let verdict = match config_op(&msg.tx) { - Some(op) - if view - .target - .as_ref() - .is_some_and(|target| matches(target, op)) => - { - Verdict::Sign - } - Some(_) => Verdict::Refuse, - None => self.check_pin(&msg.tx, &view.live_keys), - }; - match verdict { - Verdict::Sign => {} - Verdict::Park => { - if self.parked.len() >= PARKED_PINS { - self.parked.pop_front(); - } - self.parked.push_back(msg); - return; - } - Verdict::Refuse => { - debug!("Ignoring a draft that is neither the config we want nor a pin"); - return; - } + let wanted = config_op(&msg.tx).is_some_and(|op| { + view.target + .as_ref() + .is_some_and(|target| matches(target, op)) + }); + if !wanted { + debug!("Ignoring a draft that is not the config we want"); + return; } let Some(index) = self.own_index() else { @@ -318,16 +188,8 @@ impl ChannelSigningActor { })); } - /// A peer's signature over the draft or the pin this node holds. + /// A peer's signature over the draft this node holds. fn on_peer_signature(&mut self, msg: &Signature) { - if self - .pin - .as_ref() - .is_some_and(|pin| pin.tx_hash == msg.tx_hash) - { - self.on_pin_signature(msg); - return; - } let Some(view) = &self.view else { return; }; @@ -364,52 +226,6 @@ impl ChannelSigningActor { in_flight.submission_sent = true; } } - - /// A peer's signature over the pin this node holds. - fn on_pin_signature(&mut self, msg: &Signature) { - let Some(view) = &self.view else { - return; - }; - let index = msg.signature.channel_key_index; - let Some(key) = view.live_keys.get(usize::from(index)) else { - return; - }; - if key.verify(&msg.tx_hash, &msg.signature.signature).is_err() { - debug!("Dropping a pin signature that does not verify"); - return; - } - if let Some(pin) = &mut self.pin { - pin.signatures.insert(index, msg.signature.signature); - } - self.complete_pin(); - } - - /// Answers the pin's producer once it holds the live transfer threshold. - fn complete_pin(&mut self) { - let Some(view) = &self.view else { - return; - }; - let required = usize::from(view.transfer_signatures); - if self - .pin - .as_ref() - .is_none_or(|pin| pin.signatures.len() < required) - { - return; - } - let Some(pin) = self.pin.take() else { - return; - }; - // Bedrock wants exactly the threshold, never more, so take the lowest - // indices and leave the rest. - let signatures = pin - .signatures - .iter() - .take(required) - .map(|(index, signature)| IndexedSignature::new(*index, *signature)) - .collect(); - pin.reply.send(Some(signatures)); - } } impl Actor for ChannelSigningActor { @@ -501,7 +317,7 @@ impl Message for ChannelSigningActor { /// carries it. async fn handle(&mut self, msg: Wire, _ctx: &mut Context) { match msg { - Wire::Draft(draft) => self.on_peer_draft(draft), + Wire::Draft(draft) => self.on_peer_draft(&draft), Wire::Signature(signature) => self.on_peer_signature(&signature), } } @@ -539,74 +355,6 @@ impl Message for ChannelSigningActor { } } -impl Message for ChannelSigningActor { - type Reply = (); - - async fn handle( - &mut self, - ObservedDeposits(deposits): ObservedDeposits, - _ctx: &mut Context, - ) { - for deposit in deposits { - for note in deposit.notes { - self.deposit_notes.insert( - note.note_id, - (deposit.op_id, Note::new(note.value, note.pk)), - ); - } - } - for draft in std::mem::take(&mut self.parked) { - self.on_peer_draft(draft); - } - } -} - -impl Message for ChannelSigningActor { - type Reply = (); - - async fn handle( - &mut self, - FinalMints(op_ids): FinalMints, - _ctx: &mut Context, - ) { - self.deposit_notes - .retain(|_note, (op_id, _)| !op_ids.contains(op_id)); - } -} - -impl Message for ChannelSigningActor { - type Reply = DelegatedReply>>; - - /// Replaces any earlier pin: its producer has stopped waiting on it. - async fn handle( - &mut self, - SignPin(tx): SignPin, - ctx: &mut Context, - ) -> Self::Reply { - let (delegated, reply) = ctx.reply_sender(); - let Some(reply) = reply else { - return delegated; - }; - let Some(index) = self.own_index() else { - warn!("Not in the live accredited list; cannot sign our pin"); - reply.send(None); - return delegated; - }; - - self.pin = Some(OwnPin { - tx_hash: tx.hash().0, - signatures: BTreeMap::from([(index, self.sign(&tx))]), - reply, - }); - self.complete_pin(); - if self.pin.is_some() { - self.publish(Wire::Draft(Draft { tx })); - } - - delegated - } -} - /// The channel config a transaction would install. /// /// A signature covers the whole transaction, and the same signatures satisfy @@ -632,12 +380,11 @@ fn config_op(tx: &Ops) -> Option<&ChannelConfigOp> { Op::ChannelInscribe(_) | Op::ChannelDeposit(_) | Op::ChannelWithdraw(_) - | Op::ChannelTransfer(_) | Op::SDPDeclare(_) | Op::SDPWithdraw(_) | Op::SDPActive(_) - | Op::LeaderClaim(_) - | Op::ClaimPowReward(_) => return None, + | Op::ClaimPowReward(_) + | Op::ProgramRegister(_) => return None, } } @@ -651,7 +398,6 @@ fn matches(target: &ConfigTarget, op: &ChannelConfigOp) -> bool { && u32::from(op.posting_timeframe().clone()) == target.posting_timeframe && u32::from(op.posting_timeout().clone()) == target.posting_timeout && op.configuration_threshold() == target.configuration_threshold - && op.transfer_threshold() == target.transfer_threshold } #[cfg(test)] diff --git a/lez/sequencer/actors/channel_signing/src/actor/tests.rs b/lez/sequencer/actors/channel_signing/src/actor/tests.rs index fd2bc21590..0dc4a8ef0d 100644 --- a/lez/sequencer/actors/channel_signing/src/actor/tests.rs +++ b/lez/sequencer/actors/channel_signing/src/actor/tests.rs @@ -5,34 +5,25 @@ use logos_blockchain_zone_sdk::{ core::{ crypto::ZkHash, era::ForkDigest, - events::DepositNote, mantle::{ channel::{SlotTimeframe, SlotTimeout}, - ledger::{Inputs, Outputs}, + notes::NoteNullifier, ops::{ - channel::{ - ChannelId, MsgId, VerifiedChannelKeys, - channel_transfer::ChannelTransferOp, - inscribe::{Inscription, InscriptionOp}, - withdraw::ChannelWithdrawOp, - }, + channel::{ChannelId, MsgId, VerifiedChannelKeys, withdraw::ChannelWithdrawOp}, transfer::TransferOp, }, }, }, - key_management_system_service::keys::{Ed25519Signature, ZkPublicKey}, + key_management_system_service::keys::Ed25519Signature, }; use super::*; -use crate::protocol::ObservedDeposit; const CHANNEL: [u8; 32] = [1; 32]; const OWN_SECRET: [u8; 32] = [9; 32]; const PEER_SECRET: [u8; 32] = [8; 32]; /// A four-node committee: Bedrock asks three signatures of the next config. const COMMITTEE: [[u8; 32]; 4] = [[1; 32], [2; 32], [3; 32], [4; 32]]; -/// The deposit the pins below spend a note of. -const DEPOSIT: [u8; 32] = [6; 32]; /// Stands in for the core, the only thing that can actually submit. struct SubmitSink(mpsc::UnboundedSender); @@ -74,7 +65,6 @@ fn target() -> ConfigTarget { posting_timeframe: 300, posting_timeout: 25, configuration_threshold: NonZero::new(2).unwrap(), - transfer_threshold: NonZero::new(1).unwrap(), } } @@ -83,7 +73,6 @@ fn view(target: Option) -> ChannelView { ChannelView { live_keys: live_keys(), required_signatures: 2, - transfer_signatures: 2, target, } } @@ -97,25 +86,13 @@ fn draft_tx(target: &ConfigTarget) -> Ops { SlotTimeframe::from(target.posting_timeframe), SlotTimeout::from(target.posting_timeout), target.configuration_threshold, - target.transfer_threshold, ) .expect("the target's threshold is reachable with its keys"); Ops::new(ForkDigest::new([0; 32]), [Op::ChannelConfig(op)]) } fn actor(secret: [u8; 32]) -> ActorRef { - ChannelSigningActor::spawn(ChannelSigningActor::new( - key(secret), - ChannelId::from(CHANNEL), - listed_deposits, - )) -} - -/// Reads a test inscription as the deposit op ids it lists; `None` for one -/// that lists none whole. -fn listed_deposits(inscription: &[u8]) -> Option> { - let (op_ids, rest) = inscription.as_chunks::<32>(); - rest.is_empty().then(|| op_ids.to_vec()) + ChannelSigningActor::spawn(ChannelSigningActor::new(key(secret))) } async fn tell_view(actor: &ActorRef, view: ChannelView) { @@ -203,7 +180,6 @@ fn committee_target() -> ConfigTarget { posting_timeframe: 300, posting_timeout: 25, configuration_threshold: NonZero::new(4).unwrap(), - transfer_threshold: NonZero::new(1).unwrap(), } } @@ -211,7 +187,6 @@ fn committee_view() -> ChannelView { ChannelView { live_keys: committee_keys(), required_signatures: 3, - transfer_signatures: 3, target: Some(committee_target()), } } @@ -221,8 +196,10 @@ fn committee_view() -> ChannelView { fn rival_tx(target: &ConfigTarget, proposer: u8) -> Ops { let mut tx = draft_tx(target); tx.try_push(Op::Transfer(TransferOp::new( - Inputs::new(NoteId(ZkHash::from(u64::from(proposer)))), - Outputs::empty(), + [NoteNullifier(ZkHash::from(u64::from(proposer)))].into(), + [].into(), + ZkHash::from(0_u64), + 0, ))) .expect("a second op fits"); @@ -668,9 +645,8 @@ async fn a_peer_does_not_sign_a_config_it_did_not_ask_for() { // Same shape, but installing a committee this node never derived. let mut rogue = target(); rogue.keys = vec![key(PEER_SECRET).public_key()]; - // Thresholds a one-key committee can reach, so the op itself is well formed. + // A threshold a one-key committee can reach, so the op itself is well formed. rogue.configuration_threshold = NonZero::new(1).unwrap(); - rogue.transfer_threshold = NonZero::new(1).unwrap(); actor .ask(Wire::Draft(Draft { tx: Box::new(draft_tx(&rogue)), @@ -716,7 +692,9 @@ async fn a_draft_bundling_a_withdrawal_is_not_signed() { let mut tx = draft_tx(&target()); tx.try_push(Op::ChannelWithdraw(ChannelWithdrawOp { channel_id: ChannelId::from(CHANNEL), - inputs: Inputs::new(NoteId(ZkHash::from(7_u64))), + inputs: [NoteNullifier(ZkHash::from(7_u64))].into(), + outputs: [].into(), + commitment_merkle_root: ZkHash::from(0_u64), })) .expect("a second op fits"); actor @@ -752,312 +730,3 @@ async fn a_draft_carrying_two_configs_is_not_signed() { "a transaction must carry exactly one config to be signed" ); } - -fn deposit_note() -> DepositNote { - DepositNote { - note_id: NoteId(ZkHash::from(7_u64)), - value: 100, - pk: ZkPublicKey::from(ZkHash::from(3_u64)), - } -} - -/// `inscription` by `signer`, pinned by a transfer of `inputs` into `outputs`; -/// unfunded. -fn pin_tx_of(signer: &Ed25519Key, inscription: Vec, inputs: Inputs, outputs: Outputs) -> Ops { - let inscription = InscriptionOp { - channel_id: ChannelId::from(CHANNEL), - inscription: Inscription::new_unchecked(inscription), - parent: MsgId::root(), - signer: signer.public_key().into_unverified(), - }; - let transfer = ChannelTransferOp { - channel_id: ChannelId::from(CHANNEL), - inputs, - outputs, - }; - Ops::new( - ForkDigest::new([0; 32]), - [ - Op::ChannelInscribe(inscription), - Op::ChannelTransfer(transfer), - ], - ) -} - -fn deposit_input() -> Inputs { - Inputs::new(deposit_note().note_id) -} - -/// The deposit note re-created unchanged. -fn deposit_output() -> Outputs { - let note = deposit_note(); - Outputs::new([Note::new(note.value, note.pk)]) -} - -/// A block by `signer` minting the deposit its transfer re-creates; unfunded. -fn pin_tx(signer: &Ed25519Key) -> Ops { - pin_tx_of(signer, DEPOSIT.to_vec(), deposit_input(), deposit_output()) -} - -async fn observe_deposit(actor: &ActorRef) { - actor - .ask(ObservedDeposits(vec![ObservedDeposit { - op_id: DEPOSIT, - notes: vec![deposit_note()], - }])) - .await - .expect("the actor should accept deposits"); -} - -/// Whether `actor` signs a peer's `tx`, with the deposit observed. -async fn signs_peer_pin(actor: &ActorRef, tx: Ops) -> bool { - let mut outbound = publisher(actor).await; - actor - .ask(Wire::Draft(Draft { tx: Box::new(tx) })) - .await - .expect("the actor should accept a peer draft"); - - matches!(outbound.try_recv(), Ok(Wire::Signature(_))) -} - -#[tokio::test] -async fn a_pin_needing_only_our_signature_is_answered_at_once() { - let actor = actor(OWN_SECRET); - tell_view( - &actor, - ChannelView { - transfer_signatures: 1, - ..view(None) - }, - ) - .await; - let mut outbound = publisher(&actor).await; - - let signatures = actor - .ask(SignPin(Box::new(pin_tx(&key(OWN_SECRET))))) - .await - .expect("a reply") - .expect("this node is accredited"); - - let indices: Vec = signatures - .iter() - .map(|indexed| indexed.channel_key_index) - .collect(); - assert_eq!(indices, vec![0]); - assert!( - outbound.try_recv().is_err(), - "a pin our signature completes needs no peer" - ); -} - -#[tokio::test] -async fn a_pin_is_announced_and_answered_once_a_peer_signs() { - let actor = actor(OWN_SECRET); - tell_view(&actor, view(None)).await; - let mut outbound = publisher(&actor).await; - let tx = pin_tx(&key(OWN_SECRET)); - - let pending = tokio::spawn({ - let actor = actor.clone(); - let tx = tx.clone(); - async move { actor.ask(SignPin(Box::new(tx))).await } - }); - assert!( - matches!(outbound.recv().await, Some(Wire::Draft(_))), - "the pin should be announced" - ); - peer_signs(&actor, &tx).await; - - let signatures = pending - .await - .expect("the producer task") - .expect("a reply") - .expect("this node is accredited"); - let indices: Vec = signatures - .iter() - .map(|indexed| indexed.channel_key_index) - .collect(); - assert_eq!(indices, vec![0, 1]); -} - -#[tokio::test] -async fn a_peer_signs_a_pin() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - - assert!(signs_peer_pin(&actor, pin_tx(&key(OWN_SECRET))).await); -} - -/// The same signatures satisfy a withdraw sitting beside the transfer. -#[tokio::test] -async fn a_pin_bundling_a_withdrawal_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - - let mut tx = pin_tx(&key(OWN_SECRET)); - tx.try_push(Op::ChannelWithdraw(ChannelWithdrawOp { - channel_id: ChannelId::from(CHANNEL), - inputs: Inputs::new(NoteId(ZkHash::from(8_u64))), - })) - .expect("a third op fits"); - - assert!(!signs_peer_pin(&actor, tx).await); -} - -#[tokio::test] -async fn a_pin_by_a_key_outside_the_committee_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - - assert!(!signs_peer_pin(&actor, pin_tx(&key([5; 32]))).await); -} - -/// Our signature over the draft would also prove its inscription, so a block -/// signed as us must never get it. -#[tokio::test] -async fn a_pin_inscribed_as_us_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - - assert!(!signs_peer_pin(&actor, pin_tx(&key(PEER_SECRET))).await); -} - -#[tokio::test] -async fn a_pin_of_an_unobserved_deposit_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - - assert!(!signs_peer_pin(&actor, pin_tx(&key(OWN_SECRET))).await); -} - -#[tokio::test] -async fn a_pin_of_a_deposit_minted_in_a_final_block_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - actor - .ask(FinalMints(vec![DEPOSIT])) - .await - .expect("the actor should accept final mints"); - - assert!(!signs_peer_pin(&actor, pin_tx(&key(OWN_SECRET))).await); -} - -/// Balanced, so Bedrock would take it, but the stake moves to another key. -#[tokio::test] -async fn a_pin_re_keying_a_deposit_note_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - - let output = Note::new(deposit_note().value, ZkPublicKey::from(ZkHash::from(4_u64))); - let tx = pin_tx_of( - &key(OWN_SECRET), - DEPOSIT.to_vec(), - deposit_input(), - Outputs::new([output]), - ); - - assert!(!signs_peer_pin(&actor, tx).await); -} - -#[tokio::test] -async fn a_pin_on_a_deposit_its_block_does_not_mint_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - - let tx = pin_tx_of( - &key(OWN_SECRET), - [5_u8; 32].to_vec(), - deposit_input(), - deposit_output(), - ); - - assert!(!signs_peer_pin(&actor, tx).await); -} - -#[tokio::test] -async fn a_pin_inscribing_no_block_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - - let tx = pin_tx_of( - &key(OWN_SECRET), - vec![7_u8; 8], - deposit_input(), - deposit_output(), - ); - - assert!(!signs_peer_pin(&actor, tx).await); -} - -#[tokio::test] -async fn a_pin_spending_no_note_is_not_signed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - observe_deposit(&actor).await; - - let tx = pin_tx_of( - &key(OWN_SECRET), - DEPOSIT.to_vec(), - Inputs::empty(), - Outputs::empty(), - ); - - assert!(!signs_peer_pin(&actor, tx).await); -} - -/// A peer's L1 node can be behind the proposer's, so its draft can arrive -/// before the deposit does. -#[tokio::test] -async fn a_pin_is_signed_once_its_deposit_is_observed() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - let mut outbound = publisher(&actor).await; - - actor - .ask(Wire::Draft(Draft { - tx: Box::new(pin_tx(&key(OWN_SECRET))), - })) - .await - .expect("the actor should accept a peer draft"); - assert!(outbound.try_recv().is_err()); - observe_deposit(&actor).await; - - assert!(matches!(outbound.try_recv(), Ok(Wire::Signature(_)))); -} - -#[tokio::test] -async fn only_the_latest_pins_wait_for_their_deposit() { - let actor = actor(PEER_SECRET); - tell_view(&actor, view(None)).await; - let mut outbound = publisher(&actor).await; - - // Distinct pins of the one deposit: each block lists it a different - // number of times. - for listed in 1..=PARKED_PINS.saturating_add(1) { - let tx = pin_tx_of( - &key(OWN_SECRET), - DEPOSIT.repeat(listed), - deposit_input(), - deposit_output(), - ); - actor - .ask(Wire::Draft(Draft { tx: Box::new(tx) })) - .await - .expect("the actor should accept a peer draft"); - } - observe_deposit(&actor).await; - - let mut signed = 0_usize; - while let Ok(Wire::Signature(_)) = outbound.try_recv() { - signed = signed.saturating_add(1); - } - assert_eq!(signed, PARKED_PINS); -} diff --git a/lez/sequencer/actors/channel_signing/src/lib.rs b/lez/sequencer/actors/channel_signing/src/lib.rs index 4fd7662d33..59b7cc8bdc 100644 --- a/lez/sequencer/actors/channel_signing/src/lib.rs +++ b/lez/sequencer/actors/channel_signing/src/lib.rs @@ -1,5 +1,4 @@ -//! Collects the accredited-key signatures a `ChannelConfigOp` needs, and those -//! of the `ChannelTransfer` pinning a block on its deposits. +//! Collects the accredited-key signatures a `ChannelConfigOp` needs. //! //! Bedrock verifies a config against the channel's own //! `configuration_threshold`, so raising it above one is a matter of gathering diff --git a/lez/sequencer/actors/channel_signing/src/protocol.rs b/lez/sequencer/actors/channel_signing/src/protocol.rs index 069ecb6cc2..590aae413d 100644 --- a/lez/sequencer/actors/channel_signing/src/protocol.rs +++ b/lez/sequencer/actors/channel_signing/src/protocol.rs @@ -4,7 +4,6 @@ use kameo::Reply; use logos_blockchain_zone_sdk::{ binary_codec::canonical::{BinaryDecodeExt as _, BinaryEncode as _}, core::{ - events::DepositNote, mantle::{ ops::channel::{ChannelKeyIndex, MsgId}, transactions::Ops, @@ -35,7 +34,6 @@ pub struct ConfigTarget { pub posting_timeout: u32, /// Signatures the *next* config will have to carry, not this one. pub configuration_threshold: NonZero, - pub transfer_threshold: NonZero, } /// What this node last saw of the live channel, plus the committee it should @@ -46,8 +44,6 @@ pub struct ChannelView { pub live_keys: Vec, /// Signatures the live channel demands of the next config op. pub required_signatures: u16, - /// Signatures the live channel demands of a channel transfer. - pub transfer_signatures: u16, /// The config to install, or `None` when live already matches. pub target: Option, } @@ -86,8 +82,8 @@ pub struct FundedTx { pub signing_threshold: u16, } -/// A funded config or pin transaction on the wire, for whoever receives it -/// to check and sign. +/// A funded config transaction on the wire, for whoever receives it to check +/// and sign. #[derive(Clone, Debug)] pub struct Draft { pub tx: Box, @@ -117,29 +113,6 @@ pub struct SetSubmitter(pub kameo::actor::WeakRecipient); /// Drops the draft this node holds, for a core that has given up on it. pub struct Reset; -/// Collects signatures over a funded pin, starting with this node's own, and -/// answers with exactly the live transfer threshold in index order, or `None` -/// when this node cannot sign. -pub struct SignPin(pub Box); - -/// The deposit op ids a block inscription mints, or `None` when it is not a -/// block. -pub type BlockDeposits = fn(&[u8]) -> Option>; - -/// A deposit seen on L1, whose notes a peer's pin may re-create. -#[derive(Clone, Debug)] -pub struct ObservedDeposit { - pub op_id: [u8; 32], - pub notes: Vec, -} - -/// Deposits seen on L1 since the last of these. -pub struct ObservedDeposits(pub Vec); - -/// Op ids of deposits minted in final blocks. A pin lands only on the channel -/// tip, which holds their mints already, so no valid pin carries them. -pub struct FinalMints(pub Vec<[u8; 32]>); - /// The two message shapes the channel-config topic carries, either way. #[derive(Clone, Debug)] pub enum Wire { diff --git a/lez/sequencer/actors/executor/Cargo.toml b/lez/sequencer/actors/executor/Cargo.toml index 9d3fad7359..344ee5f71a 100644 --- a/lez/sequencer/actors/executor/Cargo.toml +++ b/lez/sequencer/actors/executor/Cargo.toml @@ -23,7 +23,6 @@ actor = [ "dep:programs", "dep:system_accounts", "dep:fee_core", - "dep:bridge_core", "dep:tokio", "dep:futures", @@ -65,7 +64,6 @@ cross_zone = { workspace = true, optional = true } system_accounts = { workspace = true, optional = true } programs = { workspace = true, optional = true } fee_core = { workspace = true, optional = true } -bridge_core = { workspace = true, optional = true } kameo.workspace = true anyhow.workspace = true @@ -83,7 +81,6 @@ mockall = { workspace = true, optional = true } lee = { workspace = true, features = ["test-utils"] } sequencer_storage_actor = { workspace = true, features = ["mock"] } sequencer_bedrock_actor = { workspace = true, features = ["mock"] } -bridge_core.workspace = true chain_state.workspace = true cross_zone = { workspace = true, features = ["test-utils"] } cross_zone_inbox_core.workspace = true diff --git a/lez/sequencer/actors/executor/src/actor.rs b/lez/sequencer/actors/executor/src/actor.rs index 0191c248d8..39fa20e99b 100644 --- a/lez/sequencer/actors/executor/src/actor.rs +++ b/lez/sequencer/actors/executor/src/actor.rs @@ -52,8 +52,8 @@ use crate::{ GetLastBlockId, GetMessagePath, GetProofsAndRoot, GetProofsAndRootReply, GetPublications, GetPublicationsReply, GetRecoveryBinding, GetStatus, GetSystemProposals, GetSystemProposalsReply, GetTransaction, GetTransactionReceipt, ProduceBlock, - RequeueCrossZoneDeadLetter, RequeueCrossZoneDeadLetterReply, SubmitSystemApproval, - Transaction, + RequeueCrossZoneDeadLetter, RequeueCrossZoneDeadLetterReply, SubmitProgramDeposit, + SubmitSystemApproval, Transaction, }, }; @@ -819,6 +819,27 @@ impl Message } } +impl Message + for ExecutorActor +{ + type Reply = Result<()>; + + async fn handle( + &mut self, + SubmitProgramDeposit { deposit }: SubmitProgramDeposit, + _ctx: &mut Context, + ) -> Self::Reply { + let State::Online(online) = &mut self.state else { + return Err(Error::NotOnline); + }; + online + .sequencer_mut() + .admit_deposit(deposit) + .await + .map_err(Error::ProgramDepositRefused) + } +} + impl Message for ExecutorActor { type Reply = Result>; @@ -906,22 +927,6 @@ impl Message for Execu }) .await?; } - ChannelEventKind::FinalizedDeposit(deposit) => match &self.state { - State::Error(details) => panic!("Actor has encountered an error state: {details}"), - State::Bootstrapping(bootstrapping) => { - bootstrapping.on_finalized_deposit(&deposit).await?; - } - // Online state listens for Publisher events - State::Online(_) => {} - }, - ChannelEventKind::FinalizedWithdrawal(withdrawal) => match &self.state { - State::Error(details) => panic!("Actor has encountered an error state: {details}"), - State::Bootstrapping(bootstrapping) => { - bootstrapping.on_finalized_withdrawal(&withdrawal).await?; - } - // Online state listens for Publisher events - State::Online(_) => {} - }, ChannelEventKind::Publisher(publisher_event) => match &mut self.state { State::Error(details) => panic!("Actor has encountered an error state: {details}"), State::Bootstrapping(_) => { @@ -948,9 +953,6 @@ impl Message for Execu .on_channel_config_update(live_channel_config) .await; } - PublisherEvent::Deposits(deposits) => { - online.sequencer_mut().on_observed_deposits(deposits).await; - } }, }, } diff --git a/lez/sequencer/actors/executor/src/actor/state/bootstrapping.rs b/lez/sequencer/actors/executor/src/actor/state/bootstrapping.rs index 69b32071a9..3fb7cd6ebc 100644 --- a/lez/sequencer/actors/executor/src/actor/state/bootstrapping.rs +++ b/lez/sequencer/actors/executor/src/actor/state/bootstrapping.rs @@ -8,17 +8,11 @@ use common::{ use kameo::actor::ActorRef; use sequencer_bedrock_actor::{ BedrockActorTrait, - protocol::{ - BlockData, DepositInfo, Ed25519Key, FinalizedBlock, FinalizedUpTo, L1Position, MsgId, Slot, - WithdrawInfo, - }, + protocol::{BlockData, Ed25519Key, FinalizedBlock, FinalizedUpTo, L1Position, MsgId, Slot}, }; use sequencer_core::{config::SequencerConfig, faults, release_finality}; use sequencer_slasher_actor::protocol::{Report, ReportedOffence}; -use sequencer_storage_actor::{ - StorageActorTrait, - protocol::{AtomicUpdate, ZoneAnchorRecord}, -}; +use sequencer_storage_actor::{StorageActorTrait, protocol::ZoneAnchorRecord}; use tracing::warn; use crate::{ @@ -141,34 +135,6 @@ impl BootstrappingState { Ok(()) } - /// Records a finalized deposit read alongside the finalized blocks. - pub async fn on_finalized_deposit(&self, deposit: &DepositInfo) -> Result<()> { - let outcome = self - .actors - .storage_ref - .ask(AtomicUpdate { - new_deposit_events: vec![sequencer_core::pending_deposit_event_record(deposit)], - ..sequencer_core::chain_update(&self.chain) - }) - .await?; - sequencer_core::log_recorded_deposits(&outcome); - Ok(()) - } - - /// Reconciles a finalized withdrawal read alongside the finalized blocks. - pub async fn on_finalized_withdrawal(&self, withdrawal: &WithdrawInfo) -> Result<()> { - let outcome = self - .actors - .storage_ref - .ask(AtomicUpdate { - consumed_withdrawals: sequencer_core::released_note_keys(withdrawal).collect(), - ..sequencer_core::chain_update(&self.chain) - }) - .await?; - sequencer_core::log_unmatched_withdrawals(&outcome); - Ok(()) - } - /// Applies one finalized channel entry, moving the final entry to it only on the lineage. A /// block the store already holds only settles its deliveries, a block that does not apply is /// skipped, like the follow path does. Advances the persisted anchor to a block the store @@ -244,15 +210,8 @@ impl BootstrappingState { let mut update = sequencer_core::chain_update(&self.chain); update.blocks = sequencer_core::new_head_blocks(&self.chain, &head_before); if !newly_final.is_empty() { - // A reconstructed block is finalized, so any deposit it mints is - // permanently reflected in state (its receipt PDA); drop the - // pending record backfill may have re-delivered, so the drain - // stops re-minting. The same for the deliveries it carries. - update.finalized_deposit_records = newly_final - .iter() - .flat_map(|block| block.body.transactions.iter()) - .filter_map(sequencer_core::extract_bridge_deposit_id) - .collect(); + // A reconstructed block is finalized, so the deliveries it carries + // are settled: drop their pending records. for block in &newly_final { update .finalized_dispatch_records @@ -292,19 +251,11 @@ impl BootstrappingState { } // A block we already hold verbatim needs no replay, but the // channel serving it is what makes it irreversible, so its - // deposits and deliveries are settled and their records are - // owed nothing. + // deliveries are settled and their records are owed nothing. Some(AcceptOutcome::AlreadyApplied | AcceptOutcome::Parked(_)) if let Some(stored) = held_final => { Self::settle_reconstructed_deliveries(storage_ref, &stored).await?; - update.finalized_deposit_records.extend( - stored - .body - .transactions - .iter() - .filter_map(sequencer_core::extract_bridge_deposit_id), - ); update.zone_anchor = Some(record); } Some(AcceptOutcome::AlreadyApplied) | None => {} diff --git a/lez/sequencer/actors/executor/src/actor/state/online.rs b/lez/sequencer/actors/executor/src/actor/state/online.rs index 6697418308..3b71db8333 100644 --- a/lez/sequencer/actors/executor/src/actor/state/online.rs +++ b/lez/sequencer/actors/executor/src/actor/state/online.rs @@ -314,9 +314,9 @@ impl OnlineState { .ask(sequencer_bedrock_actor::protocol::PublishBlock { channel_id: config.bedrock_config.channel_id, block: block.clone(), - withdrawals: Vec::new(), parent: None, expected_seq: None, + bridge: sequencer_bedrock_actor::protocol::BridgeMoves::default(), }) .await .map_err(SendErrorExt::flatten)?; @@ -377,7 +377,6 @@ impl OnlineState { keys, channel_params, configuration_threshold, - transfer_threshold: configuration_threshold, }) .await .map_err(SendErrorExt::flatten)? @@ -386,9 +385,9 @@ impl OnlineState { .ask(sequencer_bedrock_actor::protocol::PublishBlock { channel_id, block: genesis.clone(), - withdrawals: Vec::new(), parent: None, expected_seq: None, + bridge: sequencer_bedrock_actor::protocol::BridgeMoves::default(), }) .await .map_err(SendErrorExt::flatten)?, diff --git a/lez/sequencer/actors/executor/src/actor/tests.rs b/lez/sequencer/actors/executor/src/actor/tests.rs index 0d55953cf0..abee088726 100644 --- a/lez/sequencer/actors/executor/src/actor/tests.rs +++ b/lez/sequencer/actors/executor/src/actor/tests.rs @@ -35,7 +35,6 @@ use sequencer_stake_core::{SequencerEntry, SequencerKey}; use sequencer_storage_actor::{ StorageActorTrait, mock::{MockStorageActor, SharedStore}, - protocol::StoreUpdateOutcome, }; use sharding_pool_actor::{RestartConfig, ShardingPoolActor, protocol::Reset}; use tempfile::TempDir; @@ -301,7 +300,7 @@ fn prepare_mock_storage_with_stake( mock_storage .expect_handle_apply_store_update() - .returning(|_, _| Ok(StoreUpdateOutcome::default())); + .returning(|_, _| Ok(())); mock_storage .expect_handle_get_dead_letter_dispatches() @@ -347,7 +346,7 @@ pub(super) async fn executor_args( .expect("Failed to load or create channel signing key"); let slasher_ref = spawn_slasher(&config, &storage_ref, &channel_signing_key).await; - let channel_signer_ref = spawn_channel_signer(&config, &channel_signing_key); + let channel_signer_ref = spawn_channel_signer(&channel_signing_key); Args { config, @@ -395,14 +394,9 @@ async fn spawn_slasher( /// A channel-signing actor signing with `channel_signing_key`. fn spawn_channel_signer( - config: &SequencerConfig, channel_signing_key: &sequencer_bedrock_actor::protocol::Ed25519Key, ) -> ActorRef { - ChannelSigningActor::spawn(ChannelSigningActor::new( - channel_signing_key.clone(), - config.bedrock_config.channel_id, - sequencer_core::inscribed_block_deposits, - )) + ChannelSigningActor::spawn(ChannelSigningActor::new(channel_signing_key.clone())) } /// Initializes the executor state over `store`, against a Bedrock serving `channel`. @@ -418,7 +412,7 @@ pub(super) async fn initialize_state( let channel = channel.clone(); let storage_ref = MockStorageActor::spawn(store.mock()); let slasher_ref = spawn_slasher(&config, &storage_ref, &channel_signing_key).await; - let channel_signer_ref = spawn_channel_signer(&config, &channel_signing_key); + let channel_signer_ref = spawn_channel_signer(&channel_signing_key); Box::pin(State::initialize(Args { config, @@ -493,10 +487,7 @@ async fn a_publish_refused_as_stale_returns_its_transactions_to_the_mempool() -> let _res = logging::try_init(); let (config, _home, sequencer_key) = staked_sequencer_config(); - let mut mock_storage = prepare_mock_storage_with_stake(stake_entries(sequencer_key)); - mock_storage - .expect_handle_get_pending_deposit_events() - .returning(|_msg, _ctx| Ok(Vec::new())); + let mock_storage = prepare_mock_storage_with_stake(stake_entries(sequencer_key)); // The first publish loses the race; the second is served and its block // recorded, so the test can see what the retry carried. @@ -534,12 +525,11 @@ async fn a_publish_refused_as_stale_returns_its_transactions_to_the_mempool() -> pending_txs: Vec::new(), lib: HeaderId::from([0; 32]), lib_slot: Slot::from(0), - channel_notes: Vec::new(), finalized_config: MsgId::root(), funding: Vec::new(), + program_notes: None, }, seq: ChannelSeq::mocked(8), - released_notes: Vec::new(), }) }); mock_bedrock @@ -600,10 +590,7 @@ async fn a_publish_expects_the_sequence_the_publisher_started_at() -> Result<()> let _res = logging::try_init(); let (config, _home, sequencer_key) = staked_sequencer_config(); - let mut mock_storage = prepare_mock_storage_with_stake(stake_entries(sequencer_key)); - mock_storage - .expect_handle_get_pending_deposit_events() - .returning(|_msg, _ctx| Ok(Vec::new())); + let mock_storage = prepare_mock_storage_with_stake(stake_entries(sequencer_key)); let (expected_tx, mut expected_rx) = mpsc::unbounded_channel(); let executor = spawn_on_genesis( @@ -669,10 +656,7 @@ async fn spawn_supervised_on_genesis( ActorRef>, mpsc::UnboundedReceiver<()>, )> { - let mut mock_storage = prepare_mock_storage_with_empty_genesis(); - mock_storage - .expect_handle_get_pending_deposit_events() - .returning(|_msg, _ctx| Ok(Vec::new())); + let mock_storage = prepare_mock_storage_with_empty_genesis(); let storage_ref = MockStorageActor::spawn(mock_storage); let (publisher_init_tx, publisher_inits) = mpsc::unbounded_channel(); @@ -775,10 +759,7 @@ async fn a_failed_production_turn_does_not_stop_the_actor() -> Result<()> { let _res = logging::try_init(); let (config, _home) = sequencer_config(); - let mut mock_storage = prepare_mock_storage_with_empty_genesis(); - mock_storage - .expect_handle_get_pending_deposit_events() - .returning(|_msg, _ctx| Ok(Vec::new())); + let mock_storage = prepare_mock_storage_with_empty_genesis(); let storage_ref = MockStorageActor::spawn(mock_storage); let executor = spawn_on_genesis( diff --git a/lez/sequencer/actors/executor/src/actor/tests/reconstruction.rs b/lez/sequencer/actors/executor/src/actor/tests/reconstruction.rs index 213d971b98..30a7c930f0 100644 --- a/lez/sequencer/actors/executor/src/actor/tests/reconstruction.rs +++ b/lez/sequencer/actors/executor/src/actor/tests/reconstruction.rs @@ -1,10 +1,7 @@ //! Startup reconstruction: a starting executor replays the finalized channel //! history its store misses. -use std::{ - collections::{BTreeMap, BTreeSet}, - sync::Arc, -}; +use std::{collections::BTreeSet, sync::Arc}; use anyhow::Result; use chain_state::{ChainState, ChannelEntry, Tip}; @@ -15,10 +12,7 @@ use common::{ transaction::LeeTransaction, }; use kameo::actor::Spawn as _; -use lee::{ - AccountId, Actor, PublicTransaction, V03State, - public_transaction::{Message, WitnessSet}, -}; +use lee::{Actor, V03State}; use ping_core::{ReceiverMessage, ping_record_pda, receiver_config_account_id}; use sequencer_bedrock_actor::{ mock::{CannedChannel, mock_msg_of}, @@ -29,7 +23,7 @@ use sequencer_bedrock_actor::{ }; use sequencer_storage_actor::{ mock::{CannedStore, MockStorageActor, SharedStore}, - protocol::{PendingCrossZoneDispatchRecord, PendingDepositEventRecord, ZoneAnchorRecord}, + protocol::{PendingCrossZoneDispatchRecord, ZoneAnchorRecord}, }; use tokio::test; @@ -151,45 +145,6 @@ fn dispatch_tx(src_block_id: u64, payload: &[u8]) -> LeeTransaction { )) } -/// The mint a finalized L1 deposit event injects, as the sequencer builds it. -fn deposit_tx( - op_id: [u8; 32], - recipient: AccountId, - amount: bridge_core::BridgeAmount, -) -> LeeTransaction { - let bridge_program_id = programs::bridge_account_id(); - // The receipt PDA carries the exactly-once check, so the deposit is addressed to it. - let receipt = Actor::new( - bridge_core::deposit_receipt_account_id(bridge_program_id, op_id), - bridge_program_id, - ); - let message = Message { - admission_evidence: vec![lee::PublicAccountEvidence::Pda { - program: bridge_program_id, - seed: bridge_core::deposit_receipt_seed(op_id), - }], - ..Message::try_new( - receipt, - vec![ - receipt, - Actor::native_balance(system_accounts::bridge_account_id()), - Actor::native_balance(recipient), - ], - BTreeMap::new(), - bridge_core::Message::Deposit { - l1_deposit_op_id: op_id, - recipient_id: recipient, - amount, - }, - ) - .expect("deposit message builds") - }; - LeeTransaction::Public(PublicTransaction::new( - message, - WitnessSet::from_raw_parts(Vec::new()), - )) -} - /// Slashing exists because a sequencer can inscribe a non-block payload, and /// the channel keeps it forever. A replay that treated one as fatal would stop /// every later node from ever joining. @@ -660,122 +615,3 @@ async fn a_verified_own_block_settles_its_delivery_records() -> Result<()> { assert!(store.lock().pending_dispatches.is_empty()); Ok(()) } - -/// A deposit whose mint this node already holds final, re-recorded as its L1 event is read again -/// below the stored anchor. The channel serving the minting block back must settle the record, -/// as nothing later will ever mint it again. -#[test] -async fn a_verified_own_block_settles_its_deposit_records() -> Result<()> { - let recipient = testnet_initial_state::initial_public_user_accounts()[0].account_id; - let deposit_op_id = [0x1b_u8; 32]; - - let genesis = genesis(); - let block2 = produce_dummy_block( - 2, - Some(genesis.header.hash), - vec![deposit_tx(deposit_op_id, recipient, 400)], - ); - let store = CannedStore { - pending_deposits: vec![PendingDepositEventRecord { - deposit_op_id: HashType(deposit_op_id), - source_tx_hash: HashType([0; 32]), - amount: 400, - metadata: Vec::new(), - }], - ..with_finalized(finalized_genesis_store(), block2.clone()) - } - .share(); - - start( - &store, - vec![finalized_at(&genesis, 10), finalized_at(&block2, 20)], - ) - .await?; - - assert_eq!(store.lock().anchor, Some(anchor_at(&block2, 20))); - assert!(store.lock().pending_deposits.is_empty()); - Ok(()) -} - -/// A deposit whose L1 event was observed (a pending record exists) and whose L2 -/// mint is already contained in a finalized channel block. Reconstruction must -/// apply the mint exactly once and settle the pending record on the way through, -/// so the next production neither re-mints it nor re-injects it. -#[test] -async fn reconstruction_reconciles_already_finished_deposit() -> Result<()> { - let recipient = testnet_initial_state::initial_public_user_accounts()[0].account_id; - let funded = testnet_initial_state::initial_public_user_accounts()[0].balance; - let deposit_amount = 400_u64; - let deposit_op_id = [0x1a_u8; 32]; - let bridge_program_id = programs::bridge_account_id(); - let receipt_id = bridge_core::deposit_receipt_account_id(bridge_program_id, deposit_op_id); - - let genesis = genesis(); - let block2 = produce_dummy_block( - 2, - Some(genesis.header.hash), - vec![deposit_tx(deposit_op_id, recipient, deposit_amount)], - ); - let store = CannedStore { - pending_deposits: vec![PendingDepositEventRecord { - deposit_op_id: HashType(deposit_op_id), - source_tx_hash: HashType([0; 32]), - amount: deposit_amount, - metadata: Vec::new(), - }], - ..finalized_genesis_store() - } - .share(); - - start( - &store, - vec![finalized_at(&genesis, 10), finalized_at(&block2, 20)], - ) - .await?; - - // The mint lands once and the record its L1 event left behind is dropped. - assert_reconstructed(&store, &block2, 20); - let stored = store.lock(); - let head_state = stored - .head_state - .as_ref() - .expect("the head state is stored"); - assert_eq!( - head_state - .get_account_by_id(recipient) - .data - .native_balance() - .expect("the recipient holds a native balance"), - funded + u128::from(deposit_amount) - ); - assert!( - !head_state - .get_account_by_id(receipt_id) - .data - .actor_state(bridge_program_id) - .is_empty(), - "the bridge claimed the deposit receipt" - ); - assert!(stored.pending_deposits.is_empty()); - Ok(()) -} - -// TODO(withdrawals): the two cases below need bridge withdrawals, which panic -// today (`Withdraws are disabled in the current version of LEZ`), so neither the -// withdraw block nor the L1 event it awaits can be built. Reinstate them when -// withdrawals are enabled; the second also needs whatever replaces the -// unseen-withdraw counter, whose storage API no longer exists. -// -// /// A reconstructed deposit must not be re-minted after cold-start backfill -// /// re-delivers its event: the mint is permanently reflected in the -// /// reconstructed state (the receipt PDA), so the drain has nothing to re-emit. -// /// The withdraw block that follows it must likewise leave no phantom count. -// #[test] -// async fn reconstructed_deposit_is_not_reminted_after_backfill_redelivery() {} -// -// /// A reconstructed withdraw block must not touch the unseen-withdraw counter. -// /// Its finalized L1 Withdraw event was already re-delivered (and dropped as a -// /// no-op) by cold-start backfill, so counting it during reconstruction would -// /// leave a permanent phantom that nothing ever consumes. -// #[test] -// async fn reconstructed_withdraw_leaves_no_phantom_unseen_count() {} diff --git a/lez/sequencer/actors/executor/src/actor/tests/startup.rs b/lez/sequencer/actors/executor/src/actor/tests/startup.rs index 722206b429..7f098abf07 100644 --- a/lez/sequencer/actors/executor/src/actor/tests/startup.rs +++ b/lez/sequencer/actors/executor/src/actor/tests/startup.rs @@ -9,15 +9,11 @@ use kameo::{ error::HookError, }; use lee_core::BlockId; -use logos_blockchain_zone_sdk::core::{ - events::DepositRecreatedNotes, - mantle::{TxHash, ledger::Inputs, ops::channel::deposit::Metadata}, -}; use sequencer_bedrock_actor::{ mock::{CannedChannel, MockBedrockActor, SharedChannel, checkpoint_at, mock_msg_of}, protocol::{ - ChannelEntry, ChannelEvent, ChannelEventKind, ChannelSeq, ChannelUpdate, DepositInfo, - MsgId, PublisherEvent, Slot, ViewChange, + ChannelEntry, ChannelEvent, ChannelEventKind, ChannelSeq, ChannelUpdate, MsgId, + PublisherEvent, Slot, ViewChange, }, }; use sequencer_core::config::SequencerConfig; @@ -66,8 +62,6 @@ fn empty_channel_update() -> ChannelUpdate { seq: ChannelSeq::mocked(0), view: ViewChange::Extension(Vec::new()), finalized: Vec::new(), - deposits: Vec::new(), - withdrawals: Vec::new(), undecodable: Vec::new(), finalized_signers: Vec::new(), } @@ -84,19 +78,6 @@ fn entry(block: &Block, parent: &Block) -> ChannelEntry { } } -/// A finalized L1 deposit identified by `op_id`. -fn deposit(op_id: [u8; 32]) -> DepositInfo { - DepositInfo { - tx_hash: TxHash::from(op_id), - op_id, - channel_id: [0; 32].into(), - inputs: Inputs::empty(), - notes: DepositRecreatedNotes::default(), - amount: 5, - metadata: Metadata::new_unchecked(Vec::new()), - } -} - fn transfer(nonce: u128, amount: u128) -> LeeTransaction { common::test_utils::create_transaction_native_token_transfer( initial_public_user_accounts()[0].account_id, @@ -379,10 +360,9 @@ async fn the_channel_is_followed_from_the_stored_anchor() -> Result<()> { Ok(()) } -/// Bootstrapping records the deposits the channel replay carries, and hands the publisher the slot -/// it replayed up to, past which the publisher reports them instead. +/// Bootstrapping hands the publisher the slot it replayed up to. #[test] -async fn bootstrapping_records_replayed_deposits_up_to_the_publisher_handoff() -> Result<()> { +async fn bootstrapping_hands_the_publisher_the_slot_it_replayed_up_to() -> Result<()> { let (config, _home) = sequencer_config(); let channel_id = config.bedrock_config.channel_id; let genesis = genesis(); @@ -394,12 +374,7 @@ async fn bootstrapping_records_replayed_deposits_up_to_the_publisher_handoff() - .share(); let store = SharedStore::default(); let executor = start(&config, &store, &channel).await?; - let deposit_event = |op_id| ChannelEvent { - channel_id, - event: ChannelEventKind::FinalizedDeposit(Arc::new(deposit(op_id))), - }; - executor.ask(deposit_event([1; 32])).await?; executor .ask(ChannelEvent { channel_id, @@ -412,19 +387,6 @@ async fn bootstrapping_records_replayed_deposits_up_to_the_publisher_handoff() - ExecutorStatus::Online { .. } )); assert_eq!(channel.lock().replayed_up_to, Some(Slot::from(10))); - executor.ask(deposit_event([2; 32])).await?; - - let recorded: Vec<[u8; 32]> = store - .lock() - .pending_deposits - .iter() - .map(|record| record.deposit_op_id.0) - .collect(); - assert_eq!( - recorded, - [[1; 32]], - "the publisher reports what follows the handoff" - ); Ok(()) } diff --git a/lez/sequencer/actors/executor/src/actor/tests/stored_chain.rs b/lez/sequencer/actors/executor/src/actor/tests/stored_chain.rs index c8b91b19a2..e9e41e0199 100644 --- a/lez/sequencer/actors/executor/src/actor/tests/stored_chain.rs +++ b/lez/sequencer/actors/executor/src/actor/tests/stored_chain.rs @@ -169,9 +169,9 @@ pub(in crate::actor) fn checkpoint_record() -> ZoneCheckpointRecord { pending_txs: Vec::new(), lib: HeaderId::from([0; 32]), lib_slot: Slot::from(0), - channel_notes: Vec::new(), finalized_config: MsgId::root(), funding: Vec::new(), + program_notes: None, } .to_bytes() .expect("checkpoint serializes") diff --git a/lez/sequencer/actors/executor/src/error.rs b/lez/sequencer/actors/executor/src/error.rs index b5dcf5d5bd..6526f98fed 100644 --- a/lez/sequencer/actors/executor/src/error.rs +++ b/lez/sequencer/actors/executor/src/error.rs @@ -90,6 +90,9 @@ pub enum Error { #[error("Refused the system_upgrader approval: {0:#}")] SystemApprovalRefused(#[source] anyhow::Error), + #[error("Refused the program deposit: {0:#}")] + ProgramDepositRefused(#[source] anyhow::Error), + #[error("Incorrect fee")] IncorrectFee(#[source] anyhow::Error), diff --git a/lez/sequencer/actors/executor/src/mock.rs b/lez/sequencer/actors/executor/src/mock.rs index f3188dfa18..a86cb8a653 100644 --- a/lez/sequencer/actors/executor/src/mock.rs +++ b/lez/sequencer/actors/executor/src/mock.rs @@ -31,7 +31,7 @@ use crate::{ GetProofsAndRoot, GetProofsAndRootReply, GetPublications, GetPublicationsReply, GetRecoveryBinding, GetStatus, GetSystemProposals, GetSystemProposalsReply, GetTransaction, GetTransactionReceipt, ProduceBlock, RequeueCrossZoneDeadLetter, - RequeueCrossZoneDeadLetterReply, SubmitSystemApproval, Transaction, + RequeueCrossZoneDeadLetterReply, SubmitProgramDeposit, SubmitSystemApproval, Transaction, }, }; @@ -163,6 +163,12 @@ mockall::mock! { ctx: &mut Context> ) -> Result<()>; + pub fn handle_submit_program_deposit( + &mut self, + msg: SubmitProgramDeposit, + ctx: &mut Context> + ) -> Result<()>; + pub fn handle_get_fee_quote( &mut self, msg: GetFeeQuote, @@ -443,6 +449,18 @@ impl Message for MockExecutorActor { } } +impl Message for MockExecutorActor { + type Reply = Result<()>; + + async fn handle( + &mut self, + msg: SubmitProgramDeposit, + ctx: &mut Context, + ) -> Self::Reply { + self.handle_submit_program_deposit(msg, ctx) + } +} + impl Message for MockExecutorActor { type Reply = Result<()>; diff --git a/lez/sequencer/actors/executor/src/protocol.rs b/lez/sequencer/actors/executor/src/protocol.rs index 598d7ca8b6..7985b27e43 100644 --- a/lez/sequencer/actors/executor/src/protocol.rs +++ b/lez/sequencer/actors/executor/src/protocol.rs @@ -200,6 +200,12 @@ pub struct GetSystemProposalsReply { pub proposals: Vec, } +/// A program deposit its holder wants the vault to take in: the step, then its proof, in +/// Bedrock's encoding. +pub struct SubmitProgramDeposit { + pub deposit: Vec, +} + /// A committee member's approval of a `system_upgrader` change, for the producer's pool. pub struct SubmitSystemApproval { pub approval: system_upgrader_core::SignedApproval, diff --git a/lez/sequencer/actors/executor/src/trait.rs b/lez/sequencer/actors/executor/src/trait.rs index 18f6e31bad..0688a73426 100644 --- a/lez/sequencer/actors/executor/src/trait.rs +++ b/lez/sequencer/actors/executor/src/trait.rs @@ -20,7 +20,7 @@ use crate::{ GetProofsAndRoot, GetProofsAndRootReply, GetPublications, GetPublicationsReply, GetRecoveryBinding, GetStatus, GetSystemProposals, GetSystemProposalsReply, GetTransaction, GetTransactionReceipt, ProduceBlock, RequeueCrossZoneDeadLetter, - RequeueCrossZoneDeadLetterReply, SubmitSystemApproval, Transaction, + RequeueCrossZoneDeadLetterReply, SubmitProgramDeposit, SubmitSystemApproval, Transaction, }, }; @@ -48,5 +48,6 @@ pub trait ExecutorActorTrait: + Message> + Message> + Message> + + Message> { } diff --git a/lez/sequencer/actors/rpc_server/src/actor/service.rs b/lez/sequencer/actors/rpc_server/src/actor/service.rs index 9c062a783f..24fe154567 100644 --- a/lez/sequencer/actors/rpc_server/src/actor/service.rs +++ b/lez/sequencer/actors/rpc_server/src/actor/service.rs @@ -425,6 +425,13 @@ impl sequencer_service_rpc::RpcServer for Service { } Ok(()) } + + async fn submit_program_deposit(&self, deposit: HexBytes) -> Result<(), ErrorObjectOwned> { + self.executor_ref + .ask(sequencer_executor_actor::protocol::SubmitProgramDeposit { deposit: deposit.0 }) + .await + .map_err(map_executor_error) + } } #[expect(clippy::needless_pass_by_value, reason = "More convenient mapping")] @@ -449,7 +456,8 @@ fn map_executor_error( ) -> ErrorObjectOwned { match err { SendError::HandlerError(handle_err) => match handle_err { - refused @ sequencer_executor_actor::error::Error::SystemApprovalRefused(_) => { + refused @ (sequencer_executor_actor::error::Error::SystemApprovalRefused(_) + | sequencer_executor_actor::error::Error::ProgramDepositRefused(_)) => { ErrorObjectOwned::owned( ErrorCode::InvalidParams.code(), format!("{refused:#}"), diff --git a/lez/sequencer/actors/storage/src/actor.rs b/lez/sequencer/actors/storage/src/actor.rs index 749c97a3d6..f2a1945a07 100644 --- a/lez/sequencer/actors/storage/src/actor.rs +++ b/lez/sequencer/actors/storage/src/actor.rs @@ -1,8 +1,4 @@ -use std::{ - collections::{BTreeMap, HashSet}, - path::Path, - sync::Arc, -}; +use std::{collections::BTreeMap, path::Path, sync::Arc}; use borsh::BorshDeserialize as _; use common::{ @@ -35,14 +31,13 @@ use crate::{ GetCrossZonePeerTip, GetDeadLetterDispatchCount, GetDeadLetterDispatchRetainedCount, GetDeadLetterDispatches, GetEventFilter, GetFinalConfigsBytes, GetFinalSnapshot, GetFirstBlockId, GetLastBlockId, GetLatestBlockMeta, GetLeeState, - GetPendingCrossZoneDispatchCount, GetPendingCrossZoneDispatches, GetPendingDepositEvents, - GetSlashRecordBytes, GetSystemApprovalsBytes, GetTransactionByHash, - GetTransactionReceiptByHash, GetTxHashToBlockIdMapItem, GetZoneAnchor, GetZoneCheckpoint, - PendingCrossZoneDispatchRecord, PendingDepositEventRecord, PutFinalConfigsBytes, - PutSlashRecordBytes, PutSystemApprovalsBytes, RecordDispatchFailure, - RequeueDeadLetterDispatch, SetCrossZonePeerFloorBytes, SetCrossZonePeerTip, SetZoneAnchor, - StoreUpdateOutcome, UpdateZoneCheckpoint, WithdrawalReconciliationKey, ZoneAnchorRecord, - ZoneCheckpointRecord, + GetPendingCrossZoneDispatchCount, GetPendingCrossZoneDispatches, GetSlashRecordBytes, + GetSystemApprovalsBytes, GetTransactionByHash, GetTransactionReceiptByHash, + GetTxHashToBlockIdMapItem, GetZoneAnchor, GetZoneCheckpoint, + PendingCrossZoneDispatchRecord, PutFinalConfigsBytes, PutSlashRecordBytes, + PutSystemApprovalsBytes, RecordDispatchFailure, RequeueDeadLetterDispatch, + SetCrossZonePeerFloorBytes, SetCrossZonePeerTip, SetZoneAnchor, UpdateZoneCheckpoint, + ZoneAnchorRecord, ZoneCheckpointRecord, }, }; @@ -495,94 +490,6 @@ impl StorageActor { .map_err(Into::into) } - /// Records the deposits `new_deposit_events` observes and drops the records - /// of `finalized_deposit_records`, returning how many were newly recorded. - fn update_pending_deposits( - &self, - batch: &mut db::WriteBatch, - new_deposit_events: Vec, - finalized_deposit_records: &HashSet, - ) -> Result { - #[expect( - clippy::iter_over_hash_type, - reason = "HashSet is more efficient and delete order doesn't matter" - )] - for finalized_deposit in finalized_deposit_records { - self.db() - .delete_batch::(batch, finalized_deposit); - } - - let mut accepted_deposits_count = 0_usize; - for deposit in new_deposit_events - .into_iter() - .unique_by(|event| event.deposit_op_id) - .filter(|event| !finalized_deposit_records.contains(&event.deposit_op_id)) - { - if self - .db() - .get::(&deposit.deposit_op_id)? - .is_some() - { - continue; - } - - let deposit_op_id = deposit.deposit_op_id; - self.db().put_batch( - batch, - &deposit_op_id, - &entities::PendingDeposit::from(deposit), - )?; - accepted_deposits_count = accepted_deposits_count.saturating_add(1); - } - - Ok(accepted_deposits_count) - } - - /// Raises the intents `new_withdrawals` publishes and settles the ones - /// `consumed_withdrawals` reports, returning the reported withdrawals this - /// node holds no intent for. - fn update_pending_withdrawals( - &self, - batch: &mut db::WriteBatch, - new_withdrawals: HashSet, - consumed_withdrawals: &HashSet, - ) -> Result> { - let mut unmatched_withdrawals = Vec::new(); - - #[expect( - clippy::iter_over_hash_type, - reason = "HashSet is more efficient and delete order doesn't matter" - )] - for consumed in consumed_withdrawals { - let key = entities::WithdrawalReconciliationKey::from(*consumed); - let matched = new_withdrawals.contains(consumed) - || self - .db() - .get::(&key)? - .is_some(); - - if matched { - self.db() - .delete_batch::(batch, &key); - } else { - unmatched_withdrawals.push(*consumed); - } - } - - for new_withdrawal in new_withdrawals - .into_iter() - .filter(|withdrawal| !consumed_withdrawals.contains(withdrawal)) - { - self.db().put_batch( - batch, - &entities::WithdrawalReconciliationKey::from(new_withdrawal), - &entities::PendingWithdrawal, - )?; - } - - Ok(unmatched_withdrawals) - } - /// Drops the records of the deliveries `settled_dispatches` reports as /// settled for good. fn stage_settled_dispatches( @@ -1041,22 +948,6 @@ impl Message for StorageActor { } } -impl Message for StorageActor { - type Reply = Result>; - - async fn handle( - &mut self, - GetPendingDepositEvents: GetPendingDepositEvents, - _ctx: &mut Context, - ) -> Self::Reply { - self.db() - .iter::() - .map_ok(Into::into) - .collect::>() - .map_err(Into::into) - } -} - impl Message for StorageActor { type Reply = Result; @@ -1072,7 +963,7 @@ impl Message for StorageActor { } impl Message for StorageActor { - type Reply = Result; + type Reply = Result<()>; async fn handle( &mut self, @@ -1087,10 +978,6 @@ impl Message for StorageActor { head_state, final_snapshot, finalized_up_to, - new_deposit_events, - finalized_deposit_records, - consumed_withdrawals, - new_withdraw_intents, finalized_dispatch_records, zone_anchor, events, @@ -1124,20 +1011,6 @@ impl Message for StorageActor { // Blocks let updated_blocks = self.update_blocks(&mut batch, blocks, finalized_up_to, head_tip)?; - // Deposits - let accepted_deposits_count = self.update_pending_deposits( - &mut batch, - new_deposit_events, - &finalized_deposit_records, - )?; - - // Withdrawals - let unmatched_withdrawals = self.update_pending_withdrawals( - &mut batch, - new_withdraw_intents, - &consumed_withdrawals, - )?; - // Cross-zone dispatches self.stage_settled_dispatches(&mut batch, finalized_dispatch_records)?; @@ -1178,10 +1051,7 @@ impl Message for StorageActor { self.tx_index.delete_block(block_id); } - Ok(StoreUpdateOutcome { - accepted_deposits: accepted_deposits_count, - unmatched_withdrawals, - }) + Ok(()) } } diff --git a/lez/sequencer/actors/storage/src/actor/conversions.rs b/lez/sequencer/actors/storage/src/actor/conversions.rs index 4a4c05c57e..286dc5d8ca 100644 --- a/lez/sequencer/actors/storage/src/actor/conversions.rs +++ b/lez/sequencer/actors/storage/src/actor/conversions.rs @@ -76,41 +76,3 @@ impl From for protocol::ZoneAnchorRecord { } } } - -impl From for entities::PendingDeposit { - fn from(record: protocol::PendingDepositEventRecord) -> Self { - Self { - deposit_op_id: record.deposit_op_id, - source_tx_hash: record.source_tx_hash, - amount: record.amount, - metadata: record.metadata, - } - } -} - -impl From for protocol::PendingDepositEventRecord { - fn from(event: entities::PendingDeposit) -> Self { - Self { - deposit_op_id: event.deposit_op_id, - source_tx_hash: event.source_tx_hash, - amount: event.amount, - metadata: event.metadata, - } - } -} - -impl From for entities::WithdrawalReconciliationKey { - fn from(value: protocol::WithdrawalReconciliationKey) -> Self { - Self { - released_note_id: value.released_note_id, - } - } -} - -impl From for protocol::WithdrawalReconciliationKey { - fn from(value: entities::WithdrawalReconciliationKey) -> Self { - Self { - released_note_id: value.released_note_id, - } - } -} diff --git a/lez/sequencer/actors/storage/src/actor/entities.rs b/lez/sequencer/actors/storage/src/actor/entities.rs index 8f22de08ac..9eee169e46 100644 --- a/lez/sequencer/actors/storage/src/actor/entities.rs +++ b/lez/sequencer/actors/storage/src/actor/entities.rs @@ -195,48 +195,6 @@ impl db::Storable for ChannelView { const TYPE_NAME: &'static str = db::type_name!(ChannelView); } -/// An L1 deposit event observed but not yet seen finalized. -#[derive(BorshSerialize, BorshDeserialize)] -pub struct PendingDeposit { - pub deposit_op_id: HashType, - pub source_tx_hash: HashType, - pub amount: u64, - pub metadata: Vec, -} - -impl db::Storable for PendingDeposit { - type Key = HashType; - - const COLUMN_FAMILY: ColumnFamily = ColumnFamily::Pending; - const TYPE_NAME: &'static str = db::type_name!(PendingDeposit); -} - -/// Identity of one withdrawal: the id of the channel note it releases. -#[derive(Clone, Copy, PartialEq, Eq, Hash, BorshSerialize, BorshDeserialize)] -pub struct WithdrawalReconciliationKey { - pub released_note_id: [u8; 32], -} - -impl AsRef<[u8]> for WithdrawalReconciliationKey { - fn as_ref(&self) -> &[u8] { - &self.released_note_id - } -} - -/// An L2 withdraw intent this sequencer published, awaiting the Bedrock event -/// that reports it. -/// -/// Carries no value: the key is the whole fact, and presence is the intent. -#[derive(BorshSerialize, BorshDeserialize)] -pub struct PendingWithdrawal; - -impl db::Storable for PendingWithdrawal { - type Key = WithdrawalReconciliationKey; - - const COLUMN_FAMILY: ColumnFamily = ColumnFamily::Pending; - const TYPE_NAME: &'static str = db::type_name!(PendingWithdrawal); -} - /// A cross-zone delivery read off a peer block but not yet known to be /// irreversibly delivered. #[derive(BorshSerialize, BorshDeserialize)] diff --git a/lez/sequencer/actors/storage/src/actor/tests.rs b/lez/sequencer/actors/storage/src/actor/tests.rs index 846fa0e8ad..7ccfbfce33 100644 --- a/lez/sequencer/actors/storage/src/actor/tests.rs +++ b/lez/sequencer/actors/storage/src/actor/tests.rs @@ -25,11 +25,10 @@ use crate::{ GetCrossZonePeerFloorBytes, GetCrossZonePeerTip, GetDeadLetterDispatchCount, GetDeadLetterDispatchRetainedCount, GetDeadLetterDispatches, GetFinalSnapshot, GetFirstBlockId, GetLastBlockId, GetLatestBlockMeta, GetLeeState, - GetPendingCrossZoneDispatchCount, GetPendingCrossZoneDispatches, GetPendingDepositEvents, - GetTransactionByHash, GetTransactionReceiptByHash, GetZoneCheckpoint, - PendingCrossZoneDispatchRecord, PendingDepositEventRecord, RecordDispatchFailure, - RequeueDeadLetterDispatch, SetCrossZonePeerFloorBytes, SetCrossZonePeerTip, - UpdateZoneCheckpoint, WithdrawalReconciliationKey, ZoneCheckpointRecord, + GetPendingCrossZoneDispatchCount, GetPendingCrossZoneDispatches, GetTransactionByHash, + GetTransactionReceiptByHash, GetZoneCheckpoint, PendingCrossZoneDispatchRecord, + RecordDispatchFailure, RequeueDeadLetterDispatch, SetCrossZonePeerFloorBytes, + SetCrossZonePeerTip, UpdateZoneCheckpoint, ZoneCheckpointRecord, }, }; @@ -42,11 +41,7 @@ fn bookkeeping_update() -> AtomicUpdate { head_state: Arc::new(V03State::new()), final_snapshot: None, finalized_up_to: None, - new_deposit_events: Vec::new(), - finalized_deposit_records: HashSet::new(), finalized_dispatch_records: HashSet::new(), - consumed_withdrawals: HashSet::new(), - new_withdraw_intents: HashSet::new(), zone_anchor: None, events: Vec::new(), channel_view: None, @@ -70,21 +65,6 @@ async fn stored_checkpoint(storage_ref: &ActorRef) -> Option WithdrawalReconciliationKey { - WithdrawalReconciliationKey { - released_note_id: [byte; 32], - } -} - -fn deposit_record(byte: u8) -> PendingDepositEventRecord { - PendingDepositEventRecord { - deposit_op_id: HashType([byte; 32]), - source_tx_hash: HashType([byte; 32]), - amount: u64::from(byte), - metadata: Vec::new(), - } -} - /// An update pinning the head to `head_tip` and writing `blocks`, nothing else. /// /// `from_block` supplies the head tip and the empty rest; only `blocks` varies, @@ -669,160 +649,6 @@ async fn shrink_only_reorg_rewinds_the_tip() { ); } -/// The reconciliation is a set membership test, so an intent has to outlive the -/// update that raised it and every later update that touches the set. -#[tokio::test] -async fn withdraw_intents_survive_later_updates() { - let dir = tempfile::tempdir().expect("Failed to create temp dir"); - let storage_ref = spawn_with_blocks(dir.path(), vec![]).await; - - // Raised one at a time, as the produce path does: each update must leave the - // earlier intents alone. - for byte in 1..=3 { - storage_ref - .ask(AtomicUpdate { - new_withdraw_intents: HashSet::from([withdrawal_key(byte)]), - ..bookkeeping_update() - }) - .await - .expect("Failed to raise the intent"); - } - - let outcome = storage_ref - .ask(AtomicUpdate { - consumed_withdrawals: (1..=3).map(withdrawal_key).collect(), - ..bookkeeping_update() - }) - .await - .expect("Failed to reconcile the events"); - - assert!( - outcome.unmatched_withdrawals.is_empty(), - "Every reported note was published by this node, so none is unmatched" - ); -} - -/// The outcome reports the events this node cannot account for — never the -/// intents it is still waiting on. -#[tokio::test] -async fn withdraw_event_without_an_intent_is_reported_unmatched() { - let dir = tempfile::tempdir().expect("Failed to create temp dir"); - let storage_ref = spawn_with_blocks(dir.path(), vec![]).await; - - storage_ref - .ask(AtomicUpdate { - new_withdraw_intents: HashSet::from([withdrawal_key(1)]), - ..bookkeeping_update() - }) - .await - .expect("Failed to raise the intent"); - - // Note 2 was never published here; note 1 is still outstanding and must not - // be reported just because another event arrived. - let outcome = storage_ref - .ask(AtomicUpdate { - consumed_withdrawals: HashSet::from([withdrawal_key(2)]), - ..bookkeeping_update() - }) - .await - .expect("Failed to reconcile the event"); - - assert_eq!(outcome.unmatched_withdrawals, vec![withdrawal_key(2)]); -} - -/// A settled intent is gone for good, so a re-delivered event has nothing left -/// to match. -#[tokio::test] -async fn consumed_withdrawal_is_not_matched_twice() { - let dir = tempfile::tempdir().expect("Failed to create temp dir"); - let storage_ref = spawn_with_blocks(dir.path(), vec![]).await; - - storage_ref - .ask(AtomicUpdate { - new_withdraw_intents: HashSet::from([withdrawal_key(1)]), - ..bookkeeping_update() - }) - .await - .expect("Failed to raise the intent"); - let first = storage_ref - .ask(AtomicUpdate { - consumed_withdrawals: HashSet::from([withdrawal_key(1)]), - ..bookkeeping_update() - }) - .await - .expect("Failed to reconcile the event"); - assert!(first.unmatched_withdrawals.is_empty()); - - let second = storage_ref - .ask(AtomicUpdate { - consumed_withdrawals: HashSet::from([withdrawal_key(1)]), - ..bookkeeping_update() - }) - .await - .expect("Failed to reconcile the re-delivery"); - - assert_eq!(second.unmatched_withdrawals, vec![withdrawal_key(1)]); -} - -/// `accepted_deposits` is what the caller logs as newly owed mints, so a -/// re-delivery of an already-pending deposit must count for nothing. -#[tokio::test] -async fn only_newly_recorded_deposits_are_counted() { - let dir = tempfile::tempdir().expect("Failed to create temp dir"); - let storage_ref = spawn_with_blocks(dir.path(), vec![]).await; - - let first = storage_ref - .ask(AtomicUpdate { - new_deposit_events: vec![deposit_record(1), deposit_record(2)], - ..bookkeeping_update() - }) - .await - .expect("Failed to record the deposits"); - assert_eq!(first.accepted_deposits, 2); - - // One already pending, one new: only the new one is owed. - let second = storage_ref - .ask(AtomicUpdate { - new_deposit_events: vec![deposit_record(2), deposit_record(3)], - ..bookkeeping_update() - }) - .await - .expect("Failed to record the deposits"); - assert_eq!(second.accepted_deposits, 1); - - let pending = storage_ref - .ask(GetPendingDepositEvents) - .await - .expect("Failed to read the pending deposits"); - assert_eq!(pending.len(), 3); -} - -/// Backfill can deliver a deposit and its finalization in one event: the record -/// is owed nothing, and counting it would log a mint that never comes. -#[tokio::test] -async fn deposit_finalized_in_the_same_update_is_never_recorded() { - let dir = tempfile::tempdir().expect("Failed to create temp dir"); - let storage_ref = spawn_with_blocks(dir.path(), vec![]).await; - - let outcome = storage_ref - .ask(AtomicUpdate { - new_deposit_events: vec![deposit_record(1)], - finalized_deposit_records: HashSet::from([HashType([1; 32])]), - ..bookkeeping_update() - }) - .await - .expect("Failed to apply the update"); - - assert_eq!(outcome.accepted_deposits, 0); - assert!( - storage_ref - .ask(GetPendingDepositEvents) - .await - .expect("Failed to read the pending deposits") - .is_empty() - ); -} - /// The drain re-feeds every pending record, so a delivery that is irreversible /// has to lose its record or the transaction is re-included forever. #[tokio::test] @@ -1470,37 +1296,6 @@ async fn acc_id_to_tx_map_corectness() { ); } -/// A record goes by its own op id, never because some other deposit finalized. -#[tokio::test] -async fn only_the_finalized_deposit_record_is_dropped() { - let dir = tempfile::tempdir().expect("Failed to create temp dir"); - let storage_ref = spawn_with_blocks(dir.path(), vec![]).await; - - storage_ref - .ask(AtomicUpdate { - new_deposit_events: vec![deposit_record(1), deposit_record(2)], - ..bookkeeping_update() - }) - .await - .expect("Failed to record the deposits"); - - storage_ref - .ask(AtomicUpdate { - finalized_deposit_records: HashSet::from([HashType([1; 32])]), - ..bookkeeping_update() - }) - .await - .expect("Failed to settle the deposit"); - - assert_eq!( - storage_ref - .ask(GetPendingDepositEvents) - .await - .expect("Failed to read the pending deposits"), - vec![deposit_record(2)] - ); -} - /// The floor and the tip of one peer are keyed by the same zone id and differ /// only in what they are, so a write of either must leave the other alone: a /// shared key would let one peer's chain decide which blocks another peer's diff --git a/lez/sequencer/actors/storage/src/mock.rs b/lez/sequencer/actors/storage/src/mock.rs index faa71461a2..647efda2d6 100644 --- a/lez/sequencer/actors/storage/src/mock.rs +++ b/lez/sequencer/actors/storage/src/mock.rs @@ -28,13 +28,12 @@ use crate::{ GetCrossZonePeerTip, GetDeadLetterDispatchCount, GetDeadLetterDispatchRetainedCount, GetDeadLetterDispatches, GetEventFilter, GetFinalConfigsBytes, GetFinalSnapshot, GetFirstBlockId, GetLastBlockId, GetLatestBlockMeta, GetLeeState, - GetPendingCrossZoneDispatchCount, GetPendingCrossZoneDispatches, GetPendingDepositEvents, - GetSlashRecordBytes, GetSystemApprovalsBytes, GetTransactionByHash, - GetTransactionReceiptByHash, GetZoneAnchor, GetZoneCheckpoint, - PendingCrossZoneDispatchRecord, PendingDepositEventRecord, PutFinalConfigsBytes, + GetPendingCrossZoneDispatchCount, GetPendingCrossZoneDispatches, GetSlashRecordBytes, + GetSystemApprovalsBytes, GetTransactionByHash, GetTransactionReceiptByHash, GetZoneAnchor, + GetZoneCheckpoint, PendingCrossZoneDispatchRecord, PutFinalConfigsBytes, PutSlashRecordBytes, PutSystemApprovalsBytes, RecordDispatchFailure, RequeueDeadLetterDispatch, SetCrossZonePeerFloorBytes, SetCrossZonePeerTip, SetZoneAnchor, - StoreUpdateOutcome, UpdateZoneCheckpoint, ZoneAnchorRecord, ZoneCheckpointRecord, + UpdateZoneCheckpoint, ZoneAnchorRecord, ZoneCheckpointRecord, }, }; @@ -168,17 +167,11 @@ mockall::mock! { ctx: &mut Context>>> ) -> Result>>; - pub fn handle_get_pending_deposit_events( - &mut self, - msg: GetPendingDepositEvents, - ctx: &mut Context>> - ) -> Result>; - pub fn handle_apply_store_update( &mut self, msg: AtomicUpdate, - ctx: &mut Context> - ) -> Result; + ctx: &mut Context> + ) -> Result<()>; pub fn handle_get_final_snapshot( &mut self, @@ -574,18 +567,6 @@ impl Message for MockStorageActor { } } -impl Message for MockStorageActor { - type Reply = Result>; - - async fn handle( - &mut self, - msg: GetPendingDepositEvents, - ctx: &mut Context, - ) -> Self::Reply { - self.handle_get_pending_deposit_events(msg, ctx) - } -} - impl Message for MockStorageActor { type Reply = Result; @@ -595,7 +576,7 @@ impl Message for MockStorageActor { } impl Message for MockStorageActor { - type Reply = Result; + type Reply = Result<()>; async fn handle( &mut self, diff --git a/lez/sequencer/actors/storage/src/mock/canned_store.rs b/lez/sequencer/actors/storage/src/mock/canned_store.rs index 067c94202c..7e9a63f7ed 100644 --- a/lez/sequencer/actors/storage/src/mock/canned_store.rs +++ b/lez/sequencer/actors/storage/src/mock/canned_store.rs @@ -12,8 +12,8 @@ use lee_core::BlockId; use super::MockStorageActor; use crate::protocol::{ AtomicUpdate, DropSettledCrossZoneDispatches, GetBlock, PendingCrossZoneDispatchRecord, - PendingDepositEventRecord, PutSlashRecordBytes, PutSystemApprovalsBytes, SetZoneAnchor, - StoreUpdateOutcome, UpdateZoneCheckpoint, ZoneAnchorRecord, ZoneCheckpointRecord, + PutSlashRecordBytes, PutSystemApprovalsBytes, SetZoneAnchor, UpdateZoneCheckpoint, + ZoneAnchorRecord, ZoneCheckpointRecord, }; /// What a mocked store holds. @@ -28,7 +28,6 @@ pub struct CannedStore { pub checkpoint: Option, /// Serialized unfinalized channel view. pub channel_view: Option>, - pub pending_deposits: Vec, pub pending_dispatches: Vec, pub slash_record: Option>, pub system_approvals: Option>, @@ -59,16 +58,6 @@ impl CannedStore { if let Some(view) = update.channel_view { self.channel_view = Some(view); } - for record in update.new_deposit_events { - if !self.pending_deposits.contains(&record) { - self.pending_deposits.push(record); - } - } - self.pending_deposits.retain(|record| { - !update - .finalized_deposit_records - .contains(&record.deposit_op_id) - }); self.pending_dispatches.retain(|record| { !update .finalized_dispatch_records @@ -162,13 +151,9 @@ impl SharedStore { let store = self.clone(); move |update, _ctx| { store.lock().apply(update); - Ok(StoreUpdateOutcome::default()) + Ok(()) } }); - mock.expect_handle_get_pending_deposit_events().returning({ - let store = self.clone(); - move |_msg, _ctx| Ok(store.lock().pending_deposits.clone()) - }); mock.expect_handle_get_pending_cross_zone_dispatches() .returning({ let store = self.clone(); diff --git a/lez/sequencer/actors/storage/src/protocol.rs b/lez/sequencer/actors/storage/src/protocol.rs index 8b2b609562..48315e63f5 100644 --- a/lez/sequencer/actors/storage/src/protocol.rs +++ b/lez/sequencer/actors/storage/src/protocol.rs @@ -93,8 +93,6 @@ pub struct SetZoneAnchor { /// The serialized unfinalized channel view. pub struct GetChannelViewBytes; -pub struct GetPendingDepositEvents; - pub struct GetFinalSnapshot; pub struct GetPendingCrossZoneDispatches; @@ -217,15 +215,6 @@ pub struct AtomicUpdate { /// it become finalized. pub finalized_up_to: Option, - /// Deposit events observed on L1, recorded unless already pending. - pub new_deposit_events: Vec, - /// Deposit op ids whose mint finalized: their pending records are dropped. - pub finalized_deposit_records: HashSet, - /// L1 withdraw events to reconcile against the intents held locally. - pub consumed_withdrawals: HashSet, - /// L2 withdraw intents this update raises, awaiting their L1 event. - pub new_withdraw_intents: HashSet, - /// Message keys whose delivery finalized: their pending records are dropped. pub finalized_dispatch_records: HashSet, @@ -254,26 +243,13 @@ impl AtomicUpdate { head_state: state, final_snapshot: None, finalized_up_to: None, - new_deposit_events: Vec::new(), - finalized_deposit_records: HashSet::new(), finalized_dispatch_records: HashSet::new(), - consumed_withdrawals: HashSet::new(), - new_withdraw_intents: HashSet::new(), zone_anchor: None, events, } } } -/// Identity of one withdrawal: the id of the channel note it releases. -/// -/// Shared by the intent recorded when the sequencer publishes a withdrawal and -/// the Bedrock event that later reports it. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct WithdrawalReconciliationKey { - pub released_note_id: [u8; 32], -} - /// The last channel block read back and verified from Bedrock: the anchor for /// the startup consistency check and the resume point for reconstruction. /// @@ -286,18 +262,6 @@ pub struct ZoneAnchorRecord { pub hash: HashType, } -/// An L1 deposit event observed but not yet seen finalized. -/// -/// Purely a liveness queue: whether to emit a mint is decided against chain -/// state, and the record is dropped once its mint finalizes. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PendingDepositEventRecord { - pub deposit_op_id: HashType, - pub source_tx_hash: HashType, - pub amount: u64, - pub metadata: Vec, -} - /// A cross-zone delivery read off a peer block but not yet known to be /// irreversibly delivered. /// @@ -385,18 +349,6 @@ pub enum DispatchFailure { Absent, } -/// What [`ApplyStoreUpdate`] observed while staging, for the caller to act on -/// *after* the write committed. -#[derive(Debug, Default)] -pub struct StoreUpdateOutcome { - /// How many deposit events were newly recorded; the rest were already - /// pending, and so already owed. - pub accepted_deposits: usize, - /// The `consumed_withdrawals` this node holds no intent for: a released - /// note it never published, and so cannot account for. - pub unmatched_withdrawals: Vec, -} - /// Schema-agnostic snapshot of a whole store, opaque by design. pub struct DbDump { pub bytes: Vec, diff --git a/lez/sequencer/actors/storage/src/trait.rs b/lez/sequencer/actors/storage/src/trait.rs index f6ca8ee7c0..7c74e352b7 100644 --- a/lez/sequencer/actors/storage/src/trait.rs +++ b/lez/sequencer/actors/storage/src/trait.rs @@ -17,18 +17,18 @@ use crate::{ GetDeadLetterDispatchCount, GetDeadLetterDispatchRetainedCount, GetDeadLetterDispatches, GetFinalConfigsBytes, GetFinalSnapshot, GetFirstBlockId, GetLastBlockId, GetLatestBlockMeta, GetLeeState, GetPendingCrossZoneDispatchCount, - GetPendingCrossZoneDispatches, GetPendingDepositEvents, GetSlashRecordBytes, - GetSystemApprovalsBytes, GetTransactionByHash, GetTransactionReceiptByHash, GetZoneAnchor, - GetZoneCheckpoint, PendingCrossZoneDispatchRecord, PendingDepositEventRecord, - PutFinalConfigsBytes, PutSlashRecordBytes, PutSystemApprovalsBytes, RecordDispatchFailure, - RequeueDeadLetterDispatch, SetCrossZonePeerFloorBytes, SetCrossZonePeerTip, SetZoneAnchor, - StoreUpdateOutcome, UpdateZoneCheckpoint, ZoneAnchorRecord, ZoneCheckpointRecord, + GetPendingCrossZoneDispatches, GetSlashRecordBytes, GetSystemApprovalsBytes, + GetTransactionByHash, GetTransactionReceiptByHash, GetZoneAnchor, GetZoneCheckpoint, + PendingCrossZoneDispatchRecord, PutFinalConfigsBytes, PutSlashRecordBytes, + PutSystemApprovalsBytes, RecordDispatchFailure, RequeueDeadLetterDispatch, + SetCrossZonePeerFloorBytes, SetCrossZonePeerTip, SetZoneAnchor, UpdateZoneCheckpoint, + ZoneAnchorRecord, ZoneCheckpointRecord, }, }; pub trait StorageActorTrait: Actor - + Message> + + Message> + Message>> + Message>> + Message>> @@ -51,7 +51,6 @@ pub trait StorageActorTrait: + Message>> + Message> + Message>>> - + Message>> + Message>> + Message> + Message> diff --git a/lez/sequencer/core/Cargo.toml b/lez/sequencer/core/Cargo.toml index f746743a69..f19525d1da 100644 --- a/lez/sequencer/core/Cargo.toml +++ b/lez/sequencer/core/Cargo.toml @@ -14,7 +14,6 @@ chain_state.workspace = true common.workspace = true sequencer_core_metrics = { workspace = true, features = ["record"] } sequencer_channel_signing_actor.workspace = true -sequencer_bridge.workspace = true sequencer_genesis.workspace = true sequencer_slasher_actor.workspace = true sequencer_storage_actor.workspace = true @@ -47,7 +46,6 @@ rand.workspace = true borsh.workspace = true hex.workspace = true url.workspace = true -num-bigint.workspace = true futures.workspace = true libp2p.workspace = true thiserror.workspace = true @@ -58,6 +56,7 @@ default = [] prove = ["lee/prove", "chain_state/prove"] [dev-dependencies] +sequencer_bridge.workspace = true chain_state = { workspace = true, features = ["test-utils"] } cross_zone = { workspace = true, features = ["test-utils"] } sequencer_storage_actor = { workspace = true, features = ["actor", "mock"] } diff --git a/lez/sequencer/core/src/committee_discovery.rs b/lez/sequencer/core/src/committee_discovery.rs index 3de0a7f0d1..5769ec97bd 100644 --- a/lez/sequencer/core/src/committee_discovery.rs +++ b/lez/sequencer/core/src/committee_discovery.rs @@ -10,7 +10,6 @@ use tracing::warn; pub struct LiveChannel<'keys> { pub accredited_keys: &'keys [SequencerKey], pub configuration_threshold: u16, - pub transfer_threshold: u16, pub posting_timeframe: u32, pub posting_timeout: u32, } @@ -85,10 +84,9 @@ pub fn committee_update( let mut live_keys = live.accredited_keys.to_vec(); live_keys.sort_unstable(); - // A mismatch in either threshold or either posting param triggers a channel update too. - let threshold = channel_config_threshold(desired.len()).get(); + // A mismatch in the threshold or either posting param triggers a channel update too. let stale_threshold = - live.configuration_threshold != threshold || live.transfer_threshold != threshold; + live.configuration_threshold != channel_config_threshold(desired.len()).get(); let stale_posting = live.posting_timeframe != params.posting_timeframe || live.posting_timeout != params.posting_timeout; @@ -189,11 +187,10 @@ mod tests { } /// A live channel at the default posting params. - fn live(keys: &[SequencerKey], configuration: u16, transfer: u16) -> LiveChannel<'_> { + fn live(keys: &[SequencerKey], configuration: u16) -> LiveChannel<'_> { LiveChannel { accredited_keys: keys, configuration_threshold: configuration, - transfer_threshold: transfer, posting_timeframe: system_accounts::DEFAULT_SEQUENCER_POSTING_TIMEFRAME, posting_timeout: system_accounts::DEFAULT_SEQUENCER_POSTING_TIMEOUT, } @@ -285,7 +282,7 @@ mod tests { fn candidate_below_minimum_is_not_accredited() { let staked = Staked::new(1, MINIMUM - 1); - assert!(committee_update(&state_with([staked]), &live(&[], 1, 1)).is_none()); + assert!(committee_update(&state_with([staked]), &live(&[], 1)).is_none()); } #[test] @@ -293,7 +290,7 @@ mod tests { let staked = Staked::new(2, MINIMUM); assert_eq!( - committee_update(&state_with([staked]), &live(&[], 1, 1)), + committee_update(&state_with([staked]), &live(&[], 1)), Some(vec![staked.key]) ); } @@ -302,7 +299,7 @@ mod tests { fn already_matching_live_committee_is_not_re_submitted() { let staked = Staked::new(3, MINIMUM); - assert!(committee_update(&state_with([staked]), &live(&[staked.key], 1, 1)).is_none()); + assert!(committee_update(&state_with([staked]), &live(&[staked.key], 1)).is_none()); } #[test] @@ -316,26 +313,10 @@ mod tests { keys.sort_unstable(); assert_eq!( - committee_update(&state_with(committee), &live(&keys, 1, 2)), - Some(keys.to_vec()) - ); - assert!(committee_update(&state_with(committee), &live(&keys, 2, 2)).is_none()); - } - - #[test] - fn matching_keys_at_a_stale_transfer_threshold_are_re_submitted() { - let committee = [ - Staked::new(1, MINIMUM), - Staked::new(2, MINIMUM), - Staked::new(3, MINIMUM), - ]; - let mut keys = committee.map(|staked| staked.key); - keys.sort_unstable(); - - assert_eq!( - committee_update(&state_with(committee), &live(&keys, 2, 1)), + committee_update(&state_with(committee), &live(&keys, 1)), Some(keys.to_vec()) ); + assert!(committee_update(&state_with(committee), &live(&keys, 2)).is_none()); } #[test] @@ -346,7 +327,7 @@ mod tests { assert_eq!( committee_update( &state_with([exiting, staying]), - &live(&[exiting.key, staying.key], 1, 1) + &live(&[exiting.key, staying.key], 1) ), Some(vec![staying.key]) ); @@ -360,7 +341,7 @@ mod tests { assert_eq!( committee_update( &state_with([discounted, staying]), - &live(&[discounted.key, staying.key], 1, 1), + &live(&[discounted.key, staying.key], 1), ), Some(vec![staying.key]) ); @@ -371,7 +352,7 @@ mod tests { let exiting = Staked::new(4, MINIMUM).pending(MINIMUM); assert_eq!( - committee_update(&state_with([exiting]), &live(&[exiting.key], 1, 1)), + committee_update(&state_with([exiting]), &live(&[exiting.key], 1)), None ); } @@ -387,10 +368,10 @@ mod tests { keys.sort_unstable(); let state = state_with(committee); - assert!(committee_update(&state, &live(&keys, 2, 2)).is_none()); + assert!(committee_update(&state, &live(&keys, 2)).is_none()); let stale_timeframe = LiveChannel { posting_timeframe: system_accounts::DEFAULT_SEQUENCER_POSTING_TIMEFRAME + 1, - ..live(&keys, 2, 2) + ..live(&keys, 2) }; assert_eq!( committee_update(&state, &stale_timeframe), @@ -398,7 +379,7 @@ mod tests { ); let stale_timeout = LiveChannel { posting_timeout: system_accounts::DEFAULT_SEQUENCER_POSTING_TIMEOUT + 1, - ..live(&keys, 2, 2) + ..live(&keys, 2) }; assert_eq!( committee_update(&state, &stale_timeout), @@ -412,8 +393,8 @@ mod tests { // asked for once and forgotten. let state = state_with([Staked::new(8, MINIMUM)]); - assert!(committee_update(&state, &live(&[], 1, 1)).is_some()); - assert!(committee_update(&state, &live(&[], 1, 1)).is_some()); + assert!(committee_update(&state, &live(&[], 1)).is_some()); + assert!(committee_update(&state, &live(&[], 1)).is_some()); } #[test] @@ -422,7 +403,7 @@ mod tests { let low = Staked::new(1, MINIMUM); assert_eq!( - committee_update(&state_with([high, low]), &live(&[], 1, 1)), + committee_update(&state_with([high, low]), &live(&[], 1)), Some(vec![low.key, high.key]) ); } diff --git a/lez/sequencer/core/src/cross_zone_watcher.rs b/lez/sequencer/core/src/cross_zone_watcher.rs index 86a63a4273..1160c918d1 100644 --- a/lez/sequencer/core/src/cross_zone_watcher.rs +++ b/lez/sequencer/core/src/cross_zone_watcher.rs @@ -926,6 +926,7 @@ mod tests { id: MsgId::from([0; 32]), data: Inscription::new_unchecked(data), signer: UnverifiedEd25519PublicKey::from_bytes(&[0; 32]).expect("valid key"), + steps: logos_blockchain_zone_sdk::InscriptionSteps::default(), }), Slot::from(slot), ) diff --git a/lez/sequencer/core/src/lib.rs b/lez/sequencer/core/src/lib.rs index d3c15d079e..4f5b9911b5 100644 --- a/lez/sequencer/core/src/lib.rs +++ b/lez/sequencer/core/src/lib.rs @@ -8,8 +8,6 @@ use std::{ }; use anyhow::{Context as _, Result, anyhow}; -use borsh::BorshDeserialize as _; -use bridge_core::DepositMetadata; use chain_state::{AcceptOutcome, ChainState, ChannelEntry, PublishRecord, full_stake_releases}; use common::{ HashType, @@ -28,22 +26,16 @@ use logos_blockchain_zone_sdk::{ Slot, binary_codec::bincode::{DeserializeOp as _, SerializeOp as _}, key_management_system_service::keys::{ED25519_SECRET_KEY_SIZE, ZkPublicKey}, - sequencer::{DepositInfo, SequencerCheckpoint, WithdrawArg, WithdrawInfo}, + sequencer::SequencerCheckpoint, }; pub use logos_blockchain_zone_sdk::{ - core::mantle::{NoteId, ops::channel::MsgId}, - key_management_system_service::keys::Ed25519PublicKey, + core::mantle::ops::channel::MsgId, key_management_system_service::keys::Ed25519PublicKey, }; use mempool::MemPool; -use num_bigint::BigUint; use sequencer_bedrock_actor::{ BedrockActorTrait, - protocol::{ - ChannelId, Ed25519Key, GetChannelNotes, IndexedSignature, LiveChannelConfig, PreparedPin, - PublishOutcome, ViewChange, - }, + protocol::{ChannelId, Ed25519Key, LiveChannelConfig, PublishOutcome, ViewChange}, }; -use sequencer_bridge::Credited; use sequencer_channel_signing_actor::{ChannelSigningActor, protocol as channel_signing}; use sequencer_slasher_actor::{ SlasherActor, @@ -55,10 +47,9 @@ use sequencer_storage_actor::{ AtomicUpdate, CrossZoneMessageKey, DeadLetterDispatch, DeadLetterRequeue, DispatchFailure, DispatchOrigin, DropSettledCrossZoneDispatches, GetAllBlocks, GetDeadLetterDispatchCount, GetDeadLetterDispatchRetainedCount, GetDeadLetterDispatches, GetLeeState, - GetPendingCrossZoneDispatches, GetPendingDepositEvents, GetSystemApprovalsBytes, - GetZoneCheckpoint, PendingCrossZoneDispatchRecord, PendingDepositEventRecord, - RecordDispatchFailure, RequeueDeadLetterDispatch, StoreUpdateOutcome, - WithdrawalReconciliationKey, ZoneCheckpointRecord, + GetPendingCrossZoneDispatches, GetSystemApprovalsBytes, GetZoneCheckpoint, + PendingCrossZoneDispatchRecord, RecordDispatchFailure, RequeueDeadLetterDispatch, + ZoneCheckpointRecord, }, }; use sharding_pool_actor::ShardingPoolActor; @@ -195,19 +186,19 @@ pub struct SequencerCore { watchers: TaskGroup, /// Signs this node's approval of a slash. channel_signing_key: Ed25519Key, - /// Collects the accredited signatures a channel config update or a pin needs. + /// Collects the accredited signatures a channel config update needs. channel_signer: ActorRef, /// The config draft zone-sdk last funded for us, submitted once its /// signatures are in. config_draft: Option, + /// Deposits admitted to the vault and not minted yet, each with the bytes its holder + /// submitted. Lost on a restart: a holder whose deposit never landed submits it again. + pending_deposits: VecDeque<(Vec, chain_state::vault::VaultMint)>, finalized_config: MsgId, /// Channel sequence of the last thing `BedrockActor` handed us. applied_seq: Option, /// Committee approvals of `system_upgrader` changes, until a threshold builds one. system_approvals: system_approvals::SystemApprovals, - /// Deposits seen on L1 but not yet final, minted in a block pinned on - /// their notes. In memory only: after a restart they mint once final. - observed_deposits: Vec, /// The update last published to the gossip mesh. stake_config: StakeConfigUpdate, @@ -225,6 +216,8 @@ pub struct SequencerCore { /// disposable. struct ConfigDraft { prepared: sequencer_bedrock_actor::protocol::PreparedConfig, + /// Production turns it has waited for its signatures. + turns_unsigned: u8, /// Submitted once; zone-sdk re-posts it from there on. submitted: bool, /// Channel slot the submission went out at, which starts the clock on @@ -236,6 +229,11 @@ impl SequencerCore { /// Channel slots a submitted config gets to land before this node funds /// another; a margin over observed Bedrock confirmation lag. const CONFIG_LANDING_DEADLINE: SlotCount = 30; + /// Production turns a draft gets to collect its signatures. Funding one takes the node a + /// proof, which can leave the peers less than a turn to answer. + const CONFIG_SIGNING_TURNS: u8 = 3; + /// Admitted deposits held for a block at once. + const MAX_PENDING_DEPOSITS: usize = 64; #[expect( clippy::too_many_arguments, @@ -312,12 +310,12 @@ impl SequencerCore { watchers, channel_signer, config_draft: None, + pending_deposits: VecDeque::new(), finalized_config, applied_seq, channel_signing_key, sequencer_config: config, system_approvals, - observed_deposits: Vec::new(), }; sequencer_core_metrics::record_mempool_max_size( sequencer.sequencer_config.mempool_max_size, @@ -345,8 +343,6 @@ impl SequencerCore { seq, view, finalized, - deposits, - withdrawals, undecodable, finalized_signers, } = &update; @@ -382,29 +378,11 @@ impl SequencerCore { }; self.applied_seq = Some(*seq); - // NOTE: Theoretically Zone SDK may re-deliver an already seen deposit or - // finalization. Both are idempotent here: a deposit already on record is - // not re-appended, and a finalization only ever moves the tier forward. - let deposit_records: Vec = - deposits.iter().map(pending_deposit_event_record).collect(); - // A final deposit is minted from its store record from here on. - self.observed_deposits.retain(|observed_deposit| { - deposits - .iter() - .all(|deposit| deposit.op_id != observed_deposit.op_id) - }); - - // A set, because a released note identifies its withdrawal outright: the - // chain releases a note once, so a repeat here is a re-delivery, not a - // second withdrawal. - let consumed_withdrawals: HashSet = - withdrawals.iter().flat_map(released_note_keys).collect(); - let own_key = self.channel_signing_key.public_key(); // The lock is held across the persist below so disk writes land in apply // order — the produce path persists under this same lock. - let (resubmit_txs, outcome, head_height, settled_deliveries) = { + let (resubmit_txs, head_height, settled_deliveries) = { let mut chain = self.chain.lock().await; let head_before: Vec = chain.head_blocks().cloned().collect(); @@ -515,19 +493,7 @@ impl SequencerCore { // stored blocks there can be marked finalized. let last_finalized = irreversible.iter().map(|block| block.header.block_id).max(); - // A deposit observed in a finalized block is permanently minted (its - // receipt is now in the irreversible tier), so its pending record can be - // dropped. Keyed by op id, not block id: a record only goes once its own - // deposit finalizes, never because some other block finalized at its - // height. - let finalized_deposit_ids: HashSet = irreversible - .iter() - .flat_map(|block| block.body.transactions.iter()) - .filter_map(extract_bridge_deposit_id) - .collect(); - self.tell_final_mints(&finalized_deposit_ids).await; - - // The same for cross-zone deliveries, keyed by message key: a record + // A cross-zone delivery's record is keyed by message key: it // goes once its own delivery is irreversible, never because another // block finalized at its height. let mut finalized_dispatch_keys = HashSet::new(); @@ -537,17 +503,13 @@ impl SequencerCore { } let settled_deliveries = !finalized_dispatch_keys.is_empty(); - let outcome = self - .storage_ref + self.storage_ref .ask(AtomicUpdate { checkpoint: Some(checkpoint_record), blocks: to_persist, final_snapshot: final_meta.map(|meta| (chain.share_final_state(), meta)), finalized_up_to: last_finalized, - new_deposit_events: deposit_records, - finalized_deposit_records: finalized_deposit_ids, finalized_dispatch_records: finalized_dispatch_keys, - consumed_withdrawals, events, ..chain_update(&chain) }) @@ -556,7 +518,7 @@ impl SequencerCore { panic!("Failed to persist follow update: {:#}", anyhow!(err)) }); - (resubmit_txs, outcome, head_tip_id, settled_deliveries) + (resubmit_txs, head_tip_id, settled_deliveries) }; sequencer_core_metrics::record_chain_height(head_height); @@ -568,9 +530,6 @@ impl SequencerCore { record_pending_dispatch_gauge(&self.storage_ref).await; } - log_recorded_deposits(&outcome); - log_unmatched_withdrawals(&outcome); - self.resubmit_orphaned(resubmit_txs); self.finalized_config = checkpoint.finalized_config; @@ -604,111 +563,6 @@ impl SequencerCore { } } - /// Holds deposits seen before finality, for production to mint pinned and - /// for peers' pins to be checked against. - pub async fn on_observed_deposits(&mut self, deposits: &[DepositInfo]) { - let observed = channel_signing::ObservedDeposits( - deposits - .iter() - .map(|deposit| channel_signing::ObservedDeposit { - op_id: deposit.op_id, - notes: deposit.notes.to_vec(), - }) - .collect(), - ); - if let Err(err) = self.channel_signer.tell(observed).await { - warn!( - error = format_args!("{:#}", anyhow!(err)), - "Failed to tell the channel-signing actor of observed deposits" - ); - } - for deposit in deposits { - if self - .observed_deposits - .iter() - .all(|observed_deposit| observed_deposit.op_id != deposit.op_id) - { - self.observed_deposits.push(deposit.clone()); - } - } - } - - /// Tells the channel-signing actor which deposits final blocks mint, so it - /// stops holding their notes. - async fn tell_final_mints(&self, op_ids: &HashSet) { - if op_ids.is_empty() { - return; - } - let final_mints = channel_signing::FinalMints(op_ids.iter().map(|op_id| op_id.0).collect()); - if let Err(err) = self.channel_signer.tell(final_mints).await { - warn!( - error = format_args!("{:#}", anyhow!(err)), - "Failed to tell the channel-signing actor of final mints" - ); - } - } - - /// Mints for the observed deposits that are unminted on `state`, not yet - /// recorded as final, and have every note on the current L1 branch, each - /// with the notes its block must pin. Forgets the unminted ones with a note - /// off the branch, which can no longer be pinned. - async fn pinnable_deposits( - &mut self, - state: &lee::V03State, - recorded_op_ids: &HashSet, - ) -> Vec<(LeeTransaction, Vec)> { - if self.observed_deposits.is_empty() { - return Vec::new(); - } - let channel_notes = match self - .bedrock_pool_ref - .ask(GetChannelNotes { - channel_id: self.channel_id, - }) - .await - { - Ok(notes) => notes, - Err(err) => { - warn!( - error = format_args!("{:#}", anyhow!(err)), - "Pinning no deposits this turn" - ); - return Vec::new(); - } - }; - self.observed_deposits.retain(|deposit| { - deposit_already_minted(state, HashType(deposit.op_id)) - || deposit - .notes - .iter() - .all(|note| channel_notes.contains(¬e.note_id)) - }); - - self.observed_deposits - .iter() - .filter(|deposit| { - let op_id = HashType(deposit.op_id); - !recorded_op_ids.contains(&op_id) && !deposit_already_minted(state, op_id) - }) - .filter_map(|deposit| { - let notes: Vec = deposit.notes.iter().map(|note| note.note_id).collect(); - if notes.is_empty() || !notes.iter().all(|note| channel_notes.contains(note)) { - return None; - } - build_bridge_deposit_tx_from_event(&pending_deposit_event_record(deposit)) - .map_err(|err| { - warn!( - deposit = %hex::encode(deposit.op_id), - error = format_args!("{:#}", anyhow!(err)), - "Skipping observed deposit due to tx build failure" - ); - }) - .ok() - .map(|tx| (tx, notes)) - }) - .collect() - } - /// Hands the channel-signing actor the live channel and the config it should /// have. Sent from the follow path, turn or not: a peer only signs a draft /// matching the config it derived for itself. @@ -721,7 +575,6 @@ impl SequencerCore { let view = channel_signing::ChannelView { live_keys: live.keys.clone(), required_signatures: live.required_signatures, - transfer_signatures: live.transfer_threshold, target, }; if let Err(err) = self.channel_signer.tell(view).await { @@ -732,68 +585,63 @@ impl SequencerCore { } } + /// Admits a program deposit its holder submitted, the step and then its proof in Bedrock's + /// encoding, to be minted by a block whose inscription has the vault take it in. + pub async fn admit_deposit(&mut self, deposit: Vec) -> Result<()> { + let mint = self + .bedrock_pool_ref + .ask(sequencer_bedrock_actor::protocol::AdmitDeposit { + channel_id: self.channel_id, + deposit: deposit.clone(), + }) + .await + .map_err(|err| anyhow!(err)) + .context("The vault does not admit the deposit")?; + anyhow::ensure!( + self.pending_deposits.len() < Self::MAX_PENDING_DEPOSITS, + "Too many deposits are waiting for a block" + ); + anyhow::ensure!( + self.pending_deposits + .iter() + .all(|(_, held)| held.id != mint.id), + "The deposit is already waiting for a block" + ); + anyhow::ensure!( + !self + .with_state(|state| deposit_already_minted(state, mint.id)) + .await, + "The deposit is already minted" + ); + info!(deposit = %hex::encode(mint.id), amount = mint.amount, "Admitted a vault deposit"); + self.pending_deposits.push_back((deposit, mint)); + Ok(()) + } + /// Runs everything this sequencer owes its turn: builds a block from /// mempool transactions, publishes it via zone-sdk, and submits any /// committee-config update the new state calls for. pub async fn run_production_turn(&mut self) -> Result { - // A draft short of signatures is dropped here, before its fee-note + // A draft still short of signatures is dropped here, before its fee-note // reservation lapses and the block below spends that note. - if self - .config_draft - .as_ref() - .is_some_and(|draft| !draft.submitted) - { - warn!("A channel-config draft is still unsigned, funding another"); - self.discard_config_draft().await; + if let Some(draft) = self.config_draft.as_mut().filter(|draft| !draft.submitted) { + draft.turns_unsigned = draft.turns_unsigned.saturating_add(1); + if draft.turns_unsigned >= Self::CONFIG_SIGNING_TURNS { + warn!("A channel-config draft is still unsigned, funding another"); + self.discard_config_draft().await; + } } - let mut built = self + let built = self .build_block_from_mempool() .await .context("Failed to build block from mempool transactions")?; - let publish_res = if built.pinned_deposit_notes.is_empty() { - self.publish_block(&built).await - } else { - let pinned = match self.sign_pin(&built).await { - Ok(Some((prepared, signatures))) => self - .bedrock_pool_ref - .ask(sequencer_bedrock_actor::protocol::PublishPin { - channel_id: self.channel_id, - prepared, - signatures, - expected_seq: self.applied_seq, - }) - .await - .map(Some) - .map_err(|err| err.flatten().map_msg(|_| ())), - Ok(None) => Ok(None), - Err(err) => Err(err), - }; - match pinned { - Ok(Some(outcome)) => Ok(outcome), - Err( - err @ kameo::error::SendError::HandlerError( - sequencer_bedrock_actor::error::Error::ChannelMoved { .. }, - ), - ) => Err(err), - // Any other failed pin goes out unpinned, its deposits left to finality. - pinned => { - if let Err(err) = pinned { - warn!( - block_id = built.block.header.block_id, - error = format_args!("{:#}", anyhow!(err)), - "Failed to pin block" - ); - } - built = self.build_block_without_pins(built).await?; - self.publish_block(&built).await - } - } - }; + let publish_res = self.publish_block(&built).await; let BlockWithMeta { block, mempool_transactions, + deposits, .. } = built; @@ -803,6 +651,19 @@ impl SequencerCore { self.mempool.push_front((origin, tx)); } } + // Minted, or refused by the vault or by Bedrock, which a later turn would not change. + // Any other failure leaves them for the next turn. + if matches!( + &publish_res, + Ok(_) + | Err(kameo::error::SendError::HandlerError( + sequencer_bedrock_actor::error::Error::InvalidVaultDeposit(_) + | sequencer_bedrock_actor::error::Error::InvalidVaultStep(_) + | sequencer_bedrock_actor::error::Error::VaultStepRefused(_) + )) + ) { + self.forget_deposits(deposits.iter().map(|(_, id)| *id)); + } let outcome = match publish_res { Ok(outcome) => outcome, Err(kameo::error::SendError::HandlerError( @@ -825,10 +686,15 @@ impl SequencerCore { Ok(block_id) } - /// Publishes `built` chained on its pin, unless it carries withdrawals. + fn forget_deposits(&mut self, ids: impl IntoIterator) { + for id in ids { + self.pending_deposits.retain(|(_, mint)| mint.id != id); + } + } + + /// Publishes `built` chained on its pin. async fn publish_block(&self, built: &BlockWithMeta) -> Result { // Height and pin together: both come from the view, read under one lock. - // Bundled withdrawals take the unpinned path, where the sdk picks the parent. info!( block_id = built.block.header.block_id, pin = %built.parent, @@ -839,113 +705,21 @@ impl SequencerCore { .ask(sequencer_bedrock_actor::protocol::PublishBlock { channel_id: self.channel_id, block: built.block.clone(), - withdrawals: built.withdrawals.clone(), - parent: built.withdrawals.is_empty().then_some(built.parent), + parent: Some(built.parent), expected_seq: self.applied_seq, + bridge: sequencer_bedrock_actor::protocol::BridgeMoves { + deposits: built + .deposits + .iter() + .map(|(deposit, _)| deposit.clone()) + .collect(), + payouts: Vec::new(), + }, }) .await .map_err(|err| err.flatten().map_msg(|_| ())) } - /// Funds the pin of `built` and collects the signatures its transfer needs, - /// or `None` when it cannot be pinned or they are not all in within half a - /// block interval. - async fn sign_pin( - &self, - built: &BlockWithMeta, - ) -> Result)>, PublishError> { - let block_id = built.block.header.block_id; - // A pin publishes on an explicit parent, which cannot carry withdrawals. - if !built.withdrawals.is_empty() { - error!( - block_id, - "Block pins deposits but carries withdrawals, not pinning it" - ); - return Ok(None); - } - info!( - block_id, - deposit_notes = built.pinned_deposit_notes.len(), - pin = %built.parent, - "Pinning block on deposit notes" - ); - let prepared = self - .bedrock_pool_ref - .ask(sequencer_bedrock_actor::protocol::PreparePin { - channel_id: self.channel_id, - block: built.block.clone(), - parent: built.parent, - notes: built.pinned_deposit_notes.clone(), - expected_seq: self.applied_seq, - }) - .await - .map_err(|err| err.flatten().map_msg(|_| ()))?; - - // Half an interval, so a pin that misses delays its block by half an interval, not a - // whole one. - let wait = self - .sequencer_config - .block_create_timeout - .checked_div(2) - .expect("the divisor is not zero"); - match self - .channel_signer - .ask(channel_signing::SignPin(Box::new(prepared.tx().clone()))) - .reply_timeout(wait) - .await - { - Ok(signatures) => Ok(signatures.map(|signatures| (prepared, signatures))), - Err(kameo::error::SendError::Timeout(_)) => { - warn!( - block_id, - ?wait, - "Pin signatures took too long, rebuilding the block without its pinned \ - deposits, which mint once final" - ); - Ok(None) - } - Err(err) => { - warn!( - block_id, - error = format_args!("{:#}", anyhow!(err)), - "Failed to collect the pin signatures of block" - ); - Ok(None) - } - } - } - - /// Leaves the deposits `built` pinned to finality and builds the block - /// again with no observed deposit in it, so nothing in it needs a pin. - async fn build_block_without_pins(&mut self, built: BlockWithMeta) -> Result { - let BlockWithMeta { - block, - mempool_transactions, - pinned_deposit_notes, - .. - } = built; - warn!( - block_id = block.header.block_id, - "Block goes out without its pin, its deposits mint once final" - ); - self.observed_deposits.retain(|deposit| { - deposit - .notes - .iter() - .all(|note| !pinned_deposit_notes.contains(¬e.note_id)) - }); - // Nothing was inscribed, so the block's transactions go back in front. - for (origin, tx) in mempool_transactions.into_iter().rev() { - self.mempool.push_front((origin, tx)); - } - - let observed_deposits = std::mem::take(&mut self.observed_deposits); - let rebuilt = self.build_block_from_mempool().await; - self.observed_deposits = observed_deposits; - - rebuilt.context("Failed to build block from mempool transactions") - } - /// Whether the channel has advanced far enough past `submitted_at` to call /// a submitted config lost. A missing tip or submission slot counts as no /// advance. @@ -993,7 +767,6 @@ impl SequencerCore { posting_timeframe: target.posting_timeframe, posting_timeout: target.posting_timeout, configuration_threshold: target.configuration_threshold, - transfer_threshold: target.transfer_threshold, }) .await { @@ -1014,6 +787,7 @@ impl SequencerCore { }; self.config_draft = Some(ConfigDraft { prepared, + turns_unsigned: 0, submitted: false, submitted_at: None, }); @@ -1145,7 +919,6 @@ impl SequencerCore { parent, checkpoint, seq, - released_notes, } = outcome; let checkpoint_record = ZoneCheckpointRecord { bytes: checkpoint_bytes(&checkpoint)?, @@ -1177,10 +950,6 @@ impl SequencerCore { } else { Vec::new() }, - new_withdraw_intents: released_notes - .iter() - .map(withdrawal_reconciliation_key) - .collect(), ..chain_update(&chain) }) .await?; @@ -1218,7 +987,6 @@ impl SequencerCore { tx: &LeeTransaction, block_height: u64, timestamp: u64, - withdrawals: &mut Vec, opening: &fee_core::state::FeeState, tx_index: u64, summary: &mut fee_core::BlockFeeSummary, @@ -1229,7 +997,7 @@ impl SequencerCore { // Gossiped transactions arrive from untrusted peers, same as // user-submitted ones, so they get the same full state validation. TransactionOrigin::User | TransactionOrigin::Gossip => { - // Only the sequencer mints deposits, from their L1 events. + // A deposit is minted from the vault's intake, never from the mempool. if extract_bridge_deposit_id(tx).is_some() { if matches!(origin, TransactionOrigin::Gossip) { debug!(%tx_hash, "Dropping gossiped bridge deposit"); @@ -1266,11 +1034,13 @@ impl SequencerCore { tx_index, &mut scratch_summary, ) { - Ok((_events, tx_receipt)) => { - if tx_receipt.success - && let Some(withdraw_data) = extract_bridge_withdraw_data(tx) - { - withdrawals.push(withdraw_data); + Ok((events, tx_receipt)) => { + // FIXME: interim. The sequencer cannot pay a withdrawal out on L1 + // yet, so every one is refused. Once it builds the vault's program + // step, check the withdrawal against what the vault holds instead. + if bridge_withdrawals(&events).next().is_some() { + warn!(%tx_hash, "Dropping bridge withdrawal: payouts are not supported yet"); + return None; } *state = scratch; *summary = scratch_summary; @@ -1304,17 +1074,10 @@ impl SequencerCore { panic!("Sequencer may only generate Public transactions, found {tx:#?}"); }; - // Bridge deposits are deduped by their receipt PDA in chain - // state (drained only when unminted, refused on replay), so no - // node-local guard is needed here. - // - // Skip-and-log rather than propagate: a drained deposit is - // re-fed from the store every turn and only finality removes it, - // so a `?` here would let a single unexecutable mint (e.g. a - // bridge escrow under-funded relative to the L1 deposit, which - // every sequencer hits identically) abort production on all of - // them forever. Skipping keeps the record queued for retry - // without halting the node. + // Skip-and-log rather than propagate: a record drained from the + // store is re-fed every turn, so a `?` here would let a single + // unexecutable one, which every sequencer hits identically, abort + // production on all of them forever. if let Err(err) = state.transition_from_public_transaction(public_tx, block_height, timestamp) { @@ -1472,7 +1235,6 @@ impl SequencerCore { let mut valid_transactions = Vec::new(); let mut receipts = Vec::new(); - let mut withdrawals = Vec::new(); let releasable_keys = release_finality::producible_releases( &self.bedrock_pool_ref, self.channel_id, @@ -1481,50 +1243,6 @@ impl SequencerCore { .await; let finalize_unstake_txs = build_finalize_unstake_txs(&working_state, &releasable_keys); - // Bridge deposit mints are drained from the store, not the mempool: the - // follow path records the event durably but cannot enqueue the mint - // itself. Draining here also subsumes the old - // startup replay. - // - // Skip deposits whose receipt has a nonempty bridge actor state. - // Reverting a block also reverts its receipts, allowing those deposits to be retried. - let deposit_records = self - .storage_ref - .ask(GetPendingDepositEvents) - .await - .context("Failed to load pending deposit events")?; - let recorded_op_ids: HashSet = deposit_records - .iter() - .map(|record| record.deposit_op_id) - .collect(); - let mut pending_deposits: VecDeque = deposit_records - .into_iter() - .filter(|record| !deposit_already_minted(&working_state, record.deposit_op_id)) - .filter_map(|record| { - build_bridge_deposit_tx_from_event(&record) - .map_err(|err| { - warn!( - deposit = %hex::encode(record.deposit_op_id), - error = format_args!("{:#}", anyhow!(err)), - "Skipping pending deposit event due to tx build failure" - ); - }) - .ok() - }) - .collect(); - - // A deposit not yet final mints only in a block pinned on its notes. - let mut pins: HashMap> = HashMap::new(); - for (tx, notes) in self - .pinnable_deposits(&working_state, &recorded_op_ids) - .await - { - pins.insert(tx.hash(), notes); - pending_deposits.push_back(tx); - } - let mut pinned_deposit_notes = Vec::new(); - let mut deferred_withdrawals = Vec::new(); - let max_block_size = usize::try_from( committee_discovery::channel_params(&working_state) .context("The chain holds no channel params")? @@ -1581,10 +1299,17 @@ impl SequencerCore { // `system_upgrader` changes in the mempool, returned by a reorg, wait for the one slot // before the fee. let mut upgrade_candidates = Vec::new(); - let mut pending_from_store = pending_deposits; - pending_from_store.extend(pending_dispatches); + let mut pending_from_store = pending_dispatches; pending_from_store.extend(slash_txs); pending_from_store.extend(finalize_unstake_txs); + // As many deposits as one vault step takes in, oldest first. + let mints: Vec<_> = self + .pending_deposits + .iter() + .take(chain_state::vault::MAX_DEPOSITS) + .filter_map(|(deposit, mint)| Some((deposit.clone(), mint.id, mint.transaction()?))) + .collect(); + pending_from_store.extend(mints.iter().map(|(_, _, tx)| tx.clone())); while let Some((origin, tx, from_store)) = pending_from_store .pop_front() .map(|tx| (TransactionOrigin::Sequencer, tx, true)) @@ -1597,22 +1322,6 @@ impl SequencerCore { continue; } - // A deposit whose notes would take the pin past Bedrock's input limit waits for the - // next block. - if pins.get(&tx_hash).is_some_and(|notes| { - pinned_deposit_notes.len().saturating_add(notes.len()) - > logos_blockchain_zone_sdk::core::mantle::ledger::MAX_TRANSACTION_INPUTS - }) { - continue; - } - - // A block pinning deposits publishes on an explicit parent, which - // cannot carry withdrawals. - if !pinned_deposit_notes.is_empty() && extract_bridge_withdraw_data(&tx).is_some() { - deferred_withdrawals.push((origin, tx)); - continue; - } - let temp_valid_transactions = [ valid_transactions.as_slice(), std::slice::from_ref(&tx), @@ -1735,7 +1444,6 @@ impl SequencerCore { full_stake_releases::stake_entries(&working_state), working_state.clone(), summary, - withdrawals.len(), ) }); let applied = Self::apply_mempool_transaction( @@ -1744,14 +1452,12 @@ impl SequencerCore { &tx, new_block_height, new_block_timestamp, - &mut withdrawals, &opening, valid_transactions.len().try_into().expect("fits u64"), &mut summary, ); if applied.is_some() - && let Some((stake_entries_before, state, summary_before, withdrawal_count)) = - snapshot + && let Some((stake_entries_before, state, summary_before)) = snapshot { let stake_entries_after = full_stake_releases::stake_entries(&working_state); let released = @@ -1769,7 +1475,6 @@ impl SequencerCore { ); working_state = state; summary = summary_before; - withdrawals.truncate(withdrawal_count); continue; } } @@ -1786,9 +1491,6 @@ impl SequencerCore { if !from_store { mempool_transactions.push((origin, tx.clone())); } - if let Some(notes) = pins.remove(&tx_hash) { - pinned_deposit_notes.extend(notes); - } valid_transactions.push(tx); } else { sequencer_core_metrics::increment_mempool_failed_transactions_total(); @@ -1808,9 +1510,6 @@ impl SequencerCore { break; } } - for (origin, tx) in deferred_withdrawals.into_iter().rev() { - self.mempool.push_front((origin, tx)); - } // At most one `system_upgrader` transaction, directly before the fee: the due `Apply` // first, then changes a threshold of collected approvals carries, then approved changes a @@ -1867,7 +1566,6 @@ impl SequencerCore { &tx, new_block_height, new_block_timestamp, - &mut withdrawals, &opening, valid_transactions.len().try_into().expect("fits u64"), &mut summary, @@ -1941,12 +1639,24 @@ impl SequencerCore { sequencer_core_metrics::record_block_creation_time(now.elapsed()); + // A deposit left out was refused by the bridge, or found the block full: its holder + // still holds the notes and may submit it again. + let (minted, refused): (Vec<_>, Vec<_>) = mints + .into_iter() + .partition(|(_, _, tx)| block.body.transactions.contains(tx)); + for (_, id, _) in &refused { + warn!(deposit = %hex::encode(id), "Dropping a vault deposit the block left out"); + } + self.forget_deposits(refused.iter().map(|(_, id, _)| *id)); + Ok(BlockWithMeta { block, - withdrawals, parent, mempool_transactions, - pinned_deposit_notes, + deposits: minted + .into_iter() + .map(|(deposit, id, _)| (deposit, id)) + .collect(), }) } @@ -2263,17 +1973,16 @@ impl SequencerCore { struct BlockWithMeta { block: Block, - withdrawals: Vec, /// The pin this block was built on, read under the same lock as its height. parent: MsgId, /// The transactions this block took from the mempool, in the order it took /// them. mempool_transactions: Vec<(TransactionOrigin, LeeTransaction)>, - /// Notes of the not-yet-final deposits this block mints, to pin on publish. - pinned_deposit_notes: Vec, + /// The vault deposits this block mints, in its order, each with its id. + deposits: Vec<(Vec, [u8; 32])>, } -/// Why a publish, pinned or not, did not go out. +/// Why a publish did not go out. type PublishError = kameo::error::SendError<(), sequencer_bedrock_actor::error::Error>; /// A turn given up because the channel moved under the block while it was @@ -2312,17 +2021,6 @@ fn checkpoint_bytes(checkpoint: &SequencerCheckpoint) -> Result> { .context("Failed to serialize zone-sdk checkpoint") } -/// Whether `deposit_op_id`'s mint is already reflected in `state` — the bridge -/// owns its receipt PDA. The receipt is the exactly-once ledger the bridge -/// program keeps. -fn deposit_already_minted(state: &lee::V03State, deposit_op_id: HashType) -> bool { - let bridge_program_id = programs::bridge_account_id(); - let receipt_id = bridge_core::deposit_receipt_account_id(bridge_program_id, deposit_op_id.0); - state - .get_account_by_id_ref(receipt_id) - .is_some_and(|receipt| !receipt.data.actor_state(bridge_program_id).is_empty()) -} - /// Whether a cross-zone delivery is already on the chain we are building on. /// /// The inbox records each peer block's delivered indices in that block's seen @@ -2418,7 +2116,6 @@ fn config_target( &committee_discovery::LiveChannel { accredited_keys: &live_keys, configuration_threshold: live.required_signatures, - transfer_threshold: live.transfer_threshold, posting_timeframe: live.posting_timeframe, posting_timeout: live.posting_timeout, }, @@ -2439,7 +2136,6 @@ fn config_target( // The op carries the threshold the *next* config must clear, so it is // measured against the committee this op installs. configuration_threshold: committee_discovery::channel_config_threshold(keys.len()), - transfer_threshold: committee_discovery::channel_config_threshold(keys.len()), keys, parent: live.config_tip, posting_timeframe: channel_params.posting_timeframe, @@ -2468,10 +2164,6 @@ pub fn chain_update(chain: &ChainState) -> AtomicUpdate { head_state: chain.share_head_state(), final_snapshot: None, finalized_up_to: None, - new_deposit_events: Vec::new(), - finalized_deposit_records: HashSet::new(), - consumed_withdrawals: HashSet::new(), - new_withdraw_intents: HashSet::new(), finalized_dispatch_records: HashSet::new(), zone_anchor: None, events: Vec::new(), @@ -2492,64 +2184,6 @@ pub fn max_transaction_size(state: &lee::V03State) -> Option { .map(|params| params.max_block_size.saturating_sub(config::BLOCK_OVERHEAD)) } -/// Logs the deposits a store update recorded. -pub fn log_recorded_deposits(outcome: &StoreUpdateOutcome) { - if outcome.accepted_deposits > 0 { - info!( - deposits = outcome.accepted_deposits, - "Recorded Bedrock Deposit events, their mints are drained from the store on our next turn" - ); - } -} - -/// Logs the withdrawals a store update found no local intent for. -pub fn log_unmatched_withdrawals(outcome: &StoreUpdateOutcome) { - for withdrawal in &outcome.unmatched_withdrawals { - warn!( - note_id = %hex::encode(withdrawal.released_note_id), - "Unexpected Bedrock Withdraw event releasing a channel note this node published no withdrawal for" - ); - } -} - -/// The reconciliation keys of the channel notes `withdrawal` releases. -pub fn released_note_keys( - withdrawal: &WithdrawInfo, -) -> impl Iterator + '_ { - withdrawal - .op - .inputs - .iter() - .map(withdrawal_reconciliation_key) -} - -/// The pending record `deposit` leaves until its mint finalizes. -#[must_use] -pub fn pending_deposit_event_record(deposit: &DepositInfo) -> PendingDepositEventRecord { - PendingDepositEventRecord { - deposit_op_id: HashType(deposit.op_id), - source_tx_hash: HashType(deposit.tx_hash.0), - amount: deposit.amount, - metadata: deposit.metadata.clone().into(), - } -} - -fn build_bridge_deposit_tx_from_event(event: &PendingDepositEventRecord) -> Result { - let metadata = DepositMetadata::try_from_slice(&event.metadata) - .context("Failed to decode finalized Bedrock deposit metadata")?; - - // The receipt PDA carries the exactly-once check: the deposit is addressed to it, - // and its own actor state detects a replay. - Ok(LeeTransaction::Public( - sequencer_bridge::deposit_tx( - event.deposit_op_id.0, - &Credited::Public(metadata.recipient.evidence()), - event.amount, - ) - .context("Failed to build bridge deposit message")?, - )) -} - /// The `Apply` of the upgrade that activates in block `block_id`, if any. fn build_due_apply_tx( state: &lee::V03State, @@ -2676,8 +2310,8 @@ fn build_finalize_unstake_tx( } /// User transactions of an orphaned block to return to the mempool: everything -/// except the trailing clock tx, sequencer-generated bridge deposits (replayed -/// from their own bedrock events) and sequencer-only txs — cross-zone dispatches +/// except the trailing clock tx, bridge deposits (only genesis mints them) and +/// sequencer-only txs — cross-zone dispatches /// (replayed by the watcher), the fee tx (regenerated every block; the ingress /// guard rejects them as `User`) and `system_upgrader`'s `Apply` (rebuilt from /// the registry). An approved `system_upgrader` change can't be rebuilt, so it @@ -2804,21 +2438,6 @@ fn classify_settled_deliveries( (keys, forged) } -/// The deposits a block inscription mints, or `None` when it is not a block. -pub fn inscribed_block_deposits(inscription: &[u8]) -> Option> { - let block = borsh::from_slice::(inscription).ok()?; - - Some( - block - .body - .transactions - .iter() - .filter_map(extract_bridge_deposit_id) - .map(|op_id| op_id.0) - .collect(), - ) -} - #[must_use] pub fn extract_bridge_deposit_id(tx: &LeeTransaction) -> Option { let (to, message) = tx.public_call()?; @@ -2834,45 +2453,26 @@ pub fn extract_bridge_deposit_id(tx: &LeeTransaction) -> Option { } } -#[must_use] -fn extract_bridge_withdraw_data(tx: &LeeTransaction) -> Option { - let (to, message) = tx.public_call()?; - if to.program_account_id != programs::bridge_account_id() { - return None; - } - - let bridge_core::Message::Withdraw { - amount, - bedrock_account_pk, - } = borsh::from_slice::(message).ok()? - else { - return None; - }; - - let recipient_pk = ZkPublicKey::from(BigUint::from_bytes_le(&bedrock_account_pk)); - - Some(WithdrawArg { - outputs: logos_blockchain_zone_sdk::core::mantle::ledger::Outputs::new( - logos_blockchain_zone_sdk::core::mantle::Note::new(amount, recipient_pk), - ), - }) +/// Whether the bridge holds the receipt of deposit `id`, which it writes when it mints one. +fn deposit_already_minted(state: &lee::V03State, id: [u8; 32]) -> bool { + let bridge_program_id = programs::bridge_account_id(); + let receipt_id = bridge_core::deposit_receipt_account_id(bridge_program_id, id); + state + .get_account_by_id_ref(receipt_id) + .is_some_and(|receipt| !receipt.data.actor_state(bridge_program_id).is_empty()) } -/// The reconciliation identity of one released channel note. -/// -/// A `ChannelWithdrawOp` releases notes the channel already owns and carries -/// only their ids — the recipient key and value live in the note itself, which -/// neither the op nor the Bedrock Withdraw event reports. The note id is -/// therefore the one handle both sides share, and it is unique: a note is spent -/// once. -fn withdrawal_reconciliation_key(note_id: &NoteId) -> WithdrawalReconciliationKey { - let released_note_id: [u8; 32] = note_id - .as_bytes() - .as_ref() - .try_into() - .expect("`NoteId` is a 32-byte field element"); - - WithdrawalReconciliationKey { released_note_id } +/// The bridge withdrawals among `events`, each a payout the vault owes on L1. +pub fn bridge_withdrawals( + events: &[lee_core::program::TransactionEvent], +) -> impl Iterator { + events + .iter() + .filter(|emitted| { + emitted.account_id == programs::bridge_account_id() + && emitted.event.selector == bridge_core::event::Withdraw::SELECTOR + }) + .filter_map(|emitted| bridge_core::event::Withdraw::from_bytes(&emitted.event.data).ok()) } /// Parses a Bedrock wallet public key from hex. diff --git a/lez/sequencer/core/src/tests.rs b/lez/sequencer/core/src/tests.rs index 35d03d471d..c3b8e42f5d 100644 --- a/lez/sequencer/core/src/tests.rs +++ b/lez/sequencer/core/src/tests.rs @@ -7,7 +7,7 @@ use std::{ time::Duration, }; -use bridge_core::{DepositMetadata, DepositRecipient}; +use bridge_core::DepositRecipient; use chain_state::{ChainState, ChannelEntry}; use common::{ HashType, @@ -25,25 +25,8 @@ use lee::{ use lee_core::{GENESIS_BLOCK_ID, account::Nonce}; use logos_blockchain_zone_sdk::{ Slot, - core::{ - events::{DepositNote, DepositRecreatedNotes}, - mantle::{ - Note, TxHash, - ledger::{Inputs, NoteId, Outputs, Utxo}, - ops::{ - Op, - channel::{ - ChannelId, MsgId, - channel_transfer::ChannelTransferOp, - deposit::Metadata, - inscribe::{Inscription, InscriptionOp}, - }, - }, - transactions::Ops, - }, - }, - key_management_system_service::keys::{Ed25519Key, Ed25519PublicKey, ZkPublicKey}, - sequencer::DepositInfo, + core::mantle::ops::channel::{ChannelId, MsgId}, + key_management_system_service::keys::{Ed25519Key, Ed25519PublicKey}, }; use mempool::{MemPool, MemPoolHandle}; use ping_core::{ReceiverMessage, ping_record_pda, receiver_config_account_id}; @@ -60,8 +43,7 @@ use sequencer_storage_actor::{ protocol::{ AddPendingCrossZoneDispatches, AtomicUpdate, CrossZoneMessageKey, DispatchOrigin, GetBlock, GetChannelViewBytes, GetFinalSnapshot, GetFirstBlockId, GetLatestBlockMeta, GetLeeState, - GetPendingCrossZoneDispatches, GetPendingDepositEvents, PendingCrossZoneDispatchRecord, - PendingDepositEventRecord, + GetPendingCrossZoneDispatches, PendingCrossZoneDispatchRecord, }, }; use sharding_pool_actor::{RestartConfig, ShardingPoolActor}; @@ -71,7 +53,7 @@ use tokio::sync::Mutex; use crate::{ MAX_DISPATCHES_PER_BLOCK, RETIRE_DISPATCH_AFTER_FAILURES, SequencerCore, TransactionOrigin, - build_bridge_deposit_tx_from_event, build_finalize_unstake_tx, classify_settled_deliveries, + build_finalize_unstake_tx, classify_settled_deliveries, config::{ self, BedrockConfig, CrossZoneConfig, CrossZonePeer, CrossZoneRoute, SequencerConfig, }, @@ -145,13 +127,12 @@ async fn start_sequencer_on( }) .await; } - // A committee of this node alone, so a pin needs only its own signature. + // A committee of this node alone. sequencer .channel_signer .tell(sequencer_channel_signing_actor::protocol::ChannelView { live_keys: vec![sequencer.channel_signing_key.public_key()], required_signatures: 1, - transfer_signatures: 1, target: None, }) .await @@ -242,11 +223,8 @@ async fn start_sequencer_bare_on( ) .await, ); - let channel_signer = ChannelSigningActor::spawn(ChannelSigningActor::new( - channel_signing_key.clone(), - config.bedrock_config.channel_id, - crate::inscribed_block_deposits, - )); + let channel_signer = + ChannelSigningActor::spawn(ChannelSigningActor::new(channel_signing_key.clone())); let sequencer = SequencerCore::new( config, @@ -312,7 +290,6 @@ fn publish_outcome(block: &Block, parent: MsgId) -> PublishOutcome { parent, checkpoint: mock_checkpoint(), seq: next_channel_seq(), - released_notes: Vec::new(), } } @@ -333,8 +310,6 @@ fn empty_channel_update() -> ChannelUpdate { seq: next_channel_seq(), view: ViewChange::Extension(Vec::new()), finalized: Vec::new(), - deposits: Vec::new(), - withdrawals: Vec::new(), undecodable: Vec::new(), finalized_signers: Vec::new(), } @@ -514,6 +489,20 @@ async fn common_setup_with_config( (sequencer, mempool_handle) } +/// A bridge `Deposit` of `amount` to `recipient` under `op_id`, as the genesis builds them. +fn bridge_deposit_tx( + op_id: [u8; 32], + recipient: &DepositRecipient, + amount: u64, +) -> PublicTransaction { + sequencer_bridge::deposit_tx( + op_id, + &sequencer_bridge::Credited::Public(recipient.evidence()), + amount, + ) + .expect("bridge deposit tx builds") +} + fn tx_is_bridge_deposit( tx: &LeeTransaction, deposit_op_id: [u8; 32], @@ -643,15 +632,13 @@ async fn a_charged_bridge_deposit_is_dropped_by_the_builder_bridge_guard() { ); assert!( !sequencer - .with_state(|state| deposit_already_minted(state, HashType(op_id))) + .with_state(|state| deposit_already_minted(state, op_id)) .await, "a dropped deposit must not mint the receipt PDA", ); } -#[tokio::test] -async fn a_reverted_withdraw_releases_nothing_on_l1() { - let (mut sequencer, mempool_handle) = common_setup().await; +fn bridge_withdraw_tx(amount: u64) -> LeeTransaction { let payer = &initial_pub_accounts_private_keys()[0]; let root = Actor::new(payer.account_id, programs::bridge_account_id()); let message = lee::public_transaction::Message::try_new_with_fees( @@ -663,7 +650,7 @@ async fn a_reverted_withdraw_releases_nothing_on_l1() { ], signer_nonces(&[&payer.pub_sign_key], vec![Nonce(0)]), bridge_core::Message::Withdraw { - amount: u64::MAX, + amount, bedrock_account_pk: [0; 32], }, common::test_utils::test_fee_declaration(payer.account_id), @@ -671,7 +658,13 @@ async fn a_reverted_withdraw_releases_nothing_on_l1() { .unwrap(); let witness_set = lee::public_transaction::WitnessSet::for_message(&message, &[&payer.pub_sign_key]); - let withdraw = LeeTransaction::Public(PublicTransaction::new(message, witness_set)); + LeeTransaction::Public(PublicTransaction::new(message, witness_set)) +} + +#[tokio::test] +async fn a_reverted_withdraw_is_included_as_reverted() { + let (mut sequencer, mempool_handle) = common_setup().await; + let withdraw = bridge_withdraw_tx(u64::MAX); mempool_handle .push((TransactionOrigin::User, withdraw.clone())) .await @@ -682,16 +675,40 @@ async fn a_reverted_withdraw_releases_nothing_on_l1() { // Withdrawing more than the payer holds reverts. assert_block_tail(&built.block, std::slice::from_ref(&withdraw)); assert!(built.block.body.is_reverted(0)); - assert!(built.withdrawals.is_empty()); } #[tokio::test] -async fn an_exempt_public_bridge_deposit_is_dropped_by_the_builder_bridge_guard() { - // An empty-witness bridge `Deposit` classifies as an exempt system - // injection, so `settle_transaction` applies it — a legit deposit replays - // through that same path. Only the builder's origin-gated guard can drop a - // *user*-submitted one. Without it the fee classification waves a forged - // public deposit straight through (the consensus replay gap is #809). +async fn a_withdrawal_is_dropped_until_payouts_are_supported() { + let (mut sequencer, mempool_handle) = common_setup().await; + let withdraw = bridge_withdraw_tx(1); + mempool_handle + .push((TransactionOrigin::User, withdraw.clone())) + .await + .unwrap(); + + // It settles and emits its withdrawal: only the guard keeps it out. + let mut state = sequencer.with_state(Clone::clone).await; + let opening = chain_state::apply::opening_fee_state(&state); + let (events, _) = chain_state::apply::settle_transaction( + &withdraw, + &mut state, + &opening, + 2, + 0, + 0, + &mut fee_core::BlockFeeSummary::default(), + ) + .expect("a withdrawal the payer can afford settles"); + assert_eq!(crate::bridge_withdrawals(&events).count(), 1); + + let built = sequencer.build_block_from_mempool().await.unwrap(); + + assert_block_tail(&built.block, &[]); +} + +#[tokio::test] +async fn an_unsigned_public_bridge_deposit_is_not_included() { + // The builder mints only the deposits it admitted itself. let config = setup_sequencer_config(); let (mut sequencer, mempool_handle) = start_sequencer(config).await; @@ -700,13 +717,7 @@ async fn an_exempt_public_bridge_deposit_is_dropped_by_the_builder_bridge_guard( PublicKey::new_from_private_key(&initial_pub_accounts_private_keys()[1].pub_sign_key), )); let op_id = [0x7c_u8; 32]; - let forged = build_bridge_deposit_tx_from_event(&PendingDepositEventRecord { - deposit_op_id: HashType(op_id), - source_tx_hash: HashType([1_u8; 32]), - amount: 1, - metadata: borsh::to_vec(&DepositMetadata { recipient }).unwrap(), - }) - .expect("bridge deposit tx builds"); + let forged = LeeTransaction::Public(bridge_deposit_tx(op_id, &recipient, 1)); mempool_handle .push((TransactionOrigin::User, forged)) @@ -731,12 +742,73 @@ async fn an_exempt_public_bridge_deposit_is_dropped_by_the_builder_bridge_guard( ); assert!( !sequencer - .with_state(|state| deposit_already_minted(state, HashType(op_id))) + .with_state(|state| deposit_already_minted(state, op_id)) .await, "a dropped deposit must not mint the receipt PDA", ); } +#[tokio::test] +async fn an_admitted_deposit_is_minted_by_the_block_that_takes_it_in() { + let recipient = DepositRecipient::Identified(lee::PublicAccountEvidence::Key( + PublicKey::new_from_private_key(&PrivateKey::try_new([3; 32]).unwrap()), + )); + let mint = chain_state::vault::VaultMint { + id: [0x7f; 32], + recipient: recipient.clone(), + amount: 9, + }; + let deposit = vec![1, 2, 3]; + let channel = CannedChannel { + admitted: vec![(deposit.clone(), mint.clone())], + ..CannedChannel::empty() + } + .share(); + let (mut sequencer, _mempool_handle) = + start_sequencer_on(setup_sequencer_config(), channel.clone()).await; + + sequencer.admit_deposit(deposit.clone()).await.unwrap(); + assert!( + sequencer.admit_deposit(deposit.clone()).await.is_err(), + "a deposit waits for its block once" + ); + assert!( + sequencer.admit_deposit(vec![4]).await.is_err(), + "the vault admits what it holds" + ); + + let block_id = sequencer.run_production_turn().await.unwrap(); + let block = sequencer + .storage_ref + .ask(GetBlock { block_id }) + .await + .unwrap() + .expect("produced block is stored"); + + assert!( + block + .body + .transactions + .contains(&mint.transaction().unwrap()) + ); + assert_eq!(channel.lock().taken_in, std::slice::from_ref(&deposit)); + assert_eq!( + sequencer + .with_state(|state| state + .get_account_by_id(recipient.account_id()) + .data + .native_balance() + .unwrap()) + .await, + 9 + ); + + // Minted once: neither a second submission nor a later block mints it again. + assert!(sequencer.admit_deposit(deposit).await.is_err()); + sequencer.run_production_turn().await.unwrap(); + assert_eq!(channel.lock().taken_in.len(), 1); +} + /// A config that receives `ping_receiver` messages from [`PEER_ZONE`], so /// `build_genesis_state` seeds the inbox config PDA and a delivery has an /// allowlist to pass. @@ -1733,7 +1805,6 @@ fn live_channel(keys: Vec) -> LiveChannelConfig { keys, config_tip: MsgId::root(), required_signatures: 1, - transfer_threshold: 1, posting_timeframe: config::default_channel_params().posting_timeframe, posting_timeout: config::default_channel_params().posting_timeout, } @@ -2487,20 +2558,13 @@ fn cooldown_rejects_before_the_cooldown_elapses() { #[test] fn resubmittable_txs_drops_clock_and_bridge_deposits() { let user_tx = common::test_utils::produce_dummy_empty_transaction(); - let deposit_tx = build_bridge_deposit_tx_from_event(&PendingDepositEventRecord { - deposit_op_id: HashType([13; 32]), - source_tx_hash: HashType([7; 32]), - amount: 1, - metadata: borsh::to_vec(&DepositMetadata { - recipient: DepositRecipient::Identified(lee::PublicAccountEvidence::Key( - PublicKey::new_from_private_key( - &initial_pub_accounts_private_keys()[0].pub_sign_key, - ), - )), - }) - .unwrap(), - }) - .unwrap(); + let deposit_tx = LeeTransaction::Public(bridge_deposit_tx( + [13; 32], + &DepositRecipient::Identified(lee::PublicAccountEvidence::Key( + PublicKey::new_from_private_key(&initial_pub_accounts_private_keys()[0].pub_sign_key), + )), + 1, + )); let withdraw_tx = { let bridge = Actor::new( system_accounts::bridge_account_id(), @@ -2528,7 +2592,7 @@ fn resubmittable_txs_drops_clock_and_bridge_deposits() { vec![user_tx.clone(), deposit_tx, withdraw_tx.clone()], ); - // The trailing clock tx and the sequencer-generated deposit are dropped; + // The trailing clock tx and the bridge deposit are dropped; // user txs (withdrawals included) are returned. assert_eq!(resubmittable_txs(&block), vec![user_tx, withdraw_tx]); } @@ -2662,1012 +2726,182 @@ async fn a_block_is_refused_when_the_channel_tip_moved_under_it() { let refused = sequencer.run_production_turn().await; assert!( refused.is_err(), - "a block chained on a stale entry must not be inscribed" - ); - assert_eq!( - sequencer.chain_height().await, - first, - "the head is unchanged" - ); -} - -/// An entry without a block (garbage, an empty payload) owns the channel tip -/// without moving the head. The pin follows it, so the next block lands on -/// the junk entry, its content chained on the last valid block. -#[tokio::test] -async fn production_chains_on_a_garbage_entry_at_the_tip() { - let config = setup_sequencer_config(); - let channel = CannedChannel::empty().share(); - let (mut sequencer, _mempool_handle) = start_sequencer_on(config, channel.clone()).await; - - let first = sequencer.run_production_turn().await.unwrap(); - - let junk = MsgId::from([42_u8; 32]); - let pin = sequencer.chain().lock().await.pin(); - channel.serve(CannedChannel { - tip: Some(junk), - ..CannedChannel::empty() - }); - sequencer - .on_channel_update(&ChannelUpdate { - view: ViewChange::Extension(vec![ChannelEntry { - msg: junk, - parent: pin, - block: None, - finally_absent_keys: BTreeSet::new(), - final_slot: None, - }]), - ..empty_channel_update() - }) - .await; - assert_eq!(sequencer.chain().lock().await.pin(), junk); - - let next = sequencer - .run_production_turn() - .await - .expect("the pin must follow the channel tip past a garbage entry"); - assert_eq!(next, first + 1, "the junk owns no height"); - let chain = sequencer.chain(); - let chain = chain.lock().await; - assert_eq!(chain.view().last().unwrap().parent, junk); -} - -/// A conflict that drops our newest block rewinds the head and the pin onto -/// what the channel kept, and the next block takes the freed height. -#[tokio::test] -async fn a_conflict_dropping_our_newest_block_rewinds_the_head_and_the_pin() { - let config = setup_sequencer_config(); - let channel = CannedChannel::empty().share(); - let (mut sequencer, _mempool_handle) = start_sequencer_on(config, channel.clone()).await; - - sequencer.run_production_turn().await.unwrap(); - let dropped = sequencer.run_production_turn().await.unwrap(); - let kept = sequencer.chain().lock().await.view()[..2].to_vec(); - let block2_msg = kept[1].msg; - - channel.serve(CannedChannel { - tip: Some(block2_msg), - ..CannedChannel::empty() - }); - sequencer - .on_channel_update(&ChannelUpdate { - view: ViewChange::Conflict { - canonical: kept, - orphaned: Vec::new(), - }, - ..empty_channel_update() - }) - .await; - - assert_eq!(sequencer.chain().lock().await.pin(), block2_msg); - assert_eq!(sequencer.chain_height().await, dropped - 1); - assert_eq!( - sequencer.run_production_turn().await.unwrap(), - dropped, - "the next block retakes the freed height on the surviving entry" - ); -} - -/// A conflict that drops only a garbage entry moves the pin back without -/// touching the head. -#[tokio::test] -async fn a_conflict_dropping_a_garbage_entry_rewinds_only_the_pin() { - let config = setup_sequencer_config(); - let (mut sequencer, _mempool_handle) = start_sequencer(config).await; - - let first = sequencer.run_production_turn().await.unwrap(); - let kept = sequencer.chain().lock().await.view().to_vec(); - let pin = kept.last().unwrap().msg; - - let junk = MsgId::from([42_u8; 32]); - sequencer - .on_channel_update(&ChannelUpdate { - view: ViewChange::Extension(vec![ChannelEntry { - msg: junk, - parent: pin, - block: None, - finally_absent_keys: BTreeSet::new(), - final_slot: None, - }]), - ..empty_channel_update() - }) - .await; - sequencer - .on_channel_update(&ChannelUpdate { - view: ViewChange::Conflict { - canonical: kept, - orphaned: Vec::new(), - }, - ..empty_channel_update() - }) - .await; - - assert_eq!(sequencer.chain().lock().await.pin(), pin); - assert_eq!(sequencer.chain_height().await, first); - sequencer - .run_production_turn() - .await - .expect("the next block must pin on the block the garbage sat on"); -} - -/// A fully finalized view still pins, on the newest finalized entry. -#[tokio::test] -async fn the_pin_stays_on_a_finalized_entry() { - let config = setup_sequencer_config(); - let (mut sequencer, _mempool_handle) = start_sequencer(config).await; - - sequencer.run_production_turn().await.unwrap(); - let block2 = block_at(&sequencer, 2).await.unwrap(); - let finalized = finalized_as_held(&sequencer.chain(), &block2).await; - let block2_msg = finalized.msg; - - sequencer - .on_channel_update(&ChannelUpdate { - finalized: vec![finalized], - ..empty_channel_update() - }) - .await; - - let chain = sequencer.chain(); - { - let chain = chain.lock().await; - assert!(chain.view().is_empty()); - assert_eq!( - chain.pin(), - block2_msg, - "the finalized entry carries the pin" - ); - } - sequencer - .run_production_turn() - .await - .expect("the next block must pin on the finalized tip"); -} - -#[tokio::test] -async fn follow_update_records_deposits_for_the_production_drain() { - let config = setup_sequencer_config(); - let (mut sequencer, _mempool_handle) = start_sequencer(config).await; - - let recipient = DepositRecipient::Identified(lee::PublicAccountEvidence::Key( - PublicKey::new_from_private_key(&initial_pub_accounts_private_keys()[0].pub_sign_key), - )); - let metadata = borsh::to_vec(&DepositMetadata { recipient }).unwrap(); - let deposit = DepositInfo { - op_id: [21; 32], - tx_hash: TxHash::from([9; 32]), - channel_id: ChannelId::from([0; 32]), - inputs: Inputs::empty(), - amount: 5, - metadata: Metadata::new_unchecked(metadata), - notes: DepositRecreatedNotes::default(), - }; - - sequencer - .on_channel_update(&ChannelUpdate { - deposits: vec![deposit], - ..empty_channel_update() - }) - .await; - - let pending = sequencer - .storage_ref - .ask(GetPendingDepositEvents) - .await - .unwrap(); - assert_eq!(pending.len(), 1); - assert_eq!(pending[0].deposit_op_id, HashType([21; 32])); -} - -/// A deposit of `amount` to the first test account, its value re-created as -/// the channel notes `notes`. -fn deposit_info(op_id: [u8; 32], amount: u64, notes: &[NoteId]) -> DepositInfo { - let recipient = DepositRecipient::Identified(lee::PublicAccountEvidence::Key( - PublicKey::new_from_private_key(&initial_pub_accounts_private_keys()[0].pub_sign_key), - )); - let metadata = borsh::to_vec(&DepositMetadata { recipient }).unwrap(); - let notes: Vec = notes - .iter() - .map(|¬e_id| DepositNote { - note_id, - value: amount, - pk: ZkPublicKey::from(num_bigint::BigUint::from(1_u8)), - }) - .collect(); - DepositInfo { - op_id, - tx_hash: TxHash::from([9; 32]), - channel_id: ChannelId::from([0; 32]), - inputs: Inputs::empty(), - amount, - metadata: Metadata::new_unchecked(metadata), - notes: DepositRecreatedNotes::try_from(notes).expect("deposit notes fit"), - } -} - -/// A distinct channel note id per `seed`. -fn channel_note(seed: u8) -> NoteId { - Utxo::new( - [seed; 32], - 0, - Note::new(1, ZkPublicKey::from(num_bigint::BigUint::from(1_u8))), - ) - .id() -} - -/// How many times the block mints `op_id`'s deposit of `amount`. -fn mint_count(block: &Block, op_id: [u8; 32], amount: u64) -> usize { - block - .body - .transactions - .iter() - .filter(|tx| tx_is_bridge_deposit(tx, op_id, amount)) - .count() -} - -#[tokio::test] -async fn an_observed_deposit_mints_in_a_block_pinned_on_its_notes() { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - - let op_id = [0x5d; 32]; - sequencer - .on_observed_deposits(&[deposit_info(op_id, 5, &[note])]) - .await; - let block_id = sequencer.run_production_turn().await.unwrap(); - - let block = block_at(&sequencer, block_id) - .await - .expect("produced block is stored"); - assert_eq!( - mint_count(&block, op_id, 5), - 1, - "the observed deposit is minted" - ); - assert_eq!( - pins.lock().unwrap().last(), - Some(&vec![note]), - "the block is published pinned on the deposit's note" - ); -} - -/// A node that observed a deposit and minted it in the block it produced, with -/// that deposit and block. -async fn sequencer_minting_an_observed_deposit() -> ( - SequencerCore, - MemPoolHandle<(TransactionOrigin, LeeTransaction)>, - DepositInfo, - Block, -) { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..CannedChannel::empty() - }; - let (mut sequencer, mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - let deposit = deposit_info([0x5d; 32], 5, &[note]); - sequencer - .on_observed_deposits(std::slice::from_ref(&deposit)) - .await; - let block_id = sequencer.run_production_turn().await.unwrap(); - let block = block_at(&sequencer, block_id) - .await - .expect("produced block is stored"); - - (sequencer, mempool_handle, deposit, block) -} - -/// Whether this node signs a peer's pin of `block` on `deposit`'s notes. -async fn signs_peer_pin( - sequencer: &SequencerCore, - block: &Block, - deposit: &DepositInfo, -) -> bool { - let peer = Ed25519Key::from_bytes(&[8; 32]); - let signer = &sequencer.channel_signer; - signer - .tell(sequencer_channel_signing_actor::protocol::ChannelView { - live_keys: vec![ - sequencer.channel_signing_key.public_key(), - peer.public_key(), - ], - required_signatures: 1, - transfer_signatures: 2, - target: None, - }) - .await - .expect("the channel-signing actor should accept a view"); - let (publisher, mut outbound) = tokio::sync::mpsc::channel(8); - signer - .tell(sequencer_channel_signing_actor::protocol::SetPublisher( - publisher, - )) - .await - .expect("the channel-signing actor should accept a publisher"); - - let channel_id = sequencer.sequencer_config.bedrock_config.channel_id; - let pin = Ops::new( - logos_blockchain_zone_sdk::core::era::ForkDigest::new([0; 32]), - [ - Op::ChannelInscribe(InscriptionOp { - channel_id, - inscription: Inscription::new_unchecked(borsh::to_vec(block).unwrap()), - parent: MsgId::root(), - signer: peer.public_key().into_unverified(), - }), - Op::ChannelTransfer(ChannelTransferOp { - channel_id, - inputs: Inputs::try_new( - deposit - .notes - .iter() - .map(|note| note.note_id) - .collect::>(), - ) - .expect("the deposit's notes fit"), - outputs: Outputs::try_new( - deposit - .notes - .iter() - .map(|note| Note::new(note.value, note.pk)) - .collect::>(), - ) - .expect("the deposit's notes fit"), - }), - ], - ); - signer - .ask(sequencer_channel_signing_actor::protocol::Wire::Draft( - sequencer_channel_signing_actor::protocol::Draft { tx: Box::new(pin) }, - )) - .await - .expect("the channel-signing actor should accept a draft"); - - matches!( - outbound.try_recv(), - Ok(sequencer_channel_signing_actor::protocol::Wire::Signature( - _ - )) - ) -} - -#[tokio::test] -async fn a_peer_pin_of_an_observed_deposit_is_signed() { - let (sequencer, _mempool_handle, deposit, block) = - sequencer_minting_an_observed_deposit().await; - - assert!(signs_peer_pin(&sequencer, &block, &deposit).await); -} - -/// A proposer whose L1 finality lags may still pin a deposit this node saw -/// finalize. -#[tokio::test] -async fn a_peer_pin_of_a_deposit_final_on_l1_is_still_signed() { - let (mut sequencer, _mempool_handle, deposit, block) = - sequencer_minting_an_observed_deposit().await; - sequencer - .on_channel_update(&ChannelUpdate { - checkpoint: checkpoint_at(mock_msg_of(&block)), - deposits: vec![deposit.clone()], - ..empty_channel_update() - }) - .await; - - assert!(signs_peer_pin(&sequencer, &block, &deposit).await); -} - -#[tokio::test] -async fn a_peer_pin_of_a_deposit_minted_in_a_final_block_is_not_signed() { - let (mut sequencer, _mempool_handle, deposit, block) = - sequencer_minting_an_observed_deposit().await; - sequencer - .on_channel_update(&ChannelUpdate { - checkpoint: checkpoint_at(mock_msg_of(&block)), - finalized: vec![finalized_as_held(&sequencer.chain(), &block).await], - ..empty_channel_update() - }) - .await; - - assert!(!signs_peer_pin(&sequencer, &block, &deposit).await); -} - -/// A committee key that never signs leaves the pin short, so the block goes -/// out unpinned without the mint and the deposit mints once final. -#[tokio::test] -async fn a_pin_short_of_signatures_leaves_its_deposit_to_finality() { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let (mut sequencer, mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - let silent_peer = Ed25519Key::from_bytes(&[8; 32]).public_key(); - sequencer - .channel_signer - .tell(sequencer_channel_signing_actor::protocol::ChannelView { - live_keys: vec![sequencer.channel_signing_key.public_key(), silent_peer], - required_signatures: 1, - transfer_signatures: 2, - target: None, - }) - .await - .expect("the channel-signing actor should accept a view"); - let user_tx = common::test_utils::create_transaction_native_token_transfer( - initial_public_user_accounts()[0].account_id, - 0, - initial_public_user_accounts()[1].account_id, - 10, - &create_signing_key_for_account1(), - ); - mempool_handle - .push((TransactionOrigin::User, user_tx.clone())) - .await - .unwrap(); - - let op_id = [0x6a; 32]; - let deposit = deposit_info(op_id, 5, &[note]); - sequencer - .on_observed_deposits(std::slice::from_ref(&deposit)) - .await; - let block_id = sequencer.run_production_turn().await.unwrap(); - - let block = block_at(&sequencer, block_id) - .await - .expect("produced block is stored"); - assert_eq!( - mint_count(&block, op_id, 5), - 0, - "an unpinned block must not mint an observed deposit" - ); - assert!( - block.body.transactions.contains(&user_tx), - "the rest of the block still goes out" - ); - assert_eq!(pins.lock().unwrap().last(), Some(&Vec::new())); - assert!( - sequencer.observed_deposits.is_empty(), - "a deposit whose pin went unsigned is not pinned again" - ); - - sequencer - .on_channel_update(&ChannelUpdate { - checkpoint: checkpoint_at(mock_msg_of(&block)), - deposits: vec![deposit], - ..empty_channel_update() - }) - .await; - let final_block_id = sequencer.run_production_turn().await.unwrap(); - let final_block = block_at(&sequencer, final_block_id) - .await - .expect("produced block is stored"); - assert_eq!( - mint_count(&final_block, op_id, 5), - 1, - "the deposit mints once final" - ); -} - -#[tokio::test] -async fn deposits_past_the_pin_input_limit_mint_in_the_next_block() { - let notes: Vec = (0..=u8::MAX).map(channel_note).collect(); - let (first_notes, second_notes) = notes.split_at(usize::from(u8::MAX)); - let channel = CannedChannel { - channel_notes: notes.iter().copied().collect(), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - - let (first, second) = ([0x6b; 32], [0x6c; 32]); - sequencer - .on_observed_deposits(&[ - deposit_info(first, 5, first_notes), - deposit_info(second, 5, second_notes), - ]) - .await; - let block_id = sequencer.run_production_turn().await.unwrap(); - - let block = block_at(&sequencer, block_id) - .await - .expect("produced block is stored"); - assert_eq!(mint_count(&block, first, 5), 1); - assert_eq!( - mint_count(&block, second, 5), - 0, - "both deposits' notes do not fit one pin" - ); - assert_eq!(pins.lock().unwrap().last(), Some(&first_notes.to_vec())); - - let next_block_id = sequencer.run_production_turn().await.unwrap(); - let next_block = block_at(&sequencer, next_block_id) - .await - .expect("produced block is stored"); - assert_eq!(mint_count(&next_block, second, 5), 1); - assert_eq!(pins.lock().unwrap().last(), Some(&second_notes.to_vec())); -} - -/// Runs a turn pinning one observed deposit on `channel`, whose pin fails, and -/// checks the block still goes out with the deposit left to finality. -async fn assert_failed_pin_leaves_its_deposit_to_finality(channel: CannedChannel) { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..channel - }; - let pins = Arc::clone(&channel.pins); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - - let op_id = [0x6d; 32]; - sequencer - .on_observed_deposits(&[deposit_info(op_id, 5, &[note])]) - .await; - let block_id = sequencer - .run_production_turn() - .await - .expect("a failed pin does not cost the turn"); - - let block = block_at(&sequencer, block_id) - .await - .expect("produced block is stored"); - assert_eq!(mint_count(&block, op_id, 5), 0); - assert_eq!(pins.lock().unwrap().last(), Some(&Vec::new())); - assert!( - sequencer.observed_deposits.is_empty(), - "a deposit whose pin failed is not pinned again" - ); -} - -#[tokio::test] -async fn a_pin_that_fails_to_prepare_leaves_its_deposit_to_finality() { - assert_failed_pin_leaves_its_deposit_to_finality(CannedChannel { - prepare_pin_fails: true, - ..CannedChannel::empty() - }) - .await; -} - -#[tokio::test] -async fn a_pin_that_fails_to_publish_leaves_its_deposit_to_finality() { - assert_failed_pin_leaves_its_deposit_to_finality(CannedChannel { - publish_pin_fails: true, - ..CannedChannel::empty() - }) - .await; -} - -#[tokio::test] -async fn an_observed_deposit_off_the_branch_is_not_minted() { - let channel = CannedChannel::empty(); - let pins = Arc::clone(&channel.pins); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - - let op_id = [0x5e; 32]; - sequencer - .on_observed_deposits(&[deposit_info(op_id, 5, &[channel_note(1)])]) - .await; - let block_id = sequencer.run_production_turn().await.unwrap(); - - let block = block_at(&sequencer, block_id) - .await - .expect("produced block is stored"); - assert_eq!( - mint_count(&block, op_id, 5), - 0, - "a deposit whose note is not a channel note on this branch is not minted" - ); - assert_eq!(pins.lock().unwrap().last(), Some(&Vec::new())); -} - -#[tokio::test] -async fn a_pinned_deposit_is_not_minted_again_once_final() { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - - let op_id = [0x5f; 32]; - let deposit = deposit_info(op_id, 5, &[note]); - sequencer - .on_observed_deposits(std::slice::from_ref(&deposit)) - .await; - let pinned_block_id = sequencer.run_production_turn().await.unwrap(); - let pinned_block = block_at(&sequencer, pinned_block_id) - .await - .expect("produced block is stored"); - assert_eq!(mint_count(&pinned_block, op_id, 5), 1); - - // The deposit finalizes before the block minting it does. - sequencer - .on_channel_update(&ChannelUpdate { - checkpoint: checkpoint_at(mock_msg_of(&pinned_block)), - deposits: vec![deposit], - ..empty_channel_update() - }) - .await; - let block_id = sequencer.run_production_turn().await.unwrap(); - - let block = block_at(&sequencer, block_id) - .await - .expect("produced block is stored"); - assert_eq!( - mint_count(&block, op_id, 5), - 0, - "the head already holds the mint, so the final record is skipped" - ); - assert_eq!(pins.lock().unwrap().last(), Some(&Vec::new())); - let records = sequencer - .storage_ref - .ask(GetPendingDepositEvents) - .await - .unwrap(); - assert!( - records - .iter() - .any(|record| record.deposit_op_id == HashType(op_id)), - "the record stays until the mint is final" - ); -} - -/// The first test account, which [`deposit_info`] credits. -fn deposit_recipient() -> AccountId { - initial_public_user_accounts()[0].account_id -} - -/// The native balance `account_id` holds in head state. -async fn native_balance( - sequencer: &SequencerCore, - account_id: AccountId, -) -> u128 { - sequencer - .with_state(|state| { - state - .get_account_by_id(account_id) - .data - .native_balance() - .unwrap() - }) - .await -} - -/// Reorgs the channel back to genesis: the view keeps only genesis, and -/// `shared` serves `channel` with its tip there. -async fn reorg_to_genesis( - sequencer: &mut SequencerCore, - shared: &SharedChannel, - channel: CannedChannel, -) { - let canonical = sequencer.chain().lock().await.view()[..1].to_vec(); - let genesis = canonical[0].msg; - sequencer - .on_channel_update(&ChannelUpdate { - view: ViewChange::Conflict { - canonical, - orphaned: Vec::new(), - }, - ..empty_channel_update() - }) - .await; - shared.serve(CannedChannel { - tip: Some(genesis), - ..channel - }); -} - -#[tokio::test] -async fn a_final_deposit_mints_in_the_next_block_and_not_again() { - let (mut sequencer, _mempool_handle) = start_sequencer(setup_sequencer_config()).await; - - let op_id = [0x61; 32]; - sequencer - .on_channel_update(&ChannelUpdate { - deposits: vec![deposit_info(op_id, 5, &[])], - ..empty_channel_update() - }) - .await; - let first = sequencer.run_production_turn().await.unwrap(); - assert!( - sequencer - .with_state(|state| deposit_already_minted(state, HashType(op_id))) - .await, - "the receipt marks the deposit minted in head state" - ); - let second = sequencer.run_production_turn().await.unwrap(); - - let first = block_at(&sequencer, first) - .await - .expect("produced block is stored"); - let second = block_at(&sequencer, second) - .await - .expect("produced block is stored"); - assert_eq!(mint_count(&first, op_id, 5), 1); - assert_eq!( - mint_count(&second, op_id, 5), - 0, - "the receipt from the first mint keeps the record from minting again" - ); -} - -#[tokio::test] -async fn an_observed_deposit_is_not_minted_again_next_turn() { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - - let op_id = [0x62; 32]; - sequencer - .on_observed_deposits(&[deposit_info(op_id, 5, &[note])]) - .await; - let first = sequencer.run_production_turn().await.unwrap(); - let second = sequencer.run_production_turn().await.unwrap(); - - let first = block_at(&sequencer, first) - .await - .expect("produced block is stored"); - let second = block_at(&sequencer, second) - .await - .expect("produced block is stored"); - assert_eq!(mint_count(&first, op_id, 5), 1); - assert_eq!( - mint_count(&second, op_id, 5), - 0, - "the receipt from the first mint keeps the observation from minting again" - ); - assert_eq!(pins.lock().unwrap().last(), Some(&Vec::new())); -} - -#[tokio::test] -async fn an_observed_deposit_with_a_note_off_the_branch_is_not_minted() { - let on_branch = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([on_branch]), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; - - let op_id = [0x66; 32]; - sequencer - .on_observed_deposits(&[deposit_info(op_id, 5, &[on_branch, channel_note(2)])]) - .await; - let block_id = sequencer.run_production_turn().await.unwrap(); - - let block = block_at(&sequencer, block_id) - .await - .expect("produced block is stored"); - assert_eq!( - mint_count(&block, op_id, 5), - 0, - "a deposit is minted only once every one of its notes is a channel note" + "a block chained on a stale entry must not be inscribed" ); - assert_eq!(pins.lock().unwrap().last(), Some(&Vec::new())); - assert!( - sequencer.observed_deposits.is_empty(), - "a deposit with a note off the branch is forgotten" + assert_eq!( + sequencer.chain_height().await, + first, + "the head is unchanged" ); } +/// An entry without a block (garbage, an empty payload) owns the channel tip +/// without moving the head. The pin follows it, so the next block lands on +/// the junk entry, its content chained on the last valid block. #[tokio::test] -async fn an_observed_deposit_without_notes_is_minted_only_once_final() { - let channel = CannedChannel::empty(); - let pins = Arc::clone(&channel.pins); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.share()).await; +async fn production_chains_on_a_garbage_entry_at_the_tip() { + let config = setup_sequencer_config(); + let channel = CannedChannel::empty().share(); + let (mut sequencer, _mempool_handle) = start_sequencer_on(config, channel.clone()).await; - let op_id = [0x67; 32]; - let deposit = deposit_info(op_id, 5, &[]); - sequencer - .on_observed_deposits(std::slice::from_ref(&deposit)) - .await; - let observed = sequencer.run_production_turn().await.unwrap(); + let first = sequencer.run_production_turn().await.unwrap(); + + let junk = MsgId::from([42_u8; 32]); + let pin = sequencer.chain().lock().await.pin(); + channel.serve(CannedChannel { + tip: Some(junk), + ..CannedChannel::empty() + }); sequencer .on_channel_update(&ChannelUpdate { - deposits: vec![deposit], + view: ViewChange::Extension(vec![ChannelEntry { + msg: junk, + parent: pin, + block: None, + finally_absent_keys: BTreeSet::new(), + final_slot: None, + }]), ..empty_channel_update() }) .await; - let finalized = sequencer.run_production_turn().await.unwrap(); + assert_eq!(sequencer.chain().lock().await.pin(), junk); - let observed = block_at(&sequencer, observed) - .await - .expect("produced block is stored"); - let finalized = block_at(&sequencer, finalized) + let next = sequencer + .run_production_turn() .await - .expect("produced block is stored"); - assert_eq!( - mint_count(&observed, op_id, 5), - 0, - "a deposit without notes has nothing to pin the block on" - ); - assert_eq!(mint_count(&finalized, op_id, 5), 1); - assert_eq!(pins.lock().unwrap().last(), Some(&Vec::new())); + .expect("the pin must follow the channel tip past a garbage entry"); + assert_eq!(next, first + 1, "the junk owns no height"); + let chain = sequencer.chain(); + let chain = chain.lock().await; + assert_eq!(chain.view().last().unwrap().parent, junk); } +/// A conflict that drops our newest block rewinds the head and the pin onto +/// what the channel kept, and the next block takes the freed height. #[tokio::test] -async fn an_orphaned_final_deposit_mint_is_minted_again_once() { +async fn a_conflict_dropping_our_newest_block_rewinds_the_head_and_the_pin() { + let config = setup_sequencer_config(); let channel = CannedChannel::empty().share(); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), channel.clone()).await; - let balance_before = native_balance(&sequencer, deposit_recipient()).await; + let (mut sequencer, _mempool_handle) = start_sequencer_on(config, channel.clone()).await; + + sequencer.run_production_turn().await.unwrap(); + let dropped = sequencer.run_production_turn().await.unwrap(); + let kept = sequencer.chain().lock().await.view()[..2].to_vec(); + let block2_msg = kept[1].msg; - let op_id = [0x63; 32]; + channel.serve(CannedChannel { + tip: Some(block2_msg), + ..CannedChannel::empty() + }); sequencer .on_channel_update(&ChannelUpdate { - deposits: vec![deposit_info(op_id, 5, &[])], + view: ViewChange::Conflict { + canonical: kept, + orphaned: Vec::new(), + }, ..empty_channel_update() }) .await; - sequencer.run_production_turn().await.unwrap(); - - reorg_to_genesis(&mut sequencer, &channel, CannedChannel::empty()).await; - assert_eq!(sequencer.chain_height().await, 1); - assert!( - !sequencer - .with_state(|state| deposit_already_minted(state, HashType(op_id))) - .await, - "the receipt reverts with the orphaned block" - ); - let replacement = sequencer.run_production_turn().await.unwrap(); - let replacement = block_at(&sequencer, replacement) - .await - .expect("produced block is stored"); - assert_eq!(mint_count(&replacement, op_id, 5), 1); + assert_eq!(sequencer.chain().lock().await.pin(), block2_msg); + assert_eq!(sequencer.chain_height().await, dropped - 1); assert_eq!( - native_balance(&sequencer, deposit_recipient()).await, - balance_before + 5, - "the recipient is credited once across the reorg" + sequencer.run_production_turn().await.unwrap(), + dropped, + "the next block retakes the freed height on the surviving entry" ); } +/// A conflict that drops only a garbage entry moves the pin back without +/// touching the head. #[tokio::test] -async fn an_orphaned_pinned_deposit_is_minted_again_pinned_on_its_notes() { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let shared = channel.clone().share(); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), shared.clone()).await; - let balance_before = native_balance(&sequencer, deposit_recipient()).await; +async fn a_conflict_dropping_a_garbage_entry_rewinds_only_the_pin() { + let config = setup_sequencer_config(); + let (mut sequencer, _mempool_handle) = start_sequencer(config).await; + + let first = sequencer.run_production_turn().await.unwrap(); + let kept = sequencer.chain().lock().await.view().to_vec(); + let pin = kept.last().unwrap().msg; - let op_id = [0x64; 32]; + let junk = MsgId::from([42_u8; 32]); + sequencer + .on_channel_update(&ChannelUpdate { + view: ViewChange::Extension(vec![ChannelEntry { + msg: junk, + parent: pin, + block: None, + finally_absent_keys: BTreeSet::new(), + final_slot: None, + }]), + ..empty_channel_update() + }) + .await; sequencer - .on_observed_deposits(&[deposit_info(op_id, 5, &[note])]) + .on_channel_update(&ChannelUpdate { + view: ViewChange::Conflict { + canonical: kept, + orphaned: Vec::new(), + }, + ..empty_channel_update() + }) .await; - sequencer.run_production_turn().await.unwrap(); - - // The deposit survived the reorg, so its note is still a channel note. - reorg_to_genesis(&mut sequencer, &shared, channel).await; - assert!( - !sequencer - .with_state(|state| deposit_already_minted(state, HashType(op_id))) - .await, - "the receipt reverts with the orphaned block" - ); - let replacement = sequencer.run_production_turn().await.unwrap(); - let replacement = block_at(&sequencer, replacement) + assert_eq!(sequencer.chain().lock().await.pin(), pin); + assert_eq!(sequencer.chain_height().await, first); + sequencer + .run_production_turn() .await - .expect("produced block is stored"); - assert_eq!(mint_count(&replacement, op_id, 5), 1); - assert_eq!(pins.lock().unwrap().last(), Some(&vec![note])); - assert_eq!( - native_balance(&sequencer, deposit_recipient()).await, - balance_before + 5, - "the recipient is credited once across the reorg" - ); + .expect("the next block must pin on the block the garbage sat on"); } +/// A fully finalized view still pins, on the newest finalized entry. #[tokio::test] -async fn an_orphaned_pinned_deposit_whose_notes_left_the_branch_is_not_minted_again() { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let shared = channel.share(); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), shared.clone()).await; - let balance_before = native_balance(&sequencer, deposit_recipient()).await; +async fn the_pin_stays_on_a_finalized_entry() { + let config = setup_sequencer_config(); + let (mut sequencer, _mempool_handle) = start_sequencer(config).await; - let op_id = [0x65; 32]; - sequencer - .on_observed_deposits(&[deposit_info(op_id, 5, &[note])]) - .await; sequencer.run_production_turn().await.unwrap(); + let block2 = block_at(&sequencer, 2).await.unwrap(); + let finalized = finalized_as_held(&sequencer.chain(), &block2).await; + let block2_msg = finalized.msg; - // The reorg that orphaned the block took the deposit with it. - reorg_to_genesis( - &mut sequencer, - &shared, - CannedChannel { - pins: Arc::clone(&pins), - ..CannedChannel::empty() - }, - ) - .await; - let replacement = sequencer.run_production_turn().await.unwrap(); + sequencer + .on_channel_update(&ChannelUpdate { + finalized: vec![finalized], + ..empty_channel_update() + }) + .await; - let replacement = block_at(&sequencer, replacement) + let chain = sequencer.chain(); + { + let chain = chain.lock().await; + assert!(chain.view().is_empty()); + assert_eq!( + chain.pin(), + block2_msg, + "the finalized entry carries the pin" + ); + } + sequencer + .run_production_turn() .await - .expect("produced block is stored"); - assert_eq!(mint_count(&replacement, op_id, 5), 0); - assert_eq!(pins.lock().unwrap().last(), Some(&Vec::new())); - assert_eq!( - native_balance(&sequencer, deposit_recipient()).await, - balance_before, - "a deposit no longer on L1 is not credited" - ); - assert!( - sequencer.observed_deposits.is_empty(), - "a deposit no longer on L1 is forgotten" - ); + .expect("the next block must pin on the finalized tip"); } -#[tokio::test] -async fn a_minted_deposit_whose_notes_its_pin_spent_stays_observed() { - let note = channel_note(1); - let channel = CannedChannel { - channel_notes: HashSet::from([note]), - ..CannedChannel::empty() - }; - let pins = Arc::clone(&channel.pins); - let shared = channel.clone().share(); - let (mut sequencer, _mempool_handle) = - start_sequencer_on(setup_sequencer_config(), shared.clone()).await; - - let op_id = [0x6e; 32]; +/// The native balance `account_id` holds in head state. +async fn native_balance( + sequencer: &SequencerCore, + account_id: AccountId, +) -> u128 { sequencer - .on_observed_deposits(&[deposit_info(op_id, 5, &[note])]) - .await; - sequencer.run_production_turn().await.unwrap(); - - // The pin spent the deposit's note. - shared.serve(CannedChannel { - pins: Arc::clone(&pins), - ..CannedChannel::empty() - }); - sequencer.run_production_turn().await.unwrap(); - assert_eq!( - sequencer.observed_deposits.len(), - 1, - "a deposit minted on the head is kept" - ); - - // The block minting it is orphaned and the deposit's note is back. - reorg_to_genesis(&mut sequencer, &shared, channel).await; - let replacement = sequencer.run_production_turn().await.unwrap(); - - let replacement = block_at(&sequencer, replacement) + .with_state(|state| { + state + .get_account_by_id(account_id) + .data + .native_balance() + .unwrap() + }) .await - .expect("produced block is stored"); - assert_eq!(mint_count(&replacement, op_id, 5), 1); - assert_eq!(pins.lock().unwrap().last(), Some(&vec![note])); } #[tokio::test] @@ -4346,78 +3580,6 @@ async fn follow_update_persists_blocks_meta_and_state_atomically() { ); } -/// A finalized block below the final tip cannot be checked against the tier, -/// so it settles nothing: an accredited key could inscribe any bytes there. -#[tokio::test] -async fn a_foreign_block_below_the_final_tip_settles_no_deposit_record() { - let config = setup_sequencer_config(); - let (mut sequencer, _mempool_handle) = start_sequencer(config).await; - - // Final tier at block 2. - sequencer.run_production_turn().await.unwrap(); - let block2 = block_at(&sequencer, 2).await.unwrap(); - let finalized = finalized_as_held(&sequencer.chain(), &block2).await; - sequencer - .on_channel_update(&ChannelUpdate { - finalized: vec![finalized], - ..empty_channel_update() - }) - .await; - - let recipient = DepositRecipient::Identified(lee::PublicAccountEvidence::Key( - PublicKey::new_from_private_key(&initial_pub_accounts_private_keys()[0].pub_sign_key), - )); - let metadata = borsh::to_vec(&DepositMetadata { recipient }).unwrap(); - let deposit = DepositInfo { - op_id: [21; 32], - tx_hash: TxHash::from([9; 32]), - channel_id: ChannelId::from([0; 32]), - inputs: Inputs::empty(), - amount: 5, - metadata: Metadata::new_unchecked(metadata), - notes: DepositRecreatedNotes::default(), - }; - sequencer - .on_channel_update(&ChannelUpdate { - deposits: vec![deposit], - ..empty_channel_update() - }) - .await; - let record = sequencer - .storage_ref - .ask(GetPendingDepositEvents) - .await - .unwrap() - .into_iter() - .next() - .expect("the deposit is recorded"); - - // A crafted block 1 carrying the deposit's mint, as the next entry. - let forged = common::test_utils::produce_dummy_block( - 1, - None, - vec![build_bridge_deposit_tx_from_event(&record).unwrap()], - ); - let pin = sequencer.chain().lock().await.pin(); - sequencer - .on_channel_update(&ChannelUpdate { - finalized: vec![entry_of(&forged, pin)], - ..empty_channel_update() - }) - .await; - - assert!( - sequencer - .storage_ref - .ask(GetPendingDepositEvents) - .await - .unwrap() - .iter() - .any(|event| event.deposit_op_id == record.deposit_op_id), - "a block the final tier cannot vouch for must not settle the deposit" - ); -} - /// A competitor at our height that finalizes takes our block off the head, /// so our user transactions go back to the mempool. #[tokio::test] @@ -7135,39 +6297,17 @@ fn a_bridge_deposit_carries_its_receipts_and_its_recipients_evidence() { seed: lee_core::program::PdaSeed::new([6; 32]), }), ] { - let LeeTransaction::Public(event) = - build_bridge_deposit_tx_from_event(&PendingDepositEventRecord { - deposit_op_id: HashType(op_id), - source_tx_hash: HashType([1; 32]), - amount: 1, - metadata: borsh::to_vec(&DepositMetadata { - recipient: recipient.clone(), - }) - .unwrap(), - }) - .expect("bridge deposit tx builds") - else { - panic!("a bridge deposit is a public transaction"); - }; - let genesis = sequencer_bridge::deposit_tx( - op_id, - &sequencer_bridge::Credited::Public(recipient.evidence()), - 1, - ) - .unwrap(); - - for tx in [event, genesis] { - let receipt = tx.message.execution.root.to.account_id; - assert_eq!( - tx.message - .admission_evidence - .iter() - .map(lee::PublicAccountEvidence::account_id) - .collect::>(), - [receipt, recipient.account_id()], - "{recipient:?}" - ); - } + let tx = bridge_deposit_tx(op_id, &recipient, 1); + let receipt = tx.message.execution.root.to.account_id; + assert_eq!( + tx.message + .admission_evidence + .iter() + .map(lee::PublicAccountEvidence::account_id) + .collect::>(), + [receipt, recipient.account_id()], + "{recipient:?}" + ); } } @@ -7186,17 +6326,7 @@ fn a_bridge_deposit_credits_a_recipient_absent_from_public_state() { assert!(state.get_account_by_id_ref(recipient_id).is_none()); let op_id = [0x7e; 32]; - let LeeTransaction::Public(deposit) = - build_bridge_deposit_tx_from_event(&PendingDepositEventRecord { - deposit_op_id: HashType(op_id), - source_tx_hash: HashType([1; 32]), - amount: 9, - metadata: borsh::to_vec(&DepositMetadata { recipient }).unwrap(), - }) - .expect("bridge deposit tx builds") - else { - panic!("a bridge deposit is a public transaction"); - }; + let deposit = bridge_deposit_tx(op_id, &recipient, 9); assert!(deposit.witness_set.signatures_and_public_keys().is_empty()); assert!(deposit.message.nonces.is_empty()); assert!( @@ -7219,7 +6349,7 @@ fn a_bridge_deposit_credits_a_recipient_absent_from_public_state() { .unwrap(), 9 ); - assert!(deposit_already_minted(&state, HashType(op_id))); + assert!(deposit_already_minted(&state, op_id)); } #[test] diff --git a/lez/sequencer/service/rpc/src/lib.rs b/lez/sequencer/service/rpc/src/lib.rs index 7ec7a13450..d1e27ad644 100644 --- a/lez/sequencer/service/rpc/src/lib.rs +++ b/lez/sequencer/service/rpc/src/lib.rs @@ -188,6 +188,11 @@ pub trait Rpc { #[method(name = "submitSystemApproval")] async fn submit_system_approval(&self, approval: HexBytes) -> Result<(), ErrorObjectOwned>; + /// Hands the node a holder-signed `ProgramDeposit` step with its proof, in Bedrock's + /// encoding, to bridge into the zone with the node's next inscription. + #[method(name = "submitProgramDeposit")] + async fn submit_program_deposit(&self, deposit: HexBytes) -> Result<(), ErrorObjectOwned>; + #[method(name = "getSystemProposals")] async fn get_system_proposals(&self) -> Result; } diff --git a/lez/sequencer/service/src/lib.rs b/lez/sequencer/service/src/lib.rs index 08a999c364..935869e5b4 100644 --- a/lez/sequencer/service/src/lib.rs +++ b/lez/sequencer/service/src/lib.rs @@ -361,11 +361,7 @@ pub fn run( info!("Slasher Actor spawned"); let channel_signer_ref = ChannelSigningActor::spawn_with_mailbox( - ChannelSigningActor::new( - channel_signing_key.clone(), - bedrock_config.channel_id, - sequencer_core::inscribed_block_deposits, - ), + ChannelSigningActor::new(channel_signing_key.clone()), kameo::mailbox::bounded(sequencer_channel_signing_actor::MAILBOX_CAPACITY), ); actor_handle::record_mailbox_capacity(&channel_signer_ref); @@ -730,14 +726,13 @@ fn bedrock_actor_args( pending_txs: Vec::new(), lib: HeaderId::from([0; 32]), lib_slot: Slot::from(0), - channel_notes: Vec::new(), finalized_config: MsgId::root(), funding: Vec::new(), + program_notes: None, }, // Block ids only grow, so a sequence derived from them continues the // stored one across restarts and the store keeps each new checkpoint. seq: ChannelSeq::mocked(block_id.saturating_add(1)), - released_notes: Vec::new(), } }; let create_outcome = outcome.clone(); diff --git a/lez/vault_circuit/Cargo.toml b/lez/vault_circuit/Cargo.toml new file mode 100644 index 0000000000..4f811fd82d --- /dev/null +++ b/lez/vault_circuit/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "vault_circuit" +version = "0.1.0" +edition = "2024" +license = { workspace = true } + +[lints] +workspace = true + +[dependencies] +ark-bn254.workspace = true +ark-ec.workspace = true +ark-ed-on-bn254.workspace = true +ark-ff.workspace = true +ark-groth16.workspace = true +ark-r1cs-std.workspace = true +ark-relations.workspace = true +jf-poseidon2.workspace = true +logos-blockchain-groth16.workspace = true +logos-blockchain-poseidon2.workspace = true +rand.workspace = true +rand_chacha.workspace = true +sha2.workspace = true +tracing.workspace = true + +[dev-dependencies] +logos-blockchain-core = { workspace = true, features = ["test-utils"] } +logos-blockchain-key-management-system-keys.workspace = true +logos-blockchain-groth16.workspace = true diff --git a/lez/vault_circuit/demo_verification_key.bin b/lez/vault_circuit/demo_verification_key.bin new file mode 100644 index 0000000000..21577d2649 Binary files /dev/null and b/lez/vault_circuit/demo_verification_key.bin differ diff --git a/lez/vault_circuit/src/circuit.rs b/lez/vault_circuit/src/circuit.rs new file mode 100644 index 0000000000..379d3218d9 --- /dev/null +++ b/lez/vault_circuit/src/circuit.rs @@ -0,0 +1,213 @@ +use ark_bn254::Fr; +use ark_ec::AffineRepr as _; +use ark_ed_on_bn254::{EdwardsAffine, Fr as Scalar, constraints::EdwardsVar}; +use ark_ff::{AdditiveGroup as _, BigInteger as _, PrimeField as _}; +use ark_r1cs_std::{ + alloc::AllocVar as _, + boolean::Boolean, + convert::ToBitsGadget as _, + eq::EqGadget as _, + fields::{FieldVar as _, fp::FpVar}, + groups::CurveVar as _, +}; +use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError}; + +use crate::{ + COMMITTEE_DST, Committee, DEPOSITS_DST, Deposit, INTENT_DST, MAX_DEPOSITS, MAX_INPUTS, + PublicInputs, SIGNATURE_DST, STEP_ID_DST, Signature, Step, domain_tag, + poseidon2::{Sponge, digest}, +}; + +const INPUT_FIELDS: usize = 6; +const OUTPUT_FIELDS: usize = 7; + +/// The vault's rule for one program step. Every field is part of the assignment: the constraints +/// are the same for every committee. +#[derive(Clone)] +pub struct VaultCircuit { + /// The committee the consumed notes and deposits name. + pub committee: Committee, + pub step: Step, + /// The deposits the step consumes, in their order in the mini-block. At most + /// [`MAX_DEPOSITS`]. + pub deposits: Vec, + pub public: PublicInputs, + /// One slot per signer of `committee`, in order. + pub signatures: Vec>, + /// The committee the vault notes of the step go to: `committee` again unless it hands over. + pub successor: Committee, + pub successor_signatures: Vec>, +} + +impl ConstraintSynthesizer for VaultCircuit { + fn generate_constraints(self, cs: ConstraintSystemRef) -> Result<(), SynthesisError> { + assert!( + self.deposits.len() <= MAX_DEPOSITS, + "a step consumes at most {MAX_DEPOSITS} deposits" + ); + let zero = FpVar::::zero(); + let one = FpVar::::one(); + + // Bedrock's order. + let step_id = FpVar::new_input(cs.clone(), || Ok(self.public.program_step_id))?; + let deposits_hash = FpVar::new_input(cs.clone(), || Ok(self.public.program_deposits_hash))?; + let op_id = FpVar::new_input(cs.clone(), || Ok(self.public.op_id))?; + + let message = [step_id.clone(), deposits_hash.clone(), op_id]; + let committee = authorize(&cs, &self.committee, &self.signatures, &message)?; + // A committee that takes the vault over proves it holds its keys, so the vault cannot + // be handed to an id nobody can sign for. + let successor = authorize(&cs, &self.successor, &self.successor_signatures, &message)?; + + // Open the step. Flags and absent notes need no checks of their own: the hash ties every + // element to the one Bedrock's program spend constrained. + let elements = self + .step + .elements() + .into_iter() + .map(|element| FpVar::new_witness(cs.clone(), || Ok(element))) + .collect::, _>>()?; + let mut opened_step = Sponge::new(); + opened_step.absorb(&FpVar::constant(domain_tag(STEP_ID_DST)))?; + for element in &elements { + opened_step.absorb(element)?; + } + opened_step.finalize()?.enforce_equal(&step_id)?; + let (inputs, outputs) = elements.split_at(MAX_INPUTS * INPUT_FIELDS); + let (inputs, _) = inputs.as_chunks::(); + let (outputs, _) = outputs.as_chunks::(); + + // Every consumed note belongs to the committee. + for [active, _value, _nonce, _public_key, _stake_public_key, data] in inputs { + active.mul_equals(&(data - &committee), &zero)?; + } + + for [ + _active, + _value, + _nonce, + public_key, + stake_public_key, + program, + data, + ] in outputs + { + // A vault note does not stake, and goes to the successor. + program.mul_equals(stake_public_key, &zero)?; + program.mul_equals(&(data - &successor), &zero)?; + + // A payout stakes under its payee's key, so vault value is never staked under + // another's. + stake_public_key.conditional_enforce_equal(public_key, &program.is_eq(&zero)?)?; + } + + // Open the deposits: each was made out to the committee. The hash covers a variable + // count, so the digest of every prefix is computed and the one at the count is kept. + let present = (0..MAX_DEPOSITS) + .map(|slot| Boolean::new_witness(cs.clone(), || Ok(slot < self.deposits.len()))) + .collect::, _>>()?; + let count = present.iter().fold(zero.clone(), |count, flag| { + count + FpVar::from(flag.clone()) + }); + let mut prefix = Sponge::new(); + prefix.absorb(&FpVar::constant(domain_tag(DEPOSITS_DST)))?; + prefix.absorb(&count)?; + let mut opened_deposits = zero.clone(); + let mut previous = one; + for (slot, flag) in present.iter().enumerate() { + let deposit = self.deposits.get(slot).copied().unwrap_or_default(); + let value = FpVar::new_witness(cs.clone(), || Ok(Fr::from(deposit.value)))?; + let recipient = FpVar::new_witness(cs.clone(), || Ok(deposit.recipient))?; + let intent = digest(&[ + FpVar::constant(domain_tag(INTENT_DST)), + committee.clone(), + recipient, + ])?; + + // The count is `slot` exactly when the previous slot is filled and this one is not. + // The difference is a bit only if the filled slots come first. + let flag = FpVar::from(flag.clone()); + let ends_here = &previous - &flag; + ends_here.mul_equals(&(&ends_here - FpVar::one()), &zero)?; + opened_deposits += ends_here * prefix.clone().finalize()?; + + prefix.absorb(&value)?; + prefix.absorb(&intent)?; + previous = flag; + } + opened_deposits += previous * prefix.finalize()?; + opened_deposits.enforce_equal(&deposits_hash) + } +} + +/// Opens `committee` and checks that its threshold signed `message`. Returns its id. +fn authorize( + cs: &ConstraintSystemRef, + committee: &Committee, + signatures: &[Option], + message: &[FpVar; 3], +) -> Result, SynthesisError> { + let zero = FpVar::::zero(); + + // Allocation checks each key is in the prime-order subgroup. + let threshold = FpVar::new_witness(cs.clone(), || Ok(Fr::from(committee.threshold)))?; + let signers = committee + .padded_signers() + .into_iter() + .map(|key| EdwardsVar::new_witness(cs.clone(), || Ok(key.into_group()))) + .collect::, _>>()?; + let mut id = Sponge::new(); + id.absorb(&FpVar::constant(domain_tag(COMMITTEE_DST)))?; + id.absorb(&threshold)?; + for key in &signers { + id.absorb(&key.x)?; + id.absorb(&key.y)?; + } + + // With no signature needed, anyone could move the notes. + threshold.enforce_not_equal(&zero)?; + + // s·B == R + e·A for each signing member. + let generator = EdwardsVar::constant(EdwardsAffine::generator().into_group()); + let mut signed = zero.clone(); + for (slot, signer) in signers.iter().enumerate() { + let signature = signatures.get(slot).copied().flatten(); + let enabled = Boolean::new_witness(cs.clone(), || Ok(signature.is_some()))?; + let signature = signature.unwrap_or(Signature { + r: EdwardsAffine::zero(), + s: Scalar::ZERO, + }); + let r = EdwardsVar::new_witness(cs.clone(), || Ok(signature.r.into_group()))?; + let s = signature + .s + .into_bigint() + .to_bits_le() + .into_iter() + .take(usize::try_from(Scalar::MODULUS_BIT_SIZE).expect("a bit size fits a usize")) + .map(|bit| Boolean::new_witness(cs.clone(), || Ok(bit))) + .collect::, _>>()?; + + let [step_id, deposits_hash, op_id] = message.clone(); + let challenge = digest(&[ + FpVar::constant(domain_tag(SIGNATURE_DST)), + r.x.clone(), + r.y.clone(), + signer.x.clone(), + signer.y.clone(), + step_id, + deposits_hash, + op_id, + ])?; + let left = generator.scalar_mul_le(s.iter())?; + let right = signer.scalar_mul_le(challenge.to_bits_le()?.iter())? + &r; + left.conditional_enforce_equal(&right, &enabled)?; + + // An unused slot holds the identity, under which anyone can sign. In the subgroup it + // is the only point with a zero x. + let enabled = FpVar::from(enabled); + enabled.mul_equals(&FpVar::from(signer.x.is_eq(&zero)?), &zero)?; + signed += enabled; + } + signed.enforce_equal(&threshold)?; + id.finalize() +} diff --git a/lez/vault_circuit/src/lib.rs b/lez/vault_circuit/src/lib.rs new file mode 100644 index 0000000000..d9385460a3 --- /dev/null +++ b/lez/vault_circuit/src/lib.rs @@ -0,0 +1,727 @@ +//! The rule of the LEZ vault, a Bedrock program holding the value behind bridged tokens. +//! +//! Bedrock's own program spend proof covers conservation and note membership. This proof adds +//! that the committee named by the vault notes signed the inscription, that the deposits it +//! consumes were made out to that committee, and that the notes it creates are well formed. + +#![expect( + clippy::arithmetic_side_effects, + reason = "Field and curve arithmetic does not overflow" +)] + +use std::sync::LazyLock; + +use ark_bn254::{Bn254, Fr}; +use ark_ec::{AffineRepr as _, CurveGroup as _}; +use ark_ed_on_bn254::{EdwardsAffine, Fr as Scalar}; +use ark_ff::{BigInteger as _, PrimeField as _}; +use ark_groth16::{Groth16, ProvingKey, VerifyingKey}; +use ark_relations::r1cs::SynthesisError; +use logos_blockchain_groth16::{ + CompressedGroth16Proof, CompressedGroth16VerificationKey, Groth16Proof, Groth16VerificationKey, +}; +use logos_blockchain_poseidon2::{Digest as _, Poseidon2Bn254Hasher}; +use rand::{CryptoRng, RngCore, SeedableRng as _}; +use rand_chacha::ChaCha20Rng; +use sha2::{Digest as _, Sha512}; + +pub use crate::circuit::VaultCircuit; + +mod circuit; +mod poseidon2; + +/// The capacity of Bedrock's program spend. +pub const MAX_INPUTS: usize = 4; +pub const MAX_OUTPUTS: usize = 8; +/// The most members a committee holds. +pub const MAX_SIGNERS: usize = 4; +/// The most program deposits one step consumes. +pub const MAX_DEPOSITS: usize = 4; +/// The size of a program key in Bedrock's encoding. +pub const VERIFICATION_KEY_SIZE: usize = 352; +/// The verification key of [`demo_proving_key`], as `PROGRAM_REGISTER` takes it. +pub const DEMO_VERIFICATION_KEY: &[u8; VERIFICATION_KEY_SIZE] = + include_bytes!("../demo_verification_key.bin"); + +const DEMO_SETUP_SEED: u64 = 0x4c45_5a5f_5641_554c; + +const STEP_ID_DST: &[u8] = b"PROGRAM_STEP_ID_V1"; +const DEPOSITS_DST: &[u8] = b"PROGRAM_DEPOSITS_V1"; +const COMMITTEE_DST: &[u8] = b"LEZ_VAULT_COMMITTEE_V1"; +const INTENT_DST: &[u8] = b"LEZ_VAULT_INTENT_V1"; +const SIGNATURE_DST: &[u8] = b"LEZ_VAULT_SIG_V1"; + +/// The keys that move the vault notes carrying its id, and how many of them must sign. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Committee { + pub threshold: u64, + /// At most [`MAX_SIGNERS`]. + pub signers: Vec, +} + +impl Committee { + /// The value a vault note carries in its `data` to name this committee. + #[must_use] + pub fn id(&self) -> Fr { + let mut preimage = vec![domain_tag(COMMITTEE_DST), Fr::from(self.threshold)]; + for key in self.padded_signers() { + preimage.extend([key.x, key.y]); + } + Poseidon2Bn254Hasher::digest(&preimage) + } + + /// The signers, with the identity in the unused slots. + pub(crate) fn padded_signers(&self) -> [EdwardsAffine; MAX_SIGNERS] { + assert!( + self.signers.len() <= MAX_SIGNERS, + "a committee holds at most {MAX_SIGNERS} signers" + ); + std::array::from_fn(|slot| { + self.signers + .get(slot) + .copied() + .unwrap_or_else(EdwardsAffine::zero) + }) + } +} + +/// A program deposit a step consumes, with the opening of its intent. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Deposit { + pub value: u64, + /// Who the zone credits. Opaque to the circuit. + pub recipient: Fr, +} + +impl Deposit { + /// The recipient of a deposit crediting the zone account `account_id`. + #[must_use] + pub fn recipient_element(account_id: &[u8; 32]) -> Fr { + Fr::from_le_bytes_mod_order(account_id) + } + + /// The intent the depositor signs: it pays `recipient` through the vault of `committee` only. + #[must_use] + pub fn intent(&self, committee: Fr) -> Fr { + Poseidon2Bn254Hasher::digest(&[domain_tag(INTENT_DST), committee, self.recipient]) + } +} + +/// A note the program spend consumes. Always a note of the program, held by `PK0`. +#[derive(Clone, Copy, Debug, Default)] +pub struct InputNote { + pub value: u64, + pub nonce: Fr, + pub public_key: Fr, + pub stake_public_key: Fr, + pub data: Fr, +} + +/// A note the program spend creates: a vault note when `program` is set, a payout otherwise. +#[derive(Clone, Copy, Debug, Default)] +pub struct OutputNote { + pub value: u64, + pub nonce: Fr, + pub public_key: Fr, + pub stake_public_key: Fr, + pub program: Fr, + pub data: Fr, +} + +/// The notes of one program spend, the preimage of its `program_step_id`. +#[derive(Clone, Debug, Default)] +pub struct Step { + pub inputs: [Option; MAX_INPUTS], + pub outputs: [Option; MAX_OUTPUTS], +} + +impl Step { + /// The elements Bedrock hashes after the domain tag: a flag then the fields of each note, an + /// absent note reading as zeros. + pub(crate) fn elements(&self) -> Vec { + let inputs = self.inputs.iter().flat_map(|input| { + input.map_or([Fr::from(0_u64); 6], |note| { + [ + Fr::from(1_u64), + Fr::from(note.value), + note.nonce, + note.public_key, + note.stake_public_key, + note.data, + ] + }) + }); + let outputs = self.outputs.iter().flat_map(|output| { + output.map_or([Fr::from(0_u64); 7], |note| { + [ + Fr::from(1_u64), + Fr::from(note.value), + note.nonce, + note.public_key, + note.stake_public_key, + note.program, + note.data, + ] + }) + }); + inputs.chain(outputs).collect() + } + + /// Bedrock's `program_step_id`. + #[must_use] + pub fn id(&self) -> Fr { + let mut preimage = vec![domain_tag(STEP_ID_DST)]; + preimage.extend(self.elements()); + Poseidon2Bn254Hasher::digest(&preimage) + } +} + +/// The public inputs of a program proof, in Bedrock's order. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PublicInputs { + pub program_step_id: Fr, + pub program_deposits_hash: Fr, + pub op_id: Fr, +} + +impl PublicInputs { + /// An operation id as the third input: Bedrock reduces its bytes into the field. + #[must_use] + pub fn op_id_element(op_id: &[u8; 32]) -> Fr { + Fr::from_le_bytes_mod_order(op_id) + } + + #[must_use] + pub const fn to_array(&self) -> [Fr; 3] { + [self.program_step_id, self.program_deposits_hash, self.op_id] + } +} + +/// A committee member's key on Baby Jubjub. +#[derive(Clone)] +pub struct SigningKey(Scalar); + +impl SigningKey { + /// Derives the key from the seed of the sequencer's Ed25519 channel key. + #[must_use] + pub fn from_channel_seed(seed: &[u8; 32]) -> Self { + Self(hash_to_scalar(&[b"LEZ/vault-signing/v1", seed])) + } + + pub fn public_key(&self) -> EdwardsAffine { + (EdwardsAffine::generator() * self.0).into_affine() + } + + /// Authorizes the program step of one inscription. + #[must_use] + pub fn sign(&self, public: &PublicInputs) -> Signature { + let message: Vec = public + .to_array() + .iter() + .flat_map(|element| element.into_bigint().to_bytes_le()) + .collect(); + let secret = self.0.into_bigint().to_bytes_le(); + let nonce = hash_to_scalar(&[b"LEZ/vault-nonce/v1", &secret, &message]); + let r = (EdwardsAffine::generator() * nonce).into_affine(); + let e = challenge(&r, &self.public_key(), public); + Signature { + r, + s: nonce + e * self.0, + } + } +} + +/// A Schnorr signature over the public inputs of a program proof. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Signature { + pub r: EdwardsAffine, + pub s: Scalar, +} + +impl Signature { + #[must_use] + pub fn verify(&self, signer: &EdwardsAffine, public: &PublicInputs) -> bool { + let e = challenge(&self.r, signer, public); + EdwardsAffine::generator() * self.s == self.r + *signer * e + } +} + +/// Bedrock's `program_deposits_hash` over the value and intent of each deposit. +#[must_use] +pub fn deposits_hash(deposits: &[(u64, Fr)]) -> Fr { + let count = u64::try_from(deposits.len()).expect("a deposit count fits a u64"); + let mut preimage = vec![domain_tag(DEPOSITS_DST), Fr::from(count)]; + for (value, intent) in deposits { + preimage.extend([Fr::from(*value), *intent]); + } + Poseidon2Bn254Hasher::digest(&preimage) +} + +/// Generates the keys of the circuit. The registered program is their verification key, the +/// same for every committee. +/// +/// Whoever knows the randomness can forge proofs, so a real deployment needs a ceremony. +pub fn setup(rng: &mut (impl RngCore + CryptoRng)) -> Result, SynthesisError> { + let blank = VaultCircuit { + committee: Committee::default(), + step: Step::default(), + deposits: vec![], + public: PublicInputs::default(), + signatures: vec![], + successor: Committee::default(), + successor_signatures: vec![], + }; + untraced(|| Groth16::::generate_random_parameters_with_reduction(blank, rng)) +} + +/// The keys of a setup whose randomness is public: anyone can forge proofs under them. For +/// demos and tests only. +#[must_use] +pub fn demo_proving_key() -> &'static ProvingKey { + static KEY: LazyLock> = LazyLock::new(|| { + setup(&mut ChaCha20Rng::seed_from_u64(DEMO_SETUP_SEED)).expect("the circuit has a setup") + }); + &KEY +} + +/// A verification key in the encoding `PROGRAM_REGISTER` takes. +#[must_use] +pub fn verification_key_bytes(key: &VerifyingKey) -> [u8; VERIFICATION_KEY_SIZE] { + let key = Groth16VerificationKey { + alpha_1: key.alpha_g1, + beta_2: key.beta_g2, + gamma_2: key.gamma_g2, + delta_2: key.delta_g2, + ic: key.gamma_abc_g1.clone(), + }; + CompressedGroth16VerificationKey::try_from(&key) + .expect("the points of a setup compress") + .to_bytes() + .try_into() + .expect("a key of three public inputs has the size of a program key") +} + +/// Proves `circuit`, in the encoding a program step carries. +/// +/// # Errors +/// +/// [`SynthesisError::Unsatisfiable`] when the assignment breaks the vault's rule: a release +/// build would otherwise hand back a proof that does not verify. +pub fn prove( + proving_key: &ProvingKey, + circuit: VaultCircuit, + rng: &mut (impl RngCore + CryptoRng), +) -> Result { + let public = circuit.public.to_array(); + let proof = untraced(|| { + Groth16::::create_random_proof_with_reduction(circuit, proving_key, rng) + })?; + let key = ark_groth16::prepare_verifying_key(&proving_key.vk); + if !Groth16::::verify_proof(&key, &proof, &public)? { + return Err(SynthesisError::Unsatisfiable); + } + Ok(CompressedGroth16Proof::try_from(&Groth16Proof { + pi_a: proof.a, + pi_b: proof.b, + pi_c: proof.c, + }) + .expect("the points of a proof compress")) +} + +/// Runs `synthesis` with no log subscriber. arkworks opens a span for every constraint, which a +/// subscriber records: enough of them to stall a setup and exhaust memory. +fn untraced(synthesis: impl FnOnce() -> T) -> T { + tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), synthesis) +} + +/// A domain tag as Bedrock encodes them: the bytes as a little-endian integer. +pub(crate) fn domain_tag(tag: &[u8]) -> Fr { + Fr::from_le_bytes_mod_order(tag) +} + +fn challenge(r: &EdwardsAffine, signer: &EdwardsAffine, public: &PublicInputs) -> Scalar { + let hash = Poseidon2Bn254Hasher::digest(&[ + domain_tag(SIGNATURE_DST), + r.x, + r.y, + signer.x, + signer.y, + public.program_step_id, + public.program_deposits_hash, + public.op_id, + ]); + Scalar::from_le_bytes_mod_order(&hash.into_bigint().to_bytes_le()) +} + +fn hash_to_scalar(parts: &[&[u8]]) -> Scalar { + let mut hasher = Sha512::new(); + for part in parts { + hasher.update(part); + } + Scalar::from_le_bytes_mod_order(&hasher.finalize()) +} + +#[cfg(test)] +mod tests { + use ark_relations::r1cs::{ConstraintSynthesizer as _, ConstraintSystem}; + use logos_blockchain_core::mantle::{ + ops::channel::program_step::{ProgramDeposit, program_deposits_hash}, + programs::{ + ProgramVerificationKey, RegisteredProgram, SpendInputFields, SpendOutputFields, + program_step_id, + }, + }; + use logos_blockchain_key_management_system_keys::keys::ZkPublicKey; + + use super::*; + + const VAULT_PROGRAM: u64 = 0xBEEF; + + fn key(seed: u8) -> SigningKey { + SigningKey::from_channel_seed(&[seed; 32]) + } + + fn committee() -> Committee { + Committee { + threshold: 2, + signers: vec![ + key(1).public_key(), + key(2).public_key(), + key(3).public_key(), + ], + } + } + + fn vault_note(value: u64, committee: &Committee) -> OutputNote { + OutputNote { + value, + nonce: Fr::from(11_u64), + public_key: Fr::from(42_u64), + stake_public_key: Fr::from(0_u64), + program: Fr::from(VAULT_PROGRAM), + data: committee.id(), + } + } + + fn payout(value: u64, payee: u64) -> OutputNote { + OutputNote { + value, + nonce: Fr::from(12_u64), + public_key: Fr::from(payee), + stake_public_key: Fr::from(payee), + program: Fr::from(0_u64), + data: Fr::from(0_u64), + } + } + + /// A step consuming a vault note of 100, paying 30 to a user and keeping 70. + fn withdraw_step() -> Step { + let mut step = Step::default(); + step.inputs[0] = Some(InputNote { + value: 100, + nonce: Fr::from(10_u64), + public_key: Fr::from(42_u64), + stake_public_key: Fr::from(0_u64), + data: committee().id(), + }); + step.outputs[0] = Some(vault_note(70, &committee())); + step.outputs[1] = Some(payout(30, 1234)); + step + } + + /// The step and deposits made out to `committee()`, signed by its first two members. + fn circuit(step: Step, deposits: Vec) -> VaultCircuit { + let committee = committee(); + let intents: Vec<_> = deposits + .iter() + .map(|deposit| (deposit.value, deposit.intent(committee.id()))) + .collect(); + let public = PublicInputs { + program_step_id: step.id(), + program_deposits_hash: deposits_hash(&intents), + op_id: Fr::from(6_u64), + }; + let signatures = vec![Some(key(1).sign(&public)), Some(key(2).sign(&public))]; + VaultCircuit { + committee: committee.clone(), + step, + deposits, + public, + signatures: signatures.clone(), + successor: committee, + successor_signatures: signatures, + } + } + + fn is_satisfied(circuit: VaultCircuit) -> bool { + let cs = ConstraintSystem::new_ref(); + // An assignment the gadgets cannot complete, such as the inverse of zero, is refused too. + circuit.generate_constraints(cs.clone()).is_ok() && cs.is_satisfied().unwrap() + } + + #[test] + fn step_id_matches_bedrock() { + let step = withdraw_step(); + let inputs = step.inputs.map(|input| { + input.map_or_else(SpendInputFields::inactive, |note| SpendInputFields { + active: true, + value: note.value, + nonce: note.nonce, + public_key: ZkPublicKey::new(note.public_key), + stake_public_key: ZkPublicKey::new(note.stake_public_key), + data: note.data, + }) + }); + let outputs = step.outputs.map(|output| { + output.map_or_else(SpendOutputFields::inactive, |note| SpendOutputFields { + active: true, + value: note.value, + nonce: note.nonce, + public_key: ZkPublicKey::new(note.public_key), + stake_public_key: ZkPublicKey::new(note.stake_public_key), + program: note.program, + data: note.data, + }) + }); + + assert_eq!(step.id(), program_step_id(&inputs, &outputs)); + } + + #[test] + fn deposits_hash_matches_bedrock() { + let deposit = |value, intent| ProgramDeposit { + value, + intent, + ..ProgramDeposit::sample() + }; + let (first, second) = (deposit(5, Fr::from(8_u64)), deposit(7, Fr::from(9_u64))); + + assert_eq!(deposits_hash(&[]), program_deposits_hash(&[])); + assert_eq!( + deposits_hash(&[(5, Fr::from(8_u64)), (7, Fr::from(9_u64))]), + program_deposits_hash(&[&first, &second]) + ); + } + + #[test] + fn signature_verifies_only_for_its_inputs_and_signer() { + let public = PublicInputs { + op_id: Fr::from(1_u64), + ..PublicInputs::default() + }; + let signature = key(1).sign(&public); + let other_op = PublicInputs { + op_id: Fr::from(2_u64), + ..public + }; + + assert!(signature.verify(&key(1).public_key(), &public)); + assert!(!signature.verify(&key(1).public_key(), &other_op)); + assert!(!signature.verify(&key(2).public_key(), &public)); + } + + #[test] + fn withdraw_step_satisfies_the_rule() { + assert!(is_satisfied(circuit(withdraw_step(), vec![]))); + } + + #[test] + fn signature_over_another_inscription_is_refused() { + let mut circuit = circuit(withdraw_step(), vec![]); + circuit.public.op_id = Fr::from(999_u64); + assert!(!is_satisfied(circuit)); + } + + #[test] + fn fewer_signatures_than_the_threshold_are_refused() { + let mut circuit = circuit(withdraw_step(), vec![]); + circuit.signatures[1] = None; + assert!(!is_satisfied(circuit)); + } + + #[test] + fn signature_of_a_stranger_is_refused() { + let mut circuit = circuit(withdraw_step(), vec![]); + circuit.signatures[1] = Some(key(9).sign(&circuit.public)); + assert!(!is_satisfied(circuit)); + } + + /// Anyone can sign under the identity key that fills an unused slot. + #[test] + fn signature_in_an_unused_slot_is_refused() { + let mut circuit = circuit(withdraw_step(), vec![]); + let s = Scalar::from(5_u64); + circuit.signatures = vec![ + Some(key(1).sign(&circuit.public)), + None, + None, + Some(Signature { + r: (EdwardsAffine::generator() * s).into_affine(), + s, + }), + ]; + circuit.successor_signatures = circuit.signatures.clone(); + assert!(!is_satisfied(circuit)); + } + + #[test] + fn note_of_another_committee_is_refused() { + let mut circuit = circuit(withdraw_step(), vec![]); + circuit.committee.signers[2] = key(9).public_key(); + assert!(!is_satisfied(circuit)); + } + + fn successor() -> Committee { + Committee { + threshold: 1, + signers: vec![key(9).public_key()], + } + } + + /// `committee()` handing the vault over to `successor()`, not yet signed by the latter. + fn hand_over() -> VaultCircuit { + let mut step = withdraw_step(); + step.outputs[0] = Some(vault_note(70, &successor())); + let mut circuit = circuit(step, vec![]); + circuit.successor = successor(); + circuit.successor_signatures = vec![]; + circuit + } + + #[test] + fn committee_hands_the_vault_to_a_successor_that_signs() { + let mut circuit = hand_over(); + circuit.successor_signatures = vec![Some(key(9).sign(&circuit.public))]; + assert!(is_satisfied(circuit)); + } + + #[test] + fn hand_over_to_a_successor_that_did_not_sign_is_refused() { + assert!(!is_satisfied(hand_over())); + } + + #[test] + fn vault_note_naming_neither_committee_is_refused() { + let mut step = withdraw_step(); + step.outputs[0] = Some(vault_note(70, &successor())); + assert!(!is_satisfied(circuit(step, vec![]))); + } + + #[test] + fn committee_needing_no_signature_is_refused() { + let mut circuit = hand_over(); + circuit.successor = Committee { + threshold: 0, + signers: vec![], + }; + circuit.step.outputs[0] = Some(vault_note(70, &circuit.successor)); + circuit.public.program_step_id = circuit.step.id(); + circuit.signatures = vec![ + Some(key(1).sign(&circuit.public)), + Some(key(2).sign(&circuit.public)), + ]; + assert!(!is_satisfied(circuit)); + } + + #[test] + fn step_other_than_the_committed_one_is_refused() { + let mut circuit = circuit(withdraw_step(), vec![]); + circuit.step.outputs[1] = Some(payout(31, 1234)); + assert!(!is_satisfied(circuit)); + } + + #[test] + fn payout_its_payee_cannot_spend_is_refused() { + let mut step = withdraw_step(); + step.outputs[1] = Some(OutputNote { + stake_public_key: Fr::from(1_u64), + ..payout(30, 1234) + }); + assert!(!is_satisfied(circuit(step, vec![]))); + } + + #[test] + fn staked_vault_note_is_refused() { + let mut step = withdraw_step(); + step.outputs[0] = Some(OutputNote { + stake_public_key: Fr::from(1_u64), + ..vault_note(70, &committee()) + }); + assert!(!is_satisfied(circuit(step, vec![]))); + } + + #[test] + fn deposits_made_out_to_the_committee_are_consumed() { + let deposits = vec![ + Deposit { + value: 20, + recipient: Fr::from(77_u64), + }, + Deposit { + value: 5, + recipient: Fr::from(78_u64), + }, + ]; + let mut step = withdraw_step(); + step.outputs[0] = Some(vault_note(95, &committee())); + assert!(is_satisfied(circuit(step, deposits))); + } + + #[test] + fn deposit_made_out_to_another_committee_is_refused() { + let deposit = Deposit { + value: 20, + recipient: Fr::from(77_u64), + }; + let mut circuit = circuit(withdraw_step(), vec![deposit]); + let other = Committee { + threshold: 1, + signers: vec![key(9).public_key()], + }; + circuit.public.program_deposits_hash = + deposits_hash(&[(deposit.value, deposit.intent(other.id()))]); + circuit.signatures = vec![ + Some(key(1).sign(&circuit.public)), + Some(key(2).sign(&circuit.public)), + ]; + circuit.successor_signatures = circuit.signatures.clone(); + assert!(!is_satisfied(circuit)); + } + + #[test] + fn step_consuming_nothing_takes_the_deposits_in() { + let deposit = Deposit { + value: 50, + recipient: Fr::from(77_u64), + }; + let mut step = Step::default(); + step.outputs[0] = Some(vault_note(50, &committee())); + assert!(is_satisfied(circuit(step, vec![deposit]))); + } + + /// Run with `UPDATE_DEMO_KEY=1` after changing the circuit. + #[test] + fn demo_key_is_current_and_proves_for_bedrock() { + let proving_key = demo_proving_key(); + let key_bytes = verification_key_bytes(&proving_key.vk); + if std::env::var_os("UPDATE_DEMO_KEY").is_some() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/demo_verification_key.bin"); + std::fs::write(path, key_bytes).unwrap(); + } + assert_eq!(&key_bytes, DEMO_VERIFICATION_KEY); + + let circuit = circuit(withdraw_step(), vec![]); + let public = circuit.public.to_array(); + let proof = prove(proving_key, circuit, &mut ChaCha20Rng::seed_from_u64(1)).unwrap(); + + let program = RegisteredProgram::new( + ProgramVerificationKey::try_from_bytes(DEMO_VERIFICATION_KEY).unwrap(), + ) + .unwrap(); + assert!(program.verify(&proof, &public).unwrap()); + + let mut other_op = public; + other_op[2] = Fr::from(999_u64); + assert!(!program.verify(&proof, &other_op).unwrap()); + } +} diff --git a/lez/vault_circuit/src/poseidon2.rs b/lez/vault_circuit/src/poseidon2.rs new file mode 100644 index 0000000000..3a1c62377f --- /dev/null +++ b/lez/vault_circuit/src/poseidon2.rs @@ -0,0 +1,106 @@ +//! Bedrock's Poseidon2 sponge (BN254, state of 3, rate 1) as R1CS constraints. + +use ark_bn254::Fr; +use ark_r1cs_std::fields::{FieldVar as _, fp::FpVar}; +use ark_relations::r1cs::SynthesisError; +use jf_poseidon2::{Poseidon2Params as _, constants::bn254::Poseidon2ParamsBn3 as Params}; + +/// The state of a hash in progress, mirroring `lb_poseidon2::Poseidon2Hasher`. +#[derive(Clone)] +pub struct Sponge([FpVar; 3]); + +impl Sponge { + pub fn new() -> Self { + Self([FpVar::zero(), FpVar::zero(), FpVar::zero()]) + } + + pub fn absorb(&mut self, input: &FpVar) -> Result<(), SynthesisError> { + self.0[0] += input; + permute(&mut self.0) + } + + pub fn finalize(mut self) -> Result, SynthesisError> { + self.absorb(&FpVar::one())?; + let [digest, _, _] = self.0; + Ok(digest) + } +} + +/// `lb_poseidon2::Digest::digest` over variables. +pub fn digest(inputs: &[FpVar]) -> Result, SynthesisError> { + let mut sponge = Sponge::new(); + for input in inputs { + sponge.absorb(input)?; + } + sponge.finalize() +} + +fn permute(state: &mut [FpVar; 3]) -> Result<(), SynthesisError> { + let external_rc = Params::external_rc(); + let (initial, terminal) = external_rc.split_at(external_rc.len().div_euclid(2)); + + external_matrix(state); + for rc in initial { + external_round(state, rc)?; + } + for rc in Params::internal_rc() { + state[0] += *rc; + state[0] = sbox(&state[0])?; + let sum = &state[0] + &state[1] + &state[2]; + state[0] += ∑ + state[1] += ∑ + state[2] = state[2].double()? + ∑ + } + for rc in terminal { + external_round(state, rc)?; + } + Ok(()) +} + +fn external_round(state: &mut [FpVar; 3], constants: &[Fr; 3]) -> Result<(), SynthesisError> { + for (element, rc) in state.iter_mut().zip(constants) { + *element += *rc; + *element = sbox(element)?; + } + external_matrix(state); + Ok(()) +} + +fn external_matrix(state: &mut [FpVar; 3]) { + let sum = &state[0] + &state[1] + &state[2]; + for element in state { + *element += ∑ + } +} + +fn sbox(x: &FpVar) -> Result, SynthesisError> { + debug_assert_eq!(Params::D, 5, "the s-box below is x^5"); + Ok(x.square()?.square()? * x) +} + +#[cfg(test)] +mod tests { + use ark_ff::Field as _; + use ark_r1cs_std::{R1CSVar as _, alloc::AllocVar as _}; + use ark_relations::r1cs::ConstraintSystem; + use logos_blockchain_poseidon2::{Digest as _, Poseidon2Bn254Hasher}; + + use super::*; + + #[test] + fn gadget_matches_bedrock_hash() { + for len in [0_u64, 1, 2, 3, 7] { + let inputs: Vec = (0..len).map(|i| Fr::from(i).pow([5]) + Fr::ONE).collect(); + let cs = ConstraintSystem::new_ref(); + let vars: Vec<_> = inputs + .iter() + .map(|input| FpVar::new_witness(cs.clone(), || Ok(*input)).unwrap()) + .collect(); + + let hash = digest(&vars).unwrap(); + + assert_eq!(hash.value().unwrap(), Poseidon2Bn254Hasher::digest(&inputs)); + assert!(cs.is_satisfied().unwrap()); + } + } +} diff --git a/test_fixtures/fixtures/prebuilt_sequencer_db.dump b/test_fixtures/fixtures/prebuilt_sequencer_db.dump index e6de62670d..122ef622aa 100644 Binary files a/test_fixtures/fixtures/prebuilt_sequencer_db.dump and b/test_fixtures/fixtures/prebuilt_sequencer_db.dump differ diff --git a/test_fixtures/src/bin/regenerate_test_fixture.rs b/test_fixtures/src/bin/regenerate_test_fixture.rs index d01a47eb1a..c989955340 100644 --- a/test_fixtures/src/bin/regenerate_test_fixture.rs +++ b/test_fixtures/src/bin/regenerate_test_fixture.rs @@ -131,11 +131,7 @@ async fn generate_prebuilt_fixture(dest: &Path) -> Result<()> { final_snapshot: Some((state, tip)), // Blocks must stay Pending for the re-publish; only the snapshot moves. finalized_up_to: None, - new_deposit_events: vec![], - finalized_deposit_records: HashSet::new(), finalized_dispatch_records: HashSet::new(), - consumed_withdrawals: HashSet::new(), - new_withdraw_intents: HashSet::new(), zone_anchor: None, events: vec![], }) diff --git a/test_fixtures/src/config.rs b/test_fixtures/src/config.rs index 4932999785..c5d4ac5f6b 100644 --- a/test_fixtures/src/config.rs +++ b/test_fixtures/src/config.rs @@ -66,7 +66,7 @@ const PRIVATE_FUNDER_ACCOUNT_SEED: [u8; 32] = [0x11; 32]; /// Funding key of the Bedrock test node, matching `funding_pk` in `bedrock/node-config.yaml`. const BEDROCK_FUNDING_KEY_HEX: &str = - "2e03b2eff5a45478e7e79668d2a146cf2c5c7925bce927f2b1c67f2ab4fc0d26"; + "756b77fcff387d7358943535aca10505f1bda72343ceadf45433c5dbf4e2c903"; #[derive(Clone)] pub struct InitialPrivateAccountForWallet {