问题
Is it possible to have private variables stored in substrate storage, specifically in the following forms and access them in private functions?
#[derive(Encode, Decode, Default, Clone, PartialEq, Debug)]
pub struct MyStruct {
id: Hash, // the `id` is public
// 1. Can this be a private variable not returned by API / to client?
private_var: u64,
}
decl_storage! {
trait Store for Module<T: Trait> as MyModule {
// 2. Can this be private storage used only within module function implementation, but cannot be called by API/client?
PrivateStorage: u64 = 0;
PublicStruct: MyStruct;
}
}
decl_module! { }
impl<T: Trait> Module<T> {
fn _private_function() -> Result {
//can access both private variable/storage
let var1 = <PrivateStorage<T>>::get();
let var2 = <MyStruct<T>>::get();
if var2.private_var == 0 {
// some more code
}
Ok(())
}
}
回答1:
Due to the distributed nature of blockchain systems, all storage is inherently public to the world. Since anyone can sync the blockchain, they will ultimately be able to generate the current blockchain state including any variables in storage. In order to come to consensus about the state of those storage items, they must be visible and known to all parties.
One solution you might be able to use in order to keep "secret data" on a public blockchain is to encrypt the data before it goes on chain, and keep the encryption key off chain.
If you later want other users to know the secret data, the user can "reveal" the encryption key, exposing the data that was originally encrypted.
This commit/reveal pattern is used on some simple blockchain games like rock, paper, scissors.
来源:https://stackoverflow.com/questions/56867236/possibility-of-private-variables-in-substrate-storage