From cc6b835a8f738572743d78793b0518b7cc1809f9 Mon Sep 17 00:00:00 2001 From: cboh4 Date: Mon, 17 Nov 2025 22:08:17 +0200 Subject: [PATCH 1/5] enable cron --- cosmwasm/enclaves/Cargo.lock | 6 +-- cosmwasm/enclaves/execute/Cargo.toml | 6 +-- cosmwasm/enclaves/execute/Enclave.edl | 4 +- cosmwasm/enclaves/execute/src/ecalls.rs | 4 -- .../enclaves/shared/block-verifier/Cargo.toml | 6 +-- .../src/submit_block_signatures.rs | 50 ------------------- .../block-verifier/src/verify/header.rs | 1 - cosmwasm/enclaves/shared/utils/Cargo.toml | 4 +- cosmwasm/packages/sgx-vm/src/random.rs | 8 +-- deployment/dockerfiles/Dockerfile | 2 +- go-cosmwasm/api/bindings.h | 1 - go-cosmwasm/api/lib.go | 6 +-- go-cosmwasm/api/lib_mock.go | 2 +- go-cosmwasm/src/lib.rs | 9 +--- go.mod | 4 +- go.sum | 8 +-- x/compute/module.go | 47 +++++++++-------- 17 files changed, 48 insertions(+), 120 deletions(-) diff --git a/cosmwasm/enclaves/Cargo.lock b/cosmwasm/enclaves/Cargo.lock index 821004c2b..07a236037 100644 --- a/cosmwasm/enclaves/Cargo.lock +++ b/cosmwasm/enclaves/Cargo.lock @@ -2206,7 +2206,7 @@ dependencies = [ [[package]] name = "tendermint" version = "0.38.0" -source = "git+https://github.com/scrtlabs/tendermint-rs?tag=v0.38.0-secret.6#9067bdcfec84b0fcfa1ef76eba143a73a766e5cf" +source = "git+https://github.com/scrtlabs/tendermint-rs?tag=v0.38.0-secret.7-beta#945e948889ddc56414d081efd56a7b7ca7449aa4" dependencies = [ "bytes 1.7.1", "digest 0.10.7", @@ -2234,7 +2234,7 @@ dependencies = [ [[package]] name = "tendermint-light-client-verifier" version = "0.38.0" -source = "git+https://github.com/scrtlabs/tendermint-rs?tag=v0.38.0-secret.6#9067bdcfec84b0fcfa1ef76eba143a73a766e5cf" +source = "git+https://github.com/scrtlabs/tendermint-rs?tag=v0.38.0-secret.7-beta#945e948889ddc56414d081efd56a7b7ca7449aa4" dependencies = [ "derive_more", "flex-error", @@ -2246,7 +2246,7 @@ dependencies = [ [[package]] name = "tendermint-proto" version = "0.38.0" -source = "git+https://github.com/scrtlabs/tendermint-rs?tag=v0.38.0-secret.6#9067bdcfec84b0fcfa1ef76eba143a73a766e5cf" +source = "git+https://github.com/scrtlabs/tendermint-rs?tag=v0.38.0-secret.7-beta#945e948889ddc56414d081efd56a7b7ca7449aa4" dependencies = [ "bytes 1.7.1", "flex-error", diff --git a/cosmwasm/enclaves/execute/Cargo.toml b/cosmwasm/enclaves/execute/Cargo.toml index 2302c8579..1116e8e5f 100644 --- a/cosmwasm/enclaves/execute/Cargo.toml +++ b/cosmwasm/enclaves/execute/Cargo.toml @@ -91,9 +91,9 @@ block-verifier = { path = "../shared/block-verifier", optional = true } time = "=0.3.17" ed25519-dalek = { version = "1.0", default-features = false } sha2 = "0.10" -tendermint = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.6", default-features = false, features = ["rust-crypto"] } -tendermint-proto = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.6", default-features = false } -tendermint-light-client-verifier = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.6", default-features = false, features = ["rust-crypto"] } +tendermint = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.7-beta", default-features = false, features = ["rust-crypto"] } +tendermint-proto = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.7-beta", default-features = false } +tendermint-light-client-verifier = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.7-beta", default-features = false, features = ["rust-crypto"] } rsa = { version = "0.9", default-features = false, features = ["sha2"] } base64ct = { version = "1.6", default-features = false, features = ["alloc"] } diff --git a/cosmwasm/enclaves/execute/Enclave.edl b/cosmwasm/enclaves/execute/Enclave.edl index e48e04c13..14c88f72f 100644 --- a/cosmwasm/enclaves/execute/Enclave.edl +++ b/cosmwasm/enclaves/execute/Enclave.edl @@ -219,9 +219,7 @@ enclave { [in, count=in_encrypted_random_len] const uint8_t* in_encrypted_random, uintptr_t in_encrypted_random_len, [out, count=32] uint8_t* decrypted, - [out, count=32] uint8_t* next_validator_set_evidence, - [in, count=in_cron_msgs_len] const uint8_t* in_cron_msgs, - uintptr_t in_cron_msgs_len + [out, count=32] uint8_t* next_validator_set_evidence ); }; diff --git a/cosmwasm/enclaves/execute/src/ecalls.rs b/cosmwasm/enclaves/execute/src/ecalls.rs index 146530dcf..be2b33ec2 100644 --- a/cosmwasm/enclaves/execute/src/ecalls.rs +++ b/cosmwasm/enclaves/execute/src/ecalls.rs @@ -17,8 +17,6 @@ pub unsafe extern "C" fn ecall_submit_block_signatures( in_encrypted_random_len: u32, decrypted_random: &mut [u8; 32], next_validator_set_evidence: &mut [u8; 32], - in_cron_msgs: *const u8, - in_cron_msgs_len: u32, ) -> sgx_status_t { #[cfg(feature = "light-client-validation")] { @@ -33,8 +31,6 @@ pub unsafe extern "C" fn ecall_submit_block_signatures( in_encrypted_random_len, decrypted_random, next_validator_set_evidence, - in_cron_msgs, - in_cron_msgs_len, ) } diff --git a/cosmwasm/enclaves/shared/block-verifier/Cargo.toml b/cosmwasm/enclaves/shared/block-verifier/Cargo.toml index a186f7586..889b9d3c2 100644 --- a/cosmwasm/enclaves/shared/block-verifier/Cargo.toml +++ b/cosmwasm/enclaves/shared/block-verifier/Cargo.toml @@ -19,9 +19,9 @@ sgx_types = { rev = "d2d339cbb005f676bb700059bd51dc689c025f6b", git = "https://g [dependencies] sha2 = "0.10" -tendermint = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.6", default-features = false, features = ["rust-crypto"] } -tendermint-proto = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.6", default-features = false } -tendermint-light-client-verifier = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.6", default-features = false, features = ["rust-crypto"] } +tendermint = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.7-beta", default-features = false, features = ["rust-crypto"] } +tendermint-proto = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.7-beta", default-features = false } +tendermint-light-client-verifier = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.7-beta", default-features = false, features = ["rust-crypto"] } lazy_static = "1.4.0" log = "0.4.17" diff --git a/cosmwasm/enclaves/shared/block-verifier/src/submit_block_signatures.rs b/cosmwasm/enclaves/shared/block-verifier/src/submit_block_signatures.rs index 16994ec9f..c0dec456e 100644 --- a/cosmwasm/enclaves/shared/block-verifier/src/submit_block_signatures.rs +++ b/cosmwasm/enclaves/shared/block-verifier/src/submit_block_signatures.rs @@ -37,8 +37,6 @@ pub unsafe fn submit_block_signatures_impl( in_encrypted_random_len: u32, decrypted_random: &mut [u8; 32], next_validator_set_evidence: &mut [u8; 32], - in_cron_msgs: *const u8, - in_cron_msgs_len: u32, ) -> sgx_status_t { if let Err(e) = validate_inputs( in_header, @@ -64,12 +62,6 @@ pub unsafe fn submit_block_signatures_impl( &[] }; - let cron_msgs_slice = if in_cron_msgs_len != 0 && !in_cron_msgs.is_null() { - slice::from_raw_parts(in_cron_msgs, in_cron_msgs_len as usize) - } else { - &[] - }; - let (validator_set, height) = { let extra = KEY_MANAGER.extra_data.lock().unwrap(); let validator_set = match extra.decode_validator_set() { @@ -94,20 +86,6 @@ pub unsafe fn submit_block_signatures_impl( let txs = unwrap_or_return!(crate::verify::txs::validate_txs(txs_slice, &header)); - let cron_msgs = if !cron_msgs_slice.is_empty() { - let msgs = crate::txs::txs_from_bytes(cron_msgs_slice).map_err(|e| { - error!("Error parsing cron msgs from proto: {:?}", e); - sgx_status_t::SGX_ERROR_INVALID_PARAMETER - }); - if msgs.is_err() { - error!("Error parsing cron msgs from proto: {:?}", msgs); - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER; - } - Some(msgs.unwrap()) - } else { - None - }; - let mut message_verifier = VERIFIED_BLOCK_MESSAGES.lock().unwrap(); if message_verifier.remaining() != 0 { @@ -115,34 +93,6 @@ pub unsafe fn submit_block_signatures_impl( message_verifier.clear(); } - if let Some(implicit_hash_val) = header.header.implicit_hash { - let mut hasher = Sha256::new(); - hasher.update(cron_msgs_slice); - let hash_result = hasher.finalize(); - let hash_result: [u8; 32] = hash_result.into(); - - let implicit_hash = tendermint::Hash::Sha256(hash_result); - - if implicit_hash != implicit_hash_val { - error!("Implicit hash does not match header implicit hash"); - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER; - } - } else if !cron_msgs_slice.is_empty() { - error!("Implicit hash not specified, yet implicit msgs provided"); - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER; - } - - if let Some(cron_msgs) = cron_msgs { - for msg in cron_msgs { - let parsed_cron_msg = unwrap_or_return!(tx_from_bytes(msg.as_slice()).map_err(|_| { - error!("Unable to parse tx bytes from proto"); - sgx_status_t::SGX_ERROR_INVALID_PARAMETER - })); - - message_verifier.append_msg_from_tx(parsed_cron_msg); - } - } - for tx in txs.iter() { // doing this a different way makes the code unreadable or requires creating a copy of diff --git a/cosmwasm/enclaves/shared/block-verifier/src/verify/header.rs b/cosmwasm/enclaves/shared/block-verifier/src/verify/header.rs index 7b193a843..85f6be11d 100644 --- a/cosmwasm/enclaves/shared/block-verifier/src/verify/header.rs +++ b/cosmwasm/enclaves/shared/block-verifier/src/verify/header.rs @@ -44,7 +44,6 @@ pub fn validate_block_header( signed_header: &signed_header, validators: validator_set, next_validators: None, - implicit_hash: signed_header.header.implicit_hash, }; let result = verify_block(&untrusted_block); diff --git a/cosmwasm/enclaves/shared/utils/Cargo.toml b/cosmwasm/enclaves/shared/utils/Cargo.toml index 8a6562617..15e479ce0 100644 --- a/cosmwasm/enclaves/shared/utils/Cargo.toml +++ b/cosmwasm/enclaves/shared/utils/Cargo.toml @@ -32,6 +32,6 @@ serde = { git = "https://github.com/mesalock-linux/serde-sgx", features = [ "derive" ] } serde_json = { git = "https://github.com/mesalock-linux/serde-json-sgx" } -tendermint-proto = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.6", default-features = false } -tendermint = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.6", default-features = false, features = ["rust-crypto"] } +tendermint-proto = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.7-beta", default-features = false } +tendermint = { git = "https://github.com/scrtlabs/tendermint-rs", tag = "v0.38.0-secret.7-beta", default-features = false, features = ["rust-crypto"] } enclave_crypto = { path = "../crypto" } diff --git a/cosmwasm/packages/sgx-vm/src/random.rs b/cosmwasm/packages/sgx-vm/src/random.rs index 3a4c9ced4..71ad149e6 100644 --- a/cosmwasm/packages/sgx-vm/src/random.rs +++ b/cosmwasm/packages/sgx-vm/src/random.rs @@ -18,8 +18,6 @@ extern "C" { in_encrypted_random_len: u32, decrypted_random: &mut [u8; 32], next_validator_set_evidence: &mut [u8; 32], - in_cron_msgs: *const u8, - in_cron_msgs_len: u32, ) -> sgx_status_t; } @@ -28,7 +26,6 @@ pub fn untrusted_submit_block_signatures( commit: &[u8], txs: &[u8], encrypted_random: &[u8], - cron_msgs: &[u8], ) -> SgxResult<([u8; 32], [u8; 32])> { debug!("Hello from just before - untrusted_submit_block_signatures"); @@ -39,7 +36,7 @@ pub fn untrusted_submit_block_signatures( // this is here so we can loop { let (retval, decrypted, next_validator_set_evidence, status) = - submit_block_signature_impl(header, commit, txs, encrypted_random, cron_msgs)?; + submit_block_signature_impl(header, commit, txs, encrypted_random)?; if status != sgx_status_t::SGX_SUCCESS { return Err(status); } else if retval != sgx_status_t::SGX_SUCCESS { @@ -69,7 +66,6 @@ fn submit_block_signature_impl( commit: &[u8], txs: &[u8], encrypted_random: &[u8], - cron_msgs: &[u8], ) -> SgxResult<(sgx_status_t, [u8; 32], [u8; 32], sgx_status_t)> { // Bind the token to a local variable to ensure its // destructor runs in the end of the function @@ -102,8 +98,6 @@ fn submit_block_signature_impl( encrypted_random.len() as u32, &mut random_decrypted, &mut next_validator_set_evidence, - cron_msgs.as_ptr(), - cron_msgs.len() as u32, ) }; diff --git a/deployment/dockerfiles/Dockerfile b/deployment/dockerfiles/Dockerfile index 612046b09..e1971f024 100644 --- a/deployment/dockerfiles/Dockerfile +++ b/deployment/dockerfiles/Dockerfile @@ -70,7 +70,7 @@ ENV FEATURES=${FEATURES} ENV FEATURES_U=${FEATURES_U} ENV MITIGATION_CVE_2020_0551=${MITIGATION_CVE_2020_0551} -RUN git clone --branch header-implicit-hash --depth 1 https://github.com/scrtlabs/tm-secret-enclave.git +RUN git clone --branch pass-scheduled-msgs --depth 1 https://github.com/scrtlabs/tm-secret-enclave.git WORKDIR tm-secret-enclave diff --git a/go-cosmwasm/api/bindings.h b/go-cosmwasm/api/bindings.h index 3438fc0e7..154702069 100644 --- a/go-cosmwasm/api/bindings.h +++ b/go-cosmwasm/api/bindings.h @@ -253,7 +253,6 @@ TwoBuffers submit_block_signatures(Buffer header, Buffer commit, Buffer txs, Buffer random, - Buffer cron_msgs, Buffer *err); void submit_validator_set_evidence(Buffer evidence, Buffer *err); diff --git a/go-cosmwasm/api/lib.go b/go-cosmwasm/api/lib.go index defeae218..04626d666 100644 --- a/go-cosmwasm/api/lib.go +++ b/go-cosmwasm/api/lib.go @@ -47,7 +47,7 @@ func HealthCheck() ([]byte, error) { return receiveVector(res), nil } -func SubmitBlockSignatures(header []byte, commit []byte, txs []byte, encRandom []byte, cronMsgs []byte /* valSet []byte, nextValSet []byte */) ([]byte, []byte, error) { +func SubmitBlockSignatures(header []byte, commit []byte, txs []byte, encRandom []byte /* valSet []byte, nextValSet []byte */) ([]byte, []byte, error) { errmsg := C.Buffer{} spidSlice := sendSlice(header) defer freeAfterSend(spidSlice) @@ -57,10 +57,8 @@ func SubmitBlockSignatures(header []byte, commit []byte, txs []byte, encRandom [ defer freeAfterSend(encRandomSlice) txsSlice := sendSlice(txs) defer freeAfterSend(txsSlice) - cronMsgsSlice := sendSlice(cronMsgs) - defer freeAfterSend(cronMsgsSlice) - res, err := C.submit_block_signatures(spidSlice, apiKeySlice, txsSlice, encRandomSlice, cronMsgsSlice /* valSetSlice, nextValSetSlice,*/, &errmsg) + res, err := C.submit_block_signatures(spidSlice, apiKeySlice, txsSlice, encRandomSlice /* valSetSlice, nextValSetSlice,*/, &errmsg) if err != nil { return nil, nil, errorWithMessage(err, errmsg) } diff --git a/go-cosmwasm/api/lib_mock.go b/go-cosmwasm/api/lib_mock.go index f25f6e643..78d8050d0 100644 --- a/go-cosmwasm/api/lib_mock.go +++ b/go-cosmwasm/api/lib_mock.go @@ -39,7 +39,7 @@ func InitBootstrap(spid []byte, apiKey []byte) ([]byte, error) { return nil, nil } -func SubmitBlockSignatures(header []byte, commit []byte, txs []byte, random []byte, cronmsgs []byte /* valSet []byte, nextValSet []byte*/) ([]byte, []byte, error) { +func SubmitBlockSignatures(header []byte, commit []byte, txs []byte, random []byte /* valSet []byte, nextValSet []byte*/) ([]byte, []byte, error) { return nil, nil, nil } diff --git a/go-cosmwasm/src/lib.rs b/go-cosmwasm/src/lib.rs index 1b8641a99..9783fbb00 100644 --- a/go-cosmwasm/src/lib.rs +++ b/go-cosmwasm/src/lib.rs @@ -247,7 +247,6 @@ pub extern "C" fn submit_block_signatures( commit: Buffer, txs: Buffer, random: Buffer, - cron_msgs: Buffer, // val_set: Buffer, // next_val_set: Buffer, err: Option<&mut Buffer>, @@ -286,10 +285,6 @@ pub extern "C" fn submit_block_signatures( Some(r) => r, }; - let cron_msgs_slice = match unsafe { cron_msgs.read() } { - None => &[], - Some(r) => r, - }; // let val_set_slice = match unsafe { val_set.read() } { // None => { // set_error(Error::empty_arg("api_key"), err); @@ -311,8 +306,8 @@ pub extern "C" fn submit_block_signatures( commit_slice, txs_slice, random_slice, - cron_msgs_slice, // val_set_slice, - // next_val_set_slice, + // val_set_slice, + // next_val_set_slice, ) { Err(e) => { set_error(Error::enclave_err(e.to_string()), err); diff --git a/go.mod b/go.mod index efe390012..e673ca9f9 100644 --- a/go.mod +++ b/go.mod @@ -8,8 +8,8 @@ replace ( cosmossdk.io/api => github.com/scrtlabs/cosmos-sdk-api v0.7.6-secret.0 cosmossdk.io/store => github.com/scrtlabs/cosmos-sdk-store v1.1.1-secret.1 cosmossdk.io/x/tx => github.com/scrtlabs/cosmos-sdk-x-tx v0.13.7-secret.0 - github.com/cometbft/cometbft => github.com/scrtlabs/tendermint v0.38.19-secret.0 - github.com/cosmos/cosmos-sdk => github.com/scrtlabs/cosmos-sdk v0.50.14-secret.4 + github.com/cometbft/cometbft => github.com/scrtlabs/tendermint v0.38.19-secret.1 + github.com/cosmos/cosmos-sdk => github.com/scrtlabs/cosmos-sdk v0.50.14-secret.5 github.com/cosmos/iavl => github.com/scrtlabs/iavl v1.2.2-secret.0 github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 diff --git a/go.sum b/go.sum index c381967a1..472802219 100644 --- a/go.sum +++ b/go.sum @@ -1609,8 +1609,8 @@ github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWR github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= -github.com/scrtlabs/cosmos-sdk v0.50.14-secret.4 h1:YU8JJIC2LGoZ3Z8+ezgv8WI21XKxVPMOUjsbaPtw+yc= -github.com/scrtlabs/cosmos-sdk v0.50.14-secret.4/go.mod h1:otdpIqWbky7zjfzbcoAOHC0BwHruG9MWemfMx9f+rKk= +github.com/scrtlabs/cosmos-sdk v0.50.14-secret.5 h1:iijErJT8ZbFHsFhhyLH0PywYQeeVT10i+EUsthfQOSg= +github.com/scrtlabs/cosmos-sdk v0.50.14-secret.5/go.mod h1:bTJf+E1t8wKEwwNcTYFBEuAcdEYWLGXv9QlMu089hUo= github.com/scrtlabs/cosmos-sdk-api v0.7.6-secret.0 h1:9IGLySVhC2qSrxT3fZvvqwjKsnXWSSKnywQDzT8y1Gs= github.com/scrtlabs/cosmos-sdk-api v0.7.6-secret.0/go.mod h1:IcxpYS5fMemZGqyYtErK7OqvdM0C8kdW3dq8Q/XIG38= github.com/scrtlabs/cosmos-sdk-store v1.1.1-secret.1 h1:TELtwBkSg0xBrs2ObFE0pVVWF6E31fPCDX2tk8OiJPo= @@ -1619,8 +1619,8 @@ github.com/scrtlabs/cosmos-sdk-x-tx v0.13.7-secret.0 h1:i3k5706sDHKhaCvzokB+n33/ github.com/scrtlabs/cosmos-sdk-x-tx v0.13.7-secret.0/go.mod h1:V6DImnwJMTq5qFjeGWpXNiT/fjgE4HtmclRmTqRVM3w= github.com/scrtlabs/iavl v1.2.2-secret.0 h1:P96PL1Lf8OBSW9pMrlaRxhceZ4z9Hc7jk12g9ShWeHw= github.com/scrtlabs/iavl v1.2.2-secret.0/go.mod h1:GiM43q0pB+uG53mLxLDzimxM9l/5N9UuSY3/D0huuVw= -github.com/scrtlabs/tendermint v0.38.19-secret.0 h1:LwmTBt3Wze8esiyV+EtkMzp5fUINnlovgOIXJbZFBnk= -github.com/scrtlabs/tendermint v0.38.19-secret.0/go.mod h1:dNi/ShIl1T2f3bCYdoDY2tU4cbKGeyFgWIJSFJ9HSBI= +github.com/scrtlabs/tendermint v0.38.19-secret.1 h1:NxZ21CS6INBjL2QCL087/BJLb1NAIeoY07mHasTuqKs= +github.com/scrtlabs/tendermint v0.38.19-secret.1/go.mod h1:CZUJG1djTJUVbpjGS9JmQx9CFfF4goKi3LzYUQtxWO8= github.com/scrtlabs/tm-secret-enclave v1.13.0 h1:a2xH0G96chEM8Ntwlq/Fh36r4dg0ijKWTaOy0oqFsqg= github.com/scrtlabs/tm-secret-enclave v1.13.0/go.mod h1:nxZQtzzAqBNBLOEXSv4cKlUnVA4vRmHOn6ujr3kxVME= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= diff --git a/x/compute/module.go b/x/compute/module.go index 759616674..99b1b0435 100644 --- a/x/compute/module.go +++ b/x/compute/module.go @@ -2,7 +2,6 @@ package compute import ( "context" - "crypto/sha256" "encoding/json" "github.com/grpc-ecosystem/grpc-gateway/runtime" @@ -16,10 +15,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/scrtlabs/SecretNetwork/go-cosmwasm/api" + wasmtypes "github.com/scrtlabs/SecretNetwork/go-cosmwasm/types" "github.com/scrtlabs/SecretNetwork/x/compute/client/cli" "github.com/scrtlabs/SecretNetwork/x/compute/internal/keeper" "github.com/scrtlabs/SecretNetwork/x/compute/internal/types" tmenclave "github.com/scrtlabs/tm-secret-enclave" + + crontypes "github.com/scrtlabs/SecretNetwork/x/cron/types" ) var ( @@ -159,14 +161,12 @@ func (am AppModule) BeginBlock(c context.Context) error { ctx := c.(sdk.Context) block_header := ctx.BlockHeader() - // execCronMsgs, bytesCronMsgs, err := am.keeper.GetScheduledMsgs(ctx, crontypes.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) - // if err != nil { - // ctx.Logger().Error("Failed to get scheduled cron msgs") - // return err - // } + execCronMsgs, bytesCronMsgs, err := am.keeper.GetScheduledMsgs(ctx, crontypes.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) + if err != nil { + ctx.Logger().Error("Failed to get scheduled cron msgs") + return err + } - cron_msgs := tm_type.Data{Txs: [][]byte{}} - cron_data, err := cron_msgs.Marshal() if err != nil { ctx.Logger().Error("Failed to marshal cron_msgs") return err @@ -194,19 +194,19 @@ func (am AppModule) BeginBlock(c context.Context) error { } if block_header.EncryptedRandom != nil { randomAndProof := append(block_header.EncryptedRandom.Random, block_header.EncryptedRandom.Proof...) - random, validator_set_evidence, err := api.SubmitBlockSignatures(header, b_commit, data, randomAndProof, cron_data) + random, validator_set_evidence, err := api.SubmitBlockSignatures(header, b_commit, data, randomAndProof) if err != nil { ctx.Logger().Error("Failed to submit block signatures") return err } - // for idx, msg := range execCronMsgs { - // ctx = ctx.WithTxBytes(bytesCronMsgs[idx]) - // _, err := am.keeper.Execute(ctx, msg.Contract, msg.Sender, msg.Msg, msg.SentFunds, msg.CallbackSig, wasmtypes.HandleTypeExecute) - // if err != nil { - // ctx.Logger().Error("Failed to execute cron message", "error", err) - // } - // } + for idx, msg := range execCronMsgs { + ctx = ctx.WithTxBytes(bytesCronMsgs[idx]) + _, err := am.keeper.Execute(ctx, msg.Contract, msg.Sender, msg.Msg, msg.SentFunds, msg.CallbackSig, wasmtypes.HandleTypeExecute) + if err != nil { + ctx.Logger().Error("Failed to execute cron message", "error", err) + } + } am.keeper.SetRandomSeed(ctx, random, validator_set_evidence) } else { @@ -219,21 +219,20 @@ func (am AppModule) BeginBlock(c context.Context) error { func (am AppModule) EndBlock(c context.Context) error { ctx := c.(sdk.Context) - // _, _, err := am.keeper.GetScheduledMsgs(ctx, crontypes.ExecutionStage_EXECUTION_STAGE_END_BLOCKER) - // if err != nil { - // ctx.Logger().Error("Failed to get scheduled cron msgs") - // return err - // } + _, bytesCronMsgs, err := am.keeper.GetScheduledMsgs(ctx, crontypes.ExecutionStage_EXECUTION_STAGE_END_BLOCKER) + if err != nil { + ctx.Logger().Error("Failed to get scheduled cron msgs") + return err + } - cron_msgs := tm_type.Data{Txs: [][]byte{}} + cron_msgs := tm_type.Data{Txs: bytesCronMsgs} cron_data, err := cron_msgs.Marshal() if err != nil { ctx.Logger().Error("Failed to marshal cron_msgs") return err } - hash := sha256.Sum256(cron_data) - err = tmenclave.SetImplicitHash(hash[:]) + err = tmenclave.SetScheduledTxs(cron_data) if err != nil { ctx.Logger().Error("Failed to set implicit hash %+v", err) return err From e8863ae0f95f94c9f844e2b32775e0da775476d5 Mon Sep 17 00:00:00 2001 From: cboh4 Date: Mon, 24 Nov 2025 23:52:42 +0200 Subject: [PATCH 2/5] bump dependency --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index e673ca9f9..78b5329a8 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ replace ( cosmossdk.io/store => github.com/scrtlabs/cosmos-sdk-store v1.1.1-secret.1 cosmossdk.io/x/tx => github.com/scrtlabs/cosmos-sdk-x-tx v0.13.7-secret.0 github.com/cometbft/cometbft => github.com/scrtlabs/tendermint v0.38.19-secret.1 - github.com/cosmos/cosmos-sdk => github.com/scrtlabs/cosmos-sdk v0.50.14-secret.5 + github.com/cosmos/cosmos-sdk => github.com/scrtlabs/cosmos-sdk v0.50.14-secret.7 github.com/cosmos/iavl => github.com/scrtlabs/iavl v1.2.2-secret.0 github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 @@ -76,7 +76,7 @@ require ( github.com/gogo/protobuf v1.3.2 github.com/golang/mock v1.6.0 github.com/hashicorp/go-metrics v0.5.3 - github.com/scrtlabs/tm-secret-enclave v1.13.0 + github.com/scrtlabs/tm-secret-enclave v1.13.1 golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 gopkg.in/yaml.v2 v2.4.0 ) diff --git a/go.sum b/go.sum index 472802219..4f5a20ee0 100644 --- a/go.sum +++ b/go.sum @@ -1609,8 +1609,8 @@ github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWR github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= -github.com/scrtlabs/cosmos-sdk v0.50.14-secret.5 h1:iijErJT8ZbFHsFhhyLH0PywYQeeVT10i+EUsthfQOSg= -github.com/scrtlabs/cosmos-sdk v0.50.14-secret.5/go.mod h1:bTJf+E1t8wKEwwNcTYFBEuAcdEYWLGXv9QlMu089hUo= +github.com/scrtlabs/cosmos-sdk v0.50.14-secret.7 h1:D6KNM8+qfHA9uW3+tru36OpHp2j+Qye2i5tg5/MPCs8= +github.com/scrtlabs/cosmos-sdk v0.50.14-secret.7/go.mod h1:/0g1Kvg6WMZRbI5KfyDEQl/Zy30n6CzAkDa2Fs5B1PU= github.com/scrtlabs/cosmos-sdk-api v0.7.6-secret.0 h1:9IGLySVhC2qSrxT3fZvvqwjKsnXWSSKnywQDzT8y1Gs= github.com/scrtlabs/cosmos-sdk-api v0.7.6-secret.0/go.mod h1:IcxpYS5fMemZGqyYtErK7OqvdM0C8kdW3dq8Q/XIG38= github.com/scrtlabs/cosmos-sdk-store v1.1.1-secret.1 h1:TELtwBkSg0xBrs2ObFE0pVVWF6E31fPCDX2tk8OiJPo= @@ -1621,8 +1621,8 @@ github.com/scrtlabs/iavl v1.2.2-secret.0 h1:P96PL1Lf8OBSW9pMrlaRxhceZ4z9Hc7jk12g github.com/scrtlabs/iavl v1.2.2-secret.0/go.mod h1:GiM43q0pB+uG53mLxLDzimxM9l/5N9UuSY3/D0huuVw= github.com/scrtlabs/tendermint v0.38.19-secret.1 h1:NxZ21CS6INBjL2QCL087/BJLb1NAIeoY07mHasTuqKs= github.com/scrtlabs/tendermint v0.38.19-secret.1/go.mod h1:CZUJG1djTJUVbpjGS9JmQx9CFfF4goKi3LzYUQtxWO8= -github.com/scrtlabs/tm-secret-enclave v1.13.0 h1:a2xH0G96chEM8Ntwlq/Fh36r4dg0ijKWTaOy0oqFsqg= -github.com/scrtlabs/tm-secret-enclave v1.13.0/go.mod h1:nxZQtzzAqBNBLOEXSv4cKlUnVA4vRmHOn6ujr3kxVME= +github.com/scrtlabs/tm-secret-enclave v1.13.1 h1:0mXcBdoWyqEGhQEdbXMjSuTi9LKKMld2BqEj0eNpoxU= +github.com/scrtlabs/tm-secret-enclave v1.13.1/go.mod h1:nxZQtzzAqBNBLOEXSv4cKlUnVA4vRmHOn6ujr3kxVME= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= From 08d8d0ad80bf58ede70a078aa5d087d0c665af64 Mon Sep 17 00:00:00 2001 From: cboh4 Date: Wed, 26 Nov 2025 13:43:26 +0200 Subject: [PATCH 3/5] Add disk space check in CI --- .github/workflows/ci.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 994beee4d..c8e98e45e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -268,6 +268,13 @@ jobs: Build-LocalSecret: runs-on: ubuntu-22.04 steps: + - name: Check disk space BEFORE cleanup + run: | + df -h + echo "=== Checking large directories ===" + du -sh /usr/share/dotnet 2>/dev/null || echo "dotnet not found" + du -sh /usr/local/lib/android 2>/dev/null || echo "android not found" + du -sh /opt/ghc 2>/dev/null || echo "ghc not found" - name: Set up Docker Buildx uses: docker/setup-buildx-action@v2 with: From 33b833143511bbaa62a59f4d0a1d506a8b2c2c69 Mon Sep 17 00:00:00 2001 From: cboh4 Date: Wed, 26 Nov 2025 13:58:37 +0200 Subject: [PATCH 4/5] free disk space --- .github/workflows/ci.yaml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c8e98e45e..207e337b9 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -268,7 +268,13 @@ jobs: Build-LocalSecret: runs-on: ubuntu-22.04 steps: - - name: Check disk space BEFORE cleanup + - name: Free Disk Space + run: | + sudo rm -rf /usr/share/dotnet + sudo rm -rf /usr/local/lib/android + sudo docker system prune -af + df -h + - name: Check disk space after cleanup run: | df -h echo "=== Checking large directories ===" From b8c6b2907266dffb29b8e42d8c3590414c364ead Mon Sep 17 00:00:00 2001 From: cboh4 Date: Sun, 28 Dec 2025 14:44:15 +0200 Subject: [PATCH 5/5] refactor(x/cron): simplify execution flow and fix issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Major refactoring of the cron module to remove ExecutionStage distinction and consolidate all scheduled transactions through a single execution path. BREAKING CHANGES: - Removed ExecutionStage enum (BEGIN_BLOCKER/END_BLOCKER) - All scheduled messages now execute via EndBlock → Tendermint - Changed cron module authority from cron module address to gov module address Refactoring: - Moved encryption logic to separate encryption.go file - Changed from deterministic to fixed Curve25519 keypair encryption - Updated module private key to new hardcoded value - Simplified GetScheduledMsgs signature (removed execution_stage parameter) - Removed BeginBlock execution code from compute module Fixes: - Fix LastExecuteHeight to record execution block (N+1) instead of prep block (N) - Auto-create cron module account if missing (prevents consensus failures) - Fix sequence number handling for multiple transactions per block - Improve error handling in EndBlock (log errors instead of failing consensus) Improvements: - Set hardcoded gas limit (5M) and zero fees for scheduled transactions - Change several logs to debug level for cleaner output - Re-enable authority validation in message handlers Scheduled transactions can now be decrypted using standard secretcli commands thanks to the fixed keypair approach. --- app/keepers/keepers.go | 2 +- go.mod | 4 +- go.sum | 8 +- proto/secret/cron/schedule.proto | 8 -- x/compute/internal/keeper/keeper.go | 68 +++++++++------- x/compute/module.go | 34 ++------ x/cron/keeper/encryption.go | 119 ++++++++++++++++++++++++++++ x/cron/keeper/keeper.go | 119 ++++------------------------ x/cron/keeper/keeper_test.go | 16 ++-- x/cron/keeper/msg_server.go | 27 ++++--- x/cron/types/schedule.pb.go | 75 +++++------------- x/cron/types/tx.go | 5 +- 12 files changed, 230 insertions(+), 255 deletions(-) create mode 100644 x/cron/keeper/encryption.go diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index 2242d2ffc..10c6976c4 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -246,7 +246,7 @@ func (ak *SecretAppKeepers) InitSdkKeepers( ak.keys[crontypes.StoreKey], ak.memKeys[crontypes.StoreKey], ak.AccountKeeper, - authtypes.NewModuleAddress(crontypes.ModuleName).String(), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) ak.CronKeeper = cronKeeper diff --git a/go.mod b/go.mod index 78b5329a8..068e56f18 100644 --- a/go.mod +++ b/go.mod @@ -8,8 +8,8 @@ replace ( cosmossdk.io/api => github.com/scrtlabs/cosmos-sdk-api v0.7.6-secret.0 cosmossdk.io/store => github.com/scrtlabs/cosmos-sdk-store v1.1.1-secret.1 cosmossdk.io/x/tx => github.com/scrtlabs/cosmos-sdk-x-tx v0.13.7-secret.0 - github.com/cometbft/cometbft => github.com/scrtlabs/tendermint v0.38.19-secret.1 - github.com/cosmos/cosmos-sdk => github.com/scrtlabs/cosmos-sdk v0.50.14-secret.7 + github.com/cometbft/cometbft => github.com/scrtlabs/tendermint v0.38.19-secret.3 + github.com/cosmos/cosmos-sdk => github.com/scrtlabs/cosmos-sdk v0.50.14-secret.9 github.com/cosmos/iavl => github.com/scrtlabs/iavl v1.2.2-secret.0 github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 diff --git a/go.sum b/go.sum index 4f5a20ee0..c4fb38b20 100644 --- a/go.sum +++ b/go.sum @@ -1609,8 +1609,8 @@ github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWR github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= -github.com/scrtlabs/cosmos-sdk v0.50.14-secret.7 h1:D6KNM8+qfHA9uW3+tru36OpHp2j+Qye2i5tg5/MPCs8= -github.com/scrtlabs/cosmos-sdk v0.50.14-secret.7/go.mod h1:/0g1Kvg6WMZRbI5KfyDEQl/Zy30n6CzAkDa2Fs5B1PU= +github.com/scrtlabs/cosmos-sdk v0.50.14-secret.9 h1:8rkdEl4fFjJh0mz1G531MezU3SI79KwMgvO/KZlsCZw= +github.com/scrtlabs/cosmos-sdk v0.50.14-secret.9/go.mod h1:S4QwsvE3KrzJc5hwHA0LOd+P5gvfTQ8ZCOTZN9ctW4A= github.com/scrtlabs/cosmos-sdk-api v0.7.6-secret.0 h1:9IGLySVhC2qSrxT3fZvvqwjKsnXWSSKnywQDzT8y1Gs= github.com/scrtlabs/cosmos-sdk-api v0.7.6-secret.0/go.mod h1:IcxpYS5fMemZGqyYtErK7OqvdM0C8kdW3dq8Q/XIG38= github.com/scrtlabs/cosmos-sdk-store v1.1.1-secret.1 h1:TELtwBkSg0xBrs2ObFE0pVVWF6E31fPCDX2tk8OiJPo= @@ -1619,8 +1619,8 @@ github.com/scrtlabs/cosmos-sdk-x-tx v0.13.7-secret.0 h1:i3k5706sDHKhaCvzokB+n33/ github.com/scrtlabs/cosmos-sdk-x-tx v0.13.7-secret.0/go.mod h1:V6DImnwJMTq5qFjeGWpXNiT/fjgE4HtmclRmTqRVM3w= github.com/scrtlabs/iavl v1.2.2-secret.0 h1:P96PL1Lf8OBSW9pMrlaRxhceZ4z9Hc7jk12g9ShWeHw= github.com/scrtlabs/iavl v1.2.2-secret.0/go.mod h1:GiM43q0pB+uG53mLxLDzimxM9l/5N9UuSY3/D0huuVw= -github.com/scrtlabs/tendermint v0.38.19-secret.1 h1:NxZ21CS6INBjL2QCL087/BJLb1NAIeoY07mHasTuqKs= -github.com/scrtlabs/tendermint v0.38.19-secret.1/go.mod h1:CZUJG1djTJUVbpjGS9JmQx9CFfF4goKi3LzYUQtxWO8= +github.com/scrtlabs/tendermint v0.38.19-secret.3 h1:d/5XNMyhcTYjKszhBuCtgjN3XfS9BR+BZzuPRkosg5A= +github.com/scrtlabs/tendermint v0.38.19-secret.3/go.mod h1:CZUJG1djTJUVbpjGS9JmQx9CFfF4goKi3LzYUQtxWO8= github.com/scrtlabs/tm-secret-enclave v1.13.1 h1:0mXcBdoWyqEGhQEdbXMjSuTi9LKKMld2BqEj0eNpoxU= github.com/scrtlabs/tm-secret-enclave v1.13.1/go.mod h1:nxZQtzzAqBNBLOEXSv4cKlUnVA4vRmHOn6ujr3kxVME= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= diff --git a/proto/secret/cron/schedule.proto b/proto/secret/cron/schedule.proto index 804669e6a..7ec452190 100644 --- a/proto/secret/cron/schedule.proto +++ b/proto/secret/cron/schedule.proto @@ -5,14 +5,6 @@ import "gogoproto/gogo.proto"; option go_package = "github.com/scrtlabs/SecretNetwork/x/cron/types"; -// Defines when messages will be executed in the block -enum ExecutionStage { - // Execution at the end of the block - EXECUTION_STAGE_END_BLOCKER = 0; - // Execution at the beginning of the block - EXECUTION_STAGE_BEGIN_BLOCKER = 1; -} - // Defines the schedule for execution message Schedule { // Name of schedule diff --git a/x/compute/internal/keeper/keeper.go b/x/compute/internal/keeper/keeper.go index 7c2cf5e02..be95889ff 100644 --- a/x/compute/internal/keeper/keeper.go +++ b/x/compute/internal/keeper/keeper.go @@ -56,7 +56,6 @@ import ( v1wasmTypes "github.com/scrtlabs/SecretNetwork/go-cosmwasm/types/v1" cronkeeper "github.com/scrtlabs/SecretNetwork/x/cron/keeper" - crontypes "github.com/scrtlabs/SecretNetwork/x/cron/types" "github.com/scrtlabs/SecretNetwork/x/compute/internal/types" @@ -1192,8 +1191,8 @@ func (k Keeper) GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) return &contract } -func (k Keeper) GetScheduledMsgs(ctx sdk.Context, execution_stage crontypes.ExecutionStage) ([]types.MsgExecuteContract, [][]byte, error) { - cronScheduledMsgs := k.cronKeeper.GetScheduledMsgs(ctx, execution_stage) +func (k Keeper) GetScheduledMsgs(ctx sdk.Context) ([][]byte, error) { + cronScheduledMsgs := k.cronKeeper.GetScheduledMsgs(ctx) // // Update the schedule's last execution height. // schedule.LastExecuteHeight = uint64(ctx.BlockHeight()) //nolint:gosec @@ -1201,33 +1200,48 @@ func (k Keeper) GetScheduledMsgs(ctx sdk.Context, execution_stage crontypes.Exec // Get the module private key once. var txBytesList [][]byte - var executeMsgList []types.MsgExecuteContract privKey := cronkeeper.GetModulePrivateKey() pubKey := privKey.PubKey() senderAddr := sdk.AccAddress(pubKey.Address()) - // Retrieve the account info using the derived address. + // Retrieve or create the account info using the derived address. + // The cron module account needs to exist for sequence tracking, but it doesn't need funds + // since scheduled transactions are fee-free. + // Note: This address is derived from the hardcoded private key in GetModulePrivateKey(), + // so we only auto-create the account for that specific hardcoded key's address. senderAcc := k.accountKeeper.GetAccount(ctx, senderAddr) if senderAcc == nil { - return nil, nil, fmt.Errorf("account not found for address %s", senderAddr.String()) + // Create the account if it doesn't exist (first time running scheduled transactions). + // This only happens for the hardcoded cron module private key's address. + senderAcc = k.accountKeeper.NewAccountWithAddress(ctx, senderAddr) + k.accountKeeper.SetAccount(ctx, senderAcc) } accountNumber := senderAcc.GetAccountNumber() sequence := senderAcc.GetSequence() chainID := ctx.ChainID() - cacheCtx, writeFn := ctx.CacheContext() - for _, msg := range cronScheduledMsgs { + // Scheduled transactions are governance-permissioned and should be gas and fee free + // Fees are set to 0 (empty coins) + feeAmount := sdk.NewCoins() + // Gas limit is set to a high value to ensure scheduled transactions don't run out of gas. + // Since these are governance-permissioned, they should execute without gas constraints. + // Note: Gas limit must be > 0 to pass antehandler validation (ValidateBasicDecorator and ConsumeGasForTxSizeDecorator). + gasLimit := uint64(5_000_000) // 5 million gas units - effectively unlimited for scheduled txs + + for i, msg := range cronScheduledMsgs { + // Increment sequence for each transaction (must be done BEFORE signing) + currentSequence := sequence + uint64(i) // Convert contract address from bech32. contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { - ctx.Logger().Info("executeSchedule: failed to convert contract address from bech32.", "err", err) - return nil, nil, err + ctx.Logger().Debug("executeSchedule: failed to convert contract address from bech32.", "err", err) + return nil, err } encryptedMsg, err := cronkeeper.Encrypt(ctx, &k.cronKeeper, []byte(msg.Msg)) if err != nil { - ctx.Logger().Info("executeSchedule: failed to decode base64 msg", "err", err) - return nil, nil, err + ctx.Logger().Debug("executeSchedule: failed to decode base64 msg", "err", err) + return nil, err } executeMsg := types.MsgExecuteContract{ Sender: senderAddr, @@ -1240,18 +1254,18 @@ func (k Keeper) GetScheduledMsgs(ctx sdk.Context, execution_stage crontypes.Exec // Create a new transaction builder using the shared txConfig. txBuilder := k.cronKeeper.GetTxConfig().NewTxBuilder() if err := txBuilder.SetMsgs(&executeMsg); err != nil { - return nil, nil, err + return nil, err } // Set fee and gas (adjust as needed). - txBuilder.SetFeeAmount(sdk.NewCoins()) - txBuilder.SetGasLimit(0) + txBuilder.SetFeeAmount(feeAmount) + txBuilder.SetGasLimit(gasLimit) // Prepare signer data using the correct account info. signerData := authsigning.SignerData{ Address: senderAddr.String(), ChainID: chainID, AccountNumber: accountNumber, - Sequence: sequence, + Sequence: currentSequence, PubKey: pubKey, } @@ -1263,23 +1277,23 @@ func (k Keeper) GetScheduledMsgs(ctx sdk.Context, execution_stage crontypes.Exec sig := signing.SignatureV2{ PubKey: pubKey, Data: &sigData, - Sequence: sequence, + Sequence: currentSequence, } sigs := []signing.SignatureV2{sig} if err := txBuilder.SetSignatures(sigs...); err != nil { - return nil, nil, err + return nil, err } bytesToSign, err := authsigning.GetSignBytesAdapter(ctx, k.cronKeeper.GetTxConfig().SignModeHandler(), signing.SignMode_SIGN_MODE_DIRECT, signerData, txBuilder.GetTx()) if err != nil { - return nil, nil, err + return nil, err } // Sign those bytes sigBytes, err := privKey.Sign(bytesToSign) if err != nil { - return nil, nil, err + return nil, err } // Construct the SignatureV2 struct @@ -1290,29 +1304,23 @@ func (k Keeper) GetScheduledMsgs(ctx sdk.Context, execution_stage crontypes.Exec sig = signing.SignatureV2{ PubKey: pubKey, Data: &sigData, - Sequence: sequence, + Sequence: currentSequence, } err = txBuilder.SetSignatures(sig) if err != nil { - return nil, nil, fmt.Errorf("unable to set signatures on payload: %w", err) + return nil, fmt.Errorf("unable to set signatures on payload: %w", err) } txBytes, err := k.cronKeeper.GetTxConfig().TxEncoder()(txBuilder.GetTx()) if err != nil { - return nil, nil, err + return nil, err } - cacheCtx = cacheCtx.WithTxBytes(txBytes) - txBytesList = append(txBytesList, txBytes) - executeMsgList = append(executeMsgList, executeMsg) - } - // Commit changes if all messages were executed successfully. - writeFn() - return executeMsgList, txBytesList, nil + return txBytesList, nil } func (k Keeper) containsContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) bool { diff --git a/x/compute/module.go b/x/compute/module.go index 99b1b0435..af2fb113a 100644 --- a/x/compute/module.go +++ b/x/compute/module.go @@ -15,13 +15,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/scrtlabs/SecretNetwork/go-cosmwasm/api" - wasmtypes "github.com/scrtlabs/SecretNetwork/go-cosmwasm/types" "github.com/scrtlabs/SecretNetwork/x/compute/client/cli" "github.com/scrtlabs/SecretNetwork/x/compute/internal/keeper" "github.com/scrtlabs/SecretNetwork/x/compute/internal/types" tmenclave "github.com/scrtlabs/tm-secret-enclave" - - crontypes "github.com/scrtlabs/SecretNetwork/x/cron/types" ) var ( @@ -161,17 +158,6 @@ func (am AppModule) BeginBlock(c context.Context) error { ctx := c.(sdk.Context) block_header := ctx.BlockHeader() - execCronMsgs, bytesCronMsgs, err := am.keeper.GetScheduledMsgs(ctx, crontypes.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) - if err != nil { - ctx.Logger().Error("Failed to get scheduled cron msgs") - return err - } - - if err != nil { - ctx.Logger().Error("Failed to marshal cron_msgs") - return err - } - header, err := block_header.Marshal() if err != nil { ctx.Logger().Error("Failed to marshal block header") @@ -200,14 +186,6 @@ func (am AppModule) BeginBlock(c context.Context) error { return err } - for idx, msg := range execCronMsgs { - ctx = ctx.WithTxBytes(bytesCronMsgs[idx]) - _, err := am.keeper.Execute(ctx, msg.Contract, msg.Sender, msg.Msg, msg.SentFunds, msg.CallbackSig, wasmtypes.HandleTypeExecute) - if err != nil { - ctx.Logger().Error("Failed to execute cron message", "error", err) - } - } - am.keeper.SetRandomSeed(ctx, random, validator_set_evidence) } else { ctx.Logger().Debug("Non-encrypted block", "Block_hash", block_header.LastBlockId.Hash, "Height", ctx.BlockHeight(), "Txs", len(x2_data)) @@ -219,23 +197,23 @@ func (am AppModule) BeginBlock(c context.Context) error { func (am AppModule) EndBlock(c context.Context) error { ctx := c.(sdk.Context) - _, bytesCronMsgs, err := am.keeper.GetScheduledMsgs(ctx, crontypes.ExecutionStage_EXECUTION_STAGE_END_BLOCKER) + bytesCronMsgs, err := am.keeper.GetScheduledMsgs(ctx) if err != nil { - ctx.Logger().Error("Failed to get scheduled cron msgs") - return err + ctx.Logger().Error("Failed to get scheduled cron msgs for end blocker", "error", err) + // return err } cron_msgs := tm_type.Data{Txs: bytesCronMsgs} cron_data, err := cron_msgs.Marshal() if err != nil { ctx.Logger().Error("Failed to marshal cron_msgs") - return err + // return err } err = tmenclave.SetScheduledTxs(cron_data) if err != nil { - ctx.Logger().Error("Failed to set implicit hash %+v", err) - return err + ctx.Logger().Error("Failed to set scheduled txs %+v", err) + // return err } return nil } diff --git a/x/cron/keeper/encryption.go b/x/cron/keeper/encryption.go new file mode 100644 index 000000000..94c4b0464 --- /dev/null +++ b/x/cron/keeper/encryption.go @@ -0,0 +1,119 @@ +package keeper + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "fmt" + "io" + + "github.com/miscreant/miscreant.go" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/hkdf" + + secp256k1 "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdk "github.com/cosmos/cosmos-sdk/types" + regtypes "github.com/scrtlabs/SecretNetwork/x/registration" +) + +var hkdfSalt = []byte{ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x4b, 0xea, 0xd8, 0xdf, 0x69, 0x99, + 0x08, 0x52, 0xc2, 0x02, 0xdb, 0x0e, 0x00, 0x97, + 0xc1, 0xa1, 0x2e, 0xa6, 0x37, 0xd7, 0xe9, 0x6d, +} + +// GetModulePrivateKey returns the artificially generated cron module's secp256k1 private key. +// The key is stored as a base64-encoded string and is used for signing scheduled transactions. +func GetModulePrivateKey() cryptotypes.PrivKey { + privKeyBase64 := "fgAMxmXhxA/Gah7CtAM1/Li9Slmn5pHWc75XOUusPPQ=" + privKeyBytes, err := base64.StdEncoding.DecodeString(privKeyBase64) + if err != nil { + fmt.Printf("failed to decode private key: %v", err) + } + return &secp256k1.PrivKey{Key: privKeyBytes} +} + +// GetModuleTxKeyPair returns a fixed Curve25519 keypair derived from the module's secp256k1 key. +// This keypair is used for transaction encryption/decryption and allows scheduled transactions +// to be decrypted using the standard secretcli query command. +func GetModuleTxKeyPair() ([]byte, []byte) { + privKey := GetModulePrivateKey() + privKeyBytes := privKey.Bytes() + + // Derive Curve25519 private key from secp256k1 key (hash it to get 32 bytes) + txSenderPrivKey := sha256.Sum256(privKeyBytes) + + // Derive Curve25519 public key + var txSenderPubKey [32]byte + curve25519.ScalarBaseMult(&txSenderPubKey, &txSenderPrivKey) + + return txSenderPrivKey[:], txSenderPubKey[:] +} + +// getTxEncryptionKey derives the transaction encryption key using the sender's private key, +// consensus IO public key, and nonce. This follows the same key derivation process used +// by regular transactions in Secret Network. +func getTxEncryptionKey(ctx sdk.Context, k *Keeper, txSenderPrivKey []byte, nonce []byte) ([]byte, error) { + consensusIoPubKey := k.regKeeper.GetMasterKey(ctx, regtypes.MasterIoKeyId) + + txEncryptionIkm, err := curve25519.X25519(txSenderPrivKey, consensusIoPubKey.Bytes) + if err != nil { + ctx.Logger().Error("Failed to derive tx encryption key", "error", err) + return nil, err + } + + kdfFunc := hkdf.New(sha256.New, append(txEncryptionIkm, nonce...), hkdfSalt, []byte{}) + + txEncryptionKey := make([]byte, 32) + if _, err := io.ReadFull(kdfFunc, txEncryptionKey); err != nil { + ctx.Logger().Error("Failed inside the getTxEncryptionKey", "error", err) + return nil, err + } + + return txEncryptionKey, nil +} + +// Encrypt encrypts plaintext using a fixed Curve25519 keypair derived from the module's secp256k1 key. +// This allows scheduled transactions to be decrypted using the standard secretcli query command. +// The encryption uses AES-SIV (Synthetic Initialization Vector) mode for authenticated encryption. +func Encrypt(ctx sdk.Context, k *Keeper, plaintext []byte) ([]byte, error) { + // Get fixed keypair derived from the module's secp256k1 key + txSenderPrivKey, txSenderPubKey := GetModuleTxKeyPair() + + // Use random nonce (like regular transactions) instead of deterministic + nonce := make([]byte, 32) + _, err := rand.Read(nonce) + if err != nil { + ctx.Logger().Error("Failed to generate random nonce", "error", err) + return nil, err + } + + txEncryptionKey, err := getTxEncryptionKey(ctx, k, txSenderPrivKey, nonce) + if err != nil { + ctx.Logger().Error("Failed to get tx encryption key", "error", err) + return nil, err + } + + return encryptData(txEncryptionKey, txSenderPubKey, plaintext, nonce) +} + +// encryptData performs the actual encryption using AES-SIV mode. +// The output format is: nonce(32 bytes) || wallet_pubkey(32 bytes) || ciphertext +func encryptData(aesEncryptionKey []byte, txSenderPubKey []byte, plaintext []byte, nonce []byte) ([]byte, error) { + cipher, err := miscreant.NewAESCMACSIV(aesEncryptionKey) + if err != nil { + return nil, err + } + + ciphertext, err := cipher.Seal(nil, plaintext, []byte{}) + if err != nil { + return nil, err + } + + // ciphertext = nonce(32) || wallet_pubkey(32) || ciphertext + ciphertext = append(nonce, append(txSenderPubKey, ciphertext...)...) + + return ciphertext, nil +} diff --git a/x/cron/keeper/keeper.go b/x/cron/keeper/keeper.go index 5c8a2243a..3afa3c017 100644 --- a/x/cron/keeper/keeper.go +++ b/x/cron/keeper/keeper.go @@ -1,17 +1,11 @@ package keeper import ( - "crypto/sha256" - "encoding/base64" "fmt" - "io" "strconv" "cosmossdk.io/log" "github.com/hashicorp/go-metrics" - "github.com/miscreant/miscreant.go" - "golang.org/x/crypto/curve25519" - "golang.org/x/crypto/hkdf" "github.com/cosmos/cosmos-sdk/telemetry" @@ -20,11 +14,8 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - secp256k1 "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/scrtlabs/SecretNetwork/x/cron/types" - regtypes "github.com/scrtlabs/SecretNetwork/x/registration" ) var ( @@ -54,34 +45,29 @@ func (k *Keeper) GetTxConfig() client.TxConfig { } // GetScheduledMsgs implements types.CronKeeper. -func (k *Keeper) GetScheduledMsgs(ctx sdk.Context, execution_stage types.ExecutionStage) []types.MsgExecuteContract { - // func (k *Keeper) GetScheduledMsgs(ctx sdk.Context) [][]byte { - schedules := k.getSchedulesReadyForExecution(ctx, execution_stage) +func (k *Keeper) GetScheduledMsgs(ctx sdk.Context) []types.MsgExecuteContract { + schedules := k.getSchedulesReadyForExecution(ctx) var msgExecuteContractList []types.MsgExecuteContract for _, schedule := range schedules { - msgs, err := k.getCronsMsgs(ctx, schedule, execution_stage) + msgs, err := k.getCronsMsgs(ctx, schedule) if err != nil { ctx.Logger().Error("Failed to get crons msgs", "error", err) continue } msgExecuteContractList = append(msgExecuteContractList, msgs...) - if execution_stage == types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER { - recordExecutedSchedule(nil, schedule) - } + recordExecutedSchedule(nil, schedule) } return msgExecuteContractList } // executeSchedule executes all msgs in a given schedule and changes LastExecuteHeight // if at least one msg execution fails, rollback all messages -func (k *Keeper) getCronsMsgs(ctx sdk.Context, schedule types.Schedule, execution_stage types.ExecutionStage) ([]types.MsgExecuteContract, error) { +func (k *Keeper) getCronsMsgs(ctx sdk.Context, schedule types.Schedule) ([]types.MsgExecuteContract, error) { // Even if contract execution returned an error, we still increase the height // and execute it after this interval - if execution_stage == types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER { - schedule.LastExecuteHeight = uint64(ctx.BlockHeight()) //nolint:gosec - k.storeSchedule(ctx, schedule) - } + schedule.LastExecuteHeight = uint64(ctx.BlockHeight() + 1) //nolint:gosec + k.storeSchedule(ctx, schedule) var cronMsgs []types.MsgExecuteContract @@ -206,7 +192,7 @@ func (k *Keeper) GetScheduleCount(ctx sdk.Context) int32 { return k.getScheduleCount(ctx) } -func (k *Keeper) getSchedulesReadyForExecution(ctx sdk.Context, executionStage types.ExecutionStage) []types.Schedule { +func (k *Keeper) getSchedulesReadyForExecution(ctx sdk.Context) []types.Schedule { params := k.GetParams(ctx) store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ScheduleKey) count := uint64(0) @@ -219,7 +205,7 @@ func (k *Keeper) getSchedulesReadyForExecution(ctx sdk.Context, executionStage t for ; iterator.Valid(); iterator.Next() { var schedule types.Schedule k.cdc.MustUnmarshal(iterator.Value(), &schedule) - if k.intervalPassed(ctx, schedule, executionStage) { + if k.intervalPassed(ctx, schedule) { res = append(res, schedule) count++ @@ -233,82 +219,6 @@ func (k *Keeper) getSchedulesReadyForExecution(ctx sdk.Context, executionStage t return res } -var hkdfSalt = []byte{ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x02, 0x4b, 0xea, 0xd8, 0xdf, 0x69, 0x99, - 0x08, 0x52, 0xc2, 0x02, 0xdb, 0x0e, 0x00, 0x97, - 0xc1, 0xa1, 0x2e, 0xa6, 0x37, 0xd7, 0xe9, 0x6d, -} - -func getTxEncryptionKey(ctx sdk.Context, k *Keeper, txSenderPrivKey []byte, nonce []byte) ([]byte, error) { - consensusIoPubKey := k.regKeeper.GetMasterKey(ctx, regtypes.MasterIoKeyId) - - txEncryptionIkm, err := curve25519.X25519(txSenderPrivKey, consensusIoPubKey.Bytes) - if err != nil { - ctx.Logger().Error("Failed to derive tx encryption key", "error", err) - return nil, err - } - - kdfFunc := hkdf.New(sha256.New, append(txEncryptionIkm, nonce...), hkdfSalt, []byte{}) - - txEncryptionKey := make([]byte, 32) - if _, err := io.ReadFull(kdfFunc, txEncryptionKey); err != nil { - ctx.Logger().Error("Failed inside the getTxEncryptionKey", "error", err) - return nil, err - } - - return txEncryptionKey, nil -} - -// Encrypt encrypts deterministically by deriving the ephemeral keys and nonce from the plaintext. -func Encrypt(ctx sdk.Context, k *Keeper, plaintext []byte) ([]byte, error) { - txSenderPrivKey := sha256.Sum256(plaintext) - - var txSenderPubKey [32]byte - curve25519.ScalarBaseMult(&txSenderPubKey, &txSenderPrivKey) - - // Derive a deterministic nonce by hashing the plaintext with an appended constant. - nonceData := append(plaintext, []byte("nonce")...) // "nonce" is a constant string to differentiate from key derivation - nonceHash := sha256.Sum256(nonceData) - nonce := nonceHash[:] // convert fixed array to a slice - - txEncryptionKey, err := getTxEncryptionKey(ctx, k, txSenderPrivKey[:], nonce) - if err != nil { - ctx.Logger().Error("Failed to get tx encryption key", "error", err) - return nil, err - } - - return encryptData(txEncryptionKey, txSenderPubKey[:], plaintext, nonce) -} - -func encryptData(aesEncryptionKey []byte, txSenderPubKey []byte, plaintext []byte, nonce []byte) ([]byte, error) { - cipher, err := miscreant.NewAESCMACSIV(aesEncryptionKey) - if err != nil { - // log.Println(err) - return nil, err - } - - ciphertext, err := cipher.Seal(nil, plaintext, []byte{}) - if err != nil { - // log.Println(err) - return nil, err - } - - // ciphertext = nonce(32) || wallet_pubkey(32) || ciphertext - ciphertext = append(nonce, append(txSenderPubKey, ciphertext...)...) - - return ciphertext, nil -} - -func GetModulePrivateKey() cryptotypes.PrivKey { - privKeyBase64 := "8Ke2frmnGdVPipv7+xh9jClrl5EaBb9cowSUgj5GvrY=" - privKeyBytes, err := base64.StdEncoding.DecodeString(privKeyBase64) - if err != nil { - fmt.Printf("failed to decode private key: %v", err) - } - return &secp256k1.PrivKey{Key: privKeyBytes} -} - func (k *Keeper) storeSchedule(ctx sdk.Context, schedule types.Schedule) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ScheduleKey) @@ -327,12 +237,11 @@ func (k *Keeper) scheduleExists(ctx sdk.Context, name string) bool { return store.Has(types.GetScheduleKey(name)) } -func (k *Keeper) intervalPassed(ctx sdk.Context, schedule types.Schedule, executionStage types.ExecutionStage) bool { - delta := 0 - if executionStage == types.ExecutionStage_EXECUTION_STAGE_END_BLOCKER { - delta = 1 - } - return uint64(ctx.BlockHeight())+uint64(delta) >= (schedule.LastExecuteHeight + schedule.Period) //nolint:gosec +func (k *Keeper) intervalPassed(ctx sdk.Context, schedule types.Schedule) bool { + // EndBlock runs at the end of block N and prepares messages for block N+1. + // So we check if the schedule should execute in block N+1: + // (currentHeight + 1) >= (lastExecuteHeight + period) + return uint64(ctx.BlockHeight())+1 >= (schedule.LastExecuteHeight + schedule.Period) //nolint:gosec } func (k *Keeper) changeTotalCount(ctx sdk.Context, incrementAmount int32) { diff --git a/x/cron/keeper/keeper_test.go b/x/cron/keeper/keeper_test.go index 17f30027f..18a00c50d 100644 --- a/x/cron/keeper/keeper_test.go +++ b/x/cron/keeper/keeper_test.go @@ -108,7 +108,7 @@ func TestKeeperExecuteReadySchedules(t *testing.T) { ctx = ctx.WithBlockHeight(5) // Use GetScheduledMsgs instead of ExecuteReadySchedules - _ = k.GetScheduledMsgs(ctx, types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) + _ = k.GetScheduledMsgs(ctx) unready1, _ := k.GetSchedule(ctx, "1_unready1") ready1, _ := k.GetSchedule(ctx, "2_ready1") @@ -128,7 +128,7 @@ func TestKeeperExecuteReadySchedules(t *testing.T) { // Notice that now only one ready schedule left because we got limit of 2 at once ctx = ctx.WithBlockHeight(6) - _ = k.GetScheduledMsgs(ctx, types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) + _ = k.GetScheduledMsgs(ctx) unready1, _ = k.GetSchedule(ctx, "1_unready1") ready1, _ = k.GetSchedule(ctx, "2_ready1") @@ -146,7 +146,7 @@ func TestKeeperExecuteReadySchedules(t *testing.T) { ctx = ctx.WithBlockHeight(8) - _ = k.GetScheduledMsgs(ctx, types.ExecutionStage_EXECUTION_STAGE_END_BLOCKER) + _ = k.GetScheduledMsgs(ctx) unready1, _ = k.GetSchedule(ctx, "1_unready1") ready1, _ = k.GetSchedule(ctx, "2_ready1") @@ -183,14 +183,14 @@ func TestKeeperExecuteReadySchedules(t *testing.T) { // expect it to not executed right away - _ = k.GetScheduledMsgs(ctx, types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) + _ = k.GetScheduledMsgs(ctx) // LastExecuteHeight should still be at 0 s, _ = k.GetSchedule(ctx, "every_block") require.Equal(t, s.LastExecuteHeight, uint64(0)) ctx = ctx.WithBlockHeight(1) // expect it to be executed again - _ = k.GetScheduledMsgs(ctx, types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) + _ = k.GetScheduledMsgs(ctx) // last execute height changed to 1 s, _ = k.GetSchedule(ctx, "every_block") require.Equal(t, s.LastExecuteHeight, uint64(1)) @@ -217,20 +217,20 @@ func TestKeeperExecuteReadySchedules(t *testing.T) { require.NoError(t, err) // expect it to not executed on 0 and 1 blocks - _ = k.GetScheduledMsgs(ctx, types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) + _ = k.GetScheduledMsgs(ctx) // LastExecuteHeight should still be at 0 s, _ = k.GetSchedule(ctx, "once_in_two") require.Equal(t, s.LastExecuteHeight, uint64(0)) ctx = ctx.WithBlockHeight(1) - _ = k.GetScheduledMsgs(ctx, types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) + _ = k.GetScheduledMsgs(ctx) s, _ = k.GetSchedule(ctx, "once_in_two") require.Equal(t, s.LastExecuteHeight, uint64(0)) // expect it to be executed on 2 block ctx = ctx.WithBlockHeight(2) // expect it to be executed again - _ = k.GetScheduledMsgs(ctx, types.ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER) + _ = k.GetScheduledMsgs(ctx) // last execute height changed to 2 s, _ = k.GetSchedule(ctx, "once_in_two") require.Equal(t, s.LastExecuteHeight, uint64(2)) diff --git a/x/cron/keeper/msg_server.go b/x/cron/keeper/msg_server.go index 4edb43fa6..3b3fb1167 100644 --- a/x/cron/keeper/msg_server.go +++ b/x/cron/keeper/msg_server.go @@ -5,6 +5,7 @@ import ( "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/scrtlabs/SecretNetwork/x/cron/types" ) @@ -27,10 +28,10 @@ func (k msgServer) AddSchedule(goCtx context.Context, req *types.MsgAddSchedule) return nil, errors.Wrap(err, "failed to validate MsgAddSchedule") } - // authority := k.keeper.GetAuthority() - // if authority != req.Authority { - // return nil, errors.Wrapf(sdkerrors.ErrInvalidRequest, "invalid authority; expected %s, got %s", authority, req.Authority) - // } + authority := k.keeper.GetAuthority() + if authority != req.Authority { + return nil, errors.Wrapf(sdkerrors.ErrUnauthorized, "invalid authority; expected %s, got %s", authority, req.Authority) + } ctx := sdk.UnwrapSDKContext(goCtx) if err := k.keeper.AddSchedule(ctx, req.Name, req.Period, req.Msgs); err != nil { @@ -46,10 +47,10 @@ func (k msgServer) RemoveSchedule(goCtx context.Context, req *types.MsgRemoveSch return nil, errors.Wrap(err, "failed to validate MsgRemoveSchedule") } - // authority := k.keeper.GetAuthority() - // if authority != req.Authority { - // return nil, errors.Wrapf(sdkerrors.ErrInvalidRequest, "invalid authority; expected %s, got %s", authority, req.Authority) - // } + authority := k.keeper.GetAuthority() + if authority != req.Authority { + return nil, errors.Wrapf(sdkerrors.ErrUnauthorized, "invalid authority; expected %s, got %s", authority, req.Authority) + } ctx := sdk.UnwrapSDKContext(goCtx) k.keeper.RemoveSchedule(ctx, req.Name) @@ -63,14 +64,14 @@ func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParam return nil, errors.Wrap(err, "failed to validate MsgUpdateParams") } - // authority := k.keeper.GetAuthority() - // if authority != req.Authority { - // return nil, errors.Wrapf(sdkerrors.ErrInvalidRequest, "invalid authority; expected %s, got %s", authority, req.Authority) - // } + authority := k.keeper.GetAuthority() + if authority != req.Authority { + return nil, errors.Wrapf(sdkerrors.ErrUnauthorized, "invalid authority; expected %s, got %s", authority, req.Authority) + } ctx := sdk.UnwrapSDKContext(goCtx) if err := k.keeper.SetParams(ctx, req.Params); err != nil { - return nil, err + return nil, errors.Wrap(err, "failed to set params") } return &types.MsgUpdateParamsResponse{}, nil diff --git a/x/cron/types/schedule.pb.go b/x/cron/types/schedule.pb.go index 7e32c796d..604008f40 100644 --- a/x/cron/types/schedule.pb.go +++ b/x/cron/types/schedule.pb.go @@ -23,34 +23,6 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// Defines when messages will be executed in the block -type ExecutionStage int32 - -const ( - // Execution at the end of the block - ExecutionStage_EXECUTION_STAGE_END_BLOCKER ExecutionStage = 0 - // Execution at the beginning of the block - ExecutionStage_EXECUTION_STAGE_BEGIN_BLOCKER ExecutionStage = 1 -) - -var ExecutionStage_name = map[int32]string{ - 0: "EXECUTION_STAGE_END_BLOCKER", - 1: "EXECUTION_STAGE_BEGIN_BLOCKER", -} - -var ExecutionStage_value = map[string]int32{ - "EXECUTION_STAGE_END_BLOCKER": 0, - "EXECUTION_STAGE_BEGIN_BLOCKER": 1, -} - -func (x ExecutionStage) String() string { - return proto.EnumName(ExecutionStage_name, int32(x)) -} - -func (ExecutionStage) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_3d6729589d2158da, []int{0} -} - // Defines the schedule for execution type Schedule struct { // Name of schedule @@ -226,7 +198,6 @@ func (m *ScheduleCount) GetCount() int32 { } func init() { - proto.RegisterEnum("secret.cron.ExecutionStage", ExecutionStage_name, ExecutionStage_value) proto.RegisterType((*Schedule)(nil), "secret.cron.Schedule") proto.RegisterType((*MsgExecuteContract)(nil), "secret.cron.MsgExecuteContract") proto.RegisterType((*ScheduleCount)(nil), "secret.cron.ScheduleCount") @@ -235,31 +206,27 @@ func init() { func init() { proto.RegisterFile("secret/cron/schedule.proto", fileDescriptor_3d6729589d2158da) } var fileDescriptor_3d6729589d2158da = []byte{ - // 374 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x64, 0x51, 0xd1, 0x6a, 0xe2, 0x40, - 0x14, 0xcd, 0xac, 0x51, 0x74, 0x64, 0x17, 0x77, 0x56, 0x96, 0xe0, 0xb2, 0xd1, 0x15, 0x16, 0x64, - 0x1f, 0x12, 0xd8, 0x7d, 0xda, 0xc7, 0x26, 0x0d, 0x2a, 0x6d, 0x23, 0x24, 0x16, 0x4a, 0x5f, 0x42, - 0x1c, 0x87, 0x49, 0xa8, 0xc9, 0x48, 0x66, 0x42, 0xed, 0x5f, 0xf4, 0x17, 0xfa, 0x37, 0x3e, 0xfa, - 0xd8, 0xa7, 0x52, 0xf4, 0x47, 0x4a, 0x26, 0xa9, 0x94, 0xf6, 0xed, 0x9c, 0x39, 0xe7, 0xdc, 0x7b, - 0xe7, 0x5e, 0xd8, 0xe3, 0x04, 0x67, 0x44, 0x98, 0x38, 0x63, 0xa9, 0xc9, 0x71, 0x44, 0x96, 0xf9, - 0x8a, 0x18, 0xeb, 0x8c, 0x09, 0x86, 0xda, 0xa5, 0x66, 0x14, 0x5a, 0xaf, 0x4b, 0x19, 0x65, 0xf2, - 0xdd, 0x2c, 0x50, 0x69, 0x19, 0x3e, 0x00, 0xd8, 0xf4, 0xab, 0x14, 0x42, 0x50, 0x4d, 0xc3, 0x84, - 0x68, 0x60, 0x00, 0x46, 0x2d, 0x4f, 0x62, 0xf4, 0x1d, 0x36, 0xd6, 0x24, 0x8b, 0xd9, 0x52, 0xfb, - 0x34, 0x00, 0x23, 0xd5, 0xab, 0x18, 0xfa, 0x0f, 0xd5, 0x84, 0x53, 0xae, 0xd5, 0x06, 0xb5, 0x51, - 0xfb, 0x6f, 0xdf, 0x78, 0xd3, 0xca, 0xb8, 0xe0, 0xd4, 0xd9, 0x10, 0x9c, 0x0b, 0x62, 0xb3, 0x54, - 0x64, 0x21, 0x16, 0x96, 0xba, 0x7d, 0xea, 0x2b, 0x9e, 0x8c, 0x20, 0x03, 0x7e, 0x5b, 0x85, 0x5c, - 0x04, 0xa4, 0xf4, 0x04, 0x11, 0x89, 0x69, 0x24, 0x34, 0x55, 0xd6, 0xff, 0x5a, 0x48, 0x55, 0x7a, - 0x22, 0x85, 0xa1, 0x05, 0xd1, 0xc7, 0x8a, 0xa8, 0x07, 0x9b, 0xb8, 0xc2, 0xd5, 0xc0, 0x47, 0x8e, - 0x3a, 0xb0, 0x96, 0x70, 0x2a, 0x27, 0x6e, 0x79, 0x05, 0x1c, 0xfe, 0x86, 0x9f, 0x5f, 0xbf, 0x69, - 0xb3, 0x3c, 0x15, 0xa8, 0x0b, 0xeb, 0xb8, 0x00, 0x32, 0x5b, 0xf7, 0x4a, 0xf2, 0x67, 0x0e, 0xbf, - 0x94, 0x7d, 0x62, 0x96, 0xfa, 0x22, 0xa4, 0x04, 0xf5, 0xe1, 0x0f, 0xe7, 0xca, 0xb1, 0x2f, 0xe7, - 0xd3, 0x99, 0x1b, 0xf8, 0xf3, 0x93, 0xb1, 0x13, 0x38, 0xee, 0x69, 0x60, 0x9d, 0xcf, 0xec, 0x33, - 0xc7, 0xeb, 0x28, 0xe8, 0x17, 0xfc, 0xf9, 0xde, 0x60, 0x39, 0xe3, 0xa9, 0x7b, 0xb4, 0x00, 0x6b, - 0xb2, 0xdd, 0xeb, 0x60, 0xb7, 0xd7, 0xc1, 0xf3, 0x5e, 0x07, 0xf7, 0x07, 0x5d, 0xd9, 0x1d, 0x74, - 0xe5, 0xf1, 0xa0, 0x2b, 0xd7, 0x06, 0x8d, 0x45, 0x94, 0x2f, 0x0c, 0xcc, 0x12, 0x93, 0xe3, 0x4c, - 0xac, 0xc2, 0x05, 0x37, 0x7d, 0xb9, 0x4a, 0x97, 0x88, 0x5b, 0x96, 0xdd, 0x98, 0x9b, 0xf2, 0xb4, - 0xe2, 0x6e, 0x4d, 0xf8, 0xa2, 0x21, 0xaf, 0xf6, 0xef, 0x25, 0x00, 0x00, 0xff, 0xff, 0xbd, 0xb5, - 0x66, 0x39, 0xf6, 0x01, 0x00, 0x00, + // 315 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x64, 0x91, 0xc1, 0x6a, 0x3a, 0x31, + 0x10, 0xc6, 0x37, 0x7f, 0x57, 0xd1, 0xc8, 0x1f, 0xda, 0x54, 0xca, 0xe2, 0x21, 0x8a, 0x50, 0xf0, + 0x94, 0x40, 0x7b, 0xea, 0x55, 0x29, 0x78, 0x69, 0x0f, 0xeb, 0xad, 0x17, 0x59, 0xe3, 0x90, 0x95, + 0xba, 0x1b, 0x49, 0x66, 0xa9, 0x7d, 0x8b, 0xbe, 0x42, 0xdf, 0xc6, 0xa3, 0xc7, 0x9e, 0x4a, 0xd1, + 0x17, 0x29, 0x9b, 0xdd, 0x96, 0x42, 0x6f, 0xbf, 0x2f, 0xdf, 0x7c, 0x93, 0x99, 0x84, 0xf6, 0x1d, + 0x28, 0x0b, 0x28, 0x95, 0x35, 0xb9, 0x74, 0x2a, 0x85, 0x55, 0xb1, 0x01, 0xb1, 0xb5, 0x06, 0x0d, + 0xeb, 0x56, 0x9e, 0x28, 0xbd, 0x7e, 0x4f, 0x1b, 0x6d, 0xfc, 0xb9, 0x2c, 0xa9, 0x2a, 0x19, 0xbd, + 0x11, 0xda, 0x9e, 0xd7, 0x29, 0xc6, 0x68, 0x98, 0x27, 0x19, 0x44, 0x64, 0x48, 0xc6, 0x9d, 0xd8, + 0x33, 0xbb, 0xa4, 0xad, 0x2d, 0xd8, 0xb5, 0x59, 0x45, 0xff, 0x86, 0x64, 0x1c, 0xc6, 0xb5, 0x62, + 0xb7, 0x34, 0xcc, 0x9c, 0x76, 0x51, 0x63, 0xd8, 0x18, 0x77, 0xaf, 0x07, 0xe2, 0xd7, 0x55, 0xe2, + 0xde, 0xe9, 0xbb, 0x1d, 0xa8, 0x02, 0x61, 0x6a, 0x72, 0xb4, 0x89, 0xc2, 0x49, 0xb8, 0xff, 0x18, + 0x04, 0xb1, 0x8f, 0x30, 0x41, 0x2f, 0x36, 0x89, 0xc3, 0x05, 0x54, 0x35, 0x8b, 0x14, 0xd6, 0x3a, + 0xc5, 0x28, 0xf4, 0xfd, 0xcf, 0x4b, 0xab, 0x4e, 0xcf, 0xbc, 0x31, 0x9a, 0x50, 0xf6, 0xb7, 0x23, + 0xeb, 0xd3, 0xb6, 0xaa, 0xb9, 0x1e, 0xf8, 0x47, 0xb3, 0x33, 0xda, 0xc8, 0x9c, 0xf6, 0x13, 0x77, + 0xe2, 0x12, 0x47, 0x57, 0xf4, 0xff, 0xf7, 0x9a, 0x53, 0x53, 0xe4, 0xc8, 0x7a, 0xb4, 0xa9, 0x4a, + 0xf0, 0xd9, 0x66, 0x5c, 0x89, 0xc9, 0x6c, 0x7f, 0xe4, 0xe4, 0x70, 0xe4, 0xe4, 0xf3, 0xc8, 0xc9, + 0xeb, 0x89, 0x07, 0x87, 0x13, 0x0f, 0xde, 0x4f, 0x3c, 0x78, 0x14, 0x7a, 0x8d, 0x69, 0xb1, 0x14, + 0xca, 0x64, 0xd2, 0x29, 0x8b, 0x9b, 0x64, 0xe9, 0xe4, 0xdc, 0x2f, 0xfd, 0x00, 0xf8, 0x6c, 0xec, + 0x93, 0xdc, 0x55, 0x9f, 0x80, 0x2f, 0x5b, 0x70, 0xcb, 0x96, 0x7f, 0xdf, 0x9b, 0xaf, 0x00, 0x00, + 0x00, 0xff, 0xff, 0xb1, 0x42, 0x5e, 0xe1, 0xa0, 0x01, 0x00, 0x00, } func (m *Schedule) Marshal() (dAtA []byte, err error) { diff --git a/x/cron/types/tx.go b/x/cron/types/tx.go index 1bca78a71..020550540 100644 --- a/x/cron/types/tx.go +++ b/x/cron/types/tx.go @@ -113,8 +113,9 @@ func (msg *MsgUpdateParams) Validate() error { return errors.Wrap(err, "authority is invalid") } - if _, err := sdk.AccAddressFromBech32(msg.Params.SecurityAddress); err != nil { - return errors.Wrap(err, "security_address is invalid") + // Validate all params + if err := msg.Params.Validate(); err != nil { + return errors.Wrap(err, "params validation failed") } return nil