From 06866af182811815e5524adee93378e16db657bc Mon Sep 17 00:00:00 2001 From: Martin Saporiti Date: Tue, 28 May 2024 14:01:00 -0300 Subject: [PATCH] chore: clean code and change endpoint to unpack with a different message --- cmd/platform/main.go | 17 +- cmd/platform_ui/main.go | 16 +- internal/api/server.go | 3 +- internal/core/ports/revocation_service.go | 13 - internal/core/services/claims.go | 1 + internal/core/services/proof.go | 737 ---------------------- internal/core/services/revocation.go | 482 -------------- pkg/protocol/packagemanager.go | 39 +- 8 files changed, 8 insertions(+), 1300 deletions(-) delete mode 100644 internal/core/ports/revocation_service.go delete mode 100644 internal/core/services/proof.go delete mode 100644 internal/core/services/revocation.go diff --git a/cmd/platform/main.go b/cmd/platform/main.go index f221e75f0..649052168 100644 --- a/cmd/platform/main.go +++ b/cmd/platform/main.go @@ -30,7 +30,6 @@ import ( "github.com/polygonid/sh-id-platform/internal/providers/blockchain" "github.com/polygonid/sh-id-platform/internal/redis" "github.com/polygonid/sh-id-platform/internal/repositories" - "github.com/polygonid/sh-id-platform/pkg/blockchain/eth" "github.com/polygonid/sh-id-platform/pkg/cache" "github.com/polygonid/sh-id-platform/pkg/credentials/revocation_status" circuitLoaders "github.com/polygonid/sh-id-platform/pkg/loaders" @@ -147,20 +146,6 @@ func main() { claimsService := services.NewClaim(claimsRepository, identityService, qrService, mtService, identityStateRepository, schemaLoader, storage, cfg.ServerUrl, ps, cfg.IPFS.GatewayURL, revocationStatusResolver) proofService := gateways.NewProver(ctx, cfg, circuitsLoaderService) - stateService, err := eth.NewStateService(eth.StateServiceConfig{ - EthClient: ethConn, - StateAddress: common.HexToAddress(cfg.Ethereum.ContractAddress), - ResponseTimeout: cfg.Ethereum.RPCResponseTimeout, - }) - if err != nil { - log.Error(ctx, "failed init state service", "err", err) - return - } - - onChainCredentialStatusResolverService := gateways.NewOnChainCredStatusResolverService(ethConn, cfg.Ethereum.RPCResponseTimeout) - revocationService := services.NewRevocationService(common.HexToAddress(cfg.Ethereum.ContractAddress), stateService, onChainCredentialStatusResolverService) - - zkProofService := services.NewProofService(claimsService, revocationService, identityService, mtService, claimsRepository, keyStore, storage, stateService, schemaLoader) transactionService, err := gateways.NewTransaction(ethereumClient, cfg.Ethereum.ConfirmationBlockCount) if err != nil { log.Error(ctx, "error creating transaction service", "err", err) @@ -175,7 +160,7 @@ func main() { publisher := gateways.NewPublisher(storage, identityService, claimsService, mtService, keyStore, transactionService, proofService, publisherGateway, cfg.Ethereum.ConfirmationTimeout, ps) - packageManager, err := protocol.InitPackageManager(ctx, stateContract, zkProofService, cfg.Circuit.Path) + packageManager, err := protocol.InitPackageManager(stateContract, cfg.Circuit.Path) if err != nil { log.Error(ctx, "failed init package protocol", "err", err) return diff --git a/cmd/platform_ui/main.go b/cmd/platform_ui/main.go index 27d9f5e3c..3c600c2cb 100644 --- a/cmd/platform_ui/main.go +++ b/cmd/platform_ui/main.go @@ -37,7 +37,6 @@ import ( "github.com/polygonid/sh-id-platform/internal/providers/blockchain" "github.com/polygonid/sh-id-platform/internal/redis" "github.com/polygonid/sh-id-platform/internal/repositories" - "github.com/polygonid/sh-id-platform/pkg/blockchain/eth" "github.com/polygonid/sh-id-platform/pkg/cache" "github.com/polygonid/sh-id-platform/pkg/credentials/revocation_status" circuitLoaders "github.com/polygonid/sh-id-platform/pkg/loaders" @@ -181,19 +180,6 @@ func main() { connectionsService := services.NewConnection(connectionsRepository, claimsRepository, storage) linkService := services.NewLinkService(storage, claimsService, qrService, claimsRepository, linkRepository, schemaRepository, schemaLoader, sessionRepository, ps, cfg.IPFS.GatewayURL) - stateService, err := eth.NewStateService(eth.StateServiceConfig{ - EthClient: ethConn, - StateAddress: common.HexToAddress(cfg.Ethereum.ContractAddress), - ResponseTimeout: cfg.Ethereum.RPCResponseTimeout, - }) - if err != nil { - log.Error(ctx, "failed init state service", "err", err) - return - } - - onChainCredentialStatusResolverService := gateways.NewOnChainCredStatusResolverService(ethConn, cfg.Ethereum.RPCResponseTimeout) - revocationService := services.NewRevocationService(common.HexToAddress(cfg.Ethereum.ContractAddress), stateService, onChainCredentialStatusResolverService) - zkProofService := services.NewProofService(claimsService, revocationService, identityService, mtService, claimsRepository, keyStore, storage, stateService, schemaLoader) transactionService, err := gateways.NewTransaction(ethereumClient, cfg.Ethereum.ConfirmationBlockCount) if err != nil { log.Error(ctx, "error creating transaction service", "err", err) @@ -208,7 +194,7 @@ func main() { publisher := gateways.NewPublisher(storage, identityService, claimsService, mtService, keyStore, transactionService, proofService, publisherGateway, cfg.Ethereum.ConfirmationTimeout, ps) - packageManager, err := protocol.InitPackageManager(ctx, stateContract, zkProofService, cfg.Circuit.Path) + packageManager, err := protocol.InitPackageManager(stateContract, cfg.Circuit.Path) if err != nil { log.Error(ctx, "failed init package protocol", "err", err) return diff --git a/internal/api/server.go b/internal/api/server.go index 68dac11a0..a026cb94e 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -407,7 +407,8 @@ func (s *Server) Agent(ctx context.Context, request AgentRequestObject) (AgentRe log.Debug(ctx, "agent empty request") return Agent400JSONResponse{N400JSONResponse{"cannot proceed with an empty request"}}, nil } - basicMessage, err := s.packageManager.UnpackWithType(packers.MediaTypeZKPMessage, []byte(*request.Body)) + + basicMessage, _, err := s.packageManager.Unpack([]byte(*request.Body)) if err != nil { log.Debug(ctx, "agent bad request", "err", err, "body", *request.Body) return Agent400JSONResponse{N400JSONResponse{"cannot proceed with the given request"}}, nil diff --git a/internal/core/ports/revocation_service.go b/internal/core/ports/revocation_service.go deleted file mode 100644 index efd7cc726..000000000 --- a/internal/core/ports/revocation_service.go +++ /dev/null @@ -1,13 +0,0 @@ -package ports - -import ( - "context" - - "github.com/iden3/go-iden3-core/v2/w3c" - "github.com/iden3/go-schema-processor/v2/verifiable" -) - -// RevocationService is the interface implemented by the RevocationService service -type RevocationService interface { - Status(ctx context.Context, credStatus interface{}, issuerDID *w3c.DID, issuerData *verifiable.IssuerData) (*verifiable.RevocationStatus, error) -} diff --git a/internal/core/services/claims.go b/internal/core/services/claims.go index 1a8192bca..5ed45b479 100644 --- a/internal/core/services/claims.go +++ b/internal/core/services/claims.go @@ -630,6 +630,7 @@ func (c *claim) getRevocationStatus(ctx context.Context, basicMessage *ports.Age Body: protocol.RevocationStatusResponseMessageBody{RevocationStatus: *revStatus}, From: basicMessage.IssuerDID.String(), To: basicMessage.UserDID.String(), + Typ: packers.MediaTypePlainMessage, }, nil } diff --git a/internal/core/services/proof.go b/internal/core/services/proof.go deleted file mode 100644 index acb8eb366..000000000 --- a/internal/core/services/proof.go +++ /dev/null @@ -1,737 +0,0 @@ -package services - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "math/big" - "time" - - "github.com/google/uuid" - "github.com/iden3/go-circuits/v2" - core "github.com/iden3/go-iden3-core/v2" - "github.com/iden3/go-iden3-core/v2/w3c" - "github.com/iden3/go-iden3-crypto/babyjub" - "github.com/iden3/go-merkletree-sql/v2" - jsonSuite "github.com/iden3/go-schema-processor/v2/json" - "github.com/iden3/go-schema-processor/v2/merklize" - "github.com/iden3/go-schema-processor/v2/processor" - "github.com/iden3/go-schema-processor/v2/verifiable" - "github.com/jackc/pgx/v4" - "github.com/piprate/json-gold/ld" - - "github.com/polygonid/sh-id-platform/internal/common" - "github.com/polygonid/sh-id-platform/internal/core/domain" - "github.com/polygonid/sh-id-platform/internal/core/ports" - "github.com/polygonid/sh-id-platform/internal/db" - "github.com/polygonid/sh-id-platform/internal/jsonschema" - "github.com/polygonid/sh-id-platform/internal/kms" - "github.com/polygonid/sh-id-platform/internal/loader" - "github.com/polygonid/sh-id-platform/internal/log" - "github.com/polygonid/sh-id-platform/internal/repositories" - "github.com/polygonid/sh-id-platform/pkg/credentials/signature/circuit/signer" - "github.com/polygonid/sh-id-platform/pkg/protocol" -) - -const ( - defaultAtomicCircuitsID = 10 -) - -// ErrAllClaimsRevoked all claims are revoked. -var ( - ErrAllClaimsRevoked = errors.New("all claims are revoked") -) - -// Proof service generates and validates ZK zk -type Proof struct { - claimSrv ports.ClaimsService - revocationSrv ports.RevocationService - identitySrv ports.IdentityService - mtService ports.MtService - claimsRepository ports.ClaimsRepository - keyProvider *kms.KMS - storage *db.Storage - stateService ports.StateService - schemaLoader loader.DocumentLoader - merklizeOptions []merklize.MerklizeOption -} - -// NewProofService init proof service -func NewProofService(claimSrv ports.ClaimsService, revocationSrv ports.RevocationService, identitySrv ports.IdentityService, mtService ports.MtService, claimsRepository ports.ClaimsRepository, keyProvider *kms.KMS, storage *db.Storage, stateService ports.StateService, ld ld.DocumentLoader) ports.ProofService { - merklizeOptions := []merklize.MerklizeOption{ - merklize.WithDocumentLoader(ld), - } - return &Proof{ - claimSrv: claimSrv, - revocationSrv: revocationSrv, - identitySrv: identitySrv, - mtService: mtService, - claimsRepository: claimsRepository, - keyProvider: keyProvider, - storage: storage, - stateService: stateService, - schemaLoader: ld, - merklizeOptions: merklizeOptions, - } -} - -// PrepareInputs prepare inputs for circuit. -// -//nolint:gocyclo // refactor later to avoid big PR. -func (p *Proof) PrepareInputs(ctx context.Context, identifier *w3c.DID, query ports.Query) ([]byte, []*domain.Claim, error) { - var claims []*domain.Claim - var err error - var claim *domain.Claim - - var circuitInputs circuits.InputsMarshaller - switch circuits.CircuitID(query.CircuitID) { - case circuits.AtomicQuerySigV2CircuitID: - circuitInputs, claim, err = p.prepareAtomicQuerySigV2Circuit(ctx, identifier, query) - if err != nil { - return nil, nil, err - } - claims = append(claims, claim) - - case circuits.AtomicQueryMTPV2CircuitID: - circuitInputs, claim, err = p.prepareAtomicQueryMTPV2Circuit(ctx, identifier, query) - if err != nil { - return nil, nil, err - } - claims = append(claims, claim) - - case circuits.AuthV2CircuitID: - circuitInputs, err = p.prepareAuthV2Circuit(ctx, identifier, query.Challenge) - if err != nil { - return nil, nil, err - } - - default: - return nil, nil, fmt.Errorf("circuit with id %s is not supported", query.CircuitID) - } - - inputs, err := circuitInputs.InputsMarshal() - if err != nil { - return nil, nil, err - } - - log.Debug(ctx, "Circuit inputs", "inputs", string(inputs)) - - return inputs, claims, nil -} - -func (p *Proof) prepareAtomicQuerySigV2Circuit(ctx context.Context, did *w3c.DID, query ports.Query) (circuits.InputsMarshaller, *domain.Claim, error) { - claim, claimNonRevProof, err := p.getClaimDataForAtomicQueryCircuit(ctx, did, query) - if err != nil { - return nil, nil, err - } - - sigProof, err := claim.GetBJJSignatureProof2021() - if err != nil { - return nil, nil, err - } - - sig, err := signer.BJJSignatureFromHexString(sigProof.Signature) - if err != nil { - return nil, nil, err - } - - issuerDID, err := w3c.ParseDID(claim.Issuer) - if err != nil { - return nil, nil, err - } - - issuerAuthNonRevProof, err := p.callNonRevProof(ctx, sigProof.IssuerData, issuerDID) - if err != nil { - return nil, nil, err - } - - circuitQuery, err := p.toCircuitsQuery(ctx, *claim, query) - if err != nil { - return nil, nil, err - } - - authClaim := &core.Claim{} - err = authClaim.FromHex(sigProof.IssuerData.AuthCoreClaim) - if err != nil { - return nil, nil, err - } - - sig1 := circuits.BJJSignatureProof{ - Signature: sig, - IssuerAuthClaim: authClaim, - IssuerAuthIncProof: circuits.MTProof{ - Proof: sigProof.IssuerData.MTP, - TreeState: circuits.TreeState{ - State: common.StrMTHex(sigProof.IssuerData.State.Value), - ClaimsRoot: common.StrMTHex(sigProof.IssuerData.State.ClaimsTreeRoot), - RevocationRoot: common.StrMTHex(sigProof.IssuerData.State.RevocationTreeRoot), - RootOfRoots: common.StrMTHex(sigProof.IssuerData.State.RootOfRoots), - }, - }, - IssuerAuthNonRevProof: issuerAuthNonRevProof, - } - - id, err := core.IDFromDID(*did) - if err != nil { - return nil, nil, err - } - - inputs := circuits.AtomicQuerySigV2Inputs{ - RequestID: big.NewInt(defaultAtomicCircuitsID), - ID: &id, - ProfileNonce: big.NewInt(0), - ClaimSubjectProfileNonce: big.NewInt(0), - Claim: circuits.ClaimWithSigProof{ - IssuerID: &id, - Claim: claim.CoreClaim.Get(), - NonRevProof: *claimNonRevProof, - SignatureProof: sig1, - }, - Query: circuitQuery, - CurrentTimeStamp: time.Now().Unix(), - SkipClaimRevocationCheck: query.SkipClaimRevocationCheck, - } - - return inputs, claim, nil -} - -func (p *Proof) prepareAtomicQueryMTPV2Circuit(ctx context.Context, did *w3c.DID, query ports.Query) (circuits.InputsMarshaller, *domain.Claim, error) { - claim, claimNonRevProof, err := p.getClaimDataForAtomicQueryCircuit(ctx, did, query) - if err != nil { - return nil, nil, err - } - - claimInc, err := claim.GetCircuitIncProof() - if err != nil { - return nil, nil, err - } - - circuitQuery, err := p.toCircuitsQuery(ctx, *claim, query) - if err != nil { - return nil, nil, err - } - - id, err := core.IDFromDID(*did) - if err != nil { - return nil, nil, err - } - - inputs := circuits.AtomicQueryMTPV2Inputs{ - RequestID: big.NewInt(defaultAtomicCircuitsID), - ID: &id, - ProfileNonce: big.NewInt(0), - ClaimSubjectProfileNonce: big.NewInt(0), - Claim: circuits.ClaimWithMTPProof{ - IssuerID: &id, // claim.Issuer, - Claim: claim.CoreClaim.Get(), - NonRevProof: *claimNonRevProof, - IncProof: claimInc, - }, - Query: circuitQuery, - CurrentTimeStamp: time.Now().Unix(), - SkipClaimRevocationCheck: query.SkipClaimRevocationCheck, - } - - return inputs, claim, nil -} - -func (p *Proof) getClaimDataForAtomicQueryCircuit(ctx context.Context, identifier *w3c.DID, query ports.Query) (claim *domain.Claim, revStatus *circuits.MTProof, err error) { - var claims []*domain.Claim - - if query.ClaimID != "" { - // if claimID exist. Search by claimID. - claimUUID, err := uuid.Parse(query.ClaimID) - if err != nil { - return nil, nil, err - } - var c *domain.Claim - c, err = p.claimSrv.GetByID(ctx, identifier, claimUUID) - if err != nil { - return nil, nil, err - } - // we need to be sure that the hallmark selected by ID matches circuitQuery. - claims = append(claims, c) - } else { - // if claimID NOT exist in request select all claims and filter it. - claims, err = p.findClaimForQuery(ctx, identifier, query) - if err != nil { - return claim, nil, err - } - } - - var claimRs circuits.MTProof - if query.SkipClaimRevocationCheck { - claim = claims[0] - rsClaim, err := p.checkRevocationStatus(ctx, claim) - if err != nil { - return claim, nil, err - } - claimRs = circuits.MTProof{ - TreeState: domain.RevocationStatusToTreeState(*rsClaim), - Proof: &rsClaim.MTP, - } - } else { - claim, claimRs, err = p.findNonRevokedClaim(ctx, claims) - if err != nil { - return claim, nil, err - } - } - return claim, &claimRs, nil -} - -func (p *Proof) findClaimForQuery(ctx context.Context, identifier *w3c.DID, query ports.Query) ([]*domain.Claim, error) { - var err error - - // TODO "query_value": value, - // TODO "query_operator": operator, - filter := &ports.ClaimsFilter{SchemaType: query.SchemaType()} - if !query.SkipClaimRevocationCheck { - filter.Revoked = common.ToPointer(false) - } - - claim, _, err := p.claimsRepository.GetAllByIssuerID(ctx, p.storage.Pgx, *identifier, filter) - if errors.Is(err, repositories.ErrClaimDoesNotExist) { - return nil, fmt.Errorf("claim with credential type %v was not found", query) - } - - return claim, err -} - -func (p *Proof) checkRevocationStatus(ctx context.Context, claim *domain.Claim) (*verifiable.RevocationStatus, error) { - var ( - err error - claimRs *verifiable.RevocationStatus - ) - - var cs map[string]interface{} - if err = json.Unmarshal(claim.CredentialStatus.Bytes, &cs); err != nil { - return nil, fmt.Errorf("failed unmasrshal credentialStatus: %s", err) - } - issuerDID, err := w3c.ParseDID(claim.Issuer) - if err != nil { - return nil, err - } - - sigProof, err := claim.GetBJJSignatureProof2021() - if err != nil { - return nil, err - } - - claimRs, err = p.revocationSrv.Status(ctx, cs, issuerDID, &sigProof.IssuerData) - if err != nil && errors.Is(err, protocol.ErrStateNotFound) { - - bjp := new(verifiable.BJJSignatureProof2021) - if err := json.Unmarshal(claim.SignatureProof.Bytes, bjp); err != nil { - return nil, fmt.Errorf("failed parse signature proof for get genesys state: %s", err) - } - state, errIn := merkletree.NewHashFromHex(*bjp.IssuerData.State.Value) - if errIn != nil { - return nil, err - } - if common.CheckGenesisStateDID(issuerDID, state.BigInt()) != nil { - return nil, errors.New("issuer identity is not genesis and not published") - } - - return &verifiable.RevocationStatus{ - Issuer: verifiable.TreeState{ - State: bjp.IssuerData.State.Value, - RootOfRoots: bjp.IssuerData.State.RootOfRoots, - ClaimsTreeRoot: bjp.IssuerData.State.ClaimsTreeRoot, - RevocationTreeRoot: bjp.IssuerData.State.RevocationTreeRoot, - }, - MTP: merkletree.Proof{Existence: false}, - }, nil - } else if err != nil { - return nil, err - } - if claimRs.MTP.Existence { - // update revocation status - err = p.storage.Pgx.BeginFunc(ctx, func(tx pgx.Tx) error { - claim.Revoked = true - _, err = p.claimsRepository.Save(ctx, p.storage.Pgx, claim) - if err != nil { - return fmt.Errorf("can't save claim %v", err) - } - return nil - }) - if err != nil { - return nil, err - } - // claim revoked - return claimRs, nil - } - // claim not revoked - return claimRs, nil -} - -func (p *Proof) findNonRevokedClaim(ctx context.Context, claims []*domain.Claim) (*domain.Claim, circuits.MTProof, error) { - for _, claim := range claims { - rsClaim, err := p.checkRevocationStatus(ctx, claim) - if err != nil { - return nil, circuits.MTProof{}, err - } - // current claim revoked. To try next claim. - if rsClaim == nil { - continue - } - - revStatus := circuits.MTProof{ - TreeState: domain.RevocationStatusToTreeState(*rsClaim), - Proof: &rsClaim.MTP, - } - - return claim, revStatus, nil - } - return nil, circuits.MTProof{}, ErrAllClaimsRevoked -} - -func (p *Proof) toCircuitsQuery(ctx context.Context, claim domain.Claim, query ports.Query) (circuits.Query, error) { - // check if merklized - coreClaim := claim.CoreClaim.Get() - - merklizePosition, err := coreClaim.GetMerklizedPosition() - if err != nil { - return circuits.Query{}, err - } - if merklizePosition == core.MerklizedRootPositionNone { - credential, err := claim.GetVerifiableCredential() - if err != nil { - return circuits.Query{}, err - } - return p.prepareNonMerklizedQuery(ctx, credential.CredentialSchema.ID, query) - } - - return p.prepareMerklizedQuery(ctx, claim, query) -} - -func (p *Proof) prepareMerklizedQuery(ctx context.Context, claim domain.Claim, query ports.Query) (circuits.Query, error) { - vc, err := claim.GetVerifiableCredential() - if err != nil { - return circuits.Query{}, err - } - - mk, err := vc.Merklize(ctx, p.merklizeOptions...) - if err != nil { - return circuits.Query{}, err - } - - circuitQuery, field, err := parseQueryWithoutSlot(query.Req) - if err != nil { - return circuits.Query{}, err - } - - schema, err := jsonschema.Load(ctx, query.Context, p.schemaLoader) - if err != nil { - return circuits.Query{}, err - } - - fieldPath := merklize.Path{} - - if field != "" { - fieldPath, err = merklize.NewFieldPathFromContext(schema.BytesNoErr(), query.Type, field) - if err != nil { - return circuits.Query{}, err - } - } - - err = fieldPath.Prepend("https://www.w3.org/2018/credentials#credentialSubject") - if err != nil { - return circuits.Query{}, err - } - - jsonP, v, err := mk.Proof(ctx, fieldPath) - if err != nil { - return circuits.Query{}, err - } - - value, err := v.MtEntry() - if err != nil { - return circuits.Query{}, err - } - - path, err := fieldPath.MtEntry() - if err != nil { - return circuits.Query{}, err - } - - circuitQuery.ValueProof = &circuits.ValueProof{ - Path: path, - Value: value, - MTP: jsonP, - } - - return circuitQuery, nil -} - -func (p *Proof) prepareNonMerklizedQuery(ctx context.Context, jsonSchemaURL string, query ports.Query) (circuits.Query, error) { - parser := jsonSuite.Parser{} - pr := processor.InitProcessorOptions(&processor.Processor{}, - processor.WithParser(parser), - processor.WithDocumentLoader(p.schemaLoader)) - - schema, err := jsonschema.Load(ctx, jsonSchemaURL, p.schemaLoader) - if err != nil { - return circuits.Query{}, err - } - - if len(query.Req) > 1 { - return circuits.Query{}, errors.New("multiple requests are currently not supported") - } - - circuitQuery, field, err := parseQueryWithoutSlot(query.Req) - if err != nil { - return circuits.Query{}, err - } - - circuitQuery.SlotIndex, err = pr.GetFieldSlotIndex(field, query.Type, schema.BytesNoErr()) - if err != nil { - return circuits.Query{}, err - } - - return circuitQuery, nil -} - -func (p *Proof) callNonRevProof(ctx context.Context, issuerData verifiable.IssuerData, issuerDID *w3c.DID) (circuits.MTProof, error) { - nonRevProof, err := p.revocationSrv.Status(ctx, issuerData.CredentialStatus, issuerDID, &issuerData) - - if err != nil && errors.Is(err, protocol.ErrStateNotFound) { - state, errIn := merkletree.NewHashFromHex(*issuerData.State.Value) - if errIn != nil { - return circuits.MTProof{}, err - } - if common.CheckGenesisStateDID(issuerDID, state.BigInt()) != nil { - return circuits.MTProof{}, errors.New("issuer identity is not genesis and not published") - } - return circuits.MTProof{ - Proof: &merkletree.Proof{ - Existence: false, - NodeAux: nil, - }, - TreeState: domain.RevocationStatusToTreeState(verifiable.RevocationStatus{ - Issuer: verifiable.TreeState{ - State: issuerData.State.Value, - RootOfRoots: issuerData.State.RootOfRoots, - ClaimsTreeRoot: issuerData.State.ClaimsTreeRoot, - RevocationTreeRoot: issuerData.State.RevocationTreeRoot, - }, - MTP: merkletree.Proof{}, - }), - }, nil - } - - return circuits.MTProof{ - Proof: &nonRevProof.MTP, - TreeState: domain.RevocationStatusToTreeState(*nonRevProof), - }, nil -} - -func (p *Proof) prepareAuthV2Circuit(ctx context.Context, identifier *w3c.DID, challenge *big.Int) (circuits.AuthV2Inputs, error) { - authClaim, err := p.claimSrv.GetAuthClaim(ctx, identifier) - if err != nil { - return circuits.AuthV2Inputs{}, err - } - - authClaimData, err := p.fillAuthClaimData(ctx, identifier, authClaim) - if err != nil { - return circuits.AuthV2Inputs{}, err - } - signature, err := p.signChallange(ctx, authClaim, challenge) - if err != nil { - return circuits.AuthV2Inputs{}, err - } - globalTree, err := populateGlobalTree(ctx, identifier, p.stateService) - if err != nil { - return circuits.AuthV2Inputs{}, err - } - id, err := core.IDFromDID(*identifier) - if err != nil { - return circuits.AuthV2Inputs{}, err - } - circuitInputs := prepareAuthV2CircuitInputs(id, authClaimData, challenge, signature, globalTree) - return circuitInputs, nil -} - -func (p *Proof) signChallange(ctx context.Context, authClaim *domain.Claim, challenge *big.Int) (*babyjub.Signature, error) { - signingKeyID, err := p.identitySrv.GetKeyIDFromAuthClaim(ctx, authClaim) - if err != nil { - return nil, err - } - - challengeDigest := kms.BJJDigest(challenge) - - var sigBytes []byte - sigBytes, err = p.keyProvider.Sign(ctx, signingKeyID, challengeDigest) - if err != nil { - return nil, err - } - - return kms.DecodeBJJSignature(sigBytes) -} - -func (p *Proof) fillAuthClaimData(ctx context.Context, identifier *w3c.DID, authClaim *domain.Claim) (circuits.ClaimWithMTPProof, error) { - var authClaimData circuits.ClaimWithMTPProof - - err := p.storage.Pgx.BeginFunc( - ctx, func(tx pgx.Tx) error { - var errIn error - var idState *domain.IdentityState - idState, errIn = p.identitySrv.GetLatestStateByID(ctx, *identifier) - if errIn != nil { - return errIn - } - - identityTrees, errIn := p.mtService.GetIdentityMerkleTrees(ctx, tx, identifier) - if errIn != nil { - return errIn - } - - claimsTree, errIn := identityTrees.ClaimsTree() - if errIn != nil { - return errIn - } - // get index hash of authClaim - coreClaim := authClaim.CoreClaim.Get() - hIndex, errIn := coreClaim.HIndex() - if errIn != nil { - return errIn - } - - authClaimMTP, _, errIn := claimsTree.GenerateProof(ctx, hIndex, idState.TreeState().ClaimsRoot) - if errIn != nil { - return errIn - } - - authClaimData = circuits.ClaimWithMTPProof{ - Claim: coreClaim, - } - - authClaimData.IncProof = circuits.MTProof{ - Proof: authClaimMTP, - TreeState: idState.TreeState(), - } - - // revocation / non revocation MTP for the latest identity state - nonRevocationProof, errIn := identityTrees. - GenerateRevocationProof(ctx, new(big.Int).SetUint64(uint64(authClaim.RevNonce)), idState.TreeState().RevocationRoot) - - authClaimData.NonRevProof = circuits.MTProof{ - TreeState: idState.TreeState(), - Proof: nonRevocationProof, - } - - return errIn - }) - if err != nil { - return authClaimData, err - } - return authClaimData, nil -} - -func prepareAuthV2CircuitInputs(id core.ID, authClaim circuits.ClaimWithMTPProof, challenge *big.Int, signature *babyjub.Signature, globalMTP circuits.GISTProof) circuits.AuthV2Inputs { - return circuits.AuthV2Inputs{ - GenesisID: &id, - ProfileNonce: big.NewInt(0), - AuthClaim: authClaim.Claim, - AuthClaimIncMtp: authClaim.IncProof.Proof, - AuthClaimNonRevMtp: authClaim.NonRevProof.Proof, - TreeState: authClaim.IncProof.TreeState, - Signature: signature, - Challenge: challenge, - GISTProof: globalMTP, - } -} - -func populateGlobalTree(ctx context.Context, did *w3c.DID, stateService ports.StateService) (circuits.GISTProof, error) { - // get global root - gProof, err := stateService.GetGistProof(ctx, did) - if err != nil { - return circuits.GISTProof{}, err - } - - siblings := make([]*big.Int, len(gProof.Siblings)) - for i, s := range &gProof.Siblings { - siblings[i] = s - } - - proof, err := common.SmartContractProofToMtProofAdapter(common.SmartContractProof{ - Root: gProof.Root, - Existence: gProof.Existence, - Siblings: siblings, - Index: gProof.Index, - Value: gProof.Value, - AuxExistence: gProof.AuxExistence, - AuxIndex: gProof.AuxIndex, - AuxValue: gProof.AuxValue, - }) - if err != nil { - return circuits.GISTProof{}, err - } - - root, err := merkletree.NewHashFromBigInt(gProof.Root) - if err != nil { - return circuits.GISTProof{}, err - } - return circuits.GISTProof{ - Root: root, - Proof: proof, - }, nil -} - -func getValuesFromArray(v interface{}) ([]*big.Int, error) { - values := []*big.Int{} - - switch value := v.(type) { - case float64: - values = []*big.Int{new(big.Int).SetInt64(int64(value))} - case []interface{}: - for _, item := range value { - if itemFloat, ok := item.(float64); ok { - values = append(values, new(big.Int).SetInt64(int64(itemFloat))) - } else { - return nil, fmt.Errorf("unsupported values type in value element %T, expected float64", item) - } - } - default: - return nil, fmt.Errorf("unsupported values type %T", v) - } - - return values, nil -} - -func parseQueryWithoutSlot(req map[string]interface{}) (circuits.Query, string, error) { - for field, body := range req { - condition, ok := body.(map[string]interface{}) - - if !ok { - return circuits.Query{}, "", errors.New("failed cast type map[string]interface") - } - - if len(condition) > 1 { - return circuits.Query{}, "", errors.New("multiple predicates are currently not supported") - } - - for op, v := range condition { - - intOp, ok := circuits.QueryOperators[op] - if !ok { - return circuits.Query{}, "", errors.New("query operator is not supported") - } - - values, err := getValuesFromArray(v) - if err != nil { - return circuits.Query{}, "", err - } - - return circuits.Query{ - Operator: intOp, - Values: values, - }, field, nil - } - } - return circuits.Query{ - Operator: 0, - Values: []*big.Int{}, - SlotIndex: 0, - }, "", nil -} diff --git a/internal/core/services/revocation.go b/internal/core/services/revocation.go deleted file mode 100644 index 3740537fb..000000000 --- a/internal/core/services/revocation.go +++ /dev/null @@ -1,482 +0,0 @@ -package services - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "math/big" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - ethCommon "github.com/ethereum/go-ethereum/common" - "github.com/google/uuid" - abiOnchain "github.com/iden3/contracts-abi/onchain-credential-status-resolver/go/abi" - "github.com/iden3/contracts-abi/state/go/abi" - core "github.com/iden3/go-iden3-core/v2" - "github.com/iden3/go-iden3-core/v2/w3c" - "github.com/iden3/go-merkletree-sql/v2" - "github.com/iden3/go-schema-processor/v2/verifiable" - "github.com/iden3/iden3comm/v2" - "github.com/iden3/iden3comm/v2/packers" - "github.com/iden3/iden3comm/v2/protocol" - proofHttp "github.com/iden3/merkletree-proof/http" - - "github.com/polygonid/sh-id-platform/internal/common" - "github.com/polygonid/sh-id-platform/internal/core/ports" - "github.com/polygonid/sh-id-platform/internal/log" - client "github.com/polygonid/sh-id-platform/pkg/http" -) - -const ( - defaultRevocationTime = 30 - stateChildrenLength = 3 - contractPartsLength = 2 -) - -// ErrIdentityDoesNotExist - identity does not exist -var ErrIdentityDoesNotExist = errors.New("identity does not exist") - -// StateStore TBD -type StateStore interface { - GetLatestStateByID(ctx context.Context, addr ethCommon.Address, id *big.Int) (abi.IStateStateInfo, error) -} - -type onChainStatusService interface { - GetRevocationStatus(ctx context.Context, state *big.Int, nonce uint64, did *w3c.DID, address ethCommon.Address) (abiOnchain.IOnchainCredentialStatusResolverCredentialStatus, error) -} - -// Revocation TBD -type Revocation struct { - stateService ports.StateService - onChainStatusService onChainStatusService - contract ethCommon.Address -} - -// NewRevocationService returns the Revocation struct -func NewRevocationService(contract ethCommon.Address, stateService ports.StateService, onChainStatusService onChainStatusService) *Revocation { - return &Revocation{ - contract: contract, - stateService: stateService, - onChainStatusService: onChainStatusService, - } -} - -// Status returns the current revocation status -func (r *Revocation) Status(ctx context.Context, credStatus interface{}, issuerDID *w3c.DID, issuerData *verifiable.IssuerData) (*verifiable.RevocationStatus, error) { - status, err := convertCredentialStatus(credStatus) - if err != nil { - log.Error(ctx, "failed convert credential status", "error", err) - return nil, err - } - switch status.Type { - case verifiable.Iden3ReverseSparseMerkleTreeProof: - return r.getRevocationStatusFromRHS(ctx, issuerDID, status, issuerData) - case verifiable.SparseMerkleTreeProof: - return getRevocationProofFromIssuer(ctx, status.ID) - case verifiable.Iden3commRevocationStatusV1: - return getRevocationStatusFromAgent(ctx, issuerDID.String(), - issuerDID.String(), status.ID, status.RevocationNonce) - case verifiable.Iden3OnchainSparseMerkleTreeProof2023: - return r.getRevocationStatusFromOnchainCredStatusResolver(ctx, issuerDID, status) - default: - return nil, fmt.Errorf("%s type not supported", status.Type) - } -} - -func convertCredentialStatus(credStatus interface{}) (verifiable.CredentialStatus, error) { - status, ok := credStatus.(verifiable.CredentialStatus) - if ok { - return status, nil - } - pointedStatus, ok := credStatus.(*verifiable.CredentialStatus) - if ok { - return *pointedStatus, nil - } - _, ok = credStatus.(map[string]interface{}) - if ok { - b, err := json.Marshal(credStatus) - if err != nil { - return verifiable.CredentialStatus{}, err - } - var status verifiable.CredentialStatus - err = json.Unmarshal(b, &status) - if err != nil { - return verifiable.CredentialStatus{}, err - } - return status, nil - } - - return verifiable.CredentialStatus{}, errors.New("failed cast credential status to verifiable.CredentialStatus") -} - -func getRevocationStatusFromAgent(ctx context.Context, from, to, endpoint string, nonce uint64) (*verifiable.RevocationStatus, error) { - pkg := iden3comm.NewPackageManager() - if err := pkg.RegisterPackers(&packers.PlainMessagePacker{}); err != nil { - return nil, err - } - - revocationBody := protocol.RevocationStatusRequestMessageBody{ - RevocationNonce: nonce, - } - rawBody, err := json.Marshal(revocationBody) - if err != nil { - return nil, err - } - - msg := iden3comm.BasicMessage{ - ID: uuid.New().String(), - ThreadID: uuid.New().String(), - From: from, - To: to, - Type: protocol.RevocationStatusRequestMessageType, - Body: rawBody, - } - bytesMsg, err := json.Marshal(msg) - if err != nil { - return nil, err - } - - iden3commMsg, err := pkg.Pack(packers.MediaTypePlainMessage, bytesMsg, nil) - if err != nil { - return nil, err - } - - resp, err := http.DefaultClient.Post(endpoint, "application/json", bytes.NewBuffer(iden3commMsg)) - if err != nil { - return nil, err - } - defer func() { - if err := resp.Body.Close(); err != nil { - log.Warn(ctx, "failed to close response body: %s", err) - } - }() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("bad status code: %d", resp.StatusCode) - } - - b, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - basicMessage, _, err := pkg.Unpack(b) - if err != nil { - return nil, err - } - - if basicMessage.Type != protocol.RevocationStatusResponseMessageType { - return nil, fmt.Errorf("unexpected message type: %s", basicMessage.Type) - } - - var revocationStatus protocol.RevocationStatusResponseMessageBody - if err := json.Unmarshal(basicMessage.Body, &revocationStatus); err != nil { - return nil, err - } - - return &revocationStatus.RevocationStatus, nil -} - -func getRevocationProofFromIssuer(ctx context.Context, url string) (*verifiable.RevocationStatus, error) { - b, err := client.NewClient(*http.DefaultClient).Get(ctx, url) - if err != nil { - return nil, err - } - - rs := &verifiable.RevocationStatus{} - if err := json.Unmarshal(b, rs); err != nil { - return nil, err - } - return rs, nil -} - -func getNonRevocationProofFromRHS(ctx context.Context, rhsURL string, data, issuerRoot *merkletree.Hash) (*verifiable.RevocationStatus, error) { - rhsCli := proofHttp.ReverseHashCli{ - URL: rhsURL, - HTTPTimeout: time.Second * defaultRevocationTime, - } - - treeRoots, err := rhsCli.GetNode(ctx, issuerRoot) - if err != nil { - return nil, err - } - if len(treeRoots.Children) != stateChildrenLength { - return nil, fmt.Errorf("state should has tree children") - } - - var ( - s = issuerRoot.Hex() - CTR = treeRoots.Children[0].Hex() - RTR = treeRoots.Children[1].Hex() - RoTR = treeRoots.Children[2].Hex() - ) - - rtrHashed, err := merkletree.NewHashFromString(RTR) - if err != nil { - return nil, err - } - nonRevProof, err := rhsCli.GenerateProof(ctx, rtrHashed, data) - if err != nil { - return nil, fmt.Errorf("failed generate proof for root '%s' and element '%s': %s", - issuerRoot, data, err) - } - - return &verifiable.RevocationStatus{ - Issuer: verifiable.TreeState{ - State: &s, - ClaimsTreeRoot: &CTR, - RevocationTreeRoot: &RTR, - RootOfRoots: &RoTR, - }, - MTP: *nonRevProof, - }, nil -} - -func (r *Revocation) getRevocationStatusFromRHS(ctx context.Context, issuerDID *w3c.DID, status verifiable.CredentialStatus, issuerData *verifiable.IssuerData) (*verifiable.RevocationStatus, error) { - latestStateInfo, err := r.stateService.GetLatestStateByDID(ctx, issuerDID) - if err != nil && strings.Contains(err.Error(), ErrIdentityDoesNotExist.Error()) { - - currentState, err := extractState(status.ID) - if err != nil { - log.Error(ctx, "failed extract state from rhs id", "error", err) - return nil, err - } - if currentState == "" { - return getRevocationStatusFromIssuerData(issuerDID, issuerData) - } else { - latestStateInfo.State, err = getGenesisState(issuerDID, currentState) - if err != nil { - return nil, fmt.Errorf("failed get genesis state for issuer '%s'", issuerDID) - } - } - - } else if err != nil { - return nil, fmt.Errorf("failed get latest state by did '%s'", issuerDID.String()) - } - - hashedRevNonce, err := merkletree.NewHashFromBigInt(big.NewInt(int64(status.RevocationNonce))) - if err != nil { - return nil, fmt.Errorf("failed calculate mt hash for revocation nonce '%d': '%s'", - status.RevocationNonce, err) - } - - hashedIssuerState, err := merkletree.NewHashFromBigInt(latestStateInfo.State) - if err != nil { - return nil, fmt.Errorf("failed calcilate mt hash for issuer state '%s': '%s'", - latestStateInfo.State, err) - } - - u := strings.Split(status.ID, "/node") - rs, err := getNonRevocationProofFromRHS(ctx, u[0], hashedRevNonce, hashedIssuerState) - if err != nil && status.StatusIssuer.Type == verifiable.SparseMerkleTreeProof { - // try to get proof from issuer - log.Warn(ctx, "failed build revocation status from enabled RHS. Then try to fetch from issuer. RHS error: %v", err) - revocStatus, err := getRevocationProofFromIssuer(ctx, status.StatusIssuer.ID) - if err != nil { - return nil, err - } - return revocStatus, nil - } - return rs, nil -} - -func extractState(id string) (string, error) { - rhsULR, err := url.Parse(id) - if err != nil { - return "", fmt.Errorf("invalid rhs id filed '%s'", id) - } - params, err := url.ParseQuery(rhsULR.RawQuery) - if err != nil { - return "", fmt.Errorf("invalid rhs params '%s'", rhsULR.RawQuery) - } - return params.Get("state"), nil -} - -func getRevocationStatusFromIssuerData(did *w3c.DID, issuerData *verifiable.IssuerData) (*verifiable.RevocationStatus, error) { - if issuerData == nil || issuerData.State.Value == nil { - return nil, errors.New("issuer data state is empty. is not possible verify revocation status") - } - h, err := merkletree.NewHashFromHex(*issuerData.State.Value) - if err != nil { - return nil, fmt.Errorf("failed parse hex '%s'", *issuerData.State.Value) - } - err = common.CheckGenesisStateDID(did, h.BigInt()) - if err != nil { - return nil, fmt.Errorf("failed check genesis state for issuer '%s'", did) - } - - return &verifiable.RevocationStatus{ - Issuer: verifiable.TreeState{ - State: issuerData.State.Value, - RootOfRoots: issuerData.State.RootOfRoots, - ClaimsTreeRoot: issuerData.State.ClaimsTreeRoot, - RevocationTreeRoot: issuerData.State.RevocationTreeRoot, - }, - MTP: merkletree.Proof{Existence: false}, - }, nil -} - -func getGenesisState(did *w3c.DID, currentState string) (*big.Int, error) { - h, err := merkletree.NewHashFromHex(currentState) - if err != nil { - return nil, fmt.Errorf("failed parse hex '%s'", currentState) - } - err = common.CheckGenesisStateDID(did, h.BigInt()) - if err != nil { - return nil, fmt.Errorf("failed check genesis state for issuer '%s'", did) - } - return h.BigInt(), nil -} - -func (r *Revocation) getRevocationStatusFromOnchainCredStatusResolver(ctx context.Context, issuerDID *w3c.DID, status verifiable.CredentialStatus) (*verifiable.RevocationStatus, error) { - issuerID, err := core.IDFromDID(*issuerDID) - if err != nil { - return nil, fmt.Errorf("failed get issuer id from '%s'", issuerDID) - } - - onchainRevStatus, err := newOnchainRevStatusFromURI(status.ID) - if err != nil { - return nil, err - } - - if onchainRevStatus.revNonce != nil && *onchainRevStatus.revNonce != status.RevocationNonce { - return nil, fmt.Errorf("revocationNonce is not equal to the one in OnChainCredentialStatus ID {%d} {%d}", onchainRevStatus.revNonce, status.RevocationNonce) - } - - // get latest state from contract - var stateToProof *big.Int - latestStateInfo, err := r.stateService.GetLatestStateByDID(ctx, issuerDID) - //nolint:gocritic //reason: work with errors - if err != nil && strings.Contains(err.Error(), ErrIdentityDoesNotExist.Error()) { - if onchainRevStatus.state == nil { - return nil, errors.New(`latest state not found and state parameter is not present in credentialStatus.id`) - } - err = common.CheckGenesisStateDID(issuerDID, onchainRevStatus.state) - if err != nil { - return nil, err - } - stateToProof = onchainRevStatus.state - - } else if err != nil { - return nil, fmt.Errorf("failed get latest state by id '%s'", issuerID) - } else { - stateToProof = latestStateInfo.State - } - - rs, err := r.onChainStatusService.GetRevocationStatus( - ctx, stateToProof, status.RevocationNonce, issuerDID, onchainRevStatus.contractAddress, - ) - if err != nil { - return nil, errors.New("failed get revocation status from onchain cred status resolver") - } - - smProof, err := common.SmartContractProofToMtProofAdapter(common.SmartContractProof{ - Root: rs.Mtp.Root, - Existence: rs.Mtp.Existence, - Siblings: rs.Mtp.Siblings, - Index: rs.Mtp.Index, - Value: rs.Mtp.Value, - AuxExistence: rs.Mtp.AuxExistence, - AuxIndex: rs.Mtp.AuxIndex, - AuxValue: rs.Mtp.AuxValue, - }) - if err != nil { - log.Error(ctx, "failed convert smart contract proof to merkle tree proof", "error", err) - return nil, err - } - - state, err := merkletree.NewHashFromBigInt(rs.Issuer.State) - if err != nil { - log.Error(ctx, "failed convert state to merkle tree hash", "error", err) - return nil, err - } - stateHex := state.Hex() - ctr, err := merkletree.NewHashFromBigInt(rs.Issuer.ClaimsTreeRoot) - if err != nil { - return nil, err - } - ctrHex := ctr.Hex() - - rtr, err := merkletree.NewHashFromBigInt(rs.Issuer.RevocationTreeRoot) - if err != nil { - log.Error(ctx, "failed convert revocation tree root to merkle tree hash", "error", err) - return nil, err - } - rtrHex := rtr.Hex() - - ror, err := merkletree.NewHashFromBigInt(rs.Issuer.RootOfRoots) - if err != nil { - log.Error(ctx, "failed convert root of roots to merkle tree hash", "error", err) - return nil, err - } - rorHex := ror.Hex() - - return &verifiable.RevocationStatus{ - Issuer: verifiable.TreeState{ - State: &stateHex, - ClaimsTreeRoot: &ctrHex, - RevocationTreeRoot: &rtrHex, - RootOfRoots: &rorHex, - }, - MTP: *smProof, - }, nil -} - -type onchainRevStatus struct { - contractAddress ethCommon.Address - revNonce *uint64 - state *big.Int -} - -func newOnchainRevStatusFromURI(id string) (onchainRevStatus, error) { - var s onchainRevStatus - - uri, err := url.Parse(id) - if err != nil { - return s, errors.New("OnChainCredentialStatus ID is not a valid URI") - } - - contract := uri.Query().Get("contractAddress") - if contract == "" { - return s, errors.New("OnChainCredentialStatus contract address is empty") - } - - contractParts := strings.Split(contract, ":") - if len(contractParts) != contractPartsLength { - return s, errors.New( - "OnChainCredentialStatus contract address is not valid") - } - if !ethCommon.IsHexAddress(contractParts[1]) { - return s, errors.New( - "OnChainCredentialStatus incorrect contract address") - } - s.contractAddress = ethCommon.HexToAddress(contractParts[1]) - - revocationNonce := uri.Query().Get("revocationNonce") - // revnonce may be nil if params is absent in query - if revocationNonce != "" { - n, err := strconv.ParseUint(revocationNonce, 10, 64) - if err != nil { - return s, errors.New("revocationNonce is not a number in OnChainCredentialStatus ID") - } - s.revNonce = &n - } - // state may be nil if params is absent in query - stateParam := uri.Query().Get("state") - if stateParam == "" { - s.state = nil - } else { - stateHash, err := merkletree.NewHashFromHex(stateParam) - if err != nil { - return s, err - } - s.state = stateHash.BigInt() - } - - return s, nil -} diff --git a/pkg/protocol/packagemanager.go b/pkg/protocol/packagemanager.go index 35dc29846..f19f01c7a 100644 --- a/pkg/protocol/packagemanager.go +++ b/pkg/protocol/packagemanager.go @@ -1,23 +1,19 @@ package protocol import ( - "context" "fmt" - "math/big" "github.com/iden3/contracts-abi/state/go/abi" "github.com/iden3/go-circuits/v2" - "github.com/iden3/go-iden3-core/v2/w3c" "github.com/iden3/go-jwz/v2" "github.com/iden3/iden3comm/v2" "github.com/iden3/iden3comm/v2/packers" - "github.com/polygonid/sh-id-platform/internal/core/ports" "github.com/polygonid/sh-id-platform/pkg/loaders" ) // InitPackageManager initializes the iden3comm package manager -func InitPackageManager(ctx context.Context, stateContract *abi.State, zkProofService ports.ProofService, circuitsPath string) (*iden3comm.PackageManager, error) { +func InitPackageManager(stateContract *abi.State, circuitsPath string) (*iden3comm.PackageManager, error) { circuitsLoaderService := loaders.NewCircuits(circuitsPath) authV2Set, err := circuitsLoaderService.Load(circuits.AuthV2CircuitID) @@ -25,27 +21,11 @@ func InitPackageManager(ctx context.Context, stateContract *abi.State, zkProofSe return nil, fmt.Errorf("failed upload circuits files: %w", err) } - provers := make(map[jwz.ProvingMethodAlg]packers.ProvingParams) - pParams := packers.ProvingParams{ - DataPreparer: prepareAuthInputs(ctx, zkProofService), - ProvingKey: authV2Set.ProofKey, - Wasm: authV2Set.Wasm, - } - provers[jwz.AuthV2Groth16Alg] = pParams - verifications := make(map[jwz.ProvingMethodAlg]packers.VerificationParams) - verifications[jwz.AuthV2Groth16Alg] = packers.NewVerificationParams(authV2Set.VerificationKey, - stateVerificationHandler(stateContract)) - - zkpPackerV2 := packers.NewZKPPacker( - provers, - verifications, - ) - - // TODO: Why jwsPacker is not defined here? + verifications[jwz.AuthV2Groth16Alg] = packers.NewVerificationParams(authV2Set.VerificationKey, stateVerificationHandler(stateContract)) + zkpPackerV2 := packers.NewZKPPacker(nil, verifications) packageManager := iden3comm.NewPackageManager() - err = packageManager.RegisterPackers(zkpPackerV2, &packers.PlainMessagePacker{}) if err != nil { return nil, err @@ -53,16 +33,3 @@ func InitPackageManager(ctx context.Context, stateContract *abi.State, zkProofSe return packageManager, err } - -func prepareAuthInputs(ctx context.Context, proofService ports.ProofService) packers.DataPreparerHandlerFunc { - return func(hash []byte, id *w3c.DID, circuitID circuits.CircuitID) ([]byte, error) { - q := ports.Query{} - q.CircuitID = string(circuitID) - q.Challenge = new(big.Int).SetBytes(hash) - circuitInputs, _, err := proofService.PrepareInputs(ctx, id, q) - if err != nil { - return nil, err - } - return circuitInputs, nil - } -}