Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions keystore/corekeys/csa.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// `corekeys` provides utilities to generate keys that are compatible with the core node
// and can be imported by it.
package corekeys

import (
"context"
"encoding/json"
"errors"
"fmt"

gethkeystore "github.com/ethereum/go-ethereum/accounts/keystore"
"google.golang.org/protobuf/proto"

"github.com/smartcontractkit/chainlink-common/keystore"
"github.com/smartcontractkit/chainlink-common/keystore/serialization"
)

var (
ErrInvalidExportFormat = errors.New("invalid export format")
)

const (
TypeCSA = "csa"
nameDefault = "default"
exportFormat = "github.com/smartcontractkit/chainlink-common/keystore/corekeys"
)

type Store struct {
keystore.Keystore
}

type Envelope struct {
Type string
Keys []keystore.ExportKeyResponse
ExportFormat string
}

func NewStore(ks keystore.Keystore) *Store {
return &Store{
Keystore: ks,
}
}

// decryptKey decrypts an encrypted key using the provided password and returns the deserialized key.
func decryptKey(encryptedData []byte, password string) (*serialization.Key, error) {
encData := gethkeystore.CryptoJSON{}
err := json.Unmarshal(encryptedData, &encData)
if err != nil {
return nil, fmt.Errorf("could not unmarshal key material into CryptoJSON: %w", err)
}

decData, err := gethkeystore.DecryptDataV3(encData, password)
if err != nil {
return nil, fmt.Errorf("could not decrypt data: %w", err)
}

keypb := &serialization.Key{}
err = proto.Unmarshal(decData, keypb)
if err != nil {
return nil, fmt.Errorf("could not unmarshal key into serialization.Key: %w", err)
}

return keypb, nil
}

func (ks *Store) GenerateEncryptedCSAKey(ctx context.Context, password string) ([]byte, error) {
path := keystore.NewKeyPath(TypeCSA, nameDefault)
_, err := ks.CreateKeys(ctx, keystore.CreateKeysRequest{
Keys: []keystore.CreateKeyRequest{
{
KeyName: path.String(),
KeyType: keystore.Ed25519,
},
},
})
if err != nil {
return nil, fmt.Errorf("failed to generate exportable key: %w", err)
}

er, err := ks.ExportKeys(ctx, keystore.ExportKeysRequest{
Keys: []keystore.ExportKeyParam{
{
KeyName: path.String(),
Enc: keystore.EncryptionParams{
Password: password,
ScryptParams: keystore.DefaultScryptParams,
},
},
},
})
if err != nil {
return nil, fmt.Errorf("failed to export key: %w", err)
}

envelope := Envelope{
Type: TypeCSA,
Keys: er.Keys,
ExportFormat: exportFormat,
}

data, err := json.Marshal(&envelope)
if err != nil {
return nil, fmt.Errorf("failed to marshal envelope: %w", err)
}

return data, nil
}

func FromEncryptedCSAKey(data []byte, password string) ([]byte, error) {
envelope := Envelope{}
err := json.Unmarshal(data, &envelope)
if err != nil {
return nil, fmt.Errorf("could not unmarshal import data into envelope: %w", err)
}

if envelope.ExportFormat != exportFormat {
return nil, fmt.Errorf("invalid export format: %w", ErrInvalidExportFormat)
}

if envelope.Type != TypeCSA {
return nil, fmt.Errorf("invalid key type: expected %s, got %s", TypeCSA, envelope.Type)
}

if len(envelope.Keys) != 1 {
return nil, fmt.Errorf("expected exactly one key in envelope, got %d", len(envelope.Keys))
}

keypb, err := decryptKey(envelope.Keys[0].Data, password)
if err != nil {
return nil, err
}

return keypb.PrivateKey, nil
}
78 changes: 78 additions & 0 deletions keystore/corekeys/csa_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package corekeys

import (
"crypto/ed25519"
"testing"

"github.com/stretchr/testify/require"

"github.com/smartcontractkit/chainlink-common/keystore"
)

func TestCSAKeyRoundTrip(t *testing.T) {
t.Parallel()
ctx := t.Context()
password := "test-password"

st := keystore.NewMemoryStorage()
ks, err := keystore.LoadKeystore(ctx, st, "test",
keystore.WithScryptParams(keystore.FastScryptParams),
)
require.NoError(t, err)

coreshimKs := NewStore(ks)

encryptedKey, err := coreshimKs.GenerateEncryptedCSAKey(ctx, password)
require.NoError(t, err)
require.NotEmpty(t, encryptedKey)

csaKeyPath := keystore.NewKeyPath(TypeCSA, nameDefault)
getKeysResp, err := ks.GetKeys(ctx, keystore.GetKeysRequest{
KeyNames: []string{csaKeyPath.String()},
})
require.NoError(t, err)
require.Len(t, getKeysResp.Keys, 1)

storedPublicKey := getKeysResp.Keys[0].KeyInfo.PublicKey
require.NotEmpty(t, storedPublicKey)

privateKey, err := FromEncryptedCSAKey(encryptedKey, password)
require.NoError(t, err)
require.NotEmpty(t, privateKey)

require.Len(t, privateKey, 64)

derivedPublicKey := ed25519.PrivateKey(privateKey).Public().(ed25519.PublicKey)
require.Equal(t, storedPublicKey, []byte(derivedPublicKey))
}

func TestCSAKeyImportWithWrongPassword(t *testing.T) {
t.Parallel()
ctx := t.Context()
password := "test-password"
wrongPassword := "wrong-password"

st := keystore.NewMemoryStorage()
ks, err := keystore.LoadKeystore(ctx, st, "test",
keystore.WithScryptParams(keystore.FastScryptParams),
)
require.NoError(t, err)

coreshimKs := NewStore(ks)

encryptedKey, err := coreshimKs.GenerateEncryptedCSAKey(ctx, password)
require.NoError(t, err)
require.NotNil(t, encryptedKey)

_, err = FromEncryptedCSAKey(encryptedKey, wrongPassword)
require.Error(t, err)
require.Contains(t, err.Error(), "could not decrypt data")
}

func TestCSAKeyImportInvalidFormat(t *testing.T) {
t.Parallel()

_, err := FromEncryptedCSAKey([]byte("invalid json"), "password")
require.Error(t, err)
require.Contains(t, err.Error(), "could not unmarshal import data")
}
136 changes: 136 additions & 0 deletions keystore/corekeys/ocrkeybundle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package corekeys

import (
"context"
"encoding/json"
"fmt"
"strings"

chainselectors "github.com/smartcontractkit/chain-selectors"
"github.com/smartcontractkit/chainlink-common/keystore"
"github.com/smartcontractkit/chainlink-common/keystore/ocr2offchain"
)

const (
TypeOCR = "ocr"
PrefixOCR2Onchain = "ocr2_onchain"
)

type OCRKeyBundle struct {
ChainType string
OffchainSigningKey []byte
OffchainEncryptionKey []byte
OnchainSigningKey []byte
}

func (ks *Store) GenerateEncryptedOCRKeyBundle(ctx context.Context, chainType string, password string) ([]byte, error) {
_, err := ocr2offchain.CreateOCR2OffchainKeyring(ctx, ks.Keystore, nameDefault)
if err != nil {
return nil, err
}

var onchainKeyPath keystore.KeyPath
switch chainType {
case chainselectors.FamilyEVM:
path := keystore.NewKeyPath(PrefixOCR2Onchain, nameDefault, chainType)
_, ierr := ks.CreateKeys(ctx, keystore.CreateKeysRequest{
Keys: []keystore.CreateKeyRequest{
{
KeyName: path.String(),
KeyType: keystore.ECDSA_S256,
},
},
})
if ierr != nil {
return nil, fmt.Errorf("failed to generate exportable key: %w", ierr)
}

onchainKeyPath = path
default:
return nil, fmt.Errorf("unsupported chain type: %s", chainType)
}

er, err := ks.ExportKeys(ctx, keystore.ExportKeysRequest{
Keys: []keystore.ExportKeyParam{
{
KeyName: keystore.NewKeyPath(ocr2offchain.PrefixOCR2Offchain, nameDefault, ocr2offchain.OCR2OffchainSigning).String(),
Enc: keystore.EncryptionParams{
Password: password,
ScryptParams: keystore.DefaultScryptParams,
},
},
{
KeyName: keystore.NewKeyPath(ocr2offchain.PrefixOCR2Offchain, nameDefault, ocr2offchain.OCR2OffchainEncryption).String(),
Enc: keystore.EncryptionParams{
Password: password,
ScryptParams: keystore.DefaultScryptParams,
},
},
{
KeyName: onchainKeyPath.String(),
Enc: keystore.EncryptionParams{
Password: password,
ScryptParams: keystore.DefaultScryptParams,
},
},
},
})
if err != nil {
return nil, fmt.Errorf("failed to export OCR key bundle: %w", err)
}

envelope := Envelope{
Type: TypeOCR,
Keys: er.Keys,
ExportFormat: exportFormat,
}

data, err := json.Marshal(&envelope)
if err != nil {
return nil, fmt.Errorf("failed to marshal OCR key bundle envelope: %w", err)
}

return data, nil
}

func FromEncryptedOCRKeyBundle(data []byte, password string) (*OCRKeyBundle, error) {
envelope := Envelope{}
err := json.Unmarshal(data, &envelope)
if err != nil {
return nil, fmt.Errorf("could not unmarshal import data into envelope: %w", err)
}

if envelope.ExportFormat != exportFormat {
return nil, fmt.Errorf("invalid export format: %w", ErrInvalidExportFormat)
}

if envelope.Type != TypeOCR {
return nil, fmt.Errorf("invalid key type: expected %s, got %s", TypeOCR, envelope.Type)
}

if len(envelope.Keys) != 3 {
return nil, fmt.Errorf("expected exactly three keys in envelope, got %d", len(envelope.Keys))
}

bundle := &OCRKeyBundle{}

for _, key := range envelope.Keys {
keypb, err := decryptKey(key.Data, password)
if err != nil {
return nil, err
}

if strings.Contains(key.KeyName, ocr2offchain.OCR2OffchainSigning) {
bundle.OffchainSigningKey = keypb.PrivateKey
} else if strings.Contains(key.KeyName, ocr2offchain.OCR2OffchainEncryption) {
bundle.OffchainEncryptionKey = keypb.PrivateKey
} else if strings.Contains(key.KeyName, PrefixOCR2Onchain) {
bundle.OnchainSigningKey = keypb.PrivateKey
// Extract chain type from the key path
keyPath := keystore.NewKeyPathFromString(key.KeyName)
bundle.ChainType = strings.ToLower(keyPath.Base())
}
}

return bundle, nil
}
Loading
Loading