bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 14쪽 중 9쪽
ttestation } from "@ethsign/sign-protocol-evm/src/models/Attestation.sol";
// @dev This contract manages attestation data validation logic.
contract DataValidator is Ownable {
uint256 public threshold;
error NumberBelowThreshold();
constructor() Ownable(_msgSender()) { }
function setThreshold(uint256 threshold_) external onlyOwner {
threshold = threshold_;
}
function _checkThreshold(uint256 number) internal view {
// solhint-disable-next-line custom-errors
require(number >= threshold, NumberBelowThreshold());
}
}
// @dev This contract implements the actual schema hook.
contract DataValidatorHook is ISPHook, DataValidator {
error UnsupportedOperation();
function didReceiveAttestation(
address, // attester
uint64, // schemaId
uint64 attestationId,
bytes calldata // extraData
)
external
payable
{
Attestation memory attestation = ISP(_msgSender()).getAttestation(attestationId);
_checkThreshold(abi.decode(attestation.data, (uint256)));
}
function didReceiveAttestation(
address, // attester
uint64, // schemaId
uint64, // attestationId
IERC20, // resolverFeeERC20Token
uint256, // resolverFeeERC20Amount
bytes calldata // extraData
)
external
pure
{
revert UnsupportedOperation();
}
function didReceiveRevocation(
address, // attester
uint64, // schemaId
uint64, // attestationId
bytes calldata // extraData
)
external
payable
{
revert UnsupportedOperation();
}
function didReceiveRevocation(
address, // attester
uint64, // schemaId
uint64, // attestationId
IERC20, // resolverFeeERC20Token
uint256, // resolverFeeERC20Amount
bytes calldata // extraData
)
external
pure
{
revert UnsupportedOperation();
}
}
```
Once this contract has been deployed, you can create your schema and set the appropriate contract address as your schema hook. Once you have created your schema with a schema hook, move to the next page where we will go over how to create an attestation in solidity.
# Creating an Attestation (Solidity)
Now that you have created your schema with a schema hook address set, you must provide attestation data in the correct format that you set in your schema, or else verification will fail. If you are using the NPM SDK, we perform validation for you before the transaction call is sent. However, none of these safeguards exist when interacting with Sign Protocol directly from solidity.
Our simple schema only needs a `uint256`. We will use `abi.encode` to encode this number. Make sure that variables are provided in the same order they are set in the schema, which is the same order they will be decoded in your schema hook and on the SignScan attestation explorer.
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ISP } from "@ethsign/sign-protocol-evm/src/interfaces/ISP.sol";
import { Attestation } from "@ethsign/sign-protocol-evm/src/models/Attestation.sol";
import { DataLocation } from "@ethsign/sign-protocol-evm/src/models/DataLocation.sol";
contract DataAttester is Ownable {
ISP public spInstance;
uint64 public schemaId;
constructor() Ownable(_msgSender()) { }
function setSPInstance(address instance) external onlyOwner {
spInstance = ISP(instance);
}
function setSchemaID(uint64 schemaId_) external onlyOwner {
schemaId = schemaId_;
}
function attest(address recipient, uint256 someNumber) external onlyOwner returns (uint64) {
bytes[] memory recipients = new bytes[](1);
recipients[0] = abi.encode(recipient);
Attestation memory a = Attestation({
schemaId: schemaId,
linkedAttestationId: 0,
attestTimestamp: 0,
revokeTimestamp: 0,
attester: address(this),
validUntil: 0,
dataLocation: DataLocation.ONCHAIN,
revoked: false,
recipients: recipients,
data: abi.encode(someNumber)
});
return spInstance.attest(a, "", "", "");
}
}
```
# ZK Attestations
Steps to integrate ZK verifiers into Sign Protocol's Schema Hooks.
This tutorial will guide you in integrating a ZK Solidity verifier into a Sign Protocol [Schema Hook](/for-builders/advanced-topics/schema-hooks). This tutorial assumes you already know ZK basics and terminology, such as circuit, proof, and verifier. When you are ready to begin, continue to the next page.
# Compile a Circuit
There are many ZK libraries and languages that can be used with Sign Protocol, each with its pros and cons. We do not aim to cover these similarities and differences and it is up to you to decide which to use. However, we recommend using a library that can generate a Solidity verifier using your compiled circuit. We will use [Circom](https://iden3.io/circom).
First, follow Circom's docs for [installation](https://docs.circom.io/getting-started/installation/). If you have never used Circom before, we recommend reading through their [sample circuit](https://docs.circom.io/getting-started/writing-circuits/). For this tutorial, we will use a non-trivial example circuit, which you can find [here](https://github.com/boyuanx/circom-sha256-preimage-example). The circom file should contain the following:
```clike
pragma circom 2.0.0;
include "circomlib/circuits/sha256/sha256.circom";
include "circomlib/circuits/bitify.circom";
/**
* Wrapper around SHA256 to support bytes as input instead of bits
* @param N The number of input bytes
* @input in The input bytes
* @output out The SHA256 output of the n input bytes, in bytes
*
* SOURCE: https://github.com/celer-network/zk-benchmark/blob/main/circom/circuits/sha256/sha256_bytes.circom
*/
template Sha256Bytes(N) {
signal input in[N];
signal output out[32];
// convert input bytes to bits
component byte_to_bits[N];
for (var i = 0; i < N; i++) {
byte_to_bits[i] = Num2Bits(8);
byte_to_bits[i].in <== in[i];
}
// sha256 over bits
component sha256 = Sha256(N*8);
for (var i = 0; i < N; i++) {
for (var j = 0; j < 8; j++) {
sha256.in[i*8+j] <== byte_to_bits[i].out[7-j];
}
}
// convert output bytes to bits
component bits_to_bytes[32];
for (var i = 0; i < 32; i++) {
bits_to_bytes[i] = Bits2Num(8);
for (var j = 0; j < 8; j++) {
bits_to_bytes[i].in[7-j] <== sha256.out[i*8+j];
}
out[i] <== bits_to_bytes[i].out;
}
}
template Main(N) {
signal input in[N];
signal input hash[32];
signal output out[32];
component sha256 = Sha256Bytes(N);
sha256.in <== in;
out <== sha256.out;
for (var i = 0; i < 32; i++) {
out[i] === hash[i];
}
log("start ================");
for (var i = 0; i < 32; i++) {
log(out[i]);
}
log("finish ================");
}
// render this file before compilation
component main = Main(64);
```
This sha256 circuit will take in two signals as input: the first is an array of size 64 and the second is an array of size 32. The first array will be hashed using the sha256 algorithm, requiring that the output (hash) signal equals the provided hash. Next, we will compile our circuit.
### Compile Your Circuit
Your local Circom installation comes with the `circom` command. To compile your circuit, run:
```bash
> circom sha256.circom --r1cs --wasm --sym
```
This command will compile your source code into the required files, including the r1cs constraint system file, and wasm files for generating a witness. You can read more about the command flags [here](https://docs.circom.io/getting-started/compiling-circuits/). From here, you will generate your witness. Note that you do not need a witness to generate a smart contract verifier. Witnesses are used for creating proofs, which will be verified using your schema hook.
### Generate a Witness
In your output directory (likely named `sha256_js`), create a file named `input.json`. Paste the following in this file:
```json
{
"in": [
20, 207, 123, 94, 84, 118, 123, 180, 191, 195, 21, 180, 82, 88, 185, 223,
207, 101, 103, 247, 201, 113, 113, 87, 111, 84, 191, 243, 87, 47, 134, 143,
20, 207, 123, 94, 84, 118, 123, 180, 191, 195, 21, 180, 82, 88, 185, 223,
207, 101, 103, 247, 201, 113, 113, 87, 111, 84, 191, 243, 87, 47, 134, 143
],
"hash": [
29, 131, 153, 39, 255, 114, 11, 253, 116, 101, 97, 195, 155, 112, 35, 76,
226, 32, 120, 129, 165, 186, 145, 10, 192, 28, 49, 244, 143, 179, 101, 236
]
}
```
Next, navigate to your build directory and run the following command to generate a witness:
```bash
> node generate_witness.js sha256.wasm input.json witness.wtns
```
### Generating a Verifier Contract
This section follows the documentation located [here](https://docs.circom.io/getting-started/proving-circuits/). For more information about each step, please refer to Circom's documentation. Run the following commands to complete the Powers of Tau and Phase 2 requirements:
```bash
> snarkjs powersoftau new bn128 17 pot12_0000.ptau -v
> snarkjs powersoftau contribute pot12_0000.ptau pot12_0001.ptau --name="First contribution" -v
> snarkjs powersoftau prepare phase2 pot12_0001.ptau pot12_final.ptau -v
> snarkjs groth16 setup sha256.r1cs pot12_final.ptau sha256_0000.zkey
> snarkjs zkey contribute sha256_0000.zkey sha256_0001.zkey --name="1st Contributor Name" -v
> snarkjs zkey export verificationkey sha256_0001.zkey verification_key.json
```
Now that you have generated all required files, you can generate a smart contract verifier using the following command:
```bash
> snarkjs zkey export solidityverifier sha256_0001.zkey verifier.sol
```
This will generate a file named `verifier.sol` in your root project directory. To facilitate a function call for `verifyProof()`, you can run the following command:
```bash
> snarkjs generatecall
```
When you are ready, proceed to the next page to integrate `verifier.sol` with a schema hook.
# Create a Schema Hook
In this step, we will extend the verifier contract generated by the ZK library and implement the [ISPHook ](/for-builders/index-1/index/index/index/isphook)interface. From the previous step, our generated contract looks something like this:
```solidity
pragma solidity >=0.7.0 <0.9.0;
contract Groth16Verifier {
...
function verifyProof(uint[2] calldata _pA, uint[2][2] calldata _pB, uint[2] calldata _pC, uint[32] calldata _pubSignals) public view returns (bool) {
...
}
}
```
{% hint style="info" %}
In the generated verifier, change all instances of `calldata` to `memory`.
{% endhint %}
The generated verifier should now look like this:
```solidity
pragma solidity >=0.7.0 <0.9.0;
contract Groth16Verifier {
...
function verifyProof(uint[2] memory _pA, uint[2][2] memory _pB, uint[2] memory _pC, uint[32] memory _pubSignals) public view returns (bool) {
...
}
}
```
To set up your schema hook, create another file that contains the following contents:
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { Groth16Verifier } from "./Verifier.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { ISPHook } from "@ethsign/sign-protocol-evm/src/interfaces/ISPHook.sol";
contract SHA256PreimageVerifier is Groth16Verifier, Ownable {
address public spInstance;
constructor() Ownable(_msgSender()) { }
function setSPInstance(address instance) external onlyOwner {
spInstance = instance;
}
}
// @dev This contract implements the actual schema hook.
contract ZKHook is ISPHook, SHA256PreimageVerifier {
error Unsupported();
error ZKVerificationFailed();
function didReceiveAttestation(
address, // attester
uint64, // schemaId
uint64, // attestationId
bytes calldata extraData
)
external
payable
{
if (_msgSender() != spInstance) revert Unsupported();
(uint256[2] memory _pA, uint256[2][2] memory _pB, uint256[2] memory _pC, uint256[32] memory _pubSignals) =
abi.decode(extraData, (uint256[2], uint256[2][2], uint256[2], uint256[32]));
// If the SHA256 preimage proof verification fails, revert.
if (!verifyProof(_pA, _pB, _pC, _pubSignals)) revert ZKVerificationFailed();
}
function didReceiveAttestation(
address, // attester
uint64, // schemaId
uint64, // attestationId
IERC20, // resolverFeeERC20Token
uint256, // resolverFeeERC20Amount
bytes calldata // extraData
)
external
pure
{
revert Unsupported();
}
function didReceiveRevocation(
address, // attester
uint64, // schemaId
uint64, // attestationId
bytes calldata // extraData
)
external
payable
{
revert Unsupported();
}
function didReceiveRevocation(
address, // attester
uint64, // schemaId
uint64, // attestationId
IERC20, // resolverFeeERC20Token
uint256, // resolverFeeERC20Amount
bytes calldata // extraData
)
external
pure
{
revert Unsupported();
}
}
```
We begin by importing our generated `Groth16Verifier` contract, OpenZepplin packages, and the [ISPHook](/for-builders/index-1/index/index/index/isphook) contract.
Next, we create the `SHA256PreimageVerifier` contract which is responsible for setting the contract address for the Sign Protocol instance and adding ownable functionality.
Last, we create `ZKHook` to add all of our schema hook logic. Because ZK proofs can be large, we recommend making use of the `extraData` field - this data gets passed to Sign Protocol's contract when attestations are created or revoked but does not get stored onchain. `extraData` is only forwarded to schema hooks for data processing and verification, so this is a perfect scenario for providing required ZK-proof-related data. This hook decodes the inputted data and passes it to the verifier's `verifyProof()` function. The call reverts if verification fails. If verification succeeds, the attestation will be successfully created.
### Finishing Up
Once you have completed your ZK schema hook, it is time to deploy the contract to your desired network. After the contract gets deployed, [create a new schema](https://app.sign.global/create-schema) on the same network and set the hook smart contract address to the address of your deployed schema hook contract. Your ZK schema hook is ready to go!
# Private Attestations
Private, encrypted attestations using Lit Protocol.
# Querying Data
[SignScan](https://scan.sign.global) is the explorer for the Sign Protocol. Using SignScan, you can explore, create, validate, and search for schemas and attestations. Through tools that allow for no-code schema and attestation creation, we are aiming to make attestations accessible to everyone - coders and non-coders alike.
<figure><img src="https://github.com/EthSign/sign-protocol-docs/blob/main/for-builders/.gitbook/assets/sign_scan_01.png" alt=""><figcaption><p>SignScan Homepage</p></figcaption></figure>
## Feature Highlights
SignScan provides several easily accessible methods for interacting with Sign Protocol's schemas and attestations.
* Explore existing schemas and the data they require and contain.
* Search for existing schemas and attestations.
* Generate new schemas and attestations with no code.
* View the most popular schemas.
* Verify attestations.
* Retrieve all schemas and attestations made by any public address.
* And more!
# NPM SDK
### Installation
Install the [`@ethsign/sp-sdk`](https://www.npmjs.com/package/@ethsign/sp-sdk) package to use the Sign Protocol SDK in your frontend or Node backend projects.
### Creating an Index Service Client
```typescript
new IndexService(env);
```
#### Parameters
| Name | Type | Description |
| ---- | -------------------- | --------------------------------------------------------------------- |
| env | `testnet`, `mainnet` | Whether the indexing service should be querying testnets or mainnets. |
#### Example
```typescript
async function getSchemaListFromIndexService() {
const indexService = new IndexService("testnet");
const res = await indexService.querySchemaList({ page: 1 });
}
async function getSchemaFromIndexService() {
const indexService = new IndexService("testnet");
const res = await indexService.querySchema("onchain_evm_80001_0x1");
}
async function getAttestationListFromIndexService() {
const indexService = new IndexService("testnet");
const res = await indexService.queryAttestationList({ page: 1 });
}
async function getAttestationFromIndexService() {
const indexService = new IndexService("testnet");
const res = await indexService.queryAttestation("onchain_evm_80001_0x1");
}
```
# Usage & Examples
## Schemas
### Querying Schemas
```typescript
async function querySchemaList(query: {
id?: string;
registrant?: string;
mode?: "offchain" | "onchain";
page: number;
size?: number;
}): Promise<
PageInfo & {
rows: SchemaInfo[];
}
>;
```
#### Parameters
| Name | Type / Value | Description |
| ----------- | --------------------- | ---------------------------------------------------------------- |
| id? | `string` | The schema ID you are querying for. |
| registrant? | `string` | Find schemas that were created by a specific registrant address. |
| mode? | `offchain`, `onchain` | The schema's location. |
| page | `number` | The page to fetch. |
| size? | `number` | The number of results to return. |
#### Example
```typescript
const res = await indexService.querySchemaList({
id: "onchain_evm_11155111_0xd",
registrant: "0x526dDf0Cc975E0b5B039c85b5cD7ba1e1300500e",
mode: "onchain",
page: 1,
size: 2,
});
```
### Getting a Schema By ID
```typescript
async function querySchema(schemaId: string): Promise<SchemaInfo | null>;
```
#### Parameters
| Name | Type | Description |
| -------- | -------- | --------------------------------- |
| schemaId | `string` | The ID of the schema to retrieve. |
#### Example
```typescript
const res = await indexService.querySchema("onchain_evm_11155111_0xd");
```
## Attestations
### Querying Attestations
```typescript
async function queryAttestationList(query: {
id?: string;
schemaId?: string;
attester?: string;
page: number;
mode?: "offchain" | "onchain";
indexingValue?: string;
}): Promise<
PageInfo & {
rows: AttestationInfo[];
}
>;
```
#### Parameters
| Name | Type / Value | Description |
| -------------- | --------------------- | ------------------------------------------------------ |
| id? | `string` | The attestation ID you are querying for. |
| schemaId? | `string` | Find attestations that belong to a specific schema ID. |
| attester? | `string` | Find attestations that a specific attester created. |
| page | `number` | The page to fetch. |
| mode? | `offchain`, `onchain` | The attestation's location. |
| indexingValue? | `string` | Find attestations with a specific indexing value. |
#### Example
```typescript
const res = await indexService.queryAttestationList({
id: "",
schemaId: "",
attester: "",
page: 1,
mode: "onchain",
indexingValue: "",
});
```
### Getting an Attestation By ID
```typescript
async function queryAttestation(
attestationId: string
): Promise<AttestationInfo | null>;
```
#### Parameters
| Name | Type | Description |
| ------------- | -------- | --------------------------------- |
| attestationId | `string` | The ID of the schema to retrieve. |
#### Example
```typescript
const res = await indexService.queryAttestation("onchain_evm_11155111_0x5");
```
## Utils
### Decoding Attestation Data
```typescript
function decodeOnChainData(
data: any,
dataLocation: DataLocationOnChain,
schemaData: SchemaItem[]
): any;
```
#### Parameters
| Name | Type / Value | Description |
| ------------------- | --------------------- | --------------------------------------------------------------- |
| data | `string` | The hex string retrieved from an onchain attestation object. |
| DataLocationOnChain | `DataLocationOnChain` | Location of the data. Either `ONCHAIN`, `ARWEAVE`, or `IPFS`. |
| schemaData | `string` | The data string of the schema that this attestation belongs to. |
#### Example
<pre class="language-typescript"><code class="lang-typescript">const { decodeOnChainData } from "@ethsign/sp-sdk";
const attestationData = "0x0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000b1987e041b79727cd2a190b53d86c2d1cd2869ef000000000000000000000000000000000프로젝트로 돌아가기