Skip to content

Commit

Permalink
identity: createConfig (#741)
Browse files Browse the repository at this point in the history
* createConfig deprecated

* added CreateConfig with new identity

* added test for create config

* formatting

* added tests for create config

* formatting

* moved create identity and add keys to did package
  • Loading branch information
xmxanuel committed Feb 12, 2019
1 parent 5e3cb95 commit 2feca77
Show file tree
Hide file tree
Showing 13 changed files with 314 additions and 22 deletions.
2 changes: 2 additions & 0 deletions bootstrap/bootstrappers/bootstrapper.go
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/centrifuge/go-centrifuge/documents/invoice"
"github.com/centrifuge/go-centrifuge/documents/purchaseorder"
"github.com/centrifuge/go-centrifuge/ethereum"
"github.com/centrifuge/go-centrifuge/identity/did"
"github.com/centrifuge/go-centrifuge/identity/ethid"
"github.com/centrifuge/go-centrifuge/nft"
"github.com/centrifuge/go-centrifuge/node"
Expand Down Expand Up @@ -59,6 +60,7 @@ func (m *MainBootstrapper) PopulateCommandBootstrappers() {
transactions.Bootstrapper{},
&queue.Bootstrapper{},
ethereum.Bootstrapper{},
&did.Bootstrapper{},
&anchors.Bootstrapper{},
&ethid.Bootstrapper{},
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/centrifuge/create_config.go
Expand Up @@ -30,7 +30,7 @@ func init() {
Short: "Configures Node",
Long: ``,
Run: func(c *cobra.Command, args []string) {
err := cmd.CreateConfig(targetDataDir,
err := cmd.CreateConfigDeprecated(targetDataDir,
ethNodeURL,
accountKeyPath,
accountPassword,
Expand Down
2 changes: 1 addition & 1 deletion cmd/centrifuge_cmd_test.go
Expand Up @@ -21,7 +21,7 @@ func TestVersion(t *testing.T) {
assert.Contains(t, string(o), version.CentrifugeNodeVersion)
}

func TestCreateConfig(t *testing.T) {
func TestCreateConfigDeprecated(t *testing.T) {
dataDir := path.Join(os.Getenv("HOME"), "datadir")
scAddrs := testingutils.GetSmartContractAddresses()
keyPath := path.Join(testingutils.GetProjectDir(), "build/scripts/test-dependencies/test-ethereum/migrateAccount.json")
Expand Down
78 changes: 72 additions & 6 deletions cmd/common.go
Expand Up @@ -3,10 +3,10 @@ package cmd
import (
"context"

"github.com/centrifuge/go-centrifuge/bootstrap/bootstrappers"
"github.com/centrifuge/go-centrifuge/config/configstore"
"github.com/centrifuge/go-centrifuge/contextutil"

"github.com/centrifuge/go-centrifuge/bootstrap/bootstrappers"
"github.com/centrifuge/go-centrifuge/identity/did"

"github.com/centrifuge/go-centrifuge/storage"

Expand All @@ -22,7 +22,8 @@ import (

var log = logging.Logger("centrifuge-cmd")

func createIdentity(ctx context.Context, idService identity.Service) (identity.CentID, error) {
// Deprecated
func createIdentityDeprecated(ctx context.Context, idService identity.Service) (identity.CentID, error) {
centID := identity.RandomCentID()
_, confirmations, err := idService.CreateIdentity(ctx, centID)
if err != nil {
Expand All @@ -42,7 +43,8 @@ func generateKeys(config config.Configuration) {
crypto.GenerateSigningKeyPair(ethAuthPub, ethAuthPvt, "secp256k1")
}

func addKeys(config config.Configuration, idService identity.Service) error {
// Deprecated
func addKeysDeprecated(config config.Configuration, idService identity.Service) error {
err := idService.AddKeyFromConfig(config, identity.KeyPurposeP2P)
if err != nil {
return err
Expand All @@ -67,6 +69,70 @@ func CreateConfig(
p2pConnectionTimeout string,
smartContractAddrs *config.SmartContractAddresses) error {

data := map[string]interface{}{
"targetDataDir": targetDataDir,
"accountKeyPath": accountKeyPath,
"accountPassword": accountPassword,
"network": network,
"ethNodeURL": ethNodeURL,
"bootstraps": bootstraps,
"apiPort": apiPort,
"p2pPort": p2pPort,
"p2pConnectTimeout": p2pConnectionTimeout,
"txpoolaccess": txPoolAccess,
}
if smartContractAddrs != nil {
data["smartContractAddresses"] = smartContractAddrs
}
configFile, err := config.CreateConfigFile(data)
if err != nil {
return err
}
log.Infof("Config File Created: %s\n", configFile.ConfigFileUsed())
ctx, canc, _ := CommandBootstrap(configFile.ConfigFileUsed())
cfg := ctx[bootstrap.BootstrappedConfig].(config.Configuration)

// create keys locally
generateKeys(cfg)

id, err := did.CreateIdentity(ctx, cfg)
if err != nil {
return err
}

configFile.Set("identityId", id.ToAddress().String())
err = configFile.WriteConfig()
if err != nil {
return err
}
cfg.Set("identityId", id.ToAddress().String())
log.Infof("Identity created [%s]", id.ToAddress().String())

err = did.AddKeysFromConfig(ctx, cfg)
if err != nil {
return err
}

canc()
db := ctx[storage.BootstrappedDB].(storage.Repository)
dbCfg := ctx[storage.BootstrappedConfigDB].(storage.Repository)
db.Close()
dbCfg.Close()
log.Infof("---------Centrifuge node configuration file successfully created!---------")
log.Infof("Please run the Centrifuge node using the following command: centrifuge run -c %s\n", configFile.ConfigFileUsed())
return nil
}

// CreateConfigDeprecated creates a config file using provide parameters and the default config
// Deprecated
func CreateConfigDeprecated(
targetDataDir, ethNodeURL, accountKeyPath, accountPassword, network string,
apiPort, p2pPort int64,
bootstraps []string,
txPoolAccess bool,
p2pConnectionTimeout string,
smartContractAddrs *config.SmartContractAddresses) error {

data := map[string]interface{}{
"targetDataDir": targetDataDir,
"accountKeyPath": accountKeyPath,
Expand Down Expand Up @@ -102,7 +168,7 @@ func CreateConfig(
}

idService := ctx[identity.BootstrappedIDService].(identity.Service)
id, err := createIdentity(tctx, idService)
id, err := createIdentityDeprecated(tctx, idService)
if err != nil {
return err
}
Expand All @@ -113,7 +179,7 @@ func CreateConfig(
}
cfg.Set("identityId", id.String())
log.Infof("Identity created [%s] [%x]", id.String(), id)
err = addKeys(cfg, idService)
err = addKeysDeprecated(cfg, idService)
if err != nil {
return err
}
Expand Down
111 changes: 111 additions & 0 deletions cmd/common_test.go
@@ -0,0 +1,111 @@
// +build integration

package cmd

import (
"context"
"math/big"
"os"
"os/exec"
"path"
"testing"

"github.com/centrifuge/go-centrifuge/crypto/ed25519"
"github.com/centrifuge/go-centrifuge/crypto/secp256k1"
"github.com/centrifuge/go-centrifuge/identity"
"github.com/centrifuge/go-centrifuge/testingutils"
"github.com/centrifuge/go-centrifuge/testingutils/config"
"github.com/centrifuge/go-centrifuge/utils"
"github.com/ethereum/go-ethereum/common"

"github.com/centrifuge/go-centrifuge/bootstrap"
"github.com/centrifuge/go-centrifuge/bootstrap/bootstrappers/testlogging"
"github.com/centrifuge/go-centrifuge/config"
"github.com/centrifuge/go-centrifuge/config/configstore"
"github.com/centrifuge/go-centrifuge/ethereum"
"github.com/centrifuge/go-centrifuge/identity/did"
"github.com/centrifuge/go-centrifuge/identity/ethid"
"github.com/centrifuge/go-centrifuge/queue"
"github.com/centrifuge/go-centrifuge/storage/leveldb"
"github.com/centrifuge/go-centrifuge/transactions"
"github.com/stretchr/testify/assert"
)

var cfg config.Configuration
var ctx = map[string]interface{}{}

func TestMain(m *testing.M) {
var bootstappers = []bootstrap.TestBootstrapper{
&testlogging.TestLoggingBootstrapper{},
&config.Bootstrapper{},
&leveldb.Bootstrapper{},
transactions.Bootstrapper{},
&queue.Bootstrapper{},
ethereum.Bootstrapper{},
&ethid.Bootstrapper{},
&configstore.Bootstrapper{},
&did.Bootstrapper{},
&queue.Starter{},
}

bootstrap.RunTestBootstrappers(bootstappers, ctx)
cfg = ctx[bootstrap.BootstrappedConfig].(config.Configuration)
result := m.Run()
bootstrap.RunTestTeardown(bootstappers)
os.Exit(result)
}

func TestCreateConfig(t *testing.T) {
// create config
dataDir := "testconfig"
keyPath := path.Join(testingutils.GetProjectDir(), "build/scripts/test-dependencies/test-ethereum/migrateAccount.json")
scAddrs := did.GetSmartContractAddresses()
err := CreateConfig(dataDir, "http://127.0.0.1:9545", keyPath, "", "russianhill", 8028, 38202, nil, true, "", scAddrs)
assert.Nil(t, err, "Create Config should be successful")

// config exists
cfg := config.LoadConfiguration(path.Join(dataDir, "config.yaml"))
client := ctx[ethereum.BootstrappedEthereumClient].(ethereum.Client)

// contract exists
id, err := cfg.GetIdentityID()
assert.Nil(t, err, "did should exists")
contractCode, err := client.GetEthClient().CodeAt(context.Background(), common.BytesToAddress(id), nil)
assert.Nil(t, err, "should be successful to get the contract code")
assert.Equal(t, true, len(contractCode) > 3000, "current contract code should be arround 3378 bytes")

// Keys exists
// type KeyPurposeEthMsgAuth
tctx := testingconfig.CreateAccountContext(t, cfg)
idSrv := ctx[did.BootstrappedDIDService].(did.Service)
pk, _, err := secp256k1.GetEthAuthKey(cfg.GetEthAuthKeyPair())
assert.Nil(t, err)
address32Bytes := utils.AddressTo32Bytes(common.HexToAddress(secp256k1.GetAddress(pk)))
assert.Nil(t, err)
response, err := idSrv.GetKey(tctx, address32Bytes)
assert.Nil(t, err)
assert.NotNil(t, response)
assert.Equal(t, big.NewInt(identity.KeyPurposeEthMsgAuth), response.Purposes[0], "purpose should be ETHMsgAuth")

// type KeyPurposeP2P
pk, _, err = ed25519.GetSigningKeyPair(cfg.GetP2PKeyPair())
assert.Nil(t, err)
pk32, err := utils.SliceToByte32(pk)
assert.Nil(t, err)
response, _ = idSrv.GetKey(tctx, pk32)
assert.NotNil(t, response)
assert.Equal(t, big.NewInt(identity.KeyPurposeP2P), response.Purposes[0], "purpose should be P2P")

// type KeyPurposeSigning
pk, _, err = ed25519.GetSigningKeyPair(cfg.GetSigningKeyPair())
assert.Nil(t, err)
pk32, err = utils.SliceToByte32(pk)
assert.Nil(t, err)
response, _ = idSrv.GetKey(tctx, pk32)
assert.NotNil(t, response)
assert.Equal(t, big.NewInt(identity.KeyPurposeSigning), response.Purposes[0], "purpose should be Signing")

err = exec.Command("rm", "-rf", dataDir).Run()
assert.Nil(t, err, "removing testconfig folder should be successful")

}
4 changes: 2 additions & 2 deletions identity/did/bootstrapper.go
Expand Up @@ -80,7 +80,7 @@ func getAnchorAddress() common.Address {
// ---------------------------------------------------------------------------------------------------------------------
func migrateNewIdentityContracts() {
runNewSmartContractMigrations()
smartContractAddresses = getSmartContractAddresses()
smartContractAddresses = GetSmartContractAddresses()

}

Expand All @@ -107,7 +107,7 @@ func runNewSmartContractMigrations() {

// GetSmartContractAddresses finds migrated smart contract addresses for localgeth
// TODO: func will be removed after migration
func getSmartContractAddresses() *config.SmartContractAddresses {
func GetSmartContractAddresses() *config.SmartContractAddresses {
dat, err := findContractDeployJSON()
if err != nil {
panic(err)
Expand Down
34 changes: 28 additions & 6 deletions identity/did/factory.go
Expand Up @@ -3,6 +3,9 @@ package did
import (
"context"

"github.com/centrifuge/go-centrifuge/config"
"github.com/centrifuge/go-centrifuge/config/configstore"

"github.com/centrifuge/go-centrifuge/errors"

"github.com/centrifuge/go-centrifuge/contextutil"
Expand Down Expand Up @@ -117,17 +120,13 @@ func (s *factory) CreateIdentity(ctx context.Context) (did *DID, err error) {
return nil, err
}

idConfig, err := contextutil.Self(ctx)
if err != nil {
return nil, err
}

identityAddress, err := s.calculateIdentityAddress(ctx)
if err != nil {
return nil, err
}

txID, done, err := s.txManager.ExecuteWithinTX(context.Background(), idConfig.ID, uuid.Nil, "Check TX for create identity status", s.createIdentityTX(opts))
// TODO refactor randomCentID
txID, done, err := s.txManager.ExecuteWithinTX(context.Background(), id.RandomCentID(), uuid.Nil, "Check TX for create identity status", s.createIdentityTX(opts))
if err != nil {
return nil, err
}
Expand All @@ -147,3 +146,26 @@ func (s *factory) CreateIdentity(ctx context.Context) (did *DID, err error) {
createdDID := NewDID(*identityAddress)
return &createdDID, nil
}

// CreateIdentity creates an identity contract
func CreateIdentity(ctx map[string]interface{}, cfg config.Configuration) (*DID, error) {
tc, err := configstore.TempAccount(cfg.GetEthereumDefaultAccountName(), cfg)
if err != nil {
return nil, err
}

tctx, err := contextutil.New(context.Background(), tc)
if err != nil {
return nil, err
}

identityFactory := ctx[BootstrappedDIDFactory].(Factory)

did, err := identityFactory.CreateIdentity(tctx)
if err != nil {
return nil, err
}

return did, nil

}
2 changes: 1 addition & 1 deletion identity/did/factory_integration_test.go
Expand Up @@ -54,7 +54,7 @@ func TestCreateIdentity_successful(t *testing.T) {

client := ctx[ethereum.BootstrappedEthereumClient].(ethereum.Client)

contractCode, err := client.GetEthClient().CodeAt(context.Background(), did.toAddress(), nil)
contractCode, err := client.GetEthClient().CodeAt(context.Background(), did.ToAddress(), nil)
assert.Nil(t, err, "should be successful to get the contract code")

assert.Equal(t, true, len(contractCode) > 3000, "current contract code should be arround 3378 bytes")
Expand Down
5 changes: 5 additions & 0 deletions identity/did/key.go
Expand Up @@ -30,6 +30,11 @@ type key struct {
Type *big.Int
}

//NewKey returns a new key struct
func NewKey(pk [32]byte, purpose *big.Int, keyType *big.Int) Key {
return &key{pk, purpose, big.NewInt(0), keyType}
}

// GetKey returns the public key
func (idk *key) GetKey() [32]byte {
return idk.Key
Expand Down

0 comments on commit 2feca77

Please sign in to comment.