Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add set_code_hash function and example #1203

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 25 additions & 0 deletions crates/env/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,3 +534,28 @@ where
TypedEnvBackend::caller_is_origin::<E>(instance)
})
}

/// Replace the contract code at the specified address with new code.
///
/// # Note
///
/// There are a couple of important considerations which must be taken into account when
/// using this API:
///
/// 1. The storage at the code address will remain untouched. This means that contract developers
cmichi marked this conversation as resolved.
Show resolved Hide resolved
/// must ensure that the storage layout of the new code is compatible with that of the old code.
///
/// 2. Contracts using this API can't be assumed as having deterministic addresses. Said another way,
/// when using this API you lose the guarantee that an address always identifies a specific code hash.
///
/// 3. If a contract calls into itself after changing its code the new call would use
/// the new code. However, if the original caller panics after returning from the sub call it
/// would revert the changes made by `seal_set_code_hash` and the next caller would use
/// the old code.
///
/// # Errors
///
/// `ReturnCode::CodeNotFound`
cmichi marked this conversation as resolved.
Show resolved Hide resolved
pub fn set_code_hash(code_hash: &[u8; 32]) -> Result<()> {
<EnvInstance as OnInstance>::on_instance(|instance| instance.set_code_hash(code_hash))
}
7 changes: 7 additions & 0 deletions crates/env/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,13 @@ pub trait EnvBackend {
E: From<ErrorCode>,
F: FnOnce(u32) -> ::core::result::Result<(), ErrorCode>,
D: FnOnce(&[u8]) -> ::core::result::Result<T, E>;

/// Replace the contract code at the specified address with new code.
cmichi marked this conversation as resolved.
Show resolved Hide resolved
///
/// # Errors
///
/// - If code not found.
cmichi marked this conversation as resolved.
Show resolved Hide resolved
fn set_code_hash(&mut self, code_hash: &[u8]) -> Result<()>;
}

/// Environmental contract functionality.
Expand Down
4 changes: 4 additions & 0 deletions crates/env/src/engine/off_chain/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,10 @@ impl EnvBackend for EnvInstance {
let decoded = decode_to_result(&out[..])?;
Ok(decoded)
}

fn set_code_hash(&mut self, _code_hash: &[u8]) -> Result<()> {
unimplemented!("off-chain environment does not support contract invocation")
cmichi marked this conversation as resolved.
Show resolved Hide resolved
}
}

impl TypedEnvBackend for EnvInstance {
Expand Down
7 changes: 7 additions & 0 deletions crates/env/src/engine/on_chain/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,8 @@ mod sys {
message_hash_ptr: Ptr32<[u8]>,
output_ptr: Ptr32Mut<[u8]>,
) -> ReturnCode;

pub fn seal_set_code_hash(code_hash_ptr: Ptr32<[u8]>) -> ReturnCode;
}
}

Expand Down Expand Up @@ -676,3 +678,8 @@ pub fn caller_is_origin() -> bool {
let ret_val = unsafe { sys::seal_caller_is_origin() };
ret_val.into_bool()
}

pub fn set_code_hash(code_hash: &[u8]) -> Result {
let ret_val = unsafe { sys::seal_set_code_hash(Ptr32::from_slice(code_hash)) };
ret_val.into()
}
4 changes: 4 additions & 0 deletions crates/env/src/engine/on_chain/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,10 @@ impl EnvBackend for EnvInstance {
let decoded = decode_to_result(&output[..])?;
Ok(decoded)
}

fn set_code_hash(&mut self, code_hash_ptr: &[u8]) -> Result<()> {
ext::set_code_hash(code_hash_ptr).map_err(Into::into)
}
}

impl TypedEnvBackend for EnvInstance {
Expand Down
5 changes: 5 additions & 0 deletions examples/upgradeable-contracts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,8 @@ more information on proxy patterns.
* Executes any call that does not match a selector of itself with the code of another contract.
* The other contract does not need to be deployed on-chain.
* State is stored in the storage of the originally called contract.


## [`set-code`](https://github.com/paritytech/ink/tree/master/examples/upgradeable-contracts/set-code-hash)
cmichi marked this conversation as resolved.
Show resolved Hide resolved

* Update contract code by `set_code_hash`.
38 changes: 38 additions & 0 deletions examples/upgradeable-contracts/set-code-hash/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
[package]
name = "incrementer"
version = "1.0.0"
cmichi marked this conversation as resolved.
Show resolved Hide resolved
edition = "2021"
authors = ["Will"]
cmichi marked this conversation as resolved.
Show resolved Hide resolved

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ink_primitives = { version = "3.0.0", path = "../../../crates/primitives", default-features = false }
ink_prelude = { version = "3.0.0", path = "../../../crates/prelude", default-features = false }
ink_metadata = { version = "3.0.0", path = "../../../crates/metadata", default-features = false, features = ["derive"], optional = true }
ink_env = { version = "3.0.0", path = "../../../crates/env", default-features = false }
ink_storage = { version = "3.0.0", path = "../../../crates/storage", default-features = false }
ink_lang = { version = "3.0.0", path = "../../../crates/lang", default-features = false }
cmichi marked this conversation as resolved.
Show resolved Hide resolved

scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
scale-info = { version = "2", default-features = false, features = ["derive"], optional = true }

[lib]
name = "incrementer"
path = "lib.rs"
crate-type = ["cdylib"]

[features]
default = ["std"]
std = [
"ink_primitives/std",
"ink_metadata/std",
"ink_env/std",
"ink_storage/std",
"ink_lang/std",
"scale/std",
"scale-info/std",
]
ink-as-dependency = []


45 changes: 45 additions & 0 deletions examples/upgradeable-contracts/set-code-hash/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#![cfg_attr(not(feature = "std"), no_std)]

use ink_lang as ink;

#[ink::contract]
pub mod incrementer {

#[ink(storage)]
cmichi marked this conversation as resolved.
Show resolved Hide resolved
pub struct Incrementer {
count: u32,
}

impl Incrementer {
/// Creates a new counter smart contract initialized with the given base value.
#[ink(constructor)]
pub fn new(init_value: u32) -> Self {
Self { count: init_value }
}

/// Creates a new counter smart contract initialized to `0`.
#[ink(constructor)]
pub fn default() -> Self {
Self::new(0)
}

/// Splice `base` and `target` together.
cmichi marked this conversation as resolved.
Show resolved Hide resolved
#[ink(message)]
pub fn inc(&mut self) {
self.count += 1;
ink_env::debug_println!("count is {},use old code", self.count);
cmichi marked this conversation as resolved.
Show resolved Hide resolved
}

#[ink(message)]
cmichi marked this conversation as resolved.
Show resolved Hide resolved
pub fn get(&self) -> u32 {
self.count
}

/// Set new code to this contract.
cmichi marked this conversation as resolved.
Show resolved Hide resolved
#[ink(message)]
pub fn set_code(&mut self, code_hash: [u8; 32]) {
ink_env::set_code_hash(&code_hash).expect("Fail to set code.");
cmichi marked this conversation as resolved.
Show resolved Hide resolved
ink_env::debug_println!("set code_hash success");
cmichi marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
[package]
name = "new-incrementer"
cmichi marked this conversation as resolved.
Show resolved Hide resolved
version = "0.1.0"
cmichi marked this conversation as resolved.
Show resolved Hide resolved
edition = "2021"
authors = ["Will"]
cmichi marked this conversation as resolved.
Show resolved Hide resolved

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ink_primitives = { version = "3.0.0", path = "../../../../crates/primitives", default-features = false }
ink_metadata = { version = "3.0.0", path = "../../../../crates/metadata", default-features = false, features = ["derive"], optional = true }
ink_env = { version = "3.0.0", path = "../../../../crates/env", default-features = false, features = ["ink-debug"] }
ink_storage = { version = "3.0.0", path = "../../../../crates/storage", default-features = false }
ink_lang = { version = "3.0.0", path = "../../../../crates/lang", default-features = false }
cmichi marked this conversation as resolved.
Show resolved Hide resolved

scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
scale-info = { version = "2", default-features = false, features = ["derive"], optional = true }

[lib]
name = "new_incrementer"
cmichi marked this conversation as resolved.
Show resolved Hide resolved
path = "lib.rs"
crate-type = ["cdylib"]

[features]
default = ["std"]
std = [
"ink_primitives/std",
"ink_metadata/std",
"ink_env/std",
"ink_storage/std",
"ink_lang/std",
"scale/std",
"scale-info/std",
]
ink-as-dependency = []
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#![cfg_attr(not(feature = "std"), no_std)]

use ink_lang as ink;

#[ink::contract]
pub mod incrementer {

#[ink(storage)]
cmichi marked this conversation as resolved.
Show resolved Hide resolved
pub struct Incrementer {
count: u32,
}

impl Incrementer {
/// Creates a new counter smart contract initialized with the given base value.
cmichi marked this conversation as resolved.
Show resolved Hide resolved
#[ink(constructor)]
pub fn new(init_value: u32) -> Self {
Self { count: init_value }
}

/// Creates a new counter smart contract initialized to `0`.
#[ink(constructor)]
pub fn default() -> Self {
Self::new(0)
}

/// Splice `base` and `target` together.
cmichi marked this conversation as resolved.
Show resolved Hide resolved
#[ink(message)]
pub fn inc(&mut self) {
// Different step size with old contract.
cmichi marked this conversation as resolved.
Show resolved Hide resolved
self.count += 4;
ink_env::debug_println!("count is {},use new code", self.count);
cmichi marked this conversation as resolved.
Show resolved Hide resolved
}

#[ink(message)]
cmichi marked this conversation as resolved.
Show resolved Hide resolved
pub fn get(&self) -> u32 {
self.count
}

/// Set new code to this contract.
cmichi marked this conversation as resolved.
Show resolved Hide resolved
#[ink(message)]
pub fn set_code(&mut self, code_hash: [u8; 32]) {
ink_env::set_code_hash(&code_hash).expect("Fail to set code.");
cmichi marked this conversation as resolved.
Show resolved Hide resolved
ink_env::debug_println!("set code_hash success");
cmichi marked this conversation as resolved.
Show resolved Hide resolved
}
}
}