owned this note
owned this note
Published
Linked with GitHub
# (Bridge|Trust)-less & Private: BTC & ETH on Secret Network, with a Dark DEX for anonymous swaps, cross-asset fungibility and (re)?mixing.
We plan to introduce and develop a novel trustless cross-chain 'bridging' and swap method to bring BTC, ETH and other tokens onto Secret Network in a way which can rapidly support many chains with minimal effort.
If a contract can generate Bitcoin or Ethereum keypairs then deposits can be made by a counterparty to addresses on other chains without a relay or a bridge, the Secret Contract acts as an escrow - releasing the key to the appropriate party upon payment or timeout in a similar way that a hash-time-lock contract does.
The initial Phase of development will focus on the fundamentals and solution discovery given the capabilities & constraints, concluding with a proof of concept implementation of SNIP-721 wrapped Bitcoin & Ethereum keypairs and a simple decentralized UI to deposit & withdraw.
The vision that guides this research is to engineer the prerequisites for a cross-chain 'Dark DEX' (Phase 2) which could offer a higher level of privacy than SecretSwap, enable more types of cross-asset fungibility without locking-up capital in liquidity pools, or increase transactions per second.
However, because security measures must be taken to not reveal too much information to sophisticated, malicious and/or interactive actors it may not be possible to track many KPIs like: liquidity, price, number of swaps, TVL etc. without compromising the privacy of the contract users, and remaining trustless imposes its own constraints which must be balanced too.
### Milestones
#### Phase 1:
* [ ] RNG + Ignition Ceremony
* [ ] SNIP-721 contract for Bitcoin & Ethereum keypair escrow
* [ ] Minting UI to deposit & withdraw BTC and Ethereum on Secret Network
#### Phase 2:
* [ ] Privacy enhancing swaps, mixing & state-channels
* [ ] Fungibility: SNIP-20 from sets of SNIP-721
* [ ] Dark DEX proof of concept
### Team
* [HarryR](https://github.com/HarryR/) - Lead
* [MattDF](https://zklabs.io/) - Advisor
* AA - Marketing & Communications officer
* GK - UX & product testing
E-mail `scrt.network@conquest.finance` for non-public discussion.
### Funding Request
To fund Phase-1 of the project we initially require 69420.001 USD worth of SCRT. The exchange rate for USD/SCRT must be calculated on the date of payment. The legal jurisdiction can be either England & Wales, or Switzerland.
----------------
# Phase 1
## CSPRNG: Cryptographically Secure Pseudo-Random Number Generator
Underpinning everything is a CSPRNG which can be used by a secret contract to generate keys that nobody else knows, this work follows on from a previous grant for a RNG, see:
* https://github.com/scrtlabs/Grants/issues/30
* https://github.com/DDT5/scrt-rng
The `scrt-rng` project is a good bouncing board, but it has room for improvement. Firstly: to reduce the surface area for faults and reduce gas costs it's necessary to remove the admin interfaces, statistics and entropy forwarding functionality; Secondly: the RNG cryptography and protocol must be formally documented with an accompanying gas-efficient constant-time reference implementation, and Thirdly: to formalize the initialization process so its output can be trusted as being 'private'.
When entropy is provided to the contract it can only guarantee the internal seed will be private if at least one person follows the ignition protocol honestly and discards their secret contribution, otherwise if all the entropy contributors collaborate and all message data is known the RNG state can be derived.
Currently the initialization problem requires a straightforward solution: a trusted setup 'ignition ceremony' with a CLI program and website to encourage public contributions to rely on the web-of-trust effect (similar to the zkSNARKs 'Powers of Tau' ceremony), but other methods will be considered because it's an open-problem and a fuly trustless initialization would be ideal.
The 'hardfork problem' described in `scrt-rng` Option 2 ('high security') shouldn't be necessary to implement at the RNG level if the protocol enforces bock height linearity and mixes enough context information about the execution state into the seed to remain unpredictable even with malicious contracts and arbitrary playback of messages or the malleable fields being changed. For a clear separation of conerns it is the responsibility of contracts which use the RNG to implement delayed callbacks or protocol-specific defenses against the hard-fork playback attack, while the RNG will only be directly concerned about its own security.
#### Components
* [x] Grant proposal writing
* [ ] README.md
* CSPRNG algorithm references
* Interface specification
* Usage instructions
* [ ] Bare-bones Rust contract implementation
* Mock backends & unit tests
* Try several candidate algorithms + libraries
* Track gas cost and code size
* [ ] Feedback & Analysis
* Attack scenarios & mitigations
* Best algorithm + trade-offs
* Specify chosen protocol
* [ ] Produce beta version of contract
* Set default algorithms
* Testnet deployment, verifiable build
* [ ] Ignition Ceremony Website
* Securely generate random data in a browser
* Use Keplr wallet?
* Connect wallet, if already connected show 'contribute' button
* Show gas costs etc.
* Also `.sh` script using `secret-cli`
* Hosted on fleek.co (ipfs) or github pages
* [ ] Library for contract developers
* On init, seed its own RNG using the 'Secret RNG protocol'
* Internally stream random data without external contract callbacks
* Conform to standard rust random data interfaces / traits
* [ ] Continuous integration
* Give release CI env a scrt wallet for donations?
* If the wallet has enough to pay gas, contribute entropy
* If you trust the build system, you should trust the entropy too?
### Algorithms
Every time the contract is called it needs to cycle its seed using all available context information, and optionally when supplying entropy to include that in the mix too to make the output sequence unique for a specific deployment and sequence of calls.
The current `scrt-rng` project uses [rand_chacha::ChaCha20Rng](https://docs.rs/rand_chacha/0.3.1/rand_chacha/struct.ChaCha20Rng.html) to derive output from the seed, but uses sha256 and string concatenation to mix entropy into the seed and only includes the block time.
It's important to include more than just the block time, because otherwise two contracts may inadvertently output the same sequence. There are standardized ways to cycle the seed e.g. using a `HMAC` or keyed hashes, which must be considered to ensure that such an important element of the Secret Network ecosystem will be secure and the specific combination (or close-enough analogues) of constructions have previously undergone academic rigor from different perspectives so security and adversarial models can be referenced.
Function candidates which have strong security guarantees are initially:
* Output functions:
* ChaCha20 RNG
* AES-256 / other cipher construct
* Keccak RNG
* https://github.com/monero-project/monero/blob/1a4298685aa9e694bc555ae69be59d14d3790465/src/crypto/random.c
* Seed cycling functions
* HMAC?
* SHA-256
* Keccak
* Blake2s
### Attack Scenarios
* 'backtracking resistance'
* hard-fork resistance
* malicous...
* playback
* contracts
* admin / deployer
* multiple deployments
* unintentionally reveals seed via side-channel
* seed otherwise computable without SGX break?
TODO: find more + specific references for future analysis
Interesting starting points that lead upto new Linux RNG /dev/urandom overhaul + simplification:
* https://www.bsi.bund.de/SharedDocs/Downloads/EN/BSI/Publications/Studies/LinuxRNG/LinuxRNG_EN_V4_1.pdf
* https://www.bsi.bund.de/SharedDocs/Downloads/DE/BSI/Publikationen/Studien/ZufallinVMS/Randomness-in-VMs.pdf
----------------------------------------------
## KeyPair NFTs - Secret Wallet Generation
With the RNG component in-place a Secret contract can now generate its own key-pairs, sign message hashes or perform complex conditional signing protocols etc.
But, without an on-chain oracle to observe the state of other blockchains a wallet inside a Secret Contract can't determine the gas price or fees required, or know how many confirmations a transaction has or what its value is. To be as trustless as possible the wallet will avoid using any kind of oracle, and instead rely on the user to verify state and make the protocol game theoretically neutral.
Use-cases to consider include: allowing users to sign transactions with arbitrary gas prices and gas limits on Ethereum or compatible chains, using Replace By Fee (RBF) on Bitcoin to make it confirm faster, or cancelling transactions. While an SGX wallet implementation could sign the messages, without an oracle it can't track the wallet state or available balance, and without deep awareness of individual protocols there could be exploits. As such the aim is to resist signing transactions unless absolutely necessary, and then only for very safe, low-risk and well defined tasks.
The scope of the initial implementation will be limited to key-escrow to reduce the complexity of a proof of concept and help with problem discovery. When the key pair is generated and the public key is proven to have been deterministically derived inside the SGX enclave using the RNG, the secret key is then tokenized like an NFT. The current owner of the keypair NFT can reveal the secret to themselves, but this voids the NFT making it clear that any intrinsic value (holding the secret keys privately) cannot be trusted.
One interesting thing is that by publishing the raw public key for a secp256k1 curve allows the key escrow algorithm to support all blockchains which use that curve without additional modifications.
### Components
* [ ] Wallet keypair generation (Rust)
* Find secure & flexible libraries
* For BTC
* Use segwit and bech32 by default?
* Multi-network: Doge, LTC, Zcash, Pirate Chain?
* Hierarchical deterministic addresses (BIP32) - xpub etc. ?
* For Ethereum
* Must support compatible chains (Polygon, BSC)
* [ ] Simple contract for keypair generation
* One contract per address family?
* Note: supporting multiple address families in the same contract can be a privacy advantage as it doesn't externally reveal *which* chain the NFT exists on.
* Deterministic unit tests
* Verify compatibility of recovery into other wallet software
* BTC, Doge etc.
* Metamask
* Ledger?
* Tool for mnemonic recovery from raw secret?
* Deploy to testnet
* [ ] Proof of concept SNIP-721 implementation
* Specification for keypairs as NFTs: [SNIP-721](https://github.com/SecretFoundation/SNIPs/blob/master/SNIP-721.md)
* SNIP-721 contract
* SNIP-721 standards conformance
* Unit tests for NFT keypair parts
* Use `secret-cli` to mint new keypair NFT
* Deploy to testnet
* Verify compatibility with existing NFT markets on testnet?
After developing the proof of concept implementation there should be some reflection and time for feedback, so as to find things which may significantly impact integration with the rest of the ecosystem, to ensure fit-for-purpose (especially re: privacy, modularity, not over-fitting) and that it is a viable long-term solution because there is potential for it to be responsible for securing a lot of valuable keys.
* [ ] Analysis: use cases
* Bulk transfer of ownership
* Wrapping for function augmentation
* Marketplace integration and metadata
* [ ] Analysis: security
* Can NFTs be easily recovered if you lose track of which ones are yours
* Does metadata reveal too much?
* Check the cryptography is constant-time
* Side-channels of various methods:
* gas cost
* I/O access patterns
* contract messages
* data length
* [ ] Analysis: upgradability
* How to avoid being locked-in
* Can you upgrade NFTs by wrapping them?
* e.g. mint new NFT by sending old NFT to 'upgrader' contract
* Is an emergency shutdown button a backdoor?
* [ ] Analysis: is SNIP-721 too much overhead?
* Can a simpler underlying interface be made specifically for keypair generation
* Then use a SNIP-721 wrapper contract that interfaces with it
* Bulk operations aren't optimal with SNIP-721
* Research how to reduce cost of bulk ownership transfers
----------------------------------------------
## Easy Minting
To ease adoption and increase TVL it must be really simple for people to mint NFTs by depositing tokens from other chains into addresses which the Secret Contract controls.
The initial bare-bones functionality will be implemented before designing the UX flow to make essential tasks prominent and simple to follow without eroding confidence in the safety of funds or any unexpected situations which may cause alarm or are not immediately understandable.
Common UX patterns which are widely adopted across commonly used by payment systems, DEX's, swaps and wallets will be followed so the process is predictable.
### Components
* [ ] Web UI with Keplr for minting
* Check status of transaction IDs or public addresses
* Reliable third-parties to query BTC and other chains
* Generate wallet address button
* Web3 integration to make deposits
* Metamask
* Send ETH
* Small selection of ERC-20 tokens
* [ ] Verifier
* Use third-party for realtime prices
* Paste NFT IDs into a text box (or connect your wallet)
* It will verify the value and number of confirmations for each
* Display results as a table
* [ ] Nice & Simple UI
* Deposit, Verify, Withdraw flow-chart + UX mockup
* Help/support document for using wallet keys
* Total gas cost estimation
* [ ] Beta testing
* Deploy on IPFS using fleek.co
* Coordinate with scrt.network for announcement
---
# Phase 2
Upon completion of Phase 1 the grant objectives will be re-assessed and hopefully Phase 2 will be re-submitted after thorough consideration of the following questions:
* given what we've learned, is the cross-chain Dark DEX viable and how many transactions per second can it support?
* are there further novel developments which could increase both privacy and transactions per second?
* is there a viable profit-making strategy to continue long-term development as an independent company, and in which jurisdiction?
* do human resources need to be adjusted to fulfill criticial skill gaps, or establish cross-functional collaborations
* after community feedback, do the ideas and concepts need to be changed to account for their use cases?
## Privacy enhancing swaps, mixing & state-channels
#### Mixing / Swaps
It is possible to negotiate swaps between similar valued sets of a mix of different tokens, making a 10 USDT note interchangable with a 10 USDC note increases the ability to freely mix equivalent currencies.
Market makers retain access to their funds and can even deposit LP tokens without requiring the contracts needing to handle complex interest or reward calculations for specific tokens. By charging a small percentage fee or giving a small discount they can show their preference for swaps, e.g. to consolidate many smaller coins into larger coins or to account for the value of uncollected interest versus gas fees.
By making every wallet user a market maker and using portfolio balancing rules to calculate demand and supply fees their funds will be automatically and privately re-balanced while earning a return for participating in the market.
Or... is there a solution which doesn't require users to be online to provide liquidity?
#### State Channels
As the secret enclave can manage its own keys it can participate in state channels by performing on-chain signing. Or it could validate state channels to enable net settlement between multiple parties to increase transactions per second.
Can the Bitcoin Lightning Network be integrated trustlessly?
## Fungibility: SNIP-721, SNIP-20, mixed equivalent asset sets
Because the Secret contract doesn't know the value of the UTXOs or their prices it can't automatically exchange a set of UTXOs for an equivalent amount of another token, or even know if two are equivalent in value - this makes fungibility impossible without user intervention.
If an on-chain price oracle were to be trusted then the SNIP-721 style assets can be converted into SNIP-20 style fungible assets, although there may still be liquidity problems when burning arbitrary values worth of tokens to release an equal valued set of UTXO keys to the burner.
However, with non-UTXO assets and a trusted oracle then a contract could be minted on the remote chain which will accept signatures generated inside the secret contract to release funds to specific accounts.
More research into fungibility and privacy concerns must be done.
## Dark DEX proof of concept
TBD:
* increases:
* privacy & anonymity
* total value locked
* cross-chain liquidity
* transactions per-second
## Other ideas
* Social Key Recovery
* New Viewing-Key Scheme (doesn't require user to submit transaction first)
* Dark DAO / Multisig wallet
* More research into side-channel attacks