From bdd9204883b219c9e5fc41f2494bad8875e436b5 Mon Sep 17 00:00:00 2001 From: Adetula Olamide <67712894+LamsyA@users.noreply.github.com> Date: Thu, 24 Oct 2024 10:06:11 +0100 Subject: [PATCH] Commit reveal #77 (#184) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * commitment scheme implementation * scarb.lock * modified the reveal function to view * refactored * refactored * offchain commitment and onchain verification done * added erc20 unit test * added test against custom errors * formated * made requested changes and moved test to contract module * fixed zero address * chore: Remove unused test files * Library calls (#194) * final push * updated the Summary.md * fix: fmt and minor edit --------- Co-authored-by: julio4 * Chapter 0 > Basics: wording + grammar fixes (#207) * sierra->Sierra + plural/singular form fixes * ch00 > Missing attr. elems, wrong attr. names * missing dot in messages + update how legacymap modulo format * ch00 > errors > add indent to comment in complex section * ch00 > events > wording, missing code quotes * ch00 > syscalls > wording * ch00 > bytearray > wording * ch00 > stor.custom types > wording * ch00 > cust.types in entrypoints > wording * ch00 > documentation > wording * Revert comment format changes * Simplify panic_with_felt252 related comment in errors.md * Fixes for ch00 * Wording in cheatsheet * Comment update in type_casting --------- Co-authored-by: Nenad * component dependencies test (#198) * test: component dependencies * undo changes * test: countable_component * test: countable_internal_dep_switch * fix: apply requested changes * fix: small fmt fix --------- Co-authored-by: julio4 * feat(staking): Add staking contract example (#202) * feat(staking): first draft with contract and tests Missing events and some tests * feat(staking): Add events and events-related tests * feat(staking): Add a more complex test for rewards set up * feat(staking): Add md file * feat(staking): Apply changes according to PR review * feat(enums): Enums in contract (#212) * feat(enums): Enums in contract * fix: small fmt --------- Co-authored-by: julio4 * Application chapter: grammar, wording, typos, `!addr.is_zero` -> `addr.is_non_zero` (#213) * upgradeable > use is_non_zero * simple_vault > grammar * not is_zero -> is_non_zero * update sbe links * staking > wording * amm > fix brackets + grammar --------- Co-authored-by: Nenad * add time locked transactions example (#201) * add time locked transactions example * install snforge in gh-action * fix: refactor timelock example * test for upgradeable contracts (#203) * added erc20 unit test * added test against custom errors * formated * made requested changes and moved test to contract module * fixed zero address * chore: Remove unused test files * test for upgradeable contracts * fixed build issue * fix: pr#203 --------- Co-authored-by: julio4 * Components chapter: wording, grammar, formatting fixes (#210) * how-to fixes * Clean up dependencies * collisions > fixes * ownable minor fixes * remove error.log * fix typo * add comma after 'first' * add 'the' before cairo book --------- Co-authored-by: Nenad * Advanced concepts: typos, wording, grammar, formatting (#215) * formatting for write to slot * stor. arrs. > wording, grammar * hashing > wording, grammar * packing > wording, grammar, format * list > amount->amounts, wording, typos * plugins > grammar * sign. verif. > grammar * remove 'a' in how_to * update library calls -> dispatcher * Revert "update library calls -> dispatcher" This reverts commit e7d3b0c23d40e81419327e8d1b42a2ad839926e6. * align library calls header * fix tests --------- Co-authored-by: Nenad * feat: nft dutch auction (#204) * feat: nft auction * test: add tests to nft_auction app * chore: improve code and add more tests * chore: improvements and more tests * test: add more test cases for nft_auction * chore: update mdbook * chore: update nft_auction package - Add error module - Update snforge version to 0.24.0 * chore: rename package and related files from `nft_auction` to `nft_dutch_auction` * chore: reused existing package * fix: cli#204 --------- Co-authored-by: julio4 * fix: chapter-related folder names (#216) * fix: chapter-related folder names * updated all references * feat: simple storage with starknet-js (#222) * feat: simple storage with starknet-js * feat: add how_to_deploy & fix tutorial content for simple_storage * fix: update links & add section in summary * feat: revisions #222 --------- Co-authored-by: julio4 * chore: scarb, foundry, oz updates (#227) * feat: Advanced factory contract (#219) * add initial factory * add ownable component * add caller to CounterCreated event * turn counter into campaign * fix Campaign interfaced funcs + implement donate * add _assert_is_ended + update error messages * _assert_active->_assert_campaign_active * _assert_is_ended->_assert_campaign_ended * implement withdraw * add missing assert success in donate * add title & description * update comment * implement upgrade * clean up internal funcs and imports * move hardcoded errors in Errors mod * donate -> contribute + event rename * withdraw -> claim * add store impl for contract addr. array * remove store impl * add dynamic array impl * remove dyn. array * remove descr + convert title to felt + convert target to u128 * implement updating class hashes * Make title ByteArray again + target into u256 + update ctor arg serialization * refactor serialization + add back description * remove unused contracts * add 1 test * add get_description * add correct deps * add alexandria to toml * format factory.cairo * add missing snforge workspace * add missing getters + tests * add factory deploy tests * add class hash update test + event assertions * assert old class hash prior to update * remove commented out test * use common alex. storage workspace in using_lists * add missing newline in toml * move factory tests to separate file * add scaffold docs for contracts * add end_time asserts * refactor private asserts * check if target reached before claiming * add ability to withdraw funds * make contributions into a component (now iterable) * refactor 'withhold' - contrs map to amt_idx * add get_contributors func * get_contributors -> get_contributions * total_contributors->contributor_count * add tests for campaign upgrade and deploy + update all relevant code in factory * add status to campaign * add close fn * pass desired donation token in ctor * merge all getters into get_details * return total_contributions in details * remove rev version from alexandria dep * verbose names * reorg. folder structure * add tag to alexandria dep * campaign_upgrade.cairo->mock_upgrade.cairo * add explicit alexandria rev + make crowdfunding contracts standalone chapters * add status pending * field rename: factory->creator * refund users when upgrading campaign * Make owner the calling address, and creator is the campaign manager * add get_contributor (amount) func * Add successful campaign test * update comment for upgrade * _refund_all->_withdraw_all * update checks for withdraw * rework contribute * rework all funcs * unsuccessful -> failed * calc end_time in start fn * calc end_time in upgrade fn * makes upgrades callable only by creators in factory * fix factory tests * fix crowdfunding tests * reduce total contri. when withdraw from act. camp * add refund fn * refactor withdraw_all to use _refund * pending->draft * fix mock and tests * add test for close * add test for withdraw * upgrade > update end_time only if duration provided * close->cancel * rename to more align with Solidity by example * target->goal * remove comment * err CLOSED->CANCELED + check active in unpledge * contributor->pledger * add campaign doc content * remove draft status * add start_time * remove Status * update doc for campaign * move total_pledges to pledgeable * reorder alphabetically * remove Launched event + upgrade mock * TARGET->GOAL * reorder params in Details * add inline to _refund * add new pledgeable tests * add getX tests + add get_pledge_count * refactor pledger_to_amount_index->pledger_to_amount * Add tests with 1000 pledgers * add test for add + update existing pledger * reenable lib * Add link to adv. factory in crowdfunding point 9 * write the adv. factory chapter * upgrade_campaign_implementation-> upgrade_campaign + comment updates * rename get_pledgers_as_arr->array * Use ERC20Upgradeable instead of ERC20 preset * Add missing token recipient ctor argument in crowdfunding tests --------- Co-authored-by: Nenad * test: countable (switchable, ownable) components (#205) * test: implement test for countable component * test: implement test for switchable component * test: implement test for ownable component * chore: implement test for emitted events and add anchor tags * feat: apply requested changes * feat: apply requested changes * feat: revisions --------- Co-authored-by: julio4 * doc: SNIP-6 implementation (#200) * test: SNIP-6 implementation * docs: errors recheck * test: SNIP-6 implementation * docs: errors recheck * feat: add simple account example * feat/fix: revisions on #200 * feat:implement SRC5 * feat: implementation with oz * fix: oz impl src5 for account --------- Co-authored-by: Oluwaseun Jeremiah Co-authored-by: julio4 <30329843+julio4@users.noreply.github.com> * simple_vault test implementation (#220) * Update es.po (#231) Some updates and corrections. * Add Dict Cheatsheet (#235) * simple_vault test implementation * Added dict cheatsheet * Added dict cheatsheet * a little clean up * a little clean up * Mention Foundry is an option for tests (#240) * Update SUMMARY.md (#239) - Add link to NFT Dutch Auction chapter * fix: links, typos, preludes... (#241) * Update Cairo >2.8, `2024_07` edition (#246) * remove List No longer needed with Vec * chore: dependencies update >=2.8 * chore: 2024_07 edition getting-started * chore: Map getting-started * chore: update applications * chore: update dependencies * fix: storage variables PointerReadAccess * doc: update contributor guide * chore: update advanced-concepts * fix: 2024_07 edition * chore: versions update * feat: storage custom types individual members access * remove storing arrays chapter * ci/cd: remove custom test resolver script * chore: switch dependencies to scarb registry * Revert "ci/cd: remove custom test resolver script" This reverts commit 0c3549fd038c3274d7ea748fd8d89f2fee633c43. * chore: split snforge/cairo-test scarb config * Random Number Generator (#238) * feat: dice game vrf application * feat: add summary nav * fix: ran scarb fmt * fix: ran scarb fmt * Fix new lines * Add more info on randomness sources * Rename dice_game_vrf.md->random_number_generator.md and update titles * minor rewording of 1 entropy source * remove anchors * Minor changes to fn names * Implement dice game scaffold * Implement Pragma randomness * minor refactor in randomness request * Implement powerball scaffold * Turn Dice Game into CoinFlip * Implement coin_flip test * Add more tests * Update titles * Remove redundant blank line * Add premium fee calculation into tests * Assert leftover balance * Remove comment about fees * Increase the expected callback fee, update mock to expose fee calc fn * Unfinished: refunded * Store and use is_refunded flag * Implement logic necessary to successfully perform & test refund * Update callback fee limit based on manual testing + update term to deposit * Format * Use a FlipData struct instead of tuple * Fix refund * Simplify CoinFlip to pay the flips itself * CALLBACK_FEE_DEPOSIT->MAX_CALLBACK_FEE_DEPOSIT * Update tests to test the new CoinFlip contract * Fix compile errors * Increase publish_delay to 1 & remove unused imports * Remove starkli-wallet dir * Generate 3 random words for the 1st test * refactor tests * Add missng newline to scarb.toml * fix typo in md * reword 'manipulation' def * Chainlink->Pragma * link to Commit-reveal chapter issue * list 'shut down' as possible centr. issue with ext. oracles * Turn point 5 into a note * Remove Sideways enum * add contract description * Remove ResultTrait from crowdfunding tests.cairo --------- Co-authored-by: Tony Stark Co-authored-by: Nenad Co-authored-by: Nenad * feat(merkle-tree): Contract with tests (#228) * feat(merkle-tree): Contract with tests * feat(merkle-tree): Corrections according to PR reviews * feat(merkle-tree): Contract with tests * fix: 2024_07 edition * fix: Replace Map simulating Array with Vec - streamline md file explanations * fix: scarb fmt --------- Co-authored-by: julio4 <30329843+julio4@users.noreply.github.com> * Improvement: typos check in CI/CD (#248) * fix: typos * ci/cd: typos check in ci * fix: cases * fix: randomness requestor typos * feat: cairo syntax hl (#249) * Expand Constant Product AMM's description (#252) * Expand Constant Product AMM's description * Refactor --------- Co-authored-by: Julio <30329843+julio4@users.noreply.github.com> * Minor _Scarb.toml_ refactors (#251) * Set one common edition version in workspace Scarb.toml * move snforge_std to dev-deps * Remove [lib] from coin_flip and simple_storage_starknetjs * rebuild projects * remove casm attr from scarb.toml * Update foundry to 0.31.0 in tool-versions * Set workspace cairo_test in mappings * Add missing cairo_test.workspace attrbs to Scarb.tomls * Revert snforge_std to 0.30.0 * Revert "Add missing cairo_test.workspace attrbs to Scarb.tomls" This reverts commit 7a9131dd2ef35ec1457f4829dbb3b9dd0a6b7439. * scarb.lock * feat: commit-reveal pattern --------- Co-authored-by: the-first-elder Co-authored-by: julio4 Co-authored-by: Okoli Evans Co-authored-by: Nenad Misić Co-authored-by: Nenad Co-authored-by: Asher <141028690+No-bodyq@users.noreply.github.com> Co-authored-by: hudem1 <55464342+hudem1@users.noreply.github.com> Co-authored-by: saimeunt Co-authored-by: princeibs <64266194+princeibs@users.noreply.github.com> Co-authored-by: Wolf <81079370+raizo07@users.noreply.github.com> Co-authored-by: Ege Co-authored-by: Jules Doumeche <30329843+julio4@users.noreply.github.com> Co-authored-by: Nenad Misić Co-authored-by: Emmanuel A Akalo <124416278+NueloSE@users.noreply.github.com> Co-authored-by: Jemiiah <160767568+Jemiiah@users.noreply.github.com> Co-authored-by: Oluwaseun Jeremiah Co-authored-by: Orlando Sanchez Co-authored-by: Tony Stark --- Scarb.lock | 4 ++ .../commit_reveal/.gitignore | 1 + .../commit_reveal/Scarb.toml | 15 ++++ .../commit_reveal/src/commit_reveal.cairo | 71 +++++++++++++++++++ .../commit_reveal/src/lib.cairo | 1 + src/SUMMARY.md | 1 + src/advanced-concepts/commit-reveal.md | 38 ++++++++++ 7 files changed, 131 insertions(+) create mode 100644 listings/advanced-concepts/commit_reveal/.gitignore create mode 100644 listings/advanced-concepts/commit_reveal/Scarb.toml create mode 100644 listings/advanced-concepts/commit_reveal/src/commit_reveal.cairo create mode 100644 listings/advanced-concepts/commit_reveal/src/lib.cairo create mode 100644 src/advanced-concepts/commit-reveal.md diff --git a/Scarb.lock b/Scarb.lock index b73c3911..6cd8c91c 100644 --- a/Scarb.lock +++ b/Scarb.lock @@ -31,6 +31,10 @@ dependencies = [ "snforge_std", ] +[[package]] +name = "commit_reveal" +version = "0.1.0" + [[package]] name = "components" version = "0.1.0" diff --git a/listings/advanced-concepts/commit_reveal/.gitignore b/listings/advanced-concepts/commit_reveal/.gitignore new file mode 100644 index 00000000..eb5a316c --- /dev/null +++ b/listings/advanced-concepts/commit_reveal/.gitignore @@ -0,0 +1 @@ +target diff --git a/listings/advanced-concepts/commit_reveal/Scarb.toml b/listings/advanced-concepts/commit_reveal/Scarb.toml new file mode 100644 index 00000000..8a6c3454 --- /dev/null +++ b/listings/advanced-concepts/commit_reveal/Scarb.toml @@ -0,0 +1,15 @@ +[package] +name = "commit_reveal" +version.workspace = true +edition.workspace = true + +[dependencies] +starknet.workspace = true + +[dev-dependencies] +cairo_test.workspace = true + +[scripts] +test.workspace = true + +[[target.starknet-contract]] diff --git a/listings/advanced-concepts/commit_reveal/src/commit_reveal.cairo b/listings/advanced-concepts/commit_reveal/src/commit_reveal.cairo new file mode 100644 index 00000000..0d57c514 --- /dev/null +++ b/listings/advanced-concepts/commit_reveal/src/commit_reveal.cairo @@ -0,0 +1,71 @@ +#[starknet::interface] +pub trait ICommitmentRevealTrait { + fn commit(ref self: T, commitment: felt252); + fn reveal(self: @T, secret: felt252) -> bool; +} + +// ANCHOR: contract +#[starknet::contract] +pub mod CommitmentRevealTraits { + use starknet::storage::{StoragePointerWriteAccess, StoragePointerReadAccess}; + use core::hash::HashStateTrait; + use core::pedersen::PedersenTrait; + + #[storage] + struct Storage { + commitment: felt252, + } + + #[abi(embed_v0)] + impl CommitmentRevealTrait of super::ICommitmentRevealTrait { + fn commit(ref self: ContractState, commitment: felt252) { + self.commitment.write(commitment); + } + + fn reveal(self: @ContractState, secret: felt252) -> bool { + let hash = PedersenTrait::new(secret).finalize(); + self.commitment.read() == hash + } + } +} +// ANCHOR_END: contract + +#[cfg(test)] +mod tests { + use starknet::SyscallResultTrait; + use super::{ + CommitmentRevealTraits, ICommitmentRevealTraitDispatcher, + ICommitmentRevealTraitDispatcherTrait + }; + + use core::hash::HashStateTrait; + use core::pedersen::PedersenTrait; + use starknet::syscalls::deploy_syscall; + + fn deploy() -> ICommitmentRevealTraitDispatcher { + let (contract_address, _) = deploy_syscall( + CommitmentRevealTraits::TEST_CLASS_HASH.try_into().unwrap(), 0, array![].span(), false + ) + .unwrap_syscall(); + ICommitmentRevealTraitDispatcher { contract_address } + } + + #[test] + fn commit_and_reveal() { + let mut contract = deploy(); + + // ANCHOR: offchain + // Off-chain, compute the commitment hash for secret + let secret = 'My secret'; + let offchain_commitment = PedersenTrait::new(secret).finalize(); + + // Commit on-chain + contract.commit(offchain_commitment); + + // Reveal on-chain and assert the result + let reveal_result = contract.reveal(secret); + // ANCHOR_END: offchain + assert_eq!(reveal_result, true); + } +} + diff --git a/listings/advanced-concepts/commit_reveal/src/lib.cairo b/listings/advanced-concepts/commit_reveal/src/lib.cairo new file mode 100644 index 00000000..e6dc85b7 --- /dev/null +++ b/listings/advanced-concepts/commit_reveal/src/lib.cairo @@ -0,0 +1 @@ +mod commit_reveal; diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 60b89e4a..d83439a1 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -74,6 +74,7 @@ Summary - [Writing to any storage slot](./advanced-concepts/write_to_any_slot.md) - [Struct as mapping key](./advanced-concepts/struct-mapping-key.md) - [Hashing](./advanced-concepts/hashing.md) +- [Commit-Reveal](./advanced-concepts/commit-reveal.md) - [Optimisations](./advanced-concepts/optimisations/optimisations.md) diff --git a/src/advanced-concepts/commit-reveal.md b/src/advanced-concepts/commit-reveal.md new file mode 100644 index 00000000..1d5d979b --- /dev/null +++ b/src/advanced-concepts/commit-reveal.md @@ -0,0 +1,38 @@ +# Commit-Reveal + +The Commit-Reveal pattern is a fundamental blockchain pattern that enables to: +1. Commit to a value without revealing it *(commit phase)* +2. Reveal the value later to prove they knew it in advance *(reveal phase)* + +Some use cases: +- **Blind Auctions**: Bidders commit to their bids first, then reveal them after the bidding period +- **Voting Systems**: Voters commit their votes early, revealing them only after voting ends +- **Knowledge Proofs/Attestations**: Proving you knew information at a specific time without revealing it immediately +- **Fair Random Number Generation**: Players commit to random numbers that get combined later, making it harder to manipulate the outcome + +## How It Works + +1. **Commit Phase**: + - User generates a value (`secret`) + - User creates a hash of this value + - User submits only the hash on-chain (`commit`) + +2. **Reveal Phase**: + - User submits the original value (`reveal`) + - Contract verifies that the hash of the submitted value matches the previously committed hash + - If it matches then it proves that the user knew the value at the commitment time + +## Minimal commit-reveal contract: + +```cairo +{{#rustdoc_include ../../listings/advanced-concepts/commit_reveal/src/commit_reveal.cairo:contract}} +``` + +Usage example: +```cairo +{{#include ../../listings/advanced-concepts/commit_reveal/src/commit_reveal.cairo:offchain}} +``` + +Some considerations: +- The commit phase must complete before any reveals can start +- Users might choose not to reveal if the outcome is unfavorable (consider adding stake/slashing mechanics to ensure reveals)