Secret Network
WebsiteDiscordGithub
  • πŸ‘‹INTRODUCTION
    • Secret Network Introduction
    • Secret Network Techstack
      • Private transactions - A quick summary
      • Blockchain Technology
        • Cosmos Basics
        • Tendermint
        • Cosmos SDK
        • IBC
        • CosmWasm
      • Privacy Technology
        • Encryption - Key Management
          • Overview
          • Key Derivation & Encryption Techniques
          • The Initialization Of Secret Network
          • Full Node Boostrap
          • Contract State Encryption
          • Transaction Encryption
          • Consensus seed rotation
        • Trusted Execution Environmentsβ€Š (TEE) β€”β€Š Intel SGX
          • How Secret Network Uses SGX
          • SGX-SPS Security & Reliabillity
          • Remote Attestation
          • Trusted & Untrusted Core
          • Sealing
        • Private smart contracts - overview
  • πŸ’»Development
    • 🏠Getting Started
      • Setting Up Your Environment
        • Cargo.toml Best Practices (Crates vs Dependencies)
      • Compile and Deploy
      • Running the Application
      • Compile and Deploy on Secret testnet (best for Javascript devs)
      • Fullstack dApp Integration
    • πŸ€“Secret Contracts
      • Secret Contracts & CosmWasm
        • Framework overview
        • Secret Contract Components
          • Instantiation Message
          • Execution Message
          • Query Message
          • Deps/DepsMut
          • Storage
            • Prefixed Storage
            • Singleton
            • Keymap
            • Append Store
            • Best practices
        • CosmWasm vs Secret CosmWasm
      • Secret Tokens (SNIP-20)
      • Contract - module call
      • Secret contract - Design Space/Features
        • Secret Contracts introduction
        • Gas/Fee usage
        • TPS and scalability
        • Privacy Essentials
        • Access Control
          • Viewing Keys
          • Permits
        • Trusted and untrusted data
        • Secret-VRF - on-chain Randomness
        • Privacy design
          • Mitigate privacy risks - full guide
          • Gas Evaporation & Tracking
        • Confidential Computing Layer
        • Fiat/Crypto Onboarding
        • Account abstraction
        • Fee abstraction
        • Wallet support
        • Bridge (messaging/tokens)
        • IBC (Hooks, PFM, Wasm)
        • Price Oracles
        • Auto Restaking
      • Permissioned Viewing
        • Viewing Keys
        • Permits
      • Cross Contract Communication
      • Submessages
        • get_contract_code_hash
      • Randomness API - Secret VRF
        • Native On-chain randomness
        • Randomness over IBC
      • Execution Finalization
      • Factory Contracts
      • Contract Migration
        • Manual - < v1.11
        • Native - from v1.11
      • Cross-deploy Vanilla CW and Secret Contracts
      • Testing Secret Contracts
        • Unit Tests
        • Continuous Integration
        • Datatype Handling - Uint, floats etc.
    • πŸ‘€Secret Contract - Reference, Guides, Examples
      • Starter guide - Millionaire's Problem
      • Reference Contracts
      • Open source dApps
      • Tools & Libraries
        • Network interaction SDKs
          • Secret.js (JavaScript)
          • SecretPy (Python)
          • SecretK (Kotlin)
          • Secret.NET
            • Snippets
              • Deploying a Contract
              • Send Native Coin
              • Query a Contract
              • Create a new Wallet
              • Permits
              • SNIP20
              • SNIP721
          • Shade.Js
        • LocalSecret - Devnet docker
        • Smart contract - Tools/Utils
          • Secret Toolkit
          • CW-Plus
          • Fadroma - SC framework
          • Hidden Gems
          • Other
            • Secret IDE
            • Polar
    • πŸ–ΌοΈFrontend Development
      • Getting Started with SecretJS
        • Usage Examples
          • Sending Queries
          • Sending Messages
          • Contract Migration
          • Wallet Integrations
          • Query Permits
          • SNIP20 (SCRT Tokens)
          • SNIP721 (Secret NFTs)
      • Feegrant
        • Understanding Feegrant allowances
        • Grant allowances
        • Using grant allowances to execute transactions
        • Using the Fee Grant Faucet
    • πŸ“¬Deployment Addresses/ API Endpoints
      • Secret (SNIP 20) token contracts list
        • SNIP Asset naming guidelines
      • Connecting to the Network
        • API Endpoints Mainnet (Secret-4)
        • API Endpoints Testnet (Pulsar-3)
        • Usage examples
        • Comparison of endpoint types
      • Create your own SNIP-25 IBC Token
  • Secret AI
    • 🀝Introduction
    • πŸ—οΈArchitecture
    • πŸ‘©β€πŸ’»Secret AI SDK
      • Setting Up Your Environment
      • Running the Application
    • πŸͺ™Economics
    • Smart Contract Reference
      • SubscriptionManager
      • WorkerManager
      • RewardsManager
  • 🌐SecretVM - Confidential Virtual Machines
    • 🀝Introduction
    • πŸ—οΈArchitecture
    • β˜‘οΈAttestation
      • What is Attestation
      • Obtaining Attestation Data
      • Attestation Report - Key Fields
      • Chain of Trust
    • 🏁Launching a SecretVM
    • πŸ› οΈManaging SecretVM Lifecycle
    • βœ…Verifying a SecretVM
      • 🐒Full Verification
      • 🐰Quick Verification
    • πŸ’‘Best Practices for Developers
    • πŸ“–Glossary
  • πŸ”“Confidential Computing Layer
    • πŸ§‘β€πŸš€IBC Developer Toolkit
      • Basics
        • Overview
        • Cross-chain Messaging with IBC Hooks
          • Functions, Methods, and Data Structures
          • Typescript SDK
          • IBC-Hooks
        • IBC Relaying with Go Relayer
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-Value store Developer Tutorial
        • Secret VRF for IBC with IBC-Hooks
        • Confidential Voting
        • Sealed Bid Auctions
      • Supported Networks
        • Mainnet
        • Testnet
    • 🀝Ethereum (EVM) Developer Toolkit
      • Basics
        • Overview
        • Connecting Metamask to Secret Network
        • SecretPath + Reown integration
        • Cross-chain Messaging
          • SecretPath
            • Architecture Overview
            • Detailed Architecture
            • SecretPath Developer Tutorials
            • Public EVM Gateway Architecture
            • How to deploy SecretPath on your chain
          • Axelar GMP
            • Architecture Overview
            • Axelar GMP Developer Tutorial
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-Value store Developer Tutorial
        • Sealed Bid Auction
          • Sealed Bid Auction Developer Tutorial
        • Confidential Voting
          • Confidential Voting Developer Tutorial with SecretPath
        • VRF
          • Implementing VRF into any EVM Contract
          • VRF Developer Tutorial
          • Performance figures of SecretVRF vs competitors
          • Using encrypted payloads for VRF
          • Converting from Chainlink VRF to Secret VRF in four steps
        • Confidential Document Sharing
        • Tokens
          • From EVM to Secret
      • Supported Networks
        • EVM
          • EVM Mainnet
          • EVM Testnet
          • Gateway Contract ABI
        • Secret Gateway
          • SecretPath mainnet (secret-4) contracts
          • SecretPath testnet (pulsar-3) contracts
    • πŸ™ŒSolana Developer Toolkit
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-value Store Developer Tutorial
        • VRF
          • VRF Developer Tutorial
      • Program IDs
        • Solana Mainnet & Testnet
        • Gateway Contract IDL
  • 🀫Overview, Ecosystem and Technology
    • πŸš€Secret Network Overview
      • The SCRT coin
      • Private Tokens
      • Use Cases
        • Decentralized Finance (DeFi)
        • Art And Digital Media
        • Gaming
        • Data Privacy
        • Payments And Transactions
        • Communication
      • The technology
      • History
      • Roadmap (Core development)
        • Secret 2.0
      • Where To Buy SCRT?
      • Using the Testnet
    • 🐸Ecosystem Overview
      • Wallets
      • Applications
      • Explorers & tools
      • Funding
        • SCRT Labs Grants
        • Dilutive funding/VC raise
        • Community Pool
        • Developer bounties
          • SCRT Labs bounties [on-hold]
          • CCBL [on-hold]
          • CCR [On-hold]
        • Application specific
          • Shade Grants
      • Contributors & Entities
        • Validators
        • SCRT Labs
        • Secret Foundation
        • Secret Committees
          • Support
          • Governance
      • Secret Network Dictionary
  • πŸ”§Infrastructure
    • πŸ”“Use SecretCLI
      • Secretcli vs. Secretd
      • Install
      • Configuration
      • Address Types
      • Key Types
      • Generating Keys
      • Viewing Keys
      • Query Transactions
      • Send Tokens
      • Multisig Keys
      • Multisig Transactions
      • Transaction Broadcasting
      • Fees & Gas
      • Fee Distribution
      • Secret Contracts
      • Slashing
      • Minting
      • Delegating
      • Restake
      • Nodes
      • Governance
        • Creating Governance Proposals
        • Query Proposals
        • Deposits
        • Voting
    • πŸ”Use Ledger hardware wallet
      • πŸ”Ledger with SecretCLI
    • πŸ–₯️Running a node/validator
      • Setting up a node/validator
        • Hardware setup
          • Hardware Compliance
          • VPS/Bare-Metal Compliance
            • Leaseweb Setup
            • PhoenixNAP Setup
            • Psychz Setup
            • nForce Setup
            • Vultr Setup
            • OVHCloud Setup
            • Microsoft Azure Setup
          • Patching your Node
          • Enclave verification
          • Registration troubleshooting
        • Testnet Setup
          • Install SGX
          • Install secretd
          • Setup Full Node
          • Testnet State Sync
          • Becoming a Testnet Validator
          • Installing CLI & Creating A New Address
        • Mainnet Setup
          • Install SGX
          • Install secretd
          • Setup Full Node
          • Quicksync / Snapshot
          • Statesync
          • Becoming A Validator
          • Installing CLI & Creating A New Address
      • Maintaining a node/validator
        • Slashing information
        • Migrating a Validator
        • Troubleshooting
        • Validator Backup
        • Server security
          • SSH authentication
          • Server configuration
          • Uncomplicated-Firewall (UFW)
          • Local CLI
        • Node Monitoring
          • Prometheus
            • Environment Preperation
            • Install Node Exporter
            • Install Prometheus
            • Configuring Prometheus
          • Grafana
            • Install Grafana
            • Grafana Dashboard
            • Next Steps
          • Docker
            • Install Docker
            • Configuration
            • Start Containers
            • Grafana Dashboard
            • Application Ports
            • Stop Containers
          • Goaccess
            • Install Goaccess
            • Setup Goaccess
        • Helpful commands
          • Query Validators
          • Bond Tokens
          • Withdraw Rewards
          • Query Delegations
          • Unbond Tokens
          • Query Unbonding-Delegations
          • Redelegate Tokens
          • Query Redelegations
          • Query Parameters
          • Query Pool
          • Query Delegations To Validator
      • API Noderunning
        • Running Multiple Nodes on the Same Server
        • Node Loadbalancing using Nginx
          • Setup Nginx
          • Example Nginx config
        • Using Auto heal to improve cluster uptime for Nginx
      • Sentry and Archive nodes
        • Mantlemint
        • Sentry Nodes
        • Archive Nodes
    • ⛓️IBC Relayers
      • Hermes
      • RLY
      • IBC channel database
    • πŸ†™Upgrade Instructions
      • v1.13
      • v1.12
      • v1.11
      • v1.10
      • v1.9
      • v1.8
      • v1.7
      • Shockwave Omega v1.6
      • v1.5
      • Shockwave Delta v1.4
      • Shockwave Delta v1.4 (Testnet)
      • Shockwave Alpha v1.3
      • Cosmovisor
      • Vulcan Network Upgrade (OLD)
    • ☠️Postmortems
      • SNIP-20 leaks
      • xApic
      • Secpk-Verifications Bloat
      • Earn Contract Exploit
      • Testnet Halt 95
    • ✍️Contribute to the documentation
      • Report Bugs
      • Suggest Enhancements
      • First Contribution Guide
      • Pull Request Templates
        • Update Documentation
        • Bug Fix
        • Improve Performance
        • Change Functionality
      • Style Guide
    • 🌊Versioning & Changelog
      • Secret Network v1.13
      • Secret Network v1.12
      • Secret Network v1.11
      • Secret Network v1.10
      • Secret network v1.9
      • Secret Network v1.7/1.8
      • Secret Network v1.6
      • Secret Network v1.5
      • Secret Network v1.4 (CosmWasm 1.0)
Powered by GitBook
On this page
  • Overview
  • Getting Started
  • Configuring Environment Variables
  • Upload the encryption contract on Secret Network
  • Encrypt a payload with Typescript SDK
  • Encryption SDK - how it works
  • state.rs
  • msg.rs
  • contract.rs
  • Summary

Was this helpful?

Edit on GitHub
Export as PDF
  1. Confidential Computing Layer
  2. IBC Developer Toolkit
  3. Usecases
  4. Storing Encrypted Data on Secret Network

Key-Value store Developer Tutorial

Learn how to use Secret Network as the confidential computation layer of the Cosmos with IBC hooks

PreviousStoring Encrypted Data on Secret NetworkNextSecret VRF for IBC with IBC-Hooks

Last updated 6 months ago

Was this helpful?

Overview

Secret Network's Confidential Computation SDK uses IBC hooks to seamlessly handle cross-chain encrypted payloads, which means Cosmos developers can now encrypt and decrypt messages with a simple token transfer.

See fullstack demo for Osmosis Mainnet .

This tutorial explains how to upload your own Key-value store contract on Secret Network, which you can use to encrypt values on Secret Network and transmit them cross-chain from a Cosmos chain of your choice! After this tutorial, you will have the tools you need to encrypt messages on any IBC hooks-enabled Cosmos chain.

In this example, you will send a token from Osmosis mainnet to Secret Network mainnet to encrypt a stringπŸ”₯

Getting Started

To get started, clone the :

git clone https://github.com/writersblockchain/cosmos-ccl-sdk.git

Configuring Environment Variables

Install the dependencies:

npm install

Create an env file. Simply update to omit ".testnet" from the file name and then add your wallet's mnemonics:

SECRET_MNEMONIC=""
SECRET_CHAIN_ENDPOINT="https://lcd.mainnet.secretsaturn.net"
SECRET_CHAIN_ID="secret-4"
SECRET_TOKEN="uscrt"


CONSUMER_MNEMONIC=""
CONSUMER_CHAIN_ENDPOINT="https://rpc.osmosis.zone:443"
CONSUMER_CHAIN_ID="osmosis-1"
CONSUMER_TOKEN="uosmo"
CONSUMER_PREFIX="osmo"
CONSUMER_GAS_PRICE="0.25"
CONSUMER_DECIMALS=6

Upload the encryption contract on Secret Network

Now that you have your environment configured, it's time to upload the encryption contract to Secret Network.

First, compile the contract:

make build-mainnet-reproducible

This compiles the contract and creates a wasm file in the following directory:

"./optimized-wasm/gateway_simple.wasm.gz"

Compile the typescript files so you can execute them with node:

npm run build

Once you run the above command, the typescript files in ./src will be compiled as javascript files in ./dist.

Upload and instantiate the encryption contract on Secret Network Mainnet:

node dist/deploy.js

In your terminal, a codeID, codeHash, and contractAddress will be returned:

"code_id": 8882,
"code_hash": "f3c2e28cd1574d128ded60ce967cdb46f7515d807be49127bcc9249c5fd97802",
"address": "secret1q0mycclu927u5m0tn50zgl5af4utrlkzz706lm"
{
    "gateway": {
        "address": "secret1q0mycclu927u5m0tn50zgl5af4utrlkzz706lm",
        "hash": "d4a018804bf63b6cfd5be52b650368e8ad89f57c66841f6b2da7ee143dfc75fb"
    }
}

Encrypt a payload with Typescript SDK

Now that you have your encryption smart contract uploaded on Secret Network, let's use it to store encrypted messages from Osmosis Mainnet Most of the ECDH cryptography has been abstracted away so there are only a few values you need to change.

To encrypt the payload, run execute-gateway.js:

node dist/execute-gateway.js

This will initiate a Token transfer:

Sending IBC token...
receiver: secret1q0mycclu927u5m0tn50zgl5af4utrlkzz706lm
token: uosmo
amount: 1
source_channel: channel-88
memo: {"wasm":{"contract":"secret1q0mycclu927u5m0tn50zgl5af4utrlkzz706lm","msg":{"extension":{"msg":{"store_secret":{"text":"new_text_68ss4"}}}}}}

As well as an IBC Acknowledgement response:

Broadcasted IbcTX. Waiting for Ack: Promise { <pending> }
ibc Ack Received!
info ack: {
  packet: {
    sequence: '252',
    source_port: 'transfer',
    source_channel: 'channel-88',
    destination_port: 'transfer',
    destination_channel: 'channel-1',
    data: Uint8Array(887) [
      123,  34,  97, 109, 111, 117, 110, 116,  34,  58,  34,  49,
       34,  44,  34, 100, 101, 110, 111, 109,  34,  58,  34, 117,
       97, 120, 108,  34,  44,  34, 109, 101, 109, 111,  34,  58,
       34, 123,  92,  34, 119,  97, 115, 109,  92,  34,  58, 123,
       92,  34,  99, 111, 110, 116, 114,  97,  99, 116,  92,  34,
       58,  92,  34, 115, 101,  99, 114, 101, 116,  49, 113,  48,
      109, 121,  99,  99, 108, 117,  57,  50,  55, 117,  53, 109,
       48, 116, 110,  53,  48, 122, 103, 108,  53,  97, 102,  52,
      117, 116, 114, 108,
      ... 787 more items
    ],
    timeout_height: { revision_number: '0', revision_height: '0' },
    timeout_timestamp: '1722277043000000000'
  },

Congrats! You have now used the Secret Network CCL SDK to encrypt a string on Osmosis Mainnet!

Encryption SDK - how it works

At a high level, you can think of the SDK like so:

  1. There is a gateway contract deployed to Secret Network, which has the ability to encrypt a string, as well as query the encrypted string.

You can add additional functionality to the gateway contract as you see fit. For example, you could write an execute message that stores encrypted votes or encrypted NFTs, etc!

Now let's examine each of the gateway contract's files to understand how it encrypts a user-inputted string.

state.rs

msg.rs

  • GatewayExecuteMsg: Defines execution messages that can be sent to the contract, including resetting an encryption key, sending encrypted data, and extending with additional message types.

  • GatewayQueryMsg: Defines query messages that can be sent to the contract, including querying for an encryption key, querying with authentication data, querying with a permit, and extending with additional query types.

contract.rs

  • Execution: Processes messages to reset the encryption key or store a secret, ensuring only authorized access.

  • Querying: Handles queries to retrieve the encryption key and perform permissioned queries.

  1. Check if Message is Encrypted:

    • If the message is encrypted (msg.is_encrypted()), it proceeds with decryption.

  2. Extract Encryption Parameters:

    • Retrieves the encryption parameters from the message (msg.encrypted()).

  3. Check Nonce:

    • Ensures the nonce has not been used before to prevent replay attacks.

  4. Load Encryption Wallet:

    • Loads the encryption wallet from storage.

  5. Decrypt Payload:

    • Decrypts the payload using the wallet and the provided parameters (payload, user_key, and nonce).

      let decrypted  = wallet.decrypt_to_payload(
            &params.payload,
            &params.user_key,
            &params.nonce,
        )?;
  1. Verify Credentials:

  • Constructs a CosmosCredential from the decrypted data.

  • Inserts the nonce into storage to mark it as used.

  • Verifies the sender using the verify_arbitrary function with the credential.

  1. Deserialize Inner Message:

  • Converts the decrypted payload into the original message type E.

  • Ensures the decrypted message is not encrypted (nested encryption is not allowed).

  1. Return Decrypted Message and Updated Info:

  • Returns the decrypted message and updated MessageInfo with the verified sender.

Summary

In this tutorial, you learned how to utilize Secret Network's Confidential Computation SDK to encrypt and decrypt messages across Cosmos chains using IBC hooks. By following the steps outlined, you successfully:

  1. Configured the development environment with the necessary dependencies and environment variables.

  2. Uploaded and instantiated an encryption contract on the Secret Network mainnet.

  3. Encrypted and transmitted a payload from the Osmosis Mainnet to the Secret mainnet using IBC token transfers.

With these tools and knowledge, you are now equipped to handle cross-chain encrypted payloads on any IBC hooks-enabled Cosmos chain, enhancing the security and confidentiality of your blockchain applications.

Note that for our consumer chain, we are using the endpoint, chainID, token, and prefix for Osmosis Mainnet. But you could update this for any Cosmos chain that has IBC hooks enabled and a with Secret Network

The files that make up the IBC SDK, including the script to upload the contract to Secret Network, are in .

Update with your contractAddress and codeHash accordingly:

The functions in are helper functions that help us configure cross-chain network clients, IBC token transfers, etc. However, there is also an additional function which executes the gateway contract called ! Execute-gateway.js demonstrates sending a token transfer to store an unencrypted as well as an encrypted message.

Feel free to update the to be encrypted.

Now that you have used Secret Network's CCL SDK to successfully encrypt a string cross-chain, let's examine the you deployed on Secret Network to understand how everything works underneath the hood.

The gateway contract imports helper functions from the , which is where the gateway contract imports encryption and query types, etc.

To use the SDK's encryption helper functions, simply write your gateway contract messages inside of the , which imports from the SDK :)

is where we define the keymap that holds our encrypted strings. The keymap SECRETS is designed to store a mapping from account user addresses (as strings) to their secrets (also as strings), using the Bincode2 serialization format.

is where we define the functionality of our gateway contract. It has 2 primary functionalities: storing encrypted strings and querying encrypted strings. Note that the types ExecuteMsg and QueryMsg are defined in the SDK .

contains the smart contract logic which allows the following:

The encryption logic, handle_encrypted_wrapper, is imported from the SDK at . This is where the encryption magic happens ⭐.

You can review the function in the SDK . It has the following functionality:

uses chacha20poly1305 algorithm

πŸ”“
πŸ§‘β€πŸš€
here
repository
env.testnet
πŸ˜„
transfer channel
./src
contracts.json
./src
execute-gateway.js
strings
gateway smart contract
SDK
InnerMethods enum
GatewayExecuteMsg
state.rs
msg.rs
here
contract.rs
line 55
here
decrypt_to_payload