* feat(data): implement Viem lib alternative to Ethers for @semaphore-protocol/data package class
This adds a Viem-based alternative to SemaphoreEthers, allowing
developers to choose their preferred Ethereum library.
Closes#343
* chore(data): update yarn.lock for viem dependency
* chore(data): improve test coverage for SemaphoreViem class
* chore(data): improve test coverage for SemaphoreViem class
* chore: update semaphore contract address
re #978
* feat: add ethereum as a supported network
re #977
* feat: add ethereum subgraph and deploy subgraphs
re #978, #977
Update ethers version to resolve ws security issue (CVE-2024-37890).
Move contract address check outside of branch statement so Typescript can see.
Add build instructions to setup to resolve 'Cannot find module '@semaphore-protocol/...' when
running tests for the first time.
re #920
* feat(cli): remove @semaphore-protocol/cli prepublish script
The idea is to remove the prepublish script from the scripts object of the package.json file of
every cli template when the template is downloaded using the CLI.
BREAKING CHANGE: n
* refactor(cli): add comment
* refactor(cli): create seperate file for removePrePublishScript function
* refactor(cli): using updatedPackageJsonContent var instead of calling readFileSync again
* fix(subgraph): clean node_modules before building subgraph
* refactor(subgraph): fix: test typo
* refactor(subgraph): refactor: remove nohoist
* refactor(subgraph): refactor: workspaces structure
* chore(contracts): remove sub() from gas() in staticcall at SemaphoreVerifier
re #871
* refactor(contracts): using fixed gas cost on precompile calls
re #871
* refactor(contracts): increease fixed gas cost with safety buffer
* feat(cli): remove @semaphore-protocol/cli prepublish script
The idea is to remove the prepublish script from the scripts object of the package.json file of
every cli template when the template is downloaded using the CLI.
BREAKING CHANGE: n
* refactor(cli): add comment
* refactor(cli): create seperate file for removePrePublishScript function
* refactor(cli): using updatedPackageJsonContent var instead of calling readFileSync again
* refactor(scripts): added a script to convert bigint to hex
* refactor(contracts): split SemaphoreVerifier verification key points into a separate library (#330)
* chore(contracts): yarn format & lint
* refactor(contracts): update SemaphoreVerifierKeyPts library to be internal
re #330
* chore(contracts): update spacing
* chore(contracts): updated per peer review and added invariant check for VerifierKeyPts lib
* chore(contracts): update invariant check to revert with custom error
This static method is particularly useful after signature verification, as it allows retrieval of
the corresponding commitment associated with the public key.
re #873
* chore(contracts): deploy semaphore contracts on base
re #865
* chore(contracts): deploy semaphore contracts on linea
re #865
* refactor(data): add types for new networks
re #865
* chore(contracts): deploy contracts on arbitrum
re #859
* chore(contracts): deploy contracts on polygon
re #859
* chore(contracts): deploy contracts on optimism
re #859
* chore: define separate version.ts script
* chore: include publishing to soldeer in script
* fix(contracts): push to soldeer
re 800
* ci: fetch latest contract version from soldeer
* refactor: do not use execa in scripts
* fix: do not exit process in script
* chore: remove comments
* refactor: use shebang in ts scripts
* chore(contracts): add soldeerignore
* chore: inherit stdio in scripts
* chore: remove dry run flag
* chore: uncomment
* chore: fix typo in comment
The public signal of proof related to the Merkle root could obviously be different from what is
expected to be the root of the group. Therefore, for the proof to be valid, it is necessary that the
group root passed as a parameter matches the proof/circuit root output.
re #842
refactor(cli): create an empty yarn.lock file when generating a semaphore project with the cli
Now devs will be able to install dependencies successfully right after creating a project with the
CLI.
re #827
* ci(contracts): a script that moves the abi.json file created to utils folder
A script could be run immediately after compilation to copy the file
artifacts/contracts/Semaphore.sol/Semaphore.json to packages/utils/src/semaphore-abi.json. Then all
packages/apps that need the interface can import it from @semaphore-protocol/utils.
re #817
* refactor(utils): allows packages to import abi from @semaphore-protocol/utils
re #817
* refactor(cli-template-monorepo-ethers): installs ncp and exports Semaphore Abi byte code
re #817
* refactor(contracts): added a script that automates movement of semaphore-abi.json
* chore(cli): changed the dependency and moved to ncp for copying semaphore abi
Changed the importation of abi in utils to _interface and moved the ncp to a dev depency
* chore(utils): changed ab to _interface and update to package.json
* chore(cli): deleted Cli-template file and made a document change
delted some cli-template file, changed yarn commit to git commit and fixed the yarn compile script
* chore: parallelize build scripts
* chore: run tests concurrently
* chore: group test log outputs
* chore: execute lint and format scripts concurrently
* refactor: do no use wildcard for test script`
* fix(identity)!: update type of private key
The new types support buffers and text, so that there is less ambiguity on strings.
* refactor(identity): use base64 as encoding for exported priv keys
re #799
* Update packages/identity/src/index.ts
Co-authored-by: Andrew Twyman <artwyman@users.noreply.github.com>
* test(identity): add more tests
re #799
---------
Co-authored-by: Andrew Twyman <artwyman@users.noreply.github.com>
* chore(website): add trusted setup ceremony on the website
* docs(docs): add trusted setup ceremony instructions on documentation
* chore(docs): add candidate plan for prod ceremony
re n
* fix(docs): rename file to avoid mismatching hyphens
* style(website): follow style guide for hover
* fix(website): wrong link to ceremony
* fix(docs): switch emoji
* chore: shorten `docs` scripts
`githubPages` is true by default
https://rb.gy/hzopfn
* docs: update README.md
* chore: trigger docs workflow only on changes in relevant files
* refactor: provide `cname` typedoc option via config file
* chore: remove heyauthn from exclude typedoc list
* chore: update @zk-kit/baby-jubjub and @zk-kit/eddsa-poseidon dependencies
re #786
* chore(group): use the new @zk-kit/lean-imt library
re #786
* chore: update @zk-kit/utils version
re #786
* chore(contracts): use the new @zk-kit/lean-imt.sol library in contracts
re #786
* feat: support more tree depth
Now Semaphore v4 will support tree depth from 2 to 32.
re #778
* test(proof): update tests to support circuit changes and tree depth 2 - 32
re #778
* fix(contracts): update verifier VK_POINTS
re #778
* test(proof): make tests more atomic
* chore: support tree depth 1
re #778
Through Github rulesets and the definition of code owners, it is possible to automate the review
process without additional workflows. It also makes responsibilities within the project clearer. The
current CODEOWNERS file is very simple but more complex rules can be introduced in the future.
re #783
* test: add missing tests
Now all lines of js libraries are 100% covered.
re #484
* test(proof): update message type
re #484
* test(proof): update constant
re #484
* test(proof): update number constant
re #484
* chore: update lint-staged config
* chore: use czg instead of cz + cz-git
re #738
* chore: use cat instead of vim editor to write commits
re #738
* chore: use secrets.GITHUB_TOKEN instead of secrets.GH_TOKEN
re #738
* style: add a space at the end of the pre-commit file
* chore(docs): format `mdx` files with `remark`
`prettier` doesn't not have proper support for MDX v3.
Docusaurus recommends using `remark` instead.
https://docusaurus.io/docs/markdown-features/react
re #503
* chore(docs): add remark lint plugins
* chore: bump yarn.lock
* chore: add `quiet` option to remark
The ZK-Kit EdDSA Poseidon package only supports the following private key types: text, buffer. The
Semaphore identity supports text and hexadecimal strings. If the identity private key is an
hexadicimal string it needs to be converted before being passed to any ZK-Kit function.
re #733
Targeting ES2020 looks like it's generally fine today. It's widely supported across modern browsers
and environments and it would allow Semaphore bundles to use new ES features natively, like arrow
functions, promises, and classes, which can improve code readability and efficiency.
re #688
Former-commit-id: 9f49d91197
The best practice to update a group admin is through a two-step update. The existing admin assigns
the new potential admin, and the new admin accepts in a separate transaction. This prevents existing
admins from making mistakes and assigning wrong addresses.
re #690
Former-commit-id: 255bccf2eb
overrides only works with NPM and both overrides and resolutions works if they are in the project
root package.json. So they don't solve #713.
re #713
Former-commit-id: b77feebdea
Adding the 'resolutions' field with the static version of web-worker solves the problem described in
issue #713. To be regarded as a temporary solution.
re #713
Former-commit-id: ca36ed5488
The utils package will no longer provide errors and types utilities as those functions have been
moved to zk-kit. The utils package now provides a list of supported networks and a function to
decode messages instead.
re #642, #641
Former-commit-id: d2ce1070f0
The type of the identities' private key will always be a string type, either text or hexadecimal
strings. This will allow devs to store private keys more easily and avoid confusion with types.
re #700
Former-commit-id: eead04e45d
since the group ids are created incrementally internally in the contracts, there's no need to check
whether the group id has already been taken.
re #708
Former-commit-id: e205bf6ad7
The Semaphore V4 CLI templates don't support npm and pnpm yet. The documentation should reflect this
aspect. It will be updated as soon as those templates support more package managers.
re #676
Former-commit-id: e6198cfdbf
The commit adds more documentation to the Identity class and update the TypeDoc link. It also
removes the class method to verify signatures as the static method can be used instead.
re #483
Former-commit-id: b4c2887cf1
This commit add more documentation to the Semaphore circuits, with the aim of providing an overview
of the code used and to refer to other resources for futher information.
re #483
Former-commit-id: de12d471c0
<!-- Please refer to our contributing documentation for any questions on submitting a pull request -->
<!--- Provide a general summary of your changes in the Title above -->
<!-- Please refer to our CONTRIBUTING documentation for any questions on submitting a pull request. -->
<!-- Provide a general summary of your changes in the Title above. -->
## Description
<!--- Describe your changes in detail -->
<!-- Describe your changes in detail. -->
<!-- You may want to answer some of the following questions: -->
<!-- What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...) -->
<!-- What is the current behavior?** (You can also link to an open issue here) -->
<!-- What is the new behavior (if this is a feature change)? -->
<!-- Does this PR introduce a breaking change?** (What changes might users need to make in their application due to this PR?) -->
## Related Issue
## Related Issue(s)
<!--- This project accepts pull requests related to open issues -->
<!--- If suggesting a new feature or change, please discuss it in an issue first -->
<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->
<!--- Please link to the issue here: -->
<!-- This project accepts pull requests related to open issues. -->
<!-- If suggesting a new feature or change, please discuss it in an issue first. -->
<!-- If fixing a bug, there should be an issue describing it with steps to reproduce. -->
<!-- Please link to the issue(s) here -->
## Does this introduce a breaking change?
- [ ] Yes
- [ ] No
<!-- If this introduces a breaking change, please describe the impact and migration path for existing applications below. -->
<!-- Closes # -->
<!-- Fixes # -->
## Other information
<!-- Any other information that is important to this PR such as screenshots of how the component looks before and after the change. -->
<!-- Feel free to remove this section if you will not use it. -->
## Checklist
<!-- Please check if the PR fulfills these requirements. -->
- [ ] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] My changes generate no new warnings
- [ ] I have run `yarn format` and `yarn lint` without getting any errors
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
> [!IMPORTANT]
> We do not accept pull requests for minor grammatical fixes (e.g., correcting typos, rewording sentences) or for fixing broken links, unless they significantly improve clarity or functionality. These contributions, while appreciated, are not a priority for merging. If you notice any of these issues, please create a [GitHub Issue](https://github.com/semaphore-protocol/semaphore/issues/new?template=BLANK_ISSUE) to report them so they can be properly tracked and addressed.
@@ -22,13 +22,16 @@ Pull requests are great if you want to add a feature or fix a bug. Here's a quic
3. Add a test for your change. Only refactoring and documentation changes require no new tests.
4. Make sure to check out the [Style Guide](/CONTRIBUTING#style-guide) and ensure that your code complies with the rules.
4. Make sure to check out the [Style Guide](/CONTRIBUTING.md#style-guide) and ensure that your code complies with the rules.
5. Make the test pass.
6. Commit your changes.
7. Push to your fork and submit a pull request on our `dev` branch. Please provide us with some explanation of why you made the changes you made. For new features make sure to explain a standard use case to us.
7. Push to your fork and submit a pull request on our `main` branch. Please provide us with some explanation of why you made the changes you made. For new features make sure to explain a standard use case to us.
> [!IMPORTANT]
> We do not accept pull requests for minor grammatical fixes (e.g., correcting typos, rewording sentences) or for fixing broken links, unless they significantly improve clarity or functionality. These contributions, while appreciated, are not a priority for merging. If you notice any of these issues, please create a [GitHub Issue](https://github.com/semaphore-protocol/semaphore/issues/new?template=BLANK_ISSUE) to report them so they can be properly tracked and addressed.
## CI (Github Actions) Tests
@@ -42,11 +45,11 @@ When you submit your PR (or later change that code), a CI build will automatical
We always use ESLint and Prettier. To check that your code follows the rules, simply run the npm script `yarn lint`.
### Commits rules
### Commit rules
For commits it is recommended to use [Conventional Commits](https://www.conventionalcommits.org).
Don't worry if it looks complicated, in our repositories, after `git add`, you can usually run the npm script `yarn commit` to make many of these steps interactive.
Don't worry if it looks complicated, in our repositories, `git commit` opens an interactive app to create your conventional commit.
Each commit message consists of a **header**, a **body** and a **footer**. The **header** has a special format that includes a **type**, a **scope** and a **subject**:
@@ -93,7 +96,6 @@ Just as in the subject, use the imperative, present tense: "change" not "changed
### Branch rules
- There must be a `main` branch, used only for the releases.
- There must be a `dev` branch, used to merge all the branches under it.
- Avoid long descriptive names for long-lived branches.
- Use kebab-case (no CamelCase).
- Use grouping tokens (words) at the beginning of your branch names (in a similar way to the `type` of commit).
| Semaphore is a protocol, designed to be a simple and generic privacy layer for Ethereum DApps. Using zeroknowledge, Ethereum users can prove their membership of a group and send signals such as votes or endorsements without revealing their original identity. |
| Semaphore is a generic privacy layer. Leveraging zero-knowledge technology, users can prove their membership in groups and send messages (extending from votes to endorsements) off-chain or across EVM-compatible blockchains, all without revealing their personal identity. |
The core of the Semaphore protocol is in the [circuit logic](/packages/circuits/scheme.png). However Semaphore also provides [Solidity contracts](/packages/contracts) and JavaScript libraries to make the steps for offchain proof creation and onchain verification easier. To learn more about Semaphore visit [semaphore.pse.dev](https://semaphore.pse.dev).
The core of the Semaphore protocol is in the [circuit logic](/packages/circuits/scheme.png). However, Semaphore also provides [Solidity contracts](/packages/contracts) and JavaScript libraries to make the steps for offchain proof creation and onchain/offchain verification easier. To learn more about Semaphore visit [semaphore.pse.dev](https://semaphore.pse.dev).
> [!IMPORTANT]
> Help Semaphore prosper by sharing your ideas with the PSE [acceleration program](https://github.com/privacy-scaling-explorations/acceleration-program).
## 📦 Packages
@@ -69,6 +78,25 @@ The core of the Semaphore protocol is in the [circuit logic](/packages/circuits/
Run [Prettier](https://prettier.io/) to check formatting rules:
```bash
yarn prettier
yarn format
```
Or to automatically format the code:
```bash
yarn prettier:write
yarn format:write
```
### Conventional commits
@@ -288,19 +322,11 @@ yarn prettier:write
Semaphore uses [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/). A [command line utility](https://github.com/commitizen/cz-cli) to commit using the correct syntax can be used by running:
```bash
yarn commit
git commit
```
It will also automatically check that the modified files comply with ESLint and Prettier rules.
### Snark artifacts
Download the Semaphore snark artifacts needed to generate and verify proofs:
```bash
yarn download:snark-artifacts
```
### Testing
Run [Jest](https://jestjs.io/) to test the JS libraries:
@@ -323,10 +349,10 @@ yarn test
### Build libraries & compile contracts
Run [Rollup](https://www.rollupjs.org) to build all the packages:
Run [Rollup](https://www.rollupjs.org) and [TheGraph](https://www.npmjs.com/package/@graphprotocol/graph-cli) to build all the packages and the subgraph:
```bash
yarn build:libraries
yarn build
```
Compile the smart contracts with [Hardhat](https://hardhat.org/):
@@ -344,3 +370,31 @@ yarn docs
```
The output will be placed on the `docs` folder.
### Releases
Steps:
1. Bump a new version with:
```bash
yarn version:bump <version>
# e.g. yarn version:bump 2.0.0
```
This step creates a commit and a git tag.
2. Push the changes to main:
```bash
git push origin main
```
3. Push the new git tag:
```bash
git push origin <version>
# e.g. git push origin v2.0.0
```
After pushing the new git tag, a workflow will be triggered to publish the Semaphore packages on [npm](https://www.npmjs.com/) and release a new version on GitHub with its changelogs automatically.
// '<b>We are pleased to announce the release of <a target="_blank" rel="noopener noreferrer" href="https://github.com/semaphore-protocol/semaphore/releases/tag/v3.0.0">Semaphore V3</a> 🎉</b>',
'<b><a href="https://github.com/semaphore-protocol/semaphore/releases/tag/v4.0.0" target="_blank">Semaphore V4</a> is out 🎉 <a href="/getting-started">Try it out</a> and let us know if you have any feedback on <a href="https://semaphore.pse.dev/telegram" target="_blank">Telegram</a> or <a href="https://github.com/orgs/semaphore-protocol/discussions" target="_blank">Github</a>!</b>',
backgroundColor:"#dde6fc",
textColor:"#000000"
},
// Social media card
image:"img/social-media.png",
navbar:{
logo:{
alt:"Semaphore Logo",
src:"img/semaphore-logo.svg"
},
items:[
{
type:"docsVersionDropdown",
position:"left",
dropdownActiveClassDisabled: true
},
{
label:"Whitepaper",
to:"https://semaphore.pse.dev/whitepaper-v1.pdf",
position:"left",
className:"whitepaper-v1"
},
{
label:"Github",
href:"https://github.com/semaphore-protocol",
position:"right"
},
{
label:"Website",
href:"https://semaphore.pse.dev",
position:"right"
},
{
type:"localeDropdown",
position:"right"
}
]
},
colorMode:{
defaultMode:"light",
// Should we use the prefers-color-scheme media-query,
// using user system preferences, instead of the hardcoded defaultMode
"message":"Semaphore utiliza la función hash Poseidon para crear el identtity commitment a partir de los valores privados. Los identity commitments se pueden compartir públicamente, de forma similar a las direcciones Ethereum."
"message":"Semaphore utiliza la función hash Poseidon para crear el identity commitment a partir de los valores privados. Los identity commitments se pueden compartir públicamente, de forma similar a las direcciones Ethereum."
@@ -40,7 +40,7 @@ For more information, see [Merkle tree in Wikipedia](https://en.wikipedia.org/wi
A value used to prevent double entry or double signalling.
See [Circuit nullifier hash](/technical-reference/circuits/#nullifier-hash).
See [Circuit nullifier hash](/V2/technical-reference/circuits/#nullifier-hash).
## Relay
@@ -48,7 +48,7 @@ A third-party who receives a fee for including relayed transactions in the block
To preserve the anonymity of the user broadcasting a signal with Semaphore, an application may use a relayer to post the signal transaction to Ethereum on behalf of the user.
Applications may provide rewards for relayers and implement front-running prevention mechanisms, such as requiring the signals to include the relayer’s address, binding the
signal to that specific address (https://docs.semaphore.pse.dev/whitepaper-v1.pdf, p.6).
signal to that specific address (https://semaphore.pse.dev/whitepaper-v1.pdf, p.6).
## Trusted setup files
@@ -60,5 +60,5 @@ To generate or verify valid zero-knowledge proofs with Semaphore, applications m
- semaphore.wasm
- semaphore.json
For a complete list of ready-to-use files, see <http://www.trusted-setup-pse.org>.
For a complete list of ready-to-use files, see [trusted-setup-pse.org](https://www.trusted-setup-pse.org).
To learn more, see the [trusted setup ceremony](https://storage.googleapis.com/trustedsetup-a86f4.appspot.com/semaphore/semaphore_top_index.html).
Use Semaphore in your application or smart contract to create off-chain and on-chain groups.
A [Semaphore group](/glossary/#semaphore-group) contains [identity commitments](/glossary/#identity-commitment) of group members.
A [Semaphore group](/V2/glossary/#semaphore-group) contains [identity commitments](/V2/glossary/#identity-commitment) of group members.
Example uses of groups include the following:
- Poll question that attendees join to rate an event.
- Ballot that members join to vote on a proposal.
- Whistleblowers who are verified employees of an organization.
A Semaphore group is an [incremental Merkle tree](/glossary/#incremental-merkle-tree), and group members (i.e., [identity commitments](/glossary/#identity-commitments)) are tree leaves.
A Semaphore group is an [incremental Merkle tree](/V2/glossary/#merkle-tree), and group members (i.e., identity commitments) are tree leaves.
Semaphore groups set the following two parameters:
-**Tree depth**: the maximum number of members a group can contain (`max size = 2 ^ tree depth`).
Learn how to use Semaphore to generate and verify zero-knowledge proofs.
Once a user joins their [Semaphore identity](/glossary#semaphore-identity) to a [Semaphore group](/glossary#semaphore-group), the user can signal anonymously with a zero-knowledge proof that proves the following:
Once a user joins their [Semaphore identity](/V2/glossary#semaphore-identity) to a [Semaphore group](/V2/glossary#semaphore-group), the user can signal anonymously with a zero-knowledge proof that proves the following:
- The user is a member of the group.
- The same user created the signal and the proof.
@@ -27,11 +27,11 @@ To generate a proof, pass the following properties to the `generateProof` functi
-`group`: The group to which the user belongs.
-`externalNullifier`: The value that prevents double-signaling.
-`signal`: The signal the user wants to send anonymously.
-`snarkArtifacts`: The `zkey` and `wasm` [trusted setup files](/glossary/#trusted-setup-files).
-`snarkArtifacts`: The `zkey` and `wasm` [trusted setup files](/V2/glossary/#trusted-setup-files).
In the voting system use case, once all the voters have joined their [identities](/guides/identities#create-an-identity) to the ballot [group](/guides/groups),
In the voting system use case, once all the voters have joined their [identities](/V2/guides/identities#create-identities) to the ballot [group](/V2/guides/groups),
a voter can generate a proof to vote for a proposal.
In the call to `generateProof`, the voting system passes the unique ballot ID (the [Merkle tree](/glossary/#merkle-tree/) root of the group) as the
In the call to `generateProof`, the voting system passes the unique ballot ID (the [Merkle tree](/V2/glossary#merkle-tree) root of the group) as the
`externalNullifier` to prevent the voter signaling more than once for the ballot.
The following code sample shows how to use `generateProof` to generate the voting proof:
@@ -53,7 +53,7 @@ Use the [`@semaphore-protocol/proof`](https://github.com/semaphore-protocol/sema
To verify a proof, pass the following to the `verifyProof` function:
-_`proof`_: the Semaphore proof.
-_`verificationKey`_: the JavaScript object in the `semaphore.json` [trusted setup file](/glossary/#trusted-setup-files).
-_`verificationKey`_: the JavaScript object in the `semaphore.json` [trusted setup file](/V2/glossary/#trusted-setup-files).
The following code sample shows how to parse the verification key object from `semaphore.json`
The [Semaphore circuit](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/circuits) is the heart of the protocol and consists of three parts:
- [**Proof of membership**](/technical-reference/circuits#proof-of-membership)
To use Semaphore contracts and interfaces in your project,
@@ -24,7 +24,7 @@ Semaphore provides the following base contracts:
These contracts are closely related to the protocol.
You can inherit them in your contract or you can use [`Semaphore.sol`](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/Semaphore.sol), which inherits them for you.
See our [deployed contracts](/deployed-contracts#semaphore) to find the addresses for your network.
See our [deployed contracts](/V2/deployed-contracts#semaphore) to find the addresses for your network.
:::info
While some dApps may use on-chain groups, others may prefer to use off-chain groups, saving only their tree roots in the contract.
@@ -41,7 +41,7 @@ More extensions will be added in the future.
## Verifiers
To verify Semaphore proofs, the [`SemaphoreCore.sol`](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/base/SemaphoreCore.sol) contract requires the address of a deployed verifier contract.
You can choose to manually deploy the [verifier](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/verifiers) you prefer or you can use one of our [deployed verifiers](/deployed-contracts#verifiers).
You can choose to manually deploy the [verifier](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/verifiers) you prefer or you can use one of our [deployed verifiers](/V2/deployed-contracts#verifiers).
Each verifier name indicates the tree depth that it can verify.
For example, given a Semaphore proof generated with a tree depth `20`:
@@ -36,7 +36,7 @@ Community members connect their wallets to the dApp to take the following action
### Relay
To preserve anonymity and avoid disclosing the member's wallet address, the dApp may use a [relay](/glossary/#relay) to broadcast the vote.
To preserve anonymity and avoid disclosing the member's wallet address, the dApp may use a [relay](/V2/glossary/#relay) to broadcast the vote.
The relay calls the **contract** function that then posts the member's vote transaction to Ethereum.
## Private voting
@@ -52,7 +52,7 @@ The voting scenario has the following steps:
### Create a poll
A community coordinator or dApp administrator uses the deployed smart contract to create an on-chain (Ethereum) poll, a [Semaphore group](/guides/groups/) that members can join and cast votes to.
A community coordinator or dApp administrator uses the deployed smart contract to create an on-chain (Ethereum) poll, a [Semaphore group](/V2/guides/groups/) that members can join and cast votes to.
In the following sample code, the voting contract declares a `createPoll` function that uses the Semaphore base `_createGroup` function:
@@ -78,11 +78,11 @@ function createPoll(
}
```
A poll is a Semaphore [group](/guides/groups/) that stores the following:
A poll is a Semaphore [group](/V2/guides/groups/) that stores the following:
- A topic to vote on.
- The public ID of the poll creator.
- [Semaphore IDs](/guides/identities/) of members who joined the poll.
- [Semaphore IDs](/V2/guides/identities/) of members who joined the poll.
To create the poll, the administrator calls the smart contract function--for example:
@@ -128,10 +128,10 @@ With a member registered for a poll, learn how the dApp [records votes](#record-
Once members have joined a poll, the coordinator starts the poll to allow voting.
When a member votes (for example, by selecting a radio button), then the dApp takes the following actions:
1. Uses the `@semaphore-protocol/proof` library to create a proof of the vote, the poll identifier, the Semaphore ID, and a [nullifier](/glossary/#nullifier) that prevents double-voting.
1. Uses the `@semaphore-protocol/proof` library to create a proof of the vote, the poll identifier, the Semaphore ID, and a [nullifier](/V2/glossary/#nullifier) that prevents double-voting.
2. Sends the vote proof to the [relay](#relay).
### Related
- To get started developing with Semaphore, see the [Quick setup](/quick-setup/) guide.
- To get started developing with Semaphore, see the [Quick setup](/V2/quick-setup/) guide.
- For an example app that you can use to start your own project, see [Semaphore boilerplate](https://github.com/semaphore-protocol/boilerplate).
@@ -14,7 +14,7 @@ También proporciona un mecanismo simple para evitar la doble señalización, lo
## ¿Dónde puedo hacer preguntas sobre Semaphore?
Puede hacer preguntas sobre Semaphore en [Discord](https://semaphore.pse.dev/discord) o abriendo un [Semaphore Discussion](https://github.com/semaphore-protocol/semaphore/discussions).
Puede hacer preguntas sobre Semaphore en [Telegram](https://semaphore.pse.dev/telegram) o abriendo un [Semaphore Discussion](https://github.com/semaphore-protocol/semaphore/discussions).
## ¿Por qué las identidades requieren tanto `identity trapdoor` como `identity nullifier`?
La identidad de un usuario en el protocolo Semaphore.
Una identidad contiene los tres valores que se mencionan a continuación:
- [Compromiso de identidad](#identity-commitment) (identity commitment): el valor público.
- [Compromiso de identidad](#compromiso-de-identidad-identity-commitment) (identity commitment): el valor público.
- Identidad trampilla (identity trapdoor) y anulador de identidad (identity nullifier): valores secretos que únicamente son del conocimiento del usuario.
## Compromiso de identidad (Identity commitment)
El valor público de la [identidad Semaphore](#semaphore-identity) utilizado en los [grupos Semaphore](#semaphore-group).
El valor público de la [identidad Semaphore](#identidad-semaphore) utilizado en los [grupos Semaphore](#grupo-semaphore).
Semaphore utiliza la función hash [Poseidon](https://www.poseidon-hash.info/) para crear un compromiso de identidad a partir de los valores secretos de la identidad Semaphore.
## Grupo Semaphore
Un grupo es un [árbol de Merkle](#merkle-tree) binario e incremental en el que cada hoja contiene un [compromiso de identidad](#identity-commitment) para un usuario.
Un grupo es un [árbol de Merkle](#árbol-de-merkle-merkle-tree) binario e incremental en el que cada hoja contiene un [compromiso de identidad](#compromiso-de-identidad-identity-commitment) para un usuario.
El compromiso de identidad comprueba que un usuario es un miembro del grupo sin revelar la identidad Semaphore del usuario.
Semaphore utiliza la función hash **Poseidon** para crear árboles de Merkle.
@@ -39,14 +39,14 @@ Para más información, vea [árbol de Merkle en Wikipedia](https://es.wikipedia
Un valor utilizado para prevenir registros dobles o dos señales emitidas por el mismo usuario.
Ver [hash de circuito nullifier](/technical-reference/circuits/#nullifier-hash).
Ver [hash de circuito nullifier](/V3/technical-reference/circuits#hash-anulador-nullifier-hash).
## Retransmisor (Relayer)
Un tercero que recibe una comisión por incluir transacciones retransmitidas en la blockchain (McMenamin, Daza, and Fitz. https://eprint.iacr.org/2022/155.pdf, p.3).
Para preservar la anonimidad del usuario emitiendo una señal con Semaphore, una aplicación puede utilizar un retransmisor para publicar la transacción de la señal en Ethereum en nombre del usuario.
Las aplicaciones pueden ofrecer recompensas a los retransmisores e implementar mecanismos para prevenir ventajas maliciosas, como requerir que las señales incluyan la dirección del retransmisor, vinculando así la señal a esa dirección en específico (https://docs.semaphore.pse.dev/whitepaper-v1.pdf, p.6).
Las aplicaciones pueden ofrecer recompensas a los retransmisores e implementar mecanismos para prevenir ventajas maliciosas, como requerir que las señales incluyan la dirección del retransmisor, vinculando así la señal a esa dirección en específico (https://semaphore.pse.dev/whitepaper-v1.pdf, p.6).
## Archivos confiables de configuración (Trusted setup files)
@@ -58,7 +58,7 @@ Para generar o verificar pruebas válidas de conocimiento cero con Semaphore, la
- semaphore.wasm
- semaphore.json
Para ver una lista completa de archivos listos para utilizarse, vea <http://www.trusted-setup-pse.org>.
Para ver una lista completa de archivos listos para utilizarse, vea [trusted-setup-pse.org](https://www.trusted-setup-pse.org).
Para aprender más, vea la [ceremonia de configuración de confianza](https://storage.googleapis.com/trustedsetup-a86f4.appspot.com/semaphore/semaphore_top_index.html) (trusted setup ceremony).
@@ -8,7 +8,7 @@ import TabItem from "@theme/TabItem"
# Semaphore data
Para obtener datos on-chain del contrato [Semaphore.sol](https://github.com/semaphore-protocol/semaphore/blob/main/packages/contracts/contracts/Semaphore.sol), puedes usar la librería [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data).
Para obtener datos on-chain del contrato [Semaphore.sol](https://github.com/semaphore-protocol/semaphore/blob/main/packages/contracts/contracts/Semaphore.sol), puedes usar la librería [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data).
Hay dos formas para hacer esto, usando [`SemaphoreSubgraph`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/subgraph.ts) o [`SemaphoreEthers`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/ethers.ts). La clase `SemaphoreSubgraph` usa el [subgrafo de Semaphore](https://github.com/semaphore-protocol/subgraph), el cual usa [The Graph Protocol](https://thegraph.com/) detrás del telón, y la clase `SemaphoreEthers` usa [Ethers](https://github.com/ethers-io/ethers.js/).
@@ -18,31 +18,36 @@ Hay dos formas para hacer esto, usando [`SemaphoreSubgraph`](https://github.com/
## Instalar librería
<Tabs
defaultValue="npm"
groupId="package-managers"
values={[
defaultValue="npm"
groupId="package-managers"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
{label: 'pnpm', value: 'pnpm'}
]}
>
<TabItem value="npm">
```bash
npm install @semaphore-protocol/data@^3
```
</TabItem>
```bash
npm install @semaphore-protocol/data
```
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/data@^3
```
</TabItem>
</TabItem>
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/data
```
</TabItem>
<TabItem value="pnpm">
```bash
pnpm add @semaphore-protocol/data@^3
```
</TabItem>
</Tabs>
## Obtener datos usando SemaphoreSubgraph
Para obtener datos usando el subgrafo de Semaphore puedes usar la clase [`SemaphoreSubgraph`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/subgraph.ts) del paquete [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data).
Para obtener datos usando el subgrafo de Semaphore puedes usar la clase [`SemaphoreSubgraph`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/subgraph.ts) del paquete [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data).
```typescript
import { SemaphoreSubgraph } from "@semaphore-protocol/data"
@@ -105,11 +110,12 @@ const semaphoreSubgraph = new SemaphoreSubgraph("sepolia")
Para obtener datos usando Ethers puedes usar la clase [`SemaphoreEthers`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/ethers.ts) del paquete [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data).
Para obtener datos usando Ethers puedes usar la clase [`SemaphoreEthers`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/ethers.ts) del paquete [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data).
```typescript
import { SemaphoreEthers } from "@semaphore-protocol/data"
@@ -170,4 +176,5 @@ const semaphoreEthers = new SemaphoreEthers("sepolia")
const members = await semaphoreEthers.getGroupMembers(groupId)
@@ -8,65 +8,70 @@ import TabItem from "@theme/TabItem"
# Gupos Semaphore
Un [grupo Semaphore](/glossary/#semaphore-group) contiene los [identity commitments](/glossary/#identity-commitment) (compromisos de identidad) de miembros del grupo.
Un [grupo Semaphore](/V3/glossary/#grupo-semaphore) contiene los [identity commitments](/V3/glossary/#compromiso-de-identidad-identity-commitment) (compromisos de identidad) de miembros del grupo.
Estos son algunos ejemplos de uso de los grupos:
- Encuesta con preguntas a la que se unen las personas que acudieron a un evento para calificarlo,
- votación a la que se unen los miembros para votar por una propuesta,
- Denunciantes que están verificados como empleados de una organización.
- Encuesta con preguntas a la que se unen las personas que acudieron a un evento para calificarlo,
- votación a la que se unen los miembros para votar por una propuesta,
- Denunciantes que están verificados como empleados de una organización.
Un grupo Semaphore es un [árbol de Merkle incremental](/glossary/#incremental-merkle-tree), y los miembros del grupo (por ejemplo, [identity commitments](/glossary/#identity-commitments)) son las hojas del árbol.
Un grupo Semaphore es un [árbol de Merkle incremental](/V3/glossary/#árbol-de-merkle-merkle-tree), y los miembros del grupo (por ejemplo, [identity commitments](/V3/glossary/#compromiso-de-identidad-identity-commitment)) son las hojas del árbol.
Los grupos Semaphore determinan los siguientes tres parámetro:
- **Group id**: un identificador único para el grupo;
- **Tree depth**: el número máximo de miembros que puede contener un grupo (`max size = 2 ^ tree depth`);
- **Members** la lista de miembros para inicializar el grupo.
- **Group id**: un identificador único para el grupo;
- **Tree depth**: el número máximo de miembros que puede contener un grupo (`max size = 2 ^ tree depth`);
- **Members** la lista de miembros para inicializar el grupo.
- [Remover o actualizar miembros](#remove-or-update-members)
- [Crear un grupo](#crear-un-grupo)
- [Añadir miembros](#añadir-miembros)
- [Remover o actualizar miembros](#remover-o-actualizar-miembros)
### Crear un grupo
Utilice la clase `Group` de la librería [`@semaphore-protocol/group`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/group) para crear un grupo off-chain con los siguientes parámetros:
- `Group id`: un identificar único para el grupo;
- `Tree depth`: (_default `20`_) el número máximo de usuarios que puede contener un grupo, el valor por defecto es 20 (`max size = 2 ^ tree depth`).
- `Members`: (_default `[]`_) la lista de miembros para inicializar el grupo.
- `Group id`: un identificar único para el grupo;
- `Tree depth`: (*default `20`*) el número máximo de usuarios que puede contener un grupo, el valor por defecto es 20 (`max size = 2 ^ tree depth`).
- `Members`: (*default `[]`*) la lista de miembros para inicializar el grupo.
#### Instalar librería:
<Tabs
defaultValue="npm"
groupId="package-managers"
values={[
defaultValue="npm"
groupId="package-managers"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
{label: 'pnpm', value: 'pnpm'}
]}
>
<TabItem value="npm">
```bash
npm install @semaphore-protocol/group@^3
```
</TabItem>
```bash
npm install @semaphore-protocol/group
```
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/group@^3
```
</TabItem>
</TabItem>
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/group
```
</TabItem>
<TabItem value="pnpm">
```bash
pnpm add @semaphore-protocol/group@^3
```
</TabItem>
</Tabs>
Para crear un grupo con el número de usuarios que aparece por defecto (20) _`treeDepth`_, llame la función para construir un `Group` sin el segundo parámetro. Por ejemplo:
Para crear un grupo con el número de usuarios que aparece por defecto (20) *`treeDepth`*, llame la función para construir un `Group` sin el segundo parámetro. Por ejemplo:
```ts
import { Group } from "@semaphore-protocol/group"
@@ -74,7 +79,7 @@ import { Group } from "@semaphore-protocol/group"
const group = new Group(1)
```
El siguiente código de ejemplo pasa por _`treeDepth`_ para crear un grupo para `2 ^ 30 = 1073741824` miembros:
El siguiente código de ejemplo pasa por *`treeDepth`* para crear un grupo para `2 ^ 30 = 1073741824` miembros:
@@ -8,45 +8,50 @@ import TabItem from "@theme/TabItem"
# Identidades Semaphore
Para unirse a un [grupo Semaphore](/glossary#semaphore-group), un usuario primero deberá crear una [identidad Semaphore](/glossary#semaphore-identity).
Para unirse a un [grupo Semaphore](/V3/glossary#grupo-semaphore), un usuario primero deberá crear una [identidad Semaphore](/V3/glossary#identidad-semaphore).
Una identidad Semaphore contiene dos valores generados junto con la identidad:
- Identity trapdoor (Identidad trampilla)
- Identity nullifier (Anulador de identidad)
- Identity trapdoor (Identidad trampilla)
- Identity nullifier (Anulador de identidad)
Para utilizar y verificar su identidad, la persona dueña de la identidad (usuario) debe conocer los valores trapdoor y nullifier.
Para prevenir fraudes, la persona dueña debe conservar de forma secreta ambos valores.
## Crear identidades
En su código, utilice la librería [`@semaphore-protocol/identity`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/identity) para crear una identidad Semaphore _de forma determinística_ (del hash de un mensaje) o _de forma aleatoria_.
En su código, utilice la librería [`@semaphore-protocol/identity`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/identity) para crear una identidad Semaphore *de forma determinística* (del hash de un mensaje) o *de forma aleatoria*.
La nueva identidad contiene dos valores aleatorios secretos: `trapdoor` y `nullifier`, y un valor público: `commitment`.
El hash Poseidon del identity nullifier y trapdoor se conoce como _identity secret_ (el secreto de identidad),
y su hash es el _identity commitment_ (compromiso de identidad).
El hash Poseidon del identity nullifier y trapdoor se conoce como *identity secret* (el secreto de identidad),
y su hash es el *identity commitment* (compromiso de identidad).
Un identity commitment (compromiso de identidad), de forma similar a las direcciones Ethereum, es un valor público que se utiliza en los grupos Semaphore para representar la
identidad de un miembro del grupo. Los valores secretos son similares a las llaves privadas
@@ -71,7 +76,7 @@ Ethereum y se utilizan para generar pruebas de conocimiento cero (ZKP) Semaphore
### Crear identidades determinísticas
Si transmite un mensaje como un parámetro, Semaphore genera `trapdoor` y `nullifier`
del hash _SHA256_ del mensaje.
del hash *SHA256* del mensaje.
El mensaje puede ser una contraseña o un mensaje que el usuario firma de forma criptográfica con una llave privada.
Al utilizar identidades determinísticas siempre deberá mantener secreto el mensaje.
@@ -8,56 +8,61 @@ import TabItem from "@theme/TabItem"
# Pruebas Semaphore
Una vez que un usuario liga su [identidad Semaphore](/glossary#semaphore-identity) a un [grupo Semaphore](/glossary#semaphore-group), el usuario puede emitir una señal anónima con una prueba de conocimiento cero (ZKP) que demuestre lo siguiente:
Una vez que un usuario liga su [identidad Semaphore](/V3/glossary#identidad-semaphore) a un [grupo Semaphore](/V3/glossary#grupo-semaphore), el usuario puede emitir una señal anónima con una prueba de conocimiento cero (ZKP) que demuestre lo siguiente:
- el usuario es un miembro del grupo,
- el mismo usuario creo tanto la señal como la prueba.
- el usuario es un miembro del grupo,
- el mismo usuario creo tanto la señal como la prueba.
Las y los desarrolladores pueden utilizar Semaphore para realizar las siguientes acciones:
- [**Generar una prueba externa a la cadena (off-chain)**](#generate-a-proof-off-chain)
- [**Verificar una prueba externa a la cadena (off-chain)**](#verify-a-proof-off-chain)
- [**Verificar una prueba interna a la cadena (on-chain)**](#verify-a-proof-on-chain)
- [**Generar una prueba externa a la cadena (off-chain)**](#generar-una-prueba-off-chain)
- [**Verificar una prueba externa a la cadena (off-chain)**](#verificar-una-prueba-off-chain)
- [**Verificar una prueba interna a la cadena (on-chain)**](#verificar-una-prueba-on-chain)
## Generar una prueba off-chain
Utilice la librería [`@semaphore-protocol/proof`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/proof) para generar una prueba off-chain.
Para generar una prueba, transforme los siguientes parámetros con la función `generateProof`:
- `identity`: la identidad Semaphore del usuario emitiendo la señal y generando la prueba;
- `group`: el grupo al cual pertenece el usuario;
- `externalNullifier`: el valor que impide la emisión de dos señales por el mismo usuario;
- `signal`: la señal que el usuario quiere enviar de forma anónima;
- `snarkArtifacts`: la `zkey` y `wasm` de los [archivos confiables de configuración](/glossary/#trusted-setup-files).
- `identity`: la identidad Semaphore del usuario emitiendo la señal y generando la prueba;
- `group`: el grupo al cual pertenece el usuario;
- `externalNullifier`: el valor que impide la emisión de dos señales por el mismo usuario;
- `signal`: la señal que el usuario quiere enviar de forma anónima;
- `snarkArtifacts`: la `zkey` y `wasm` de los [archivos confiables de configuración](/V3/glossary/#archivos-confiables-de-configuración-trusted-setup-files).
#### Instalar librería:
<Tabs
defaultValue="npm"
groupId="package-managers"
values={[
defaultValue="npm"
groupId="package-managers"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
{label: 'pnpm', value: 'pnpm'}
]}
>
<TabItem value="npm">
```bash
npm install @semaphore-protocol/proof@^3
```
</TabItem>
```bash
npm install @semaphore-protocol/proof
```
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/proof@^3
```
</TabItem>
</TabItem>
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/proof
```
</TabItem>
<TabItem value="pnpm">
```bash
pnpm add @semaphore-protocol/proof@^3
```
</TabItem>
</Tabs>
En el caso de uso de un sistema de votación, una vez que todos los votantes hayan ligado sus [identidades](/guides/identities#create-an-identity) al [grupo](/guides/groups) de la votación,
En el caso de uso de un sistema de votación, una vez que todos los votantes hayan ligado sus [identidades](/V3/guides/identities#crear-identidades) al [grupo](/V3/guides/groups) de la votación,
un votante puede generar una prueba para votar por una propuesta.
En el llamado para `generateProof`(generar la prueba), el sistema de votación envía el ID único de la votación (la raíz del [árbol de Merkle](/glossary/#merkle-tree/) del grupo) como el
En el llamado para `generateProof`(generar la prueba), el sistema de votación envía el ID único de la votación (la raíz del [árbol de Merkle](/V3/glossary/#árbol-de-merkle-merkle-tree) del grupo) como el
`externalNullifier` para impedir que el votante emita más de una señal para esta votación.
La siguiente muestra de código demuestra cómo utilizar `generateProof` para generar una prueba de votación:
@@ -79,6 +84,7 @@ Si estás generando la prueba en el lado del cliente, puedes evitar agregar los
Utilice la librería [`@semaphore-protocol/proof`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/proof) para verificar una prueba Semaphore off-chain.
Para verificar una prueba, transforme los siguientes parámetros con la función `verifyProof`:
- `fullProof`: la prueba Semaphore;
- `treeDepth`: la profundidad del árbol de Merkle.
- `fullProof`: la prueba Semaphore;
- `treeDepth`: la profundidad del árbol de Merkle.
La siguiente muestra de código demuestra cómo verificar la prueba generada previamente:
Utilice el contrato [`Semaphore.sol`](/technical-reference/contracts#semaphoresol) para verificar pruebas on-chain.
Utilice el contrato [`Semaphore.sol`](/V3/technical-reference/contracts#semaphoresol) para verificar pruebas on-chain.
:::info
Vea nuestros [contratos desplegados](/deployed-contracts) para encontrar las direcciones adecuadas para su red.
Vea nuestros [contratos desplegados](/V3/deployed-contracts) para encontrar las direcciones adecuadas para su red.
::::
Para verificar las pruebas Semaphore en su contrato, importe `ISemaphore.sol`, transfórmelo a la dirección `Semaphore.sol` y llame el método `verifyProof` con los siguientes parámetros:
- `groupId`: el identificador del grupo;
- `merkleTreeRoot`: la raíz del árbol de Merkle;
- `signal`: la señal que el usuario quiere enviar de forma anónima ;
- `nullifierHash`: un [nullifier hash](#retrieve-a-nullifier-hash) (hash anulador);
- `externalNullifier`: el valor que impide la emisión de dos señales por el mismo usuario;
- `proof`: una [prueba Semaphore que es compatible con Solidity](#generate-a-solidity-compatible-proof).
- `groupId`: el identificador del grupo;
- `merkleTreeRoot`: la raíz del árbol de Merkle;
- `signal`: la señal que el usuario quiere enviar de forma anónima ;
- `nullifierHash`: un nullifier hash (hash anulador);
- `externalNullifier`: el valor que impide la emisión de dos señales por el mismo usuario;
- `proof`: una prueba Semaphore que es compatible con Solidity.
:::info
Puede importar `ISemaphore.sol` y otros contratos Semaphore del módulo NPM [`@semaphore-protocol/contracts`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/contracts).
[Propuesta de la comunidad: Semaphore: Señalización de conocimiento cero (ZK) en Ethereum (v1 Whitepaper)](https://docs.semaphore.pse.dev/whitepaper-v1.pdf) - Kobi Gurkan, Koh Wei Jie y Barry WhiteHat
[Propuesta de la comunidad: Semaphore: Señalización de conocimiento cero (ZK) en Ethereum (v1 Whitepaper)](https://semaphore.pse.dev/whitepaper-v1.pdf) - Kobi Gurkan, Koh Wei Jie y Barry WhiteHat
[Para Mezcladores y más allá: presentando Semaphore, una herramienta de privacidad construida en Ethereum](https://medium.com/coinmonks/to-mixers-and-beyond-presenting-semaphore-a-privacy-gadget-built-on-ethereum-4c8b00857c9b) - Koh Wei Jie
El [circuito Semaphore](https://github.com/semaphore-protocol/semaphore/tree/main/packages/circuits) es el corazón del protocolo y está compuesto por tres partes:
- [**Prueba de membresía**](/technical-reference/circuits#proof-of-membership)
- [**Contratos para la extensión**](/technical-reference/contracts#extension-contracts)
- [**Contratos base**](#contratos-base)
- [**Contratos para la extensión**](#contratos-para-la-extensión)
así como [**Semaphore.sol**](/technical-reference/contracts#semaphoresol), el principal contrato desplegado en las redes soportadas por Semaphore.
así como [**Semaphore.sol**](#semaphoresol), el principal contrato desplegado en las redes soportadas por Semaphore.
:::info
Para utilizar los contratos e interfaces Semaphore en su proyecto, instale el paquete NPM [`@semaphore-protocol/contracts`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/contracts).
@@ -19,11 +19,11 @@ Para utilizar los contratos e interfaces Semaphore en su proyecto, instale el pa
Semaphore ofrece los siguientes contratos base:
- [`SemaphoreVerifier.sol`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/contracts/base/SemaphoreVerifier.sol): contiene una función para verificar pruebas Semaphore;
- [`SemaphoreVerifier.sol`](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/contracts/contracts/base/SemaphoreVerifier.sol): contiene una función para verificar pruebas Semaphore;
- [`SemaphoreGroups.sol`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/contracts/base/SemaphoreGroups.sol): contiene las funciones para crear grupos y añadir/remover/actualizar miembros.
Los contratos base están relacionados de forma muy cercana al protocolo.
Puede utilizarlos en su contrato o puede utilizar [**Semaphore.sol**](/technical-reference/contracts#semaphoresol) que ya los tiene integrados.
Puede utilizarlos en su contrato o puede utilizar [**Semaphore.sol**](/V3/technical-reference/contracts#semaphoresol) que ya los tiene integrados.
:::info
Si bien algunas dApps pueden utilizar grupos internos a la cadena, otros puede que prefieran utilizar grupos externos a la cadena, por lo que únicamente guardarán las raíces de sus árboles en el contrato.
@@ -42,9 +42,9 @@ En un futuro se incluirán más extensiones.
[`Semaphore.sol`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/contracts/contracts/Semaphore.sol) utiliza los contratos base como punto de partida, los integra y de forma adicional brinda:
- un sistema que solamente permite que administradores (ej. cuentas de Ethereum o contratos inteligentes) controlen grupos;
- un mecanismo que guarda los [hashes anuladores](/technical-reference/circuits#nullifier-hash) (nullifier hashes) de cada grupo y evita que el mismo miembro emita dos señales;
- un mecanismo que guarda los [hashes anuladores](/V3/technical-reference/circuits#hash-anulador-nullifier-hash) (nullifier hashes) de cada grupo y evita que el mismo miembro emita dos señales;
- un mecanismo que permite que pruebas Semaphore generadas con raíces de Merkle antiguas sean verificadas por un periodo de tiempo determinado por el administrador del grupo.
:::info
Visitando [contratos desplegados](/deployed-contracts) puede encontrar las direcciones correspondientes a su red.
Visitando [contratos desplegados](/V3/deployed-contracts) puede encontrar las direcciones correspondientes a su red.
@@ -7,7 +7,7 @@ import TabItem from "@theme/TabItem"
# Solución de problemas
Si estas sugerencias no funcionan, no dude en preguntar en las [Semaphore Discussions](https://github.com/semaphore-protocol/semaphore/discussions) o en el canal `dev-chat` en el [Semaphore Discord](https://semaphore.pse.dev/discord).
Si estas sugerencias no funcionan, no dude en preguntar en las [Semaphore Discussions](https://github.com/semaphore-protocol/semaphore/discussions) o en el canal [Semaphore Telegram](https://semaphore.pse.dev/telegram).
## Usando Semaphore en the frontend
@@ -70,49 +70,59 @@ Para resolver eso:
1- Instale `@esbuild-plugins/node-globals-polyfill` y `@esbuild-plugins/node-modules-polyfill`
@@ -15,9 +15,9 @@ Algunos de los potenciales casos de uso son: votaciones, denuncias, DAOs anónim
Con Semaphore puede permitir que sus usuarios realicen las siguientes acciones:
1. [Crear una identidad Semaphore](/guides/identities/).
2. [Agregar su identidad Semaphore a un grupo (es decir: _Árbol de Merkle_)](/guides/groups/).
3. [Enviar una señal anónima, verificable (ej. un voto o una aprobación)](/guides/proofs/).
1. [Crear una identidad Semaphore](/V3/guides/identities/).
2. [Agregar su identidad Semaphore a un grupo (es decir: _Árbol de Merkle_)](/V3/guides/groups/).
3. [Enviar una señal anónima, verificable (ej. un voto o una aprobación)](/V3/guides/proofs/).
Cuando un usuario emite una señal (por ejemplo: un voto), las pruebas de conocimiento cero (ZKP) pueden asegurar que el usuario se ha incorporado al grupo y aún no ha emitido una señal con su nullifier (anulador).
@@ -39,7 +39,7 @@ y [librerías en JavaScript](https://github.com/semaphore-protocol/semaphore#-pa
### Ceremonia de configuración de confianza (Trusted Setup Ceremony)
Los [parámetros seguros](/glossary#trusted-setup-files) para generar pruebas válidas con los circuitos Semaphore fueron generados en una [ceremonia de configuración de confianza](https://storage.googleapis.com/trustedsetup-a86f4.appspot.com/semaphore/semaphore_top_index.html) que se completó con más de 300 participantes el [29 de Marzo de 2022](https://etherscan.io/tx/0xec6dbe68883c7593c2bea82f55af18b3aeb5cc146e026d0083a9b3faa9aa0b65#eventlog).
Los [parámetros seguros](/V3/glossary#archivos-confiables-de-configuración-trusted-setup-files) para generar pruebas válidas con los circuitos Semaphore fueron generados en una [ceremonia de configuración de confianza](https://storage.googleapis.com/trustedsetup-a86f4.appspot.com/semaphore/semaphore_top_index.html) que se completó con más de 300 participantes el [29 de Marzo de 2022](https://etherscan.io/tx/0xec6dbe68883c7593c2bea82f55af18b3aeb5cc146e026d0083a9b3faa9aa0b65#eventlog).
@@ -40,7 +40,7 @@ For more information, see [Merkle tree in Wikipedia](https://en.wikipedia.org/wi
A value used to prevent double entry or double signalling.
See [Circuit nullifier hash](/technical-reference/circuits/#nullifier-hash).
See [Circuit nullifier hash](/V2/technical-reference/circuits/#nullifier-hash).
## Relay
@@ -48,7 +48,7 @@ A third-party who receives a fee for including relayed transactions in the block
To preserve the anonymity of the user broadcasting a signal with Semaphore, an application may use a relayer to post the signal transaction to Ethereum on behalf of the user.
Applications may provide rewards for relayers and implement front-running prevention mechanisms, such as requiring the signals to include the relayer’s address, binding the
signal to that specific address (https://docs.semaphore.pse.dev/whitepaper-v1.pdf, p.6).
signal to that specific address (https://semaphore.pse.dev/whitepaper-v1.pdf, p.6).
## Trusted setup files
@@ -60,5 +60,5 @@ To generate or verify valid zero-knowledge proofs with Semaphore, applications m
- semaphore.wasm
- semaphore.json
For a complete list of ready-to-use files, see <http://www.trusted-setup-pse.org>.
For a complete list of ready-to-use files, see [trusted-setup-pse.org](https://www.trusted-setup-pse.org).
To learn more, see the [trusted setup ceremony](https://storage.googleapis.com/trustedsetup-a86f4.appspot.com/semaphore/semaphore_top_index.html).
Use Semaphore in your application or smart contract to create off-chain and on-chain groups.
A [Semaphore group](/glossary/#semaphore-group) contains [identity commitments](/glossary/#identity-commitment) of group members.
A [Semaphore group](/V2/glossary/#semaphore-group) contains [identity commitments](/V2/glossary/#identity-commitment) of group members.
Example uses of groups include the following:
- Poll question that attendees join to rate an event.
- Ballot that members join to vote on a proposal.
- Whistleblowers who are verified employees of an organization.
A Semaphore group is an [incremental Merkle tree](/glossary/#incremental-merkle-tree), and group members (i.e., [identity commitments](/glossary/#identity-commitments)) are tree leaves.
A Semaphore group is an [incremental Merkle tree](/V2/glossary/#merkle-tree), and group members (i.e., [identity commitments](/V2/glossary/#identity-commitment)) are tree leaves.
Semaphore groups set the following two parameters:
-**Tree depth**: the maximum number of members a group can contain (`max size = 2 ^ tree depth`).
Learn how to use Semaphore to generate and verify zero-knowledge proofs.
Once a user joins their [Semaphore identity](/glossary#semaphore-identity) to a [Semaphore group](/glossary#semaphore-group), the user can signal anonymously with a zero-knowledge proof that proves the following:
Once a user joins their [Semaphore identity](/V2/glossary#semaphore-identity) to a [Semaphore group](/V2/glossary#semaphore-group), the user can signal anonymously with a zero-knowledge proof that proves the following:
- The user is a member of the group.
- The same user created the signal and the proof.
@@ -27,11 +27,11 @@ To generate a proof, pass the following properties to the `generateProof` functi
-`group`: The group to which the user belongs.
-`externalNullifier`: The value that prevents double-signaling.
-`signal`: The signal the user wants to send anonymously.
-`snarkArtifacts`: The `zkey` and `wasm` [trusted setup files](/glossary/#trusted-setup-files).
-`snarkArtifacts`: The `zkey` and `wasm` [trusted setup files](/V2/glossary/#trusted-setup-files).
In the voting system use case, once all the voters have joined their [identities](/guides/identities#create-an-identity) to the ballot [group](/guides/groups),
In the voting system use case, once all the voters have joined their [identities](/guides/identities#create-identities) to the ballot [group](/guides/groups),
a voter can generate a proof to vote for a proposal.
In the call to `generateProof`, the voting system passes the unique ballot ID (the [Merkle tree](/glossary/#merkle-tree/) root of the group) as the
In the call to `generateProof`, the voting system passes the unique ballot ID (the [Merkle tree](/V2/glossary/#merkle-tree) root of the group) as the
`externalNullifier` to prevent the voter signaling more than once for the ballot.
The following code sample shows how to use `generateProof` to generate the voting proof:
@@ -53,7 +53,7 @@ Use the [`@semaphore-protocol/proof`](https://github.com/semaphore-protocol/sema
To verify a proof, pass the following to the `verifyProof` function:
-_`proof`_: the Semaphore proof.
-_`verificationKey`_: the JavaScript object in the `semaphore.json` [trusted setup file](/glossary/#trusted-setup-files).
-_`verificationKey`_: the JavaScript object in the `semaphore.json` [trusted setup file](/V2/glossary/#trusted-setup-files).
The following code sample shows how to parse the verification key object from `semaphore.json`
@@ -9,7 +9,7 @@ Site owners publish _subgraphs_ that expose site data for anyone to query.
Semaphore's subgraph allows you to retrieve data from the [`Semaphore.sol`](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/Semaphore.sol) smart contract.
:::tip
The Graph protocol uses the [GraphQL](https://graphql.org/) query lanaguage. For examples, see the [GraphQL API documentation](https://thegraph.com/docs/developer/graphql-api). Visit the [subgraph repository](https://github.com/semaphore-protocol/subgraph) to see the list of Semaphore subgraphs.
The Graph protocol uses the [GraphQL](https://graphql.org/) query language. For examples, see the [GraphQL API documentation](https://thegraph.com/docs/developer/graphql-api). Visit the [subgraph repository](https://github.com/semaphore-protocol/subgraph) to see the list of Semaphore subgraphs.
The [Semaphore circuit](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/circuits) is the heart of the protocol and consists of three parts:
- [**Proof of membership**](/technical-reference/circuits#proof-of-membership)
To use Semaphore contracts and interfaces in your project,
@@ -24,7 +24,7 @@ Semaphore provides the following base contracts:
These contracts are closely related to the protocol.
You can inherit them in your contract or you can use [`Semaphore.sol`](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/contracts/Semaphore.sol), which inherits them for you.
See our [deployed contracts](/deployed-contracts#semaphore) to find the addresses for your network.
See our [deployed contracts](/V2/deployed-contracts#semaphore) to find the addresses for your network.
:::info
While some dApps may use on-chain groups, others may prefer to use off-chain groups, saving only their tree roots in the contract.
@@ -41,10 +41,10 @@ More extensions will be added in the future.
## Verifiers
To verify Semaphore proofs, the [`SemaphoreCore.sol`](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/contracts/base/SemaphoreCore.sol) contract requires the address of a deployed verifier contract.
You can choose to manually deploy the [verifier](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/contracts/verifiers) you prefer or you can use one of our [deployed verifiers](/deployed-contracts#verifiers).
You can choose to manually deploy the [verifier](https://github.com/semaphore-protocol/semaphore/tree/v2.6.1/packages/contracts/contracts/verifiers) you prefer or you can use one of our [deployed verifiers](/V2/deployed-contracts#verifiers).
Each verifier name indicates the tree depth that it can verify.
For example, given a Semaphore proof generated with a tree depth `20`:
- The `Verifier20.sol` contract can verify the proof.
- The [group](/guides/groups) used for the proof can have a maximum `2^20=1048576` members.
- The [group](/V2/guides/groups) used for the proof can have a maximum `2^20=1048576` members.
@@ -36,7 +36,7 @@ Community members connect their wallets to the dApp to take the following action
### Relay
To preserve anonymity and avoid disclosing the member's wallet address, the dApp may use a [relay](/glossary/#relay) to broadcast the vote.
To preserve anonymity and avoid disclosing the member's wallet address, the dApp may use a [relay](/V2/glossary/#relay) to broadcast the vote.
The relay calls the **contract** function that then posts the member's vote transaction to Ethereum.
## Private voting
@@ -52,7 +52,7 @@ The voting scenario has the following steps:
### Create a poll
A community coordinator or dApp administrator uses the deployed smart contract to create an on-chain (Ethereum) poll, a [Semaphore group](/guides/groups/) that members can join and cast votes to.
A community coordinator or dApp administrator uses the deployed smart contract to create an on-chain (Ethereum) poll, a [Semaphore group](/V2/guides/groups/) that members can join and cast votes to.
In the following sample code, the voting contract declares a `createPoll` function that uses the Semaphore base `_createGroup` function:
@@ -77,11 +77,11 @@ function createPoll(
}
```
A poll is a Semaphore [group](/guides/groups/) that stores the following:
A poll is a Semaphore [group](/V2/guides/groups/) that stores the following:
- A topic to vote on.
- The public ID of the poll creator.
- [Semaphore IDs](/guides/identities/) of members who joined the poll.
- [Semaphore IDs](/V2/guides/identities/) of members who joined the poll.
To create the poll, the administrator calls the smart contract function--for example:
@@ -127,10 +127,10 @@ With a member registered for a poll, learn how the dApp [records votes](#record-
Once members have joined a poll, the coordinator starts the poll to allow voting.
When a member votes (for example, by selecting a radio button), then the dApp takes the following actions:
1. Uses the `@semaphore-protocol/proof` library to create a proof of the vote, the poll identifier, the Semaphore ID, and a [nullifier](/glossary/#nullifier) that prevents double-voting.
1. Uses the `@semaphore-protocol/proof` library to create a proof of the vote, the poll identifier, the Semaphore ID, and a [nullifier](/V2/glossary/#nullifier) that prevents double-voting.
2. Sends the vote proof to the [relay](#relay).
### Related
- To get started developing with Semaphore, see the [Quick setup](/quick-setup/) guide.
- To get started developing with Semaphore, see the [Quick setup](/V2/quick-setup/) guide.
- For an example app that you can use to start your own project, see [Semaphore boilerplate](https://github.com/semaphore-protocol/boilerplate).
@@ -14,7 +14,7 @@ It also provides a simple mechanism to prevent double-signaling, which means you
## Where can I ask questions about Semaphore?
You can ask questions about Semaphore on [Discord](https://semaphore.pse.dev/discord) or by opening a [Semaphore Discussion](https://github.com/semaphore-protocol/semaphore/discussions).
You can ask questions about Semaphore on [Telegram](https://semaphore.pse.dev/telegram) or by opening a [Semaphore Discussion](https://github.com/semaphore-protocol/semaphore/discussions).
## Why do identities require both the `identity trapdoor` and the `identity nullifier`?
@@ -30,7 +30,7 @@ Finally, the nullifier hash is just the hash of the identity nullifier and the e
In the case of a voting application, if you have a group and you want all members of this group to vote only once, you can use the id of the group as an external nullifier. When a user votes the first time, you can save the hash of their identity nullifier and the group id (i.e. the nullifier hash) and prevent double-voting by checking if that hash already exists.
See the [Semaphore circuits](https://docs.semaphore.pse.dev/technical-reference/circuits) for more technical information, or the [Semaphore boilerplate](https://github.com/semaphore-protocol/boilerplate) for a real use-case.
See the [Semaphore circuits](https://docs.semaphore.pse.dev/technical-reference/circuits) for more technical information, or the [Semaphore boilerplate](https://github.com/semaphore-protocol/boilerplate/tree/version/3) for a real use-case.
## Why should I prevent proofs from being verified twice?
@@ -44,11 +44,11 @@ You can find some applications that are using Semaphore in [this blog post](http
## How can I start a project using Semaphore?
There are three ways you can start using Semaphore in your project: using the [Semaphore CLI](https://github.com/semaphore-protocol/semaphore/tree/main/packages/cli), using the [Semaphore boilerplate](https://github.com/semaphore-protocol/boilerplate) as a template or forking it, or installing the Semaphore packages manually.
There are three ways you can start using Semaphore in your project: using the [Semaphore CLI](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/cli), using the [Semaphore boilerplate](https://github.com/semaphore-protocol/boilerplate/tree/version/3) as a template or forking it, or installing the Semaphore packages manually.
### Semaphore CLI
To create a new project you could use `npx` or install the [Semaphore CLI](https://github.com/semaphore-protocol/semaphore/tree/main/packages/cli) globally using `npm` and then create the new project using the `semaphore create` command. See the [Quick Setup](https://docs.semaphore.pse.dev/quick-setup) for more information.
To create a new project you could use `npx` or install the [Semaphore CLI](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/cli) globally using `npm` and then create the new project using the `semaphore create` command. See the [Quick Setup](https://docs.semaphore.pse.dev/quick-setup) for more information.
There are three supported templates right now: `contracts-hardhat`, `monorepo-ethers` and `monorepo-subgraph`.
@@ -65,7 +65,7 @@ The Semaphore CLI can also be used to get group data from a supported network. T
### Semaphore boilerplate
To create a project, you could also use the [Semaphore boilerplate](https://github.com/semaphore-protocol/boilerplate). You could fork it or use it as a template.
To create a project, you could also use the [Semaphore boilerplate](https://github.com/semaphore-protocol/boilerplate/tree/version/3). You could fork it or use it as a template.
The Semaphore CLI templates and the Semaphore boilerplate contain the same code, which is a feedback application where you can create an identity, join a group, and send your feedback anonymously. They are almost the same, the only difference is that the templates use plain CSS so you can decide the CSS framework or library you want to use and the boilerplate uses [ChakraUI](https://chakra-ui.com/) by default.
@@ -37,9 +37,9 @@ For more information, see [Merkle tree in Wikipedia](https://en.wikipedia.org/wi
## Nullifier
A value used to prevent double entry or double signalling.
A value used to prevent double entry or double signaling.
See [Circuit nullifier hash](/technical-reference/circuits/#nullifier-hash).
See [Circuit nullifier hash](/V3/technical-reference/circuits/#nullifier-hash).
## Relay
@@ -47,7 +47,7 @@ A third-party who receives a fee for including relayed transactions in the block
To preserve the anonymity of the user broadcasting a signal with Semaphore, an application may use a relayer to post the signal transaction to Ethereum on behalf of the user.
Applications may provide rewards for relayers and implement front-running prevention mechanisms, such as requiring the signals to include the relayer’s address, binding the
signal to that specific address (https://docs.semaphore.pse.dev/whitepaper-v1.pdf, p.6).
signal to that specific address (https://semaphore.pse.dev/whitepaper-v1.pdf, p.6).
## Trusted setup files
@@ -59,7 +59,7 @@ To generate or verify valid zero-knowledge proofs with Semaphore, applications m
- semaphore.wasm
- semaphore.json
For a complete list of ready-to-use files, see <http://www.trusted-setup-pse.org>.
For a complete list of ready-to-use files, see [trusted-setup-pse.org](https://www.trusted-setup-pse.org).
To learn more, see the [trusted setup ceremony](https://storage.googleapis.com/trustedsetup-a86f4.appspot.com/semaphore/semaphore_top_index.html).
@@ -8,9 +8,9 @@ import TabItem from "@theme/TabItem"
# Semaphore data
To fetch on-chain data from the [Semaphore.sol](https://github.com/semaphore-protocol/semaphore/blob/main/packages/contracts/contracts/Semaphore.sol) contract, you can use the [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data) library.
To fetch on-chain data from the [Semaphore.sol](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/contracts/contracts/Semaphore.sol) contract, you can use the [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/data) library.
There are two ways to do this, using [`SemaphoreSubgraph`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/subgraph.ts) or [`SemaphoreEthers`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/ethers.ts). The `SemaphoreSubgraph` class uses the [Semaphore subgraph](https://github.com/semaphore-protocol/subgraph), which uses [The Graph Protocol](https://thegraph.com/) under the hood, and the `SemaphoreEthers` class uses [Ethers](https://github.com/ethers-io/ethers.js/).
There are two ways to do this, using [`SemaphoreSubgraph`](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/data/src/subgraph.ts) or [`SemaphoreEthers`](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/data/src/ethers.ts). The `SemaphoreSubgraph` class uses the [Semaphore subgraph](https://github.com/semaphore-protocol/subgraph), which uses [The Graph Protocol](https://thegraph.com/) under the hood, and the `SemaphoreEthers` class uses [Ethers](https://github.com/ethers-io/ethers.js/).
- [**Fetch data using SemaphoreSubgraph**](#fetch-data-using-semaphoresubgraph)
- [**Fetch data using SemaphoreEthers**](#fetch-data-using-semaphoreethers)
@@ -18,31 +18,36 @@ There are two ways to do this, using [`SemaphoreSubgraph`](https://github.com/se
## Install library
<Tabs
defaultValue="npm"
groupId="package-managers"
values={[
defaultValue="npm"
groupId="package-managers"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
{label: 'pnpm', value: 'pnpm'}
]}
>
<TabItem value="npm">
```bash
npm install @semaphore-protocol/data@^3
```
</TabItem>
```bash
npm install @semaphore-protocol/data
```
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/data@^3
```
</TabItem>
</TabItem>
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/data
```
</TabItem>
<TabItem value="pnpm">
```bash
pnpm add @semaphore-protocol/data@^3
```
</TabItem>
</Tabs>
## Fetch data using SemaphoreSubgraph
To fetch data using the Semaphore subgraph you can use the [`SemaphoreSubgraph`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/subgraph.ts) class from the [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data) package.
To fetch data using the Semaphore subgraph you can use the [`SemaphoreSubgraph`](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/data/src/subgraph.ts) class from the [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/data) package.
```typescript
import { SemaphoreSubgraph } from "@semaphore-protocol/data"
@@ -105,11 +110,12 @@ const semaphoreSubgraph = new SemaphoreSubgraph("sepolia")
To fetch data using Ethers you can use the [`SemaphoreEthers`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/data/src/ethers.ts) class from the [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/main/packages/data) package.
To fetch data using Ethers you can use the [`SemaphoreEthers`](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/data/src/ethers.ts) class from the [@semaphore-protocol/data](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/data) package.
```typescript
import { SemaphoreEthers } from "@semaphore-protocol/data"
@@ -123,7 +129,7 @@ const semaphoreEthers = new SemaphoreEthers("homestead", {
})
// or:
const semaphoreEthers = new SemaphoreEthers("http://localhost:8545", {
const semaphoreEthers = new SemaphoreEthers("http://127.0.0.1:8545", {
address: "semaphore-address"
})
```
@@ -170,4 +176,5 @@ const semaphoreEthers = new SemaphoreEthers("sepolia")
const members = await semaphoreEthers.getGroupMembers(groupId)
@@ -8,65 +8,70 @@ import TabItem from "@theme/TabItem"
# Semaphore groups
A [Semaphore group](/glossary/#semaphore-group) contains [identity commitments](/glossary/#identity-commitment) of group members.
A [Semaphore group](/V3/glossary/#semaphore-group) contains [identity commitments](/V3/glossary/#identity-commitment) of group members.
Example uses of groups include the following:
- poll question that attendees join to rate an event,
- ballot that members join to vote on a proposal,
- whistleblowers who are verified employees of an organization.
- poll question that attendees join to rate an event,
- ballot that members join to vote on a proposal,
- whistleblowers who are verified employees of an organization.
A Semaphore group is an [incremental Merkle tree](/glossary/#incremental-merkle-tree), and group members (i.e., [identity commitments](/glossary/#identity-commitments)) are tree leaves.
A Semaphore group is an [incremental Merkle tree](/V3/glossary/#merkle-tree), and group members (i.e., [identity commitments](/V3/glossary/#identity-commitment)) are tree leaves.
Semaphore groups set the following three parameters:
- **Group id**: a unique identifier for the group;
- **Tree depth**: the maximum number of members a group can contain (`max size = 2 ^ tree depth`);
- **Members**: the list of members to initialize the group.
- **Group id**: a unique identifier for the group;
- **Tree depth**: the maximum number of members a group can contain (`max size = 2 ^ tree depth`);
- **Members**: the list of members to initialize the group.
Learn how to work with groups.
- [**Off-chain groups**](#off-chain-groups)
- [**On-chain groups**](#on-chain-groups)
- [**Off-chain groups**](#off-chain-groups)
- [**On-chain groups**](#on-chain-groups)
## Off-chain groups
- [Create a group](#create-a-group)
- [Add members](#add-members)
- [Remove or update members](#remove-or-update-members)
- [Create a group](#create-a-group)
- [Add members](#add-members)
- [Remove or update members](#remove-or-update-members)
### Create a group
Use the [`@semaphore-protocol/group`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/group) library `Group` class to create an off-chain group with the following parameters:
Use the [`@semaphore-protocol/group`](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/group) library `Group` class to create an off-chain group with the following parameters:
- `Group id`: a unique identifier for the group;
- `Tree depth`: (_default `20`_) the maximum number of members a group can contain (`max size = 2 ^ tree depth`).
- `Members`: (_default `[]`_) the list of members to initialize the group.
- `Group id`: a unique identifier for the group;
- `Tree depth`: (*default `20`*) the maximum number of members a group can contain (`max size = 2 ^ tree depth`).
- `Members`: (*default `[]`*) the list of members to initialize the group.
#### Install library:
<Tabs
defaultValue="npm"
groupId="package-managers"
values={[
defaultValue="npm"
groupId="package-managers"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
{label: 'pnpm', value: 'pnpm'}
]}
>
<TabItem value="npm">
```bash
npm install @semaphore-protocol/group@^3
```
</TabItem>
```bash
npm install @semaphore-protocol/group
```
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/group@^3
```
</TabItem>
</TabItem>
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/group
```
</TabItem>
<TabItem value="pnpm">
```bash
pnpm add @semaphore-protocol/group@^3
```
</TabItem>
</Tabs>
To create a group with default _`treeDepth`_, call the `Group` constructor without the second parameter. For example:
To create a group with default *`treeDepth`*, call the `Group` constructor without the second parameter. For example:
```ts
import { Group } from "@semaphore-protocol/group"
@@ -74,7 +79,7 @@ import { Group } from "@semaphore-protocol/group"
const group = new Group(1)
```
The following example code passes _`treeDepth`_ to create a group for `2 ^ 30 = 1073741824` members:
The following example code passes *`treeDepth`* to create a group for `2 ^ 30 = 1073741824` members:
```ts
import { Group } from "@semaphore-protocol/group"
@@ -134,13 +139,13 @@ Given that the node isn't removed, and the length of the `group.members` array d
## On-chain groups
The [`SemaphoreGroups`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/contracts/contracts/base/SemaphoreGroups.sol) contract uses the [`IncrementalBinaryTree`](https://github.com/privacy-scaling-explorations/zk-kit/blob/main/packages/incremental-merkle-tree.sol/contracts/IncrementalBinaryTree.sol) library and provides methods to create and manage groups.
The [`SemaphoreGroups`](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/contracts/contracts/base/SemaphoreGroups.sol) contract uses the [`IncrementalBinaryTree`](https://github.com/privacy-scaling-explorations/zk-kit/blob/main/packages/incremental-merkle-tree.sol/contracts/IncrementalBinaryTree.sol) library and provides methods to create and manage groups.
:::info
You can import `SemaphoreGroups.sol` and other Semaphore contracts from the [`@semaphore-protocol/contracts`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/contracts) NPM module.
You can import `SemaphoreGroups.sol` and other Semaphore contracts from the [`@semaphore-protocol/contracts`](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/contracts) NPM module.
:::
Alternatively, you can use an already deployed [`Semaphore.sol`](https://github.com/semaphore-protocol/semaphore/blob/main/packages/contracts/contracts/Semaphore.sol) contract and use its group external functions.
Alternatively, you can use an already deployed [`Semaphore.sol`](https://github.com/semaphore-protocol/semaphore/blob/v3.15.2/packages/contracts/contracts/Semaphore.sol) contract and use its group external functions.
:::caution
`Semaphore.sol` does not check if a member with a specific identity commitment already exists in a group. This check must be done off-chain.
@@ -8,45 +8,50 @@ import TabItem from "@theme/TabItem"
# Semaphore identities
In order to join a [Semaphore group](/glossary#semaphore-group), a user must first create a [Semaphore identity](/glossary#semaphore-identity).
In order to join a [Semaphore group](/V3/glossary#semaphore-group), a user must first create a [Semaphore identity](/V3/glossary#semaphore-identity).
A Semaphore identity contains two values generated with the identity:
- Identity trapdoor
- identity nullifier
- Identity trapdoor
- identity nullifier
To use and verify the identity, the identity owner (user) must know the trapdoor and nullifier values.
To prevent fraud, the owner should keep both values secret.
## Create identities
In your code, use the [`@semaphore-protocol/identity`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/identity) library to create a Semaphore identity _deterministically_ (from the hash of a message) or _randomly_.
In your code, use the [`@semaphore-protocol/identity`](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/identity) library to create a Semaphore identity *deterministically* (from the hash of a message) or *randomly*.
- [**Create random identities**](#create-random-identities)
@@ -8,56 +8,61 @@ import TabItem from "@theme/TabItem"
# Semaphore proofs
Once a user joins their [Semaphore identity](/glossary#semaphore-identity) to a [Semaphore group](/glossary#semaphore-group), the user can signal anonymously with a zero-knowledge proof that proves the following:
Once a user joins their [Semaphore identity](/V3/glossary#semaphore-identity) to a [Semaphore group](/V3/glossary#semaphore-group), the user can signal anonymously with a zero-knowledge proof that proves the following:
- the user is a member of the group,
- the same user created the signal and the proof.
- the user is a member of the group,
- the same user created the signal and the proof.
Developers can use Semaphore for the following:
- [**Generate a proof off-chain**](#generate-a-proof-off-chain)
- [**Verify a proof off-chain**](#verify-a-proof-off-chain)
- [**Verify a proof on-chain**](#verify-a-proof-on-chain)
- [**Generate a proof off-chain**](#generate-a-proof-off-chain)
- [**Verify a proof off-chain**](#verify-a-proof-off-chain)
- [**Verify a proof on-chain**](#verify-a-proof-on-chain)
## Generate a proof off-chain
Use the [`@semaphore-protocol/proof`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/proof) library to generate an off-chain proof.
Use the [`@semaphore-protocol/proof`](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/proof) library to generate an off-chain proof.
To generate a proof, pass the following parameters to the `generateProof` function:
- `identity`: the Semaphore identity of the user broadcasting the signal and generating the proof;
- `group`: the group to which the user belongs;
- `externalNullifier`: the value that prevents double-signaling;
- `signal`: the signal the user wants to send anonymously;
- `snarkArtifacts`: the `zkey` and `wasm` [trusted setup files](/glossary/#trusted-setup-files).
- `identity`: the Semaphore identity of the user broadcasting the signal and generating the proof;
- `group`: the group to which the user belongs;
- `externalNullifier`: the value that prevents double-signaling;
- `signal`: the signal the user wants to send anonymously;
- `snarkArtifacts`: the `zkey` and `wasm` [trusted setup files](/V3/glossary/#trusted-setup-files).
#### Install library:
<Tabs
defaultValue="npm"
groupId="package-managers"
values={[
defaultValue="npm"
groupId="package-managers"
values={[
{label: 'npm', value: 'npm'},
{label: 'Yarn', value: 'yarn'},
]}>
<TabItem value="npm">
{label: 'pnpm', value: 'pnpm'}
]}
>
<TabItem value="npm">
```bash
npm install @semaphore-protocol/proof@^3
```
</TabItem>
```bash
npm install @semaphore-protocol/proof
```
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/proof@^3
```
</TabItem>
</TabItem>
<TabItem value="yarn">
```bash
yarn add @semaphore-protocol/proof
```
</TabItem>
<TabItem value="pnpm">
```bash
pnpm add @semaphore-protocol/proof@^3
```
</TabItem>
</Tabs>
In the voting system use case, once all the voters have joined their [identities](/guides/identities#create-an-identity) to the ballot [group](/guides/groups),
In the voting system use case, once all the voters have joined their [identities](/V3/guides/identities#create-identities) to the ballot [group](/V3/guides/groups),
a voter can generate a proof to vote for a proposal.
In the call to `generateProof`, the voting system passes the unique ballot ID (the [Merkle tree](/glossary/#merkle-tree/) root of the group) as the
In the call to `generateProof`, the voting system passes the unique ballot ID (the [Merkle tree](/V3/glossary#merkle-tree) root of the group) as the
`externalNullifier` to prevent the voter signaling more than once for the ballot.
The following code sample shows how to use `generateProof` to generate the voting proof:
@@ -79,15 +84,16 @@ If you are generating the proof on the client side, you can avoid adding the sna
Use the [`@semaphore-protocol/proof`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/proof) library to verify a Semaphore proof off-chain.
Use the [`@semaphore-protocol/proof`](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/proof) library to verify a Semaphore proof off-chain.
To verify a proof, pass the following to the `verifyProof` function:
- `fullProof`: the Semaphore proof;
- `treeDepth`: the Merkle tree depth.
- `fullProof`: the Semaphore proof;
- `treeDepth`: the Merkle tree depth.
The following code sample shows how to verify the previously generated proof:
Use the [`Semaphore.sol`](/technical-reference/contracts#semaphoresol) contract to verify proofs on-chain.
Use the [`Semaphore.sol`](/V3/technical-reference/contracts#semaphoresol) contract to verify proofs on-chain.
:::info
See our [deployed contracts](/deployed-contracts) to find the addresses for your network.
See our [deployed contracts](/V3/deployed-contracts) to find the addresses for your network.
::::
To verify Semaphore proofs in your contract, import `ISemaphore.sol`, pass it the `Semaphore.sol` address and call the `verifyProof` method with following parameters:
- `groupId`: the identifier of the group;
- `merkleTreeRoot`: the root of the Merkle tree;
- `signal`: the signal the user wants to send anonymously;
- `nullifierHash`: a [nullifier hash](#retrieve-a-nullifier-hash);
- `externalNullifier`: the value that prevents double-signaling;
- `proof`: a [Solidity-compatible Semaphore proof](#generate-a-solidity-compatible-proof).
- `groupId`: the identifier of the group;
- `merkleTreeRoot`: the root of the Merkle tree;
- `signal`: the signal the user wants to send anonymously;
- `nullifierHash`: a nullifier hash;
- `externalNullifier`: the value that prevents double-signaling;
- `proof`: a Solidity-compatible Semaphore proof.
:::info
You can import `ISemaphore.sol` and other Semaphore contracts from the [`@semaphore-protocol/contracts`](https://github.com/semaphore-protocol/semaphore/tree/main/packages/contracts) NPM module.
You can import `ISemaphore.sol` and other Semaphore contracts from the [`@semaphore-protocol/contracts`](https://github.com/semaphore-protocol/semaphore/tree/v3.15.2/packages/contracts) NPM module.
:::
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.