Skip to content

Commit

Permalink
Add command for signing did document (#59)
Browse files Browse the repository at this point in the history
* refactor: migrate files from evm-module repo

* refactor: migrate files from evm-module repo

* refactor: migrate files from evm-module repo

* refactor: migrate files from evm-module repo

* refactor: migrate librustgo into chain repo

* refactor: cleanup go-sgxvm

* refactor: add sgx-sdk as a submodule

* refactor: set sgx-sdk version

* WIP deb dir

* WIP deb dockerfile, bash script
Fix deb systemd run command

* fix: restore vesting test

* WIP build-deb pipeline

* Fix build_deb.sh #1

* Fix build_deb.sh #2

* fix: fix build and startup issues

* Version number does not start with digit

* artifact path

* Implement draft of x/did module

* tests: start adding tests for x/did module

* tests: add more tests for DID create

* tests: extend tests

* tests: add test for DID deactivation

* tests: add tests for updating DID

* tests: extend keeper tests

* chore: add did json rpc

* fix: comments

* refactor: remove redundant submodule

* fix: fix makefile

* refactor: remove evm-module

* feat: add debug commands

* fix: trying to fix issue with verification method

* refactor: sort imports

* add: add command to generate sample payload for DID document

* chore: add unit tests in did types

* chore: add unit tests for did document payload

* chore

* refactor: update constants

* feat: add proto file for did resource

* feat: add types/utils for DID resource

* feat: add keeper methods for DID resource

* fix: fix compilation issues

* feat: add query for did resource

* feat: extend genesis impl

* feat: add cli commands for did resources

* feat: register createResource command

* refactor: merge debug commands

* feat: add draft of sample resource debug cmd

* test: add basic test for did resource creation

* refactor: comment test

* refactor: refactor to remove redundant args

* feat: register sample did resource cmd

* feat: register codec for MsgCreateResource

* hotfix: remove empty submodule

* refactor: remove empty submodule

* feat: add `did` and `util` namespaces to default list

* refactor: add keeper methods

* feat: connect DIDKeeper to EVMKeeper

* feat: pass DIDKeeper to connector

* feat: add draft of identity precompile

* fix: fixing compilation issues

* fix: fixing complication issues

* fix: fix compilation issues

* refactor: add comments and merge small files into one

* refactor: remove unused crate

* fix: fix compilation issue

* refactoring: cleanup tx handler

* feat: provide querier to precompileset

* refactor: moving precompiles into sgxvm (in progress)

* refactor: moving precompiles into sgxvm (in progress)

* refactor: fix warnings

* fix: fix compilation issue

* fix: return datacopy precompile

* refactor: prettify

* feat: provide GoQuerier to Identity precompile

* feat: add function to encode request for credentials verification

* feat: add draft of precompile for VC verification

* feat: add request for obtaining verification material

* feat: pass GoQueroer

* feat: add query for verification methods

* feat: finish precompile part

* feat: add GetVerificationMethods function to connector

* feat: implement connector for DID

* test: prepare test for VC precompile

* test: add test for getting verification methods using connector

* chore: update mod reference

* chore: refactor reference to simapp

* chore: fix referencing issue

* test: add draft of credentials contract and test

* feat: increase default balances

* test: cleanup

* test: add basic test for interaction with VC.sol

* chore: reformat code

* test: add draft of integration test

* chore: uncomment

* refactor: remove unused precompile crates

* test: add actual data

* fix: fixed precompile issue

* refactor: remove todo's and reformat the code

* refactor: reduce code size

* refactor: remove unused derived trait

* refactor: remove unused submodule

* chore: fix app.go

* chore: upgrade library and module

* chore: upgrade testing library

* fix app.go to include consensus keeper

* chore: fix iavl && exp/slices error

* fix: ante handler

* test: update test contract for VC

* test: uncomment test for gas estimation

* chore: update moudles

* fix: fix protobuf issue

* chore: remove duplicate sethook for govkeeper

* refactor: add comments + reduce code size

* refactor: use ENCLAVE_HOME instead of CHAIN_HOME

* refactor: refactor tests

* refactor: resolve todo

* chore: fix vesting module unit testing

* chore: fix setupWithT

* chore: fix chain Id

* chore: add update to date eip712

* chore: set fees acount to be gas amount multiplied

* refactor: add nosgx build flag

* refactor: cleanup

* feat: add draft of command for macos build

* chore: fix unit test failure in ante handler

* chore: fix eip unit test issue

* chore: fix chainId issue

* fix: trying to fix issue with build tags

* fix: fix build issue for linux amd64

* feat: add command for build for windows

* refactor: remove sgx-related commands from swisstronikcli

* feat: add build instructions for arm64 and amd64

* fix: typo fix

* First CI try

* CI #2

* CI #3

* CI #4

* CI #5

* CI #6 Update upload-artifact to v3

* Added badge to README, switch to tag-only runs, enable manual triggers

* fix: quick fix for identity precompile

* refactor: remove redundant debug logs and comments

* refactor: create a separate directory for sgxvm enclave

* fix: fix compilation issues during refactor

* refactor: remove sgx-sdk submodule

* refactor: remove sgx-sdk submodule from go-sgxvm

* refactor: move sgx-sdk into sgxvm directory

* refactor: set submodule version

* refactor: wip: migrating to a new structure

* refactor: apply new structure

* chore: update README

* docs: update README

* refactor: simplify build process

* fix: trying to fix issue with protobuf generation

* fix: fix issue with cyclic import

* test: update sign_tx_test.go

* chore: update protobuf & enclave

* refactor: use cometbft instead of tendermint

* fix: fix build issue

* chore: add nbf validation

* chore: fix comparison of nbf date

* fix: fix build issues in tests

* feat: cache node public key

* chore: add issuer in identiy return RLP, decode it in VC.sol

* test: small test fixes

* refactor: use cometbft instead of tendermint

* refactor: update protobuf

* chore: update wrapper dyn lib

* refactor: remove unused import

* test: update VC.sol test contract

* test: add test for nbf field of JWT proof

* chore: update protobuf and dyn lib

* refactor: return data from precompile in ABI format

* test: add check for returned data from VC.sol

* chore: update protobuf

* fix: restore tests

* feat: add method to obtain controlled DIDs by provided verification material

* chore: set eth key type to legacy Cdc

* feat: add method to add and remove associated did

* feat: use AddDIDControlledBy and RemoveControlledDID calls

* feat: add query for controlled dids

* feat: add query for all controlled documents

* test: add basic test for indexing verification material

* test: update test to check verification method index

* feat: add did_documentsControlledBy request

* test: add test for adding and removing VM from index

* feat: add cli command to query all controlled docs

* fix: trying to fix docker build

* fix: revert Cargo.lock

* refactor: rename did tx commands

* fix: fix docker build

* chore: setup handler

* chore: add eip

* refactor: update version to v1.0.1

* Iterate on deb builds, port changes to Dockerfile

* Fix env

* Enclave home, remove /opt/swisstronik on rm

* feat: take ENCLAVE_HOME from runtime

* Enclave home in systemd file

* Remove SGX-breaking options from systemd

* Modify docs accordingly

* refactor: add SEED_HOME env var

* Added SEED_HOME env var to systemd service

* chore: add distribution param keeper and feemarket keeper module check consPram Block item

* chore: add default statement

* Fix deb pipeline to react to tags, get version from git tag

* feat: update dylib

* refactor: rename comments

* refactor: update comments and names

* fix: fix issue with path to enclave file

* fix: restore ibc tests

* refactor: refactor test utils

* refactor: remove redundant code

* Fix `swisstronikd debug sample-did-resource` (#55)

* fix: fix issue with derivation of collection id

* fix: fix issue with signature for creation of resource

* Add debug command to sign DID document command (#57)

* chore: add sign did document

* chore: renaming

* chore: fix to compare with multibase address and loop all verification method

* chore: rename variable

---------

Co-authored-by: Denis <[email protected]>
Co-authored-by: kenta92115 <[email protected]>
Co-authored-by: kenta92115 <[email protected]>
  • Loading branch information
4 people authored Dec 7, 2023
1 parent 8d23cca commit bac0bcb
Show file tree
Hide file tree
Showing 2 changed files with 166 additions and 12 deletions.
147 changes: 141 additions & 6 deletions cmd/swisstronikd/cmd/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,24 @@ import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"strings"

"encoding/hex"
didutil "swisstronik/testutil/did"
"swisstronik/x/did/types"
didcli "swisstronik/x/did/client/cli"
didtypes "swisstronik/x/did/types"

"github.com/cometbft/cometbft/libs/bytes"
"github.com/cosmos/cosmos-sdk/client"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/version"
"github.com/ethereum/go-ethereum/common"
"github.com/google/uuid"
"github.com/spf13/cobra"
"github.com/cometbft/cometbft/libs/bytes"
)

type DIDDocument struct {
Expand Down Expand Up @@ -55,6 +57,11 @@ type Service struct {
ServiceEndpoint []string `json:"serviceEndpoint"`
}

type KeyPair struct {
PrivateKeyBase64 string `json:"private_key_base_64"`
PublicKeyBase64 string `json:"public_key_base_64"`
}

// Cmd creates a CLI main command
func DebugCmd() *cobra.Command {
cmd := &cobra.Command{
Expand All @@ -68,6 +75,7 @@ func DebugCmd() *cobra.Command {
cmd.AddCommand(ExtractPubkeyCmd())
cmd.AddCommand(ConvertAddressCmd())
cmd.AddCommand(SampleDIDResource())
cmd.AddCommand(SignDIDDocument())

return cmd
}
Expand Down Expand Up @@ -180,6 +188,133 @@ func SampleDIDDocument() *cobra.Command {
return cmd
}

func ReadKeyPairFromFile(file string) (KeyPair, error) {
bytes, err := os.ReadFile(file)
if err != nil {
return KeyPair{}, err
}

keyPair := KeyPair{}
err = json.Unmarshal(bytes, &keyPair)
if err != nil {
return KeyPair{}, err
}

return keyPair, nil
}

func SignDIDDocument() *cobra.Command {
cmd := &cobra.Command{
Use: "sign-did-document [did.json] [key.json]",
Short: "Generates signed DID document ready to be stored in DID registry",
Long: "Generates signed self-controlled DID document from the payload and key information provided, which is ready to be stored in DID registry.",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return errors.New("invalid input parameters")
}

signInputs := make([]didcli.SignInput, 0)

// Decode did.json to have payload
payloadJSON, err := didcli.ReadPayloadFromFile(args[0])
if err != nil {
// Decode did.json to have payload & sign inputs
payloadJSON, signInputs, err = didcli.ReadPayloadWithSignInputsFromFile(args[0])
}

if err != nil {
return errors.New("invalid payload")
}

// Decode key.json to have private and public key pair
keyPairFromFile, err := ReadKeyPairFromFile(args[1])
if err != nil {
return err
}

// Decode base64 based private key string to have byte[]
privateKeyBytesFromFile, err := base64.StdEncoding.DecodeString(keyPairFromFile.PrivateKeyBase64)
if err != nil {
return err
}

// Encode ed25519 based private key
privateKeyFromFile := ed25519.PrivateKey(privateKeyBytesFromFile)
// Encode ed25519 based public key
publicKeyFromFile := privateKeyFromFile.Public().(ed25519.PublicKey)
// Multibase public key
publicKeyMultibaseFromFile := didutil.GenerateEd25519VerificationKey2020VerificationMaterial(publicKeyFromFile)

// Unmarshal spec-compliant payload
var specPayload didcli.DIDDocument
err = json.Unmarshal([]byte(payloadJSON), &specPayload)
if err != nil {
return err
}

if len(specPayload.VerificationMethod) < 1 {
return errors.New("publicKeyMultibase is not specified")
}

validKey := false
keyId := ""
for _, v := range specPayload.VerificationMethod {
// Check if public key is addressed in verfication method
_, ok := v["publicKeyMultibase"]
if !ok {
continue
}

_, ok = v["id"]
if !ok {
continue
}

// Get multibase public key address
publicKeyMultibase := v["publicKeyMultibase"].(string)

// if there is matching verification method,
if publicKeyMultibase == publicKeyMultibaseFromFile {
keyId = v["id"].(string)
validKey = true
break
}
}

// if there is no matching verification method
if !validKey {
return errors.New("invalid key information")
}

// Construct sign inputs
if len(signInputs) < 1 {
signInputs = append(signInputs, didcli.SignInput{
VerificationMethodID: keyId,
PrivKey: privateKeyFromFile,
})
}

// Construct payload with sign inputs
result := didcli.PayloadWithSignInputs{
Payload: payloadJSON,
SignInputs: signInputs,
}

// Encode the structured result
encodedResult, err := json.Marshal(result)
if err != nil {
return err
}

// Print output.
_, err = fmt.Fprintln(cmd.OutOrStdout(), string(encodedResult))
return err
},
}

return cmd
}

func SampleDIDResource() *cobra.Command {
cmd := &cobra.Command{
Use: "sample-did-resource [existing-did] [base64-encoded-ed25519-private-key]",
Expand Down Expand Up @@ -220,12 +355,12 @@ func SampleDIDResource() *cobra.Command {
resource := didtypes.MsgCreateResourcePayload{
CollectionId: collectionId,
Id: uuid.NewString(),
Name: "sample-resource",
Version: "sample-version",
Name: "sample-resource",
Version: "sample-version",
ResourceType: "SampleResourceType",
AlsoKnownAs: []*types.AlternativeUri{
AlsoKnownAs: []*didtypes.AlternativeUri{
{
Uri: "http://example.com/example-did",
Uri: "http://example.com/example-did",
Description: "http-uri",
},
},
Expand Down
31 changes: 25 additions & 6 deletions x/did/client/cli/tx.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package cli

import (
"fmt"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client"
"crypto/ed25519"
"encoding/json"
"fmt"
"os"


"github.com/cosmos/cosmos-sdk/client"
"github.com/spf13/cobra"

"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"

"swisstronik/x/did/types"
)

Expand Down Expand Up @@ -61,6 +62,10 @@ type Service struct {
ServiceEndpoint []string `json:"serviceEndpoint"`
}

type Payload struct {
Payload json.RawMessage
}

type PayloadWithSignInputs struct {
Payload json.RawMessage
SignInputs []SignInput
Expand Down Expand Up @@ -119,6 +124,21 @@ func AccAddrByKeyRef(keyring keyring.Keyring, keyRef string) (sdk.AccAddress, er
return sdk.AccAddressFromBech32(keyRef)
}

func ReadPayloadFromFile(filePath string) (json.RawMessage, error) {
bytes, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}

payload := &Payload{}
err = json.Unmarshal(bytes, payload)
if err != nil {
return nil, err
}

return payload.Payload, nil
}

func ReadPayloadWithSignInputsFromFile(filePath string) (json.RawMessage, []SignInput, error) {
bytes, err := os.ReadFile(filePath)
if err != nil {
Expand Down Expand Up @@ -202,4 +222,3 @@ func GetFromSpecCompliantPayload(specPayload DIDDocument) ([]*types.Verification

return verificationMethod, service, nil
}

0 comments on commit bac0bcb

Please sign in to comment.