Skip to content

Commit

Permalink
Remove the KeyManager singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
mcamou committed Nov 12, 2024
1 parent f42db5f commit a47f081
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 41 deletions.
4 changes: 3 additions & 1 deletion cmd/masa-node/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package main
import (
"github.com/masa-finance/masa-oracle/node"
"github.com/masa-finance/masa-oracle/pkg/config"
"github.com/masa-finance/masa-oracle/pkg/masacrypto"
pubsub "github.com/masa-finance/masa-oracle/pkg/pubsub"
"github.com/masa-finance/masa-oracle/pkg/workers"
)

func initOptions(cfg *config.AppConfig) ([]node.Option, *workers.WorkHandlerManager, *pubsub.PublicKeySubscriptionHandler) {
func initOptions(cfg *config.AppConfig, keyManager *masacrypto.KeyManager) ([]node.Option, *workers.WorkHandlerManager, *pubsub.PublicKeySubscriptionHandler) {
// WorkerManager configuration
// TODO: this needs to be moved under config, but now it's here as there are import cycles given singletons
workerManagerOptions := []workers.WorkerOptionFunc{
Expand All @@ -29,6 +30,7 @@ func initOptions(cfg *config.AppConfig) ([]node.Option, *workers.WorkHandlerMana
node.WithMasaDir(cfg.MasaDir),
node.WithCachePath(cachePath),
node.WithLlmCfUrl(cfg.LLMCfUrl),
node.WithKeyManager(keyManager),
}

if cfg.TwitterScraper {
Expand Down
7 changes: 5 additions & 2 deletions cmd/masa-node/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ func main() {
cfg.LogConfig()
cfg.SetupLogging()

keyManager := masacrypto.KeyManagerInstance()
keyManager, err := masacrypto.NewKeyManager(cfg.PrivateKey, cfg.PrivateKeyFile)
if err != nil {
logrus.Fatal("[-] Failed to initialize keys:", err)
}

// Create a cancellable context
ctx, cancel := context.WithCancel(context.Background())
Expand Down Expand Up @@ -70,7 +73,7 @@ func main() {
logrus.Warn("No staking event found for this address")
}

masaNodeOptions, workHandlerManager, pubKeySub := initOptions(cfg)
masaNodeOptions, workHandlerManager, pubKeySub := initOptions(cfg, keyManager)
// Create a new OracleNode
masaNode, err := node.NewOracleNode(ctx, masaNodeOptions...)

Expand Down
8 changes: 8 additions & 0 deletions node/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"

"github.com/masa-finance/masa-oracle/node/types"
"github.com/masa-finance/masa-oracle/pkg/masacrypto"

"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/protocol"
Expand Down Expand Up @@ -33,6 +34,7 @@ type NodeOption struct {
MasaDir string
CachePath string
LLMCloudflareUrl string
KeyManager *masacrypto.KeyManager
}

type PubSubHandlers struct {
Expand Down Expand Up @@ -171,3 +173,9 @@ func WithLlmCfUrl(url string) Option {
o.LLMCloudflareUrl = url
}
}

func WithKeyManager(km *masacrypto.KeyManager) Option {
return func(o *NodeOption) {
o.KeyManager = km
}
}
5 changes: 2 additions & 3 deletions node/oracle_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"github.com/masa-finance/masa-oracle/internal/versioning"
"github.com/masa-finance/masa-oracle/pkg/chain"
"github.com/masa-finance/masa-oracle/pkg/config"
"github.com/masa-finance/masa-oracle/pkg/masacrypto"
myNetwork "github.com/masa-finance/masa-oracle/pkg/network"
"github.com/masa-finance/masa-oracle/pkg/pubsub"
)
Expand Down Expand Up @@ -103,7 +102,7 @@ func NewOracleNode(ctx context.Context, opts ...Option) (*OracleNode, error) {
if o.RandomIdentity {
libp2pOptions = append(libp2pOptions, libp2p.RandomIdentity)
} else {
libp2pOptions = append(libp2pOptions, libp2p.Identity(masacrypto.KeyManagerInstance().Libp2pPrivKey))
libp2pOptions = append(libp2pOptions, libp2p.Identity(o.KeyManager.Libp2pPrivKey))
}

securityOptions := []libp2p.Option{
Expand Down Expand Up @@ -180,7 +179,7 @@ func (node *OracleNode) getNodeData() *pubsub.NodeData {
if node.Options.RandomIdentity {
publicEthAddress, _ = node.generateEthHexKeyForRandomIdentity()
} else {
publicEthAddress = masacrypto.KeyManagerInstance().EthAddress
publicEthAddress = node.Options.KeyManager.EthAddress
}

nodeData := pubsub.NewNodeData(node.priorityAddrs, node.Host.ID(), publicEthAddress, pubsub.ActivityJoined)
Expand Down
3 changes: 1 addition & 2 deletions pkg/api/handlers_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (

"github.com/masa-finance/masa-oracle/pkg/consensus"
"github.com/masa-finance/masa-oracle/pkg/db"
"github.com/masa-finance/masa-oracle/pkg/masacrypto"
"github.com/sirupsen/logrus"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -181,7 +180,7 @@ func (api *API) PublishPublicKeyHandler() gin.HandlerFunc {
return
}

keyManager := masacrypto.KeyManagerInstance()
keyManager := api.Node.Options.KeyManager

// Set the data to be signed as the signer's Peer ID
data := []byte(api.Node.Host.ID().String())
Expand Down
57 changes: 24 additions & 33 deletions pkg/masacrypto/key_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ import (

ethCrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/sirupsen/logrus"

"github.com/masa-finance/masa-oracle/pkg/config"
)

// KeyManager is meant to simplify the management of cryptographic keys used in the application.
Expand Down Expand Up @@ -57,64 +54,58 @@ type KeyManager struct {
EthAddress string // Ethereum format address
}

// KeyManagerInstance returns the singleton instance of KeyManager, initializing it if necessary.
func KeyManagerInstance() *KeyManager {
once.Do(func() {
cfg := config.GetInstance()
keyManagerInstance = &KeyManager{}
if err := keyManagerInstance.loadPrivateKey(cfg.PrivateKey, cfg.PrivateKeyFile); err != nil {
logrus.Fatal("[-] Failed to initialize keys:", err)
}
})
return keyManagerInstance
}

// loadPrivateKey loads the node's private key from the environment or a file.
// It first checks for a private key set via the PrivateKey config. If not found,
// it tries to load the key from the PrivateKeyFile. As a last resort, it
// generates a new key and saves it to the private key file.

// NewKeyManager returns an initialized KeyManager. It first checks for a
// private key set via the PrivateKey config. If not found, it tries to
// load the key from the PrivateKeyFile. As a last resort, it generates
// a new key and saves it to the private key file.
// The private key is loaded into both Libp2p and ECDSA formats for use by
// different parts of the system. The public key and hex-encoded key representations
// are also derived.
func (km *KeyManager) loadPrivateKey(privateKey string, privateKeyFile string) (err error) {
var keyFile string
func NewKeyManager(privateKey string, privateKeyFile string) (*KeyManager, error) {
km := &KeyManager{}

var err error

if len(privateKey) > 0 {
km.Libp2pPrivKey, err = getPrivateKeyFromEnv(privateKey)
if err != nil {
return err
return nil, err
}
} else {
keyFile = privateKeyFile
// Check if the private key file exists
km.Libp2pPrivKey, err = getPrivateKeyFromFile(keyFile)
km.Libp2pPrivKey, err = getPrivateKeyFromFile(privateKeyFile)
if err != nil {
km.Libp2pPrivKey, err = generateNewPrivateKey(keyFile)
km.Libp2pPrivKey, err = generateNewPrivateKey(privateKeyFile)
if err != nil {
return err
return nil, err
}
}
}

km.Libp2pPubKey = km.Libp2pPrivKey.GetPublic()

// After obtaining the libp2p privKey, convert it to an ECDSA private key
km.EcdsaPrivKey, err = libp2pPrivateKeyToEcdsa(km.Libp2pPrivKey)
if err != nil {
return err
return nil, err
}

err = saveEcdesaPrivateKeyToFile(km.EcdsaPrivKey, fmt.Sprintf("%s.ecdsa", keyFile))
err = saveEcdesaPrivateKeyToFile(km.EcdsaPrivKey, fmt.Sprintf("%s.ecdsa", privateKeyFile))
if err != nil {
return err
return nil, err
}

km.HexPrivKey, err = getHexEncodedPrivateKey(km.Libp2pPrivKey)
if err != nil {
return err
return nil, err
}

km.EcdsaPubKey = &km.EcdsaPrivKey.PublicKey
km.HexPubKey, err = getHexEncodedPublicKey(km.Libp2pPubKey)
if err != nil {
return err
return nil, err
}

km.EthAddress = ethCrypto.PubkeyToAddress(km.EcdsaPrivKey.PublicKey).Hex()
return nil
return km, nil
}

0 comments on commit a47f081

Please sign in to comment.