Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Secret network uses Tendermint as a consensus engine combined with the Cosmos SDK, as such it has a relatively high throughput and the possibility for easy horizontal scalability. Because of this, there is no fee market on Secret Network, which means there is no fee-based prioritization built into the standard tendermint binary required to run Secret. Using a higher transaction fee will only increase the number of block signers (validators) that are willing to process your transaction. This might speed up finality but does not prioritize your transaction in the cue.
The fee a user pays for a transaction is based on two things: the computational resources/block space that is used and the fee that validators ask for these resources. These two elements are called gas
and the gas fee
.
The gas
required for the computation is determined by the smart contract engine. The current gas estimates per type of contract interaction are listed here (for SDK components) and here (for enclave components). More complex transactions will consume more gas.
The gas fee
is determined by validators themselves as a parameter in their node service. The min_gas_fee
parameter allows validators to set a minimum fee denominated in uSCRT
. If a transaction has a lower allocated fee, they will not add it to blocks they propose. Validators propose blocks based on random selection following their Voting power. The min_gas_fee
for each block is dependent on the proposing validator. If blocks become too full or an attacker spams the network, the validators can increase their fee.
Secret validators run three tiers of fee's; this choice is up to the validator. Overall, we can assume more than 40% of validators support the "low" fee option, meaning pushing a TX with the low fee often gets processed within a few blocks. Pushing a TX with the "High" fee will increase the chance that the next block can fit your transaction. These TXs are therefore considered "faster". The current recommended fee options are listed in the Cosmos chain registry.
Now let's assume we execute a swap for a single Dex pool. We can expect this to take roughly 150000 Gas
. Executing this at the "low" fee option, we will pay 0.0125 uSCRT
for each Gas
unit used. The total fee for this transaction then becomes: 150000 * 0.0125 = 1.875 uSCRT = 1.875/1000000 = 0.001875 SCRT
. At 40% voting power supporting a min_gas_fee
of 0.0125 uSCRT
we can expect this transaction to be finalized after 4 blocks ( 4*6s = 24s
) with a 97.5% certainty [1- (40%**4) = 0,9744
].
Secret also allows for Gas abstraction for users by leveraging the CosmosSDK FeeGrant module. This module allows one to submit transactions where a different wallet is paying the gas fees as long as they granted you a budget to do that.
Documentation to create Feegrant functionality in your UI are here. This tool is widely used in different Secret UIs (for ex: Secret dashboard) and there is a community run FeeGrant faucet available for dApps to use. - Faucet - Code
As explained in the section Secret computational load is denominated in gas
. The amount of gas that can be spend at every block is capped via the max_gas
block parameter. This cap is currently set at 6,000,000 (6 million) gas
meaning a block will never contain more computational load than what is represented by 6 million gas. The computational load per gas unit is calculated and then denominated in the chain binary.
You can find the Gas settings for Secret Network in the Network code here - ,
The max_gas
parameter is chosen in such a way that validators can ensure they process the full computational load within the target block execution time (~6s). If this computation and expected blocktime don't align the blocks will become longer and longer as they await 66% of voting power to sign the block. When block time increases the TPS of the blockchain drastically decreases only complicating the situation further.
You can read more about this interplay between blocktime, TPS and scalability in this .
One can expect the overhead of all enclave and encryption transactions to be roughly 30% over a vanilla wasm engine. This overhead comes from the decryption and re-encryption done in the enclave and the varying verification's that are required of the message input data. This overhead does not exist for standard SDK messages like "stake", "transfer", "vote" etc.
Additionally Secret leverages an older engine for the wasm VM dubbed "Wasm3". The vanilla engine "Wasmer" is roughly10-15x more performant. This engine is not yet supported as there is no Enclave compatible version, development effort to support it though is underway as listed in the .
Because of above factors the TPS of Secret is limited in comparison to vanilla Tendermint and Cosmos SDK benchmarks. Based on an average of 100.000 gas for a contract interaction (something like an NFT mint or non-routed DEX swap) Secret can process 60 TXs per block which at ~6s per block 10 WASM transactions per second. SDK interactions take a lot less gas meaning the overall TPS of Secret in practice is ~25.
As explained in the above section this number can still be significantly increased by upgrading the WASM engine but has proven sufficient so far in periods of high demand
Important to note is that Queries related to contract state require the API node to access the enclave, these are therefore more resource expensive than SDK queries. Secret API infrastructure needs to be scaled accordingly to fit heavy load user interfaces. One can expect to require more Secret API nodes than standard Cosmos API nodes for a similar application. As transaction complexity overhead decreases with better engines so does increase the ability for a node to process queries. Verified queries on Secret have already become a hundred times more performant with 1.4-1.6 upgrades, and with the current community API they are in a very stable spot.
This page describes some of the core information required to get up to speed about the state of Secret Contracts in comparison to public (cosmos) networks.
Smart contracts on Secret Network follow the widely used framework. The framework is built as a module for the Cosmos SDK and allows developers to build smart contracts with which compile to (Wasm). This type of efficient and fast binary, combined with the power of a low-level typed coding language, makes CosmWasm a secure and efficient way for developers to write smart contracts. Contracts on Secret have a public binary just like any other smart contract network, only the contract input, output and state is encrypted.
Secret Contracts slightly differ from any standard CosmWasm implementation as they handle encrypted data, secure enclaves, and the key design around that. Secret currently emulates CosmWasm v1.1.9 and is completely compatible over IBC with other V1.0+ Cosmos Smart contract networks. To learn more about IBC compatible contracts you can read .
Private data (contract input, output and state) on Secret is encrypted using an unforgeable contract encryption key which is unique for every contract. Moreover, the user dedicated state in a contract is only visible to the user themselves. Because of this design, contract migration is a privacy risk. If enabled, a contract admin could upload a malicious contract that reads and prints data entrusted to the old contract. CosmWasm native contract migration is therefore disabled on Secret; workarounds are available . Additionally, iterators and raw queries are not supported as one can not iterate over data stored by a different user as there is no access to their dedicated encryption key.
More information about the differences in implementations for a contract between Vanilla and Secret CosmWasm are listed
Secret contract encrypted input and access-controlled output is very powerful and enables many different usecases, combining this with novel development tools creates a powerful framework for developers to leverage. Below some of these tools and ideas are listed to get your brain going.
- More utility for other blockchains by leveraging Secret contracts cross-chain. Want to build on polygon, ethereum, Sei, Neutron or Aptos but want additional features only possible with data privacy? You can use Secret contracts cross-chain to keep your application decentralized and offer users new and interesting ways to explore your dApp.
Storage of private/encryption key (fragments) - One can use Secret contracts to store very sensitive info to enable cool usecases like access-controlled content or even cross-chain account ownership for DAOs and unstoppable threshold wallets.
(secret-vrf) and hidden (game) state - Games on Secret benefit of true on-chain randomness that can remain hiddin inside the contract forever if so desired. Together with a hidden gamestate this brings a whole new dimension and fairness to turn-based games for Web3 like Poker or Mario party and more clarity and ownership to casino games and lootboxes.
Frontrunning resistant and privatized DeFi - because of an encrypted mempool secret is frontrunning resistant by default. Order size - unknown, Placed bids - unknown, liquidation points - unknown and many other features from orderbooks to dark pools have these privacy features as well.
- a Javascript library for interacting with the Secret network, Secret contracts, providing encrypted input and creating viewing keys/permits for encrypted output. The library can also be considered as a more complete Cosm.js and can be used on every other cosmos chain. - Alternatives in , , and more exist as well.
, , (CW-plus) and - Secret has dedicated tooling sets built by external teams and core development that abstract boilerplate code (for DeFi), help with testing scenarios, simplify contract development nightmares like storage and type handling and even catch errors as you work in a dedicated IDE.
IBC, Interchain accounts/Queries/contracts, Axelar GMP, Bidshop messaging and more - Want to build your application crosschain? Secret has many options for both Message and Asset bridging protocols with the most renowned being IBC (current version IBC-go V4).
In practice a Secret contract developer does not have to think too much about this as its abstracted away in the data verification process in the contract module of the network.
One example of such a privacy optimized design would be the use of the Gas evaporation function as added in the v1.9 upgrade and documented here (link coming soon).
There are various types of outputs that can be expected, including:
An updated contract state (i.e., the user’s data should update the state or be stored for future computations)
A computation result encrypted for the transaction sender (i.e., a result should be returned privately to the sender)
Callbacks to other contracts (i.e., a contract is called conditional on the outcome of a Secret Contract function)
Send messages to other modules (i.e., for sending value transfer messages that depend on the outcome of a computation).
Reply - Send more detailed error logs of various submessages as explained here.
The binary of any contract is public, meaning the execution logic is verifiable just like any other smart contract blockchain.
Secret smart contracts are IBC compatible (CosmWasm v1.0+), allowing for cross-chain logic with other IBC-connected chains.
When designing Secret contracts, the verification of input-data is key to ensure the secure execution of transactions as not all blockchain data is exposed automatically to the enclave.
Developers need to be mindful of data leakage via replay attacks, improper padding, and more so that the privacy for users of their contracts is optimized.
An in-depth explanation of Secret VRF, a secure and verifiable random number generator
Want to develop with decentralized on-chain randomness?
The ability to generate fair and verifiable random numbers on blockchain without compromising security or usability is critical for many decentralized applications. However, generating true randomness is difficult because blockchains rely on consensus mechanisms, such as Proof of Work or Proof of Stake, to reach agreement on the state of the network, and these consensus mechanisms are deterministic and therefore do not provide a source of true randomness. There have been attempts to solve this problem by various methods, such as using random data from external sources (the hash of a previous block, etc) or by using off-chain solutions, such as Chainlink’s VRF oracle, but these solutions are not optimal as they are either deterministic, rely on trusted parties, and/or require additional fees for gas and infrastructure. What is needed is a verifiable random number generator that exists on-chain, and this is now possible across blockchain ecosystems through Secret Network Random Number Generator (RNG).
The ability to generate true randomness is a fundamental requirement for blockchains. Verifiable randomness guarantees that operations such as the minting of NFTs, on-chain games, and DAOs are equitable and secure. In the case of NFT minting, randomness allows for features such as unordered minting, trait randomization, and identity numbering, all of which are critical for verifying the authenticity and security of NFT collections. In Web3 gaming, components such as gambling, damage calculation, loot boxes, boss drops, etc, rely on randomness to create trust amongst players and ensure that no player has an unfair advantage. And in the case of DAO tooling, randomness is required for features such as wallet initialization, task assigning, unordered voting/liquidations, order book ordering, etc. By using Secret Network RNG in these and other applications, the Interchain can help to ensure the security, transparency, and fairness of blockchain operations, which in turn promotes the growth and adoption of the Cosmos.
Secret Network is built on top of Tendermint, a peer-to-peer networking protocol that provides Byzantine-Fault-Tolerance (BFT) and Proof-of-Stake (PoS) consensus. This consensus ensures that all nodes maintain the same blockchain and that all nodes have the ability to propose new blocks. From a high-level standpoint, a new consensus round is:
Initiated with a Proposer Node
The Proposer selects transactions in the mempool to be included in a new block
This proposed block is broadcasted to all nodes (Pre-vote phase) and nodes verify that the block is valid, simultaneously verifying that the Proposer is also valid and sign the pre-vote message
If >2/3 of nodes pre-vote for this block, the block is deemed valid
Once a block is committed, there is no way to revert it and there is instant finality
The process of block proposal and execution involves a crucial intermediary step known as the "prevote phase." Secret Network RNG creates verifiable on-chain randomness by generating a random number that is attached to each Proposer’s block proposal, and this random number can then be used for on-chain randomness for the current block and exhibits the following properties:
The number is generated with sufficient entropy
The block proposer cannot predict or influence the entropy generation
Outside actors cannot predict random numbers before they are used to compute network transactions
Secret Network achieves this by implementing the following privacy network consensus:
Secret Network is unique from other blockchains because it utilizes Software Guard Extensions (SGX) to provide a Trusted Execution Environment (TEE) by creating a secure area in memory, called an "enclave," where sensitive data and code can be processed in a way that is isolated from the rest of the blockchain. This means that even if the operating system, other applications, or an attacker were to somehow compromise the security of the blockchain, the data and code within the SGX enclave remains protected.
Secret Network’s SGX allows for private computation on-chain and uniquely positions Secret Network to be the privacy provider of the interchain. In order to provide randomness as an interchain service, Secret Network’s SGX generates a random number on-chain during the block proposal stage of Tendermint. Block proposers generate a random number inside of the Trusted Execution Environment using RDRAND/RDSEED instruction.
RDRAND and RDSEED are Intel Secure Key technology instructions used in computer processors to generate random numbers
The RDRAND instruction is used to generate random numbers, while the RDSEED instruction is used to generate seed values for cryptographic purposes. Externally influencing RDRAND that is executed inside an SGX enclave is very difficult to do, with no known practical or theoretical attacks that can reduce the resulting entropy of the instructions.
In addition to generating random numbers using SGX, Secret Network adds an additional layer of security to the output of the random number generation by pairing it with an Initial Randomness Seed (IRS). This seed originates from a shared consensus seed among all network nodes, and the random number and IRS are combined using an algorithm called HKDF(rfc5869) to certify that the final number is truly random and cannot be predicted by anyone, even if they were to influence the original random number generation.
Secret Network also includes an additional key that is available to all nodes on the network within the TEE called the Random Encryption Key (REK). The REK is used to encrypt the generated random number using symmetrical encryption, and the encrypted blob (Erand) is attached as a new field to the block proposal. The REK is derived from the consensus seed, so all network nodes can derive it without the need for key-sharing protocols.
In order to make sure the random number generated by the block proposer is secure, a majority of network validators must signal their approval of the proposed block before the encrypted number can be decrypted. Tendermint’s pre-vote mechanism allows the blockchain to “signal” that the proposed block has been authorized by a majority of network validators, and guarantees attempted execution of the block. Therefore, the only way to decrypt the Initial Randomness Seed is for nodes to submit a 66% majority of pre commits/commits to the TEE. The TEE will then verify this majority and decrypt the seed, returning it to the caller in its decrypted state, which can be then used for network randomness.
To prevent errors or malicious behavior, the encrypted number will be accompanied by a proof, which is defined so that an SGX enclave can verify that the proposed encrypted random number matches the block height and active set of the current Tendermint block. The proof is created using a one-way-function that takes the encrypted random value, the block height, active validator set, and the Random Encryption Key (known only to network nodes). With the proof key, SGX enclaves can verify that the proof was made within the enclave.
Secret Network’s TEE is continuously updated in response to changes to the active set of network validators. In order to avoid the issue of verifying changes to network validators, the active network validators influence the result of the derived random value during the decryption and verification process of the random number. Thus, changes to the active validator set produce a different random number, thereby rendering attacks using modified active validator sets ineffective. In addition, attempts to fork the chain and decrypt the number using a different active validator set are also rendered ineffective.
If a harmful actor were to attempt to fork the chain to predict the next number, the attack is rendered ineffective because the next number is generated randomly by the block proposer's enclave and cannot be predicted. Furthermore, a validator cannot execute blocks without the ability to decrypt the random number, which requires submitting prevotes to do so. If the malicious validator attempts to reuse a previous random number, the validator must submit a proof that links the encrypted random number with the block height and validator set, which it cannot.
To avoid being able to replay previous signatures with a new encrypted value, the encrypted number must be part of the transactions signed by the validators when creating their approval votes. To validate the prevotes, the TEE needs to receive the signatures and the original transactions. As an optimization, validation of the prevotes by Tendermint can be offloaded to the TEE to avoid verifying the same data twice.
Given that the voting power of validators fluctuates constantly and the computation of the active set's hash can be demanding, Secret Network achieves optimization by setting a minimum sensitivity to the changes in voting power. However, this can lead to disparities between the pre-vote weight and the weight calculated by the TEE, so the validation threshold must be lowered for the TEE. For instance, on Secret Network, if a 0.1% sensitivity to voting power changes is established, a prevote threshold of 61% would be necessary to consider the worst-case scenario where 50 validators, who together make up 66% of voting power, submitted prevotes with a 0.1%-ε higher voting power than what the TEE is aware of.
Finally, if a malicious actor were to somehow break Secret Network’s SGX and steal the REK it would be inconsequential because random numbers are generated independently for each block, so knowledge of a single random value is of no use without the ability to influence block creation. Even in a scenario where the malicious actor was a validator and could submit random numbers for blocks they propose, it would be ineffective because they do not have access to the consensus seed as stated above.
In conclusion, the Secret Network Random Number Generator (RNG) is a significant breakthrough in the generation of verifiable and fair random numbers on-chain. By leveraging the power of SGX and Tendermint consensus, Secret Network has created a first-in-class on-chain solution that generates random numbers with sufficient entropy, and these numbers are then encrypted, paired with an Initial Randomness Seed, and attached to block proposals where they are decrypted in order to generate true on-chain randomness. Coupled with cross-chain interoperable smart contracts over IBC, Secret Network enables thousands of developers and projects across the Cosmos access to state-of-the-art on-chain RNG.
Your start on privacy design for Secret smart contracts
Secret Network provides all the tools necessary to build fully private decentralized applications, but contracts do not automatically inherit perfect privacy. Privacy has a cost. Developers have both the freedom and the burden of choosing a privacy model that fits their applications' needs.
Protecting sensitive user data is not even the whole story when it comes to Secret dApps. Achieving a proper level of privacy can be mission critical in certain areas, such as competitive gaming, where an information leak could lead to a compromised system, say, if an attacker were able to cheat.
As a developer, it is your responsibility to understand the gamut of privacy risks, their implications, and how to best mitigate them.
Let's start off with a thought experiment. In an ideal world, a perfectly private application would be one that an attacker could not plausibly deduce any information about regarding its state, history, or participants. To an observer, any time a participant reads from or writes to the contract, it would be indistinguishable from every other action.
All outputs would appear to be random and unpredictable, with no discernible patterns that could be used to infer the underlying operations or data. On top of all that, the timing and frequency of executions would need to be consistent across the lifespan of the application.
Most of the items below are covered in greater detail here:
In reality, there are many forms of contextual data that an attacker can use to infer information, de-anonymize users, or compromise the privacy of applications purely through analysis:
transaction sender's address, their public transaction history, the timing and frequency of their transactions, and their relation to other accounts on the network
public inputs and outputs of an execution, such as sent or received funds (e.g., wrapping/unwrapping SCRT or IBC tokens)
timing of an execution, its temporal locality to other transactions (e.g., clustering, dispersion, co-ocurrence), and an execution's order relative to other on-chain events
size of the encrypted inputs and outputs of executions, shape and size of the event log, and public transaction metadata including gas_used
and nested calls to other contracts
timing, frequency, shape and size of query requests and query responses
storage access patterns when a contract reads from and writes to the encrypted application database
Additionally, there are active attacks that can expose unwanted leaks of information:
executions that produce measurable side-effects
tx replay attacks, side-chain attacks, the Millionaire's Problem
targeted storage access pattern attacks
Its important to note that a few of the risks listed above can only be mitigated by user OPSEC. For example, the timing and frequency of executions, tx sender address, and relations to other accounts are risks typically assumed by end-users. In these cases, education is the best instrument to protect users' privacy.
Some of the other risks should be mitigated by client-side software, such as wallets and dApp front-ends. This includes padding inputs to executions and queries, being strategic about the timing and distribution of query requests, and creating workflows that allow users to more easily create identities that are not linked to their public account.
The remaining privacy risks are those which can only be mitigated through contract design. Developers should strive to make all queries and executions appear indistinguishable from one another to an outside observer. This includes:
adding decoy attributes to the event log when necessary
understanding storage access pattern attacks and employing a system of decoys or oblivious data models (or even UTXO)
This page explains the concept of input data verification, a required mechanism to ensure reliable privacy for secret contracts.
A more in-depth explanation of input-data verification and the Replay attack vectors that come with are displayed in the "" section of the Encryption specs.
As Secret runs the compute module from within the enclave of the validator node it handles 2 types of data, data coming from within the enclave or outside of it. This data can then be separated as trusted (in-enclave) and un-trusted (outside enclave) meaning you can only rely on the trusted to be true in all cases, the untrusted data can be forged either with replay attacks on forked chains or state modification attacks.
The amount of trusted data options can be increased by additional verification mechanisms.
During execution, some contracts may want to use "external-data", meaning data generated outside of the enclave and sent into the enclave, such as the tx sender address, the funds sent with the tx, block height, etc...
As these parameters are sent to the enclave, they can theoretically be tampered with, and an attacker might send false data; making relying on this data conceivably risky.
For example, let's say we are implementing an admin interface for a contract, i.e. functionality only for a predefined address. We want to ensure the env.message.sender
parameter provided during contract execution is legitimate, so we will confirm that env.message.sender == predefined_address
. If this condition is met we can provide admin functionality. If the env.message.sender
parameter can be tampered with — we effectively can't rely on it and cannot implement the admin interface.
This verification is done by a light-client implemented inside of the enclave which validates all compute transactions and their order. It matches the set of transactions to be executed with the data hash field of the block at the current height. This means we can trust contract executions (Attention: not other modules like Bank), User address, inputs and sent funds are all part of the signed and validated inputs.
The light client does not validate internal contract calls - when your contract calls another during runtime - but these are signed in such a way that it can only be generated by another contract inside a genuine enclave. This can be considered trusted execution as well.
Looking at state modification attacks - these refer to attacks that attempt to modify the internal state of the chain to create behaviour that allows to compromise confidential data. This can be done by changing the internal state values of the chain (even encrypted values can be replaced with other valid encrypted values) and executing the real transactions to see what happens.
For example, imagine a contract that has the following logic:
Receive transaction from user with some amount of SCRT
Validate that payment is exactly 1000 SCRT
If payment is correct, reveal secret value
An attacker can use a modified chain to attack this logic in the following way:
Send a transaction on the real chain with 1000 SCRT from an address that has 1 SCRT
Wait for the transaction to fail on mainnet
On a modified chain fund the attacker's address with 1000 SCRT
Replay the real block from mainnet
Reveal the secret value
This scenario illustrates how payment systems need to consider these attack values.
Protecting against modified state is being actively developed, and will be solved by validating that values that are read from the chain are part of the merkle tree of the chain itself - Coming end of 2023
Trusted = No
means this data can easily be forged. An attacker can take its node offline and replay old inputs. This data that is Trusted = No
by itself cannot be trusted in order to reveal secrets. This is more applicable to init
and handle
, but know that an attacker can replay the input msg
to its offline node.
Full example guide on mitigating privacy risks.
Here we use a sample contract for selling a secret message to illustrate padding, gas evaporation, and side-chain attack prevention using a trusted actor to confirm transactions. In the contract we define three methods: posting a secret for sale, buying a secret, and confirming purchases. All three message types have two optional parameters: gas_target
and padding
. These will be used to help mask which message is being called.
execute
Padding and evaporation are parameters that are set for all message types.
The padding
parameter is used by the client to pad the size of message being sent to the contract. The padding
parameter is not used within the contract itself and is only necessary when using Keplr's amino format. In other cases the dapp or wallet can simply add extra space characters to the end of the json message.
We also want to pad the result sent back to the client. We can use the pad_handle_result
function from secret toolkit to format the response to a fixed block size. If you have responses that are large, you will need a sufficiently large block size to successfully mask the method being run.
After padding the result at the end of execute
entry point function, we use gas_target
along with the evaporation api functions to evaporate any remaining gas to hit the gas target. Note, we simply ignore both the padding
and the gas_target
message parameters using ..
in the match statement.
Just like we want to use padding to hide the message type when sending between the client and the contract, the number of bytes written to the chain can leak information about what is written. For example, a coin amount stored as a Uint128
will write a different number of bytes depending on the size of the number, and also in our example the secret message could leak information based on its length. For data structs we want to store on chain we usually create a stored version and create conversion methods between the unstored and stored versions. Note in the example, we use the secret toolkit space_pad
function to make all secrets stored as 256 bytes long masking the content.
Padding and evaporation help to protect privacy about what types of functions are being called in a contract and about what data is being read and written from storage. However, our contract is still vulnerable to a side chain attack if a buyer can simply purchase a secret without a trusted actor confirming the transaction. This is because a malicious actor could fork the chain and buy the secret on the forked chain without ever paying any coins on the mainnet.
In our case a trusted actor who can confirm the purchase is the seller of the secret. If all purchases must have the ConfirmPurchase
transaction performed after buying, then it is impossible for the side-chain attack to occur. Other contracts that need to implement this functionality might require a trusted third-party actor instead, for example a game contract where turns are executed on-chain.
The equivalent of padding for gas_used
When a smart contract is executed, CosmWasm meters how much gas the execution consumes while the program is running. On Secret Network, this all happens within the enclave. However, once execution completes, the total amount of gas that was consumed leaves the enclave and is made public in transaction metadata.
The public gas_used
result of a contract execution message reflects the sum of costs for the actual instructions that were executed. Within a typical smart contract, most of its methods consume different amounts of gas. With SNIP-20 for example, an attacker could deduce which method a transaction executed with a high degree of certainty; create_viewing_key
vs. transfer
vs. increase_allowance
, each of which produce a distinct gas_used
amount in the public transaction metadata.
In some cases, this can leak even more information such as which code path was taken, the value of a conditional, how many iterations a loop completed, and so on.
Evaporation is a concept that was introduced to overcome the privacy risks associated with gas_used
. Evaporation refers to the practice of deliberately consuming extra gas during execution in order to pad the gas_used
amount before it leaves the enclave.
With evaporation, clients can now instruct contracts on exactly how much gas their execution should consume, yielding a consistent gas_used
across all methods.
A contract can evaporate an arbitrary amount of gas using the built-in API function gas_evaporate
. In order to evaporate any remaining gas, the check_gas
API function allows contracts to calculate the difference between the amount consumed up to that point, and the amount the client wants the contract to consume by the end of its execution:
See the evaporation example contract's for more details.
Note that there is no API function to get the amount of actual gas remaining. Instead, that information must come from the client. This practice ensures that users are still able to execute multiple messages in a single transaction by specifying gas limits to each contract execution individually.
The new check_gas
API function essentially gives contracts read access to CosmWasm's internal gas metering. Calling this function more than once during execution allows contracts to track changes in the amount of gas consumed. This simple feature enables a realm of interesting use cases not previously possible.
In its simplest form, gas tracking can be used as a development aid to inspect the amount of gas used by certain blocks of code, giving developers more insight and help with optimizing their gas footprint.
A more advanced use case involving gas tracking is opportunistic execution, where contracts take advantage of excess gas that would otherwise be evaporated by performing work that needs to be done anyway. That work could be anything from generic housecleaning duties, such as processing items in a queue, to more intentional duties, such as notarizing previous user actions to protect against tx-replay attacks.
To give an example, imagine an NFT auction contract that accepts bids on listed items. When a listing expires, the listed NFT should be transferred to the highest bidder. In typical contract design, the transfer would only actually happen once the winning bidder calls a method to "claim" their winnings. However, with opportunistic execution, the contract can automatically perform the transfer during any execution. For example, someone creating a viewing key could end up paying the gas fees to complete the transfer of a previous listing's NFT to its winning bidder.
The section in the Encryption specs of the documentation highlights most of the privacy attacks developers should consider.
The section also quickly describes everything to take into account.
A technical deep-dive into how Secret can provide confidential computation to dApps on other blockchains by leveraging cross-chain communication and Secret contracts.
This section will go over 4 different design options with highlighted use cases. This section should hopefully spark interest into using Secret's Confidential Computing Layer (or "CCL") as a whole and help developers understand the possibilities and limitations of this contract development paradigm.
The CCL in its most basic form is the idea that one can create products with privacy or additional utility for users who are not on Secret Network itself while using Secret contracts in the backend for the application.
Do you want to tap into Ethereum's liquidity, the polygon NFT scene or just want to add additional encryption-powered use cases to your current techstack? Secret's CCL might be a perfect fit.
The below design paradigms are separated based on the data flow in the app. The simplest apps only take data to and from Secret, while more complex apps either keep all the data separate, or take private data in and return public output.
The first design pathway only takes data from a Secret contract but is non-interactive beyond that. This means implementing use cases in this path can be considered relatively simple by leveraging IBC, Axelar GMP or other cross-chain messaging solutions.
In this dApp design scheme, we see Secret as a blackbox that has data accessible useful to any other chain on request. The requested data will have to be transferred publicly. The best example is on-chain randomness via .
By leveraging a slightly altered version of Tendermint and the Secure Enclave of every validator, Secret managed to create a truly random number generator on-chain. Every block and every contract call, the number is different and the numbers are verifiable via a callback after the block finalises. A developer on another blockchain can design a lottery completely on-chain by determining the random outcome using Secret-vrf. Simply make a contract on the consumer chain that requests a random-number (over IBC) from a Secret contract. Make sure the lottery entries close before requesting the number as it will arrive over public channels after the block closes on Secret. The number is now used within the contract on the consumer chain to assign the winner; no data has to return to the Secret contract.
Want to leverage Secret-VRF for your application on EVM or IBC? -
For the second design pathway, data flows towards Secret in an encrypted format with the output merely verifying if the input matches a pre-set pattern or any other defined criteria. Secret contracts here are mainly a decentralized and immutable data-storage mechanism with easily definable access controls.
The best example for this design pathway is web2-esque authentication for application login or other access controlled services. The first dApp leveraging this to its full extent was ALTER, a p2p encrypted communication platform enhanced with Secret smart contracts. The ALTER dApp allows users to store their session encryption key on the Secret Network inside of a Secret contract. Access to this contract and the key is then gated by a Wallet login functionality that ties one's crypto wallet public key to this contract - users can now sign in with their wallet and start messaging. However, this could be taken much further into the web2 realm by allowing sign in via Google web-Auth, password or even biometrics. You can also have usecases where we merely check if a user is who they say they are against identity, credit scoring or other personal information oracles.
The Authentication use case however can be taken much further. A Secret contract could not only check the input against a string it contains, but also influence actions on another chain. The first use case in this region is Unstoppable wallets, a form of on-chain Threshold wallets with unparalleled access control and ownership designed by SCRT labs. For unstoppable wallets, a Secret contract governs one part of a larger private key (MPC) and by programming access control policies into the contract, it will decide to sign or not sign a specific message. Every wallet signer commits the signature for the proposed TX to the Secret contract, the contract checks if the set policies are met and returns a valid signature that can be posted to Ethereum or any other blockchain for that matter. One could even decide to provide the Secret contract with a majority share of the private key allowing it to process transactions on its own for automated strategies or even Walletless applications where users can sign TXs with web2 authentication methods instead.
Want to learn more about Unstoppable wallets? - Watch from the SCRT labs CEO and Secret Network founder Guy Zyskind at Gateway to Cosmos Prague 2023.
In a "sister contract" design scheme the Secret contract and the CCL consumer chain act as two separate entities with which the user interacts separately. This allows developers to work with encrypted output, something none of the other CCL design flows allow.
Sister Contracts is the idea that one can accompany applications on other networks with access controlled data or functions by leveraging a Secret contract. The simplest usecase to explain here is in the realm of NFTs, certificates or other non-fungible personally assigned data objects. It is of paramount importance to many dApps that their usecase is accessible by many, hence why developers often choose for EVM or specifically Ethereum as their home network. With Sister contracts, one can have NFTs, certificates, Invoices or any other item be created on this user-rich chain while simultaneously linking it to a counterpart on Secret network. At any moment in time, the user who owns the item on Ethereum can verify their ownership to the Secret counter-party contract to reveal additional information only visible to them.
The above scenario requires users to interact with two networks to get the full experience of the respective dApp even if cross-chain messaging is already used by the developer. This is because private metadata can only remain private if the user interacts directly with the Secret blockchain without intermediaries like public bridging solutions. Developers can abstract many of these complexities by making intuitive UIs that allow users to use the same wallet for both networks (Metamask for ex.).
Do you want to flare up your NFT with additional private metadata, have access-controlled content for your marketplace or content platform, or store sensitive information related to invoices, IDS or certificates all while keeping your assets or dApps in the most liquid markets? - Then start building a Sister contract with Data privacy for your application now!
Lastly, a hybrid approach is possible between the previous design flows, one where there is a private input from any other chain but what is returned is a delayed public output so that all interactions for the user remain to a single chain. As explained before, we can only guarantee output privacy for a user if they are directly interacting with Secret network, but sometimes privacy is not needed for the output - it is only needed for the input.
One such example is private voting. Voting is inherently a public system, the result matters to everyone who voted and maybe beyond that. However, it is important participants can vote at their discretion with full privacy so there is an honest and non-biased outcome. In blockchain, this is not the case: close to all DAOs and chain governance is public by default.
One can design a dApp that allows Ethereum (or any other chain) DAOs to vote privately by voting via a Secret contract instead. Users encrypt their vote and their VP with the TX encryption key of the Secret network contract. The contract remains open for a set amount of time to collect votes after which it tallies results and emits the output. The output can be sent back to the consumer chain to complete the official voting process.
Secret contracts are an awesome tool for native account abstraction. This all comes down to the fact that Secret-contracts can store (parts of) private keys in their state without revealing them to other network participants or observers. This concept was first thought out by scrt labs in a proof of concept multiple years ago [Code], then uttilised by Alter for easy log-in (), but the newest version uses novel additive HE and MPC to create a form of Unstoppable Threshold wallets . This proof of concept is now taken by and to develop walletless experiences and secure threshold wallets for the next million users.
Obi.money can help you setup smart accounts for your Secret dApp already, feel free to reach out to them!
Want to learn more about Unstoppable wallets? - Watch from the SCRT labs CEO and Secret Network founder Guy Zyskind at Gateway to Cosmos Prague 2023.
One can also use the native AuthZ module supported on Secret to have other accounts perform any specified action for any specified amount of time and limit. A usecase for this is more secure voting and autocompounding interfaces like Restake.app.
Smart contracts can also use ICA/ICS-999 (although host module is not supported yet) to control accounts on other chains over IBC and manage funds in interesting ways. Feel free to check out the codebases/Apps of r and calc.finance to get an idea of what that can look like.
One can also leverage cosmos wide forms of account abstraction like implemented by Larry from delphi.
Short term scalability improvements can come from a WASM engine replacement and increase in Light client verification methods so to lower the enclave load. Also storage access can become more performant with an SGX backend change which is on the short term roadmap. Long term Secret does not have to worry about blockspace with the plenty opportunities of replicated security and the cosmos sdk. For more on the core development roadmap check out the .
The privacy of Secret Network is reliant on secure enclaves, which impacts how the network performs but also how one should design their contracts to enhance privacy. Firstly, it is important to note that only data originating from inside the enclave is verifiable and any data coming from external resources has to be verified before relying on it for execution. This means data coming from contract callbacks is to be trusted, but the sender address is not. If I allow the sender to create an item on-chain, then only the sender should be able to remove that item. Verifying that it is indeed the sender (data owner) that is requesting this change is done by "input data verification". Explanation of the various network level integrated methods is available
When designing contracts for Secret network, one should take into account the usage of so-called replay attacks and other vectors on secure enclave derived privacy. An example of this is the abundant usage of the Contract hash in Secret contract development. The usage of a contract hash is required to link the input to the specific contract being called. Otherwise one could make a forked chain and replace the contract with one that reads and prints the input parameters. Although encryption for Secret contracts is handled by the protocol, developers should still be mindful of their contract design to optimize for these privacy aspects.
Want to dive deeper into the CosmWasm framework? - You can read more about it's design in the
Secret Contracts have private input, output and state. This means all data on-chain is stored as cyphertext and is only accessible by the owner (either the contract or the user). More details are available in the .
from v1.11 Secret now supports migrate-able contracts just like vanilla CW, it does not support iterators due to contract privacy design. Workarounds are highlighted under .
For documentation on using Secret VRF in a native Secret contract, .
padding query and execution results (see and from the )
using to make all methods consume a consistent amount of gas
Find code implementation of the above privacy preserving methods under our
Although query
cannot change the contract's state and the attacker cannot decrypt the query output, the attacker might be able to deduce private information by monitoring output sizes at different times. See to learn more about this kind of attack and how to mitigate it.
Type | Trusted? | Note |
---|
This same concept applies to many different use cases like sealed bid auctions and obscuring the game-state of turn-based games. The first mainnet application on Polygon called is using Secret Network in this way to enable a gamified auction platform. To enable these use cases, cross-chain messaging is needed from either Axelar GMP, IBC or other solutions. Bidshop will be allowing integrations for other dApps on their novel trustless message bridge as well, want to get connected? Let us know!
Want to get started with CCL or explore the possibilities but need some extra help?
Storage | No | Can be rolled back - merkle proofs will make it trusted (end 2023) |
Env | yes | Protected against fork attack |
Sender | yes | verified - fork protected |
Inputs from sender | yes | verified - fork protected |
Funds (input from non-compute module) | no | Fork attack can replay failed Tx from mainnet |
Contract callback input | yes | anything that originates from within the enclave is trusted |
How to design your contract to limit the amount of leaked data from storage access patterns
Coming Soon!
You can use the Feegrant module or Smart contract based fee abstraction to simplify the usage of your dApp as explained here!
Secret also allows for Gas abstraction for users by leveraging the CosmosSDK FeeGrant module. This module allows one to submit transactions where a different wallet is paying the gas fees as long as they granted you a budget to do that.
Documentation to create Feegrant functionality in your UI are here. This tool is widely used in different Secret UIs (for ex: Secret dashboard) and there is a community run FeeGrant faucet available for dApps to use. - Faucet - Code
You can use Smart-contracts with Fees deposited in them to abstract fee usage and automate tasks for users - An example of this is the Sienna rewards contract which deposits users rewards into their wallet daily. There is also the feature of "opportunistic execution" which allows additional privacy to perform automated actions by using leftover gas from the Gas evaporation function in the Secret compute module. - Here is a great guide on opportunistic execution!
Query permits are an alternative querying method introduced in the SNIP-24 design specification. Query permits use of a cryptographic technique known as public-key encryption coupled with digital signatures.
A permit is a formatted message, it outlines several arguments such as what tokens the permit applies to and what permissions the permit should allow (e.g. should the permit allow the querier to view a user’s transaction history, balance, etc.). Permits are not saved in the smart contract state and do not require the initiation of a blockchain transaction. Therefore, permits are a less permanent way of gaining viewing access with less network strain.
Users can sign permits with their account’s private key to give certain dApps or parties viewing access to specific parts of their private data for a specified amount of time. To get viewing access a user sends a query, with the signed permit as an argument, to a smart contract. Once received, the smart contract, using the user’s public key, can validate the identity based on the signature the user provided. If the user’s identity is confirmed, the smart contract returns the data as requested.
For more information on Permits check out the permissioned viewing section under development or the SNIP-24 specification
OJO - Testnet
Band - Mainnet
Secret network has active integrations with:
Using IBC Hooks, a contract on Ethereum can call a contract on Secret and get a response back.
Axelar Satellite/Squid Router
Using the Axelar SDK users can bridge Ethereum and other EVM/Non-EVM assets into Cosmos and Secret arriving immediately as Wrapped SNIP-20 private tokens into their Secret account.
Squid is a cheaper (gas wise) version for Axelar based bridging one can use as a widget.
Uses Secret's confidential computation to open a connection to any EVM chain - find examples under the EVM developer toolkit.
Coming soon:
To access all of our current token bridging interfaces, see the Secret Dashboard bridge page.
Secret Network uses the Cosmos SDK and its infrastructure which makes it so that the identity of a querier (someone requesting data) cannot be cryptographically authenticated. On public networks this might not be a problem for users as they can query data by using their public key. However, on private networks (where only the owners should have access) this is a problem. To solve this problem, viewing keys were implemented as a part of the SNIP-20 token specification.
Viewing keys act as an encrypted password for the viewing of data related to a specific smart contract and private key. The password can only be created by the private key owner, but anyone with the password who knows the accompanying public key gets access.
To create a viewing key a user signs a transaction for a specific contract (ex sSCRT token), this transaction asks for a random input from which it generates a viewing key. The viewing key is saved in the contract state together with the user's public key (address). To query for private data (ex balance, history) both the viewing key and the accompanying address is required.
Anyone who knows the correct combination of key + address can view the private data without needing access to the private key of the address. Secret Network allows users to maintain control over their data and decide what is shared and with whom.
for more on info on Viewing keys check out the Development section for permissioned viewing and the SNIP-20 specification
Secret has integrations with the following wallets:
Keplr
Leap
Fina.Cash (mobile friendly)
Starshell (added privacy)
Metamask (only signing, not SCRT storage)
Cosmostation
Citadel.One
You can check out app.shadeprotocol.io or dash.scrt.network to try out these various wallets. Documentation for wallet integration is available here: https://docs.scrt.network/secret-network-documentation/development/frontend/templates/usage-examples/wallet-integrations
Secret Network is the only non-EVM cosmos chain that supports native Metamask signing! It is an awesome onboarding tool for new users or can be the missing tool to have people use Secret in your Privacy as a Service flow without ever needing a 2nd wallet or other gas.
Secret supports IBC-Go v4 and several additional tools and middleware. ICA is supported but functions are not yet enabled nor is the host module live, if you need this please reach out to the Devrel team via discord or Telegram. Tools supported:
IBC hooks by Osmosis Labs - Secret - v1.11
WASM hooks: allows ICS-20 token transfers to initiate contract calls, serving various use cases.
Example: Sending tokens to Secret and immediately wrapping them as SNIP-20 token. For example, ATOM on Hub -> ATOM on Secret -> sATOMS on Secret
(2 transactions on 2 chains) now becomes ATOM on Hub -> sATOM on Secret
(1 transaction).
Example: Cross-chain swaps. Using IBC Hooks, an AMM on Secret can atomically swap tokens that originated on a different chain and are headed to Secret. The AMM can also send those tokens back to the originating chain.
Axelar GMP: Using IBC Hooks, a contract on Ethereum can call a contract on Secret and get a response back.
Ack callbacks: allow non-IBC contracts that send an IbcMsg::Transfer
to listen for the ack/timeout of the token transfer. This allows these contracts to definitively know whether the transfer was successful or not and act accordingly (refund if failed, continue if succeeded). See usage example here.
Packet forward middleware (PMF) by Strangelove - Secret v1.9
Other chains are able to more easily route SCRT in the interchain. For example, sending SCRT from Osmosis to Hub now becomes a single transaction from Osmosis -> Secret
rather than a transaction from Osmosis -> Secret
, then a transaction from Secret -> Hub
.
As of Secret Network V1.7 delegators can autocompound their SCRT Staking rewards using the native Restake feature.
Normally SCRT delegated to a validator accrues SCRT rewards every block as a claimable balance. With the autorestaking feature enabled however the SCRT rewards will never be claimable and also never in the claimed balance state.
Every x amount of blocks (currently 1000 set by the chain parameter - restake_period
) all claimable rewards, on the Restake enabled validators by the user, will be removed from the reward balance and accredited to the staked balance.
The code implementation for native Restake is available here
Delegators can enable Restaking independently for every validator they stake with using the set-auto-restaking
command available in SecretCLI or on any UI implementing the Secret.JS command.
The feature only activates if the delegator has a balance with the validators larger than minimum_restake_threshold
which is currently set to 10 SCRT
Start autocompouding your rewards now at the Secret Dashboard!
A high-level overview of Secret smart contracts
Since all computations are done privately inside the TEE of the network full nodes and the state of the blockchain is encrypted we would expect that users have no access to their own balance, debt positions, tokens, and other important information.
However, because users sign transactions with their own private key the protocol knows they should have access to their information. Viewing keys and Permits are the tools used to provide only the owner access to the private data of their signed transactions.
This part of the documentation will cover the no-code overview of the workings of Permits and viewing keys.
Secret network has active integrations with:
Axelar Satellite/app.squidrouter.com
Using the Axelar SDK users can bridge Ethereum and other EVM/Non-EVM assets into Cosmos and Secret arriving immediately as Wrapped SNIP-20 private tokens into their Secret account.
is a cheaper (gas wise) version for Axelar based bridging one can use as a widget.
/Xblock
One can uttilise the Xblock integration or Houdini widget to let users onboard Crypto assets like XMR, BTC, ETH and more privately directly into SCRT
Kado.money
Kado supports SCRT and direct Noble USDC onboarding onto Secret network. One can uttilise their Widget to allow for in-app onboarding via Paypal, Credit, Debit and more.
TransAk
TransAk support SCRT onboarding using Debit, Credit, paypal and other gateways