Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(cleanup): Remove the AppConfig and KeyManager singletons #625

Merged
merged 14 commits into from
Nov 12, 2024
Merged
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
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ stake: build
client: build
@./bin/masa-node-cli

# TODO Add -race and fix race conditions
# TODO: Add -race and fix race conditions
test: contracts/node_modules
@go test -coverprofile=coverage.txt -covermode=atomic -v -count=1 -shuffle=on ./...

Expand Down
24 changes: 18 additions & 6 deletions cmd/masa-node/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,23 @@
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) {

Check warning on line 11 in cmd/masa-node/config.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/config.go#L11

Added line #L11 was not covered by tests
// WorkerManager configuration
// XXX: this needs to be moved under config, but now it's here as there are import cycles given singletons
workerManagerOptions := []workers.WorkerOptionFunc{}
// TODO: this needs to be moved under config, but now it's here as there are import cycles given singletons
workerManagerOptions := []workers.WorkerOptionFunc{
workers.WithLlmChatUrl(cfg.LLMChatUrl),
workers.WithMasaDir(cfg.MasaDir),
}

cachePath := cfg.CachePath
if cachePath == "" {
cachePath = cfg.MasaDir + "/cache"
}

Check warning on line 22 in cmd/masa-node/config.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/config.go#L13-L22

Added lines #L13 - L22 were not covered by tests

masaNodeOptions := []node.Option{
node.EnableStaked,
Expand All @@ -19,6 +28,10 @@
node.WithVersion(cfg.Version),
node.WithPort(cfg.PortNbr),
node.WithBootNodes(cfg.Bootnodes...),
node.WithMasaDir(cfg.MasaDir),
node.WithCachePath(cachePath),
node.WithLLMCloudFlareURL(cfg.LLMCfUrl),
node.WithKeyManager(keyManager),

Check warning on line 34 in cmd/masa-node/config.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/config.go#L31-L34

Added lines #L31 - L34 were not covered by tests
}

if cfg.TwitterScraper {
Expand Down Expand Up @@ -50,8 +63,7 @@
blockChainEventTracker := node.NewBlockChain()
pubKeySub := &pubsub.PublicKeySubscriptionHandler{}

// TODO: Where the config is involved, move to the config the generation of
// Node options
// TODO: Where the config is involved, move to the config the generation of Node options

Check warning on line 66 in cmd/masa-node/config.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/config.go#L66

Added line #L66 was not covered by tests
masaNodeOptions = append(masaNodeOptions, []node.Option{
// Register the worker manager
node.WithMasaProtocolHandler(
Expand All @@ -68,7 +80,7 @@
// and other peers can do work we only need to check this here
// if this peer can or cannot scrape or write that is checked in other places
masaNodeOptions = append(masaNodeOptions,
node.WithService(blockChainEventTracker.Start(config.GetInstance().MasaDir)),
node.WithService(blockChainEventTracker.Start(cfg.MasaDir)),

Check warning on line 83 in cmd/masa-node/config.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/config.go#L83

Added line #L83 was not covered by tests
)
}

Expand Down
15 changes: 9 additions & 6 deletions cmd/masa-node/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,16 @@
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)
}

Check warning on line 40 in cmd/masa-node/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/main.go#L37-L40

Added lines #L37 - L40 were not covered by tests

// Create a cancellable context
ctx, cancel := context.WithCancel(context.Background())

if cfg.Faucet {
err := handleFaucet(keyManager.EcdsaPrivKey)
err := handleFaucet(cfg.RpcUrl, keyManager.EcdsaPrivKey)

Check warning on line 46 in cmd/masa-node/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/main.go#L46

Added line #L46 was not covered by tests
if err != nil {
logrus.Errorf("[-] %v", err)
os.Exit(1)
Expand All @@ -51,7 +54,7 @@
}

if cfg.StakeAmount != "" {
err := handleStaking(keyManager.EcdsaPrivKey)
err := handleStaking(cfg.RpcUrl, keyManager.EcdsaPrivKey, cfg.StakeAmount)

Check warning on line 57 in cmd/masa-node/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/main.go#L57

Added line #L57 was not covered by tests
if err != nil {
logrus.Warningf("%v", err)
} else {
Expand All @@ -61,7 +64,7 @@
}

// Verify the staking event
isStaked, err := staking.VerifyStakingEvent(keyManager.EthAddress)
isStaked, err := staking.VerifyStakingEvent(cfg.RpcUrl, keyManager.EthAddress)

Check warning on line 67 in cmd/masa-node/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/main.go#L67

Added line #L67 was not covered by tests
if err != nil {
logrus.Error(err)
}
Expand All @@ -70,7 +73,7 @@
logrus.Warn("No staking event found for this address")
}

masaNodeOptions, workHandlerManager, pubKeySub := initOptions(cfg)
masaNodeOptions, workHandlerManager, pubKeySub := initOptions(cfg, keyManager)

Check warning on line 76 in cmd/masa-node/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/main.go#L76

Added line #L76 was not covered by tests
// Create a new OracleNode
masaNode, err := node.NewOracleNode(ctx, masaNodeOptions...)

Expand All @@ -95,7 +98,7 @@
}

// Init cache resolver
db.InitResolverCache(masaNode, keyManager)
db.InitResolverCache(masaNode, keyManager, cfg.AllowedPeerId, cfg.AllowedPeerPublicKey, cfg.Validator)

Check warning on line 101 in cmd/masa-node/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/main.go#L101

Added line #L101 was not covered by tests

// Cancel the context when SIGINT is received
go handleSignals(cancel, masaNode, cfg)
Expand Down
11 changes: 5 additions & 6 deletions cmd/masa-node/staking.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,19 @@
"github.com/fatih/color"
"github.com/sirupsen/logrus"

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

func handleStaking(privateKey *ecdsa.PrivateKey) error {
func handleStaking(rpcUrl string, privateKey *ecdsa.PrivateKey, stakeAmount string) error {

Check warning on line 15 in cmd/masa-node/staking.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/staking.go#L15

Added line #L15 was not covered by tests
// Staking logic
// Convert the stake amount to the smallest unit, assuming 18 decimal places
amountBigInt, ok := new(big.Int).SetString(config.GetInstance().StakeAmount, 10)
amountBigInt, ok := new(big.Int).SetString(stakeAmount, 10)

Check warning on line 18 in cmd/masa-node/staking.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/staking.go#L18

Added line #L18 was not covered by tests
if !ok {
logrus.Fatal("Invalid stake amount")
}
amountInSmallestUnit := new(big.Int).Mul(amountBigInt, big.NewInt(1e18))

stakingClient, err := staking.NewClient(privateKey)
stakingClient, err := staking.NewClient(rpcUrl, privateKey)

Check warning on line 24 in cmd/masa-node/staking.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/staking.go#L24

Added line #L24 was not covered by tests
if err != nil {
return err
}
Expand Down Expand Up @@ -86,8 +85,8 @@
return nil
}

func handleFaucet(privateKey *ecdsa.PrivateKey) error {
faucetClient, err := staking.NewClient(privateKey)
func handleFaucet(rpcUrl string, privateKey *ecdsa.PrivateKey) error {
faucetClient, err := staking.NewClient(rpcUrl, privateKey)

Check warning on line 89 in cmd/masa-node/staking.go

View check run for this annotation

Codecov / codecov/patch

cmd/masa-node/staking.go#L88-L89

Added lines #L88 - L89 were not covered by tests
if err != nil {
logrus.Error("[-] Failed to create staking client:", err)
return err
Expand Down
2 changes: 1 addition & 1 deletion docs/oracle-node/twitter-sentiment.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const (

#### Masa cli or code integration

Tweets are fetched using the Twitter Scraper library, as seen in the [llmbridge](file:///Users/john/Projects/masa/masa-oracle/pkg/llmbridge/sentiment_twitter.go#1%2C9-1%2C9) package. This process does not require Twitter API keys, making it accessible and straightforward.
Tweets are fetched using the Twitter Scraper library, as seen in the [llmbridge](../pkg/llmbridge/sentiment_twitter.go#1%2C9-1%2C9) package. This process does not require Twitter API keys, making it accessible and straightforward.

```go
func AnalyzeSentimentTweets(tweets []*twitterscraper.Tweet, model string) (string, string, error) { ... }
Expand Down
29 changes: 29 additions & 0 deletions node/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"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 All @@ -30,6 +31,10 @@
MasaProtocolHandlers map[string]network.StreamHandler
Environment string
Version string
MasaDir string
CachePath string
LLMCloudflareUrl string
KeyManager *masacrypto.KeyManager
}

type PubSubHandlers struct {
Expand Down Expand Up @@ -150,3 +155,27 @@
o.PortNbr = port
}
}

func WithMasaDir(directory string) Option {
return func(o *NodeOption) {
o.MasaDir = directory
}

Check warning on line 162 in node/options.go

View check run for this annotation

Codecov / codecov/patch

node/options.go#L159-L162

Added lines #L159 - L162 were not covered by tests
}

func WithCachePath(path string) Option {
return func(o *NodeOption) {
o.CachePath = path
}

Check warning on line 168 in node/options.go

View check run for this annotation

Codecov / codecov/patch

node/options.go#L165-L168

Added lines #L165 - L168 were not covered by tests
}

func WithLLMCloudFlareURL(url string) Option {
return func(o *NodeOption) {
o.LLMCloudflareUrl = url
}

Check warning on line 174 in node/options.go

View check run for this annotation

Codecov / codecov/patch

node/options.go#L171-L174

Added lines #L171 - L174 were not covered by tests
}

func WithKeyManager(km *masacrypto.KeyManager) Option {
return func(o *NodeOption) {
o.KeyManager = km
}

Check warning on line 180 in node/options.go

View check run for this annotation

Codecov / codecov/patch

node/options.go#L177-L180

Added lines #L177 - L180 were not covered by tests
}
21 changes: 10 additions & 11 deletions node/oracle_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"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 All @@ -48,6 +47,7 @@
Blockchain *chain.Chain
Options NodeOption
Context context.Context
Config *config.AppConfig
}

// GetMultiAddrs returns the priority multiaddr for this node.
Expand Down Expand Up @@ -102,7 +102,7 @@
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))

Check warning on line 105 in node/oracle_node.go

View check run for this annotation

Codecov / codecov/patch

node/oracle_node.go#L105

Added line #L105 was not covered by tests
}

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

Check warning on line 182 in node/oracle_node.go

View check run for this annotation

Codecov / codecov/patch

node/oracle_node.go#L182

Added line #L182 was not covered by tests
}

nodeData := pubsub.NewNodeData(node.priorityAddrs, node.Host.ID(), publicEthAddress, pubsub.ActivityJoined)
Expand Down Expand Up @@ -245,7 +245,7 @@
go p(node.Context, node)
}

go myNetwork.Discover(node.Context, node.Host, node.DHT, node.Protocol)
go myNetwork.Discover(node.Context, node.Options.Bootnodes, node.Host, node.DHT, node.Protocol)

Check warning on line 248 in node/oracle_node.go

View check run for this annotation

Codecov / codecov/patch

node/oracle_node.go#L248

Added line #L248 was not covered by tests

nodeData := node.NodeTracker.GetNodeData(node.Host.ID().String())
if nodeData == nil {
Expand Down Expand Up @@ -328,15 +328,14 @@

// IsWorker determines if the OracleNode is configured to act as an actor.
// An actor node is one that has at least one of the following scrapers enabled:
// TwitterScraper, DiscordScraper, or WebScraper.
// TwitterScraper, DiscordScraper, TelegramScraper or WebScraper.
// It returns true if any of these scrapers are enabled, otherwise false.
func (node *OracleNode) IsWorker() bool {
// need to get this by node data
cfg := config.GetInstance()
if cfg.TwitterScraper || cfg.DiscordScraper || cfg.TelegramScraper || cfg.WebScraper {
return true
}
return false
return node.Options.IsTwitterScraper ||
node.Options.IsDiscordScraper ||
node.Options.IsTelegramScraper ||
node.Options.IsWebScraper

Check warning on line 338 in node/oracle_node.go

View check run for this annotation

Codecov / codecov/patch

node/oracle_node.go#L335-L338

Added lines #L335 - L338 were not covered by tests
}

// IsPublisher returns true if this node is a publisher node.
Expand All @@ -348,7 +347,7 @@

// Version returns the current version string of the oracle node software.
func (node *OracleNode) Version() string {
return config.GetInstance().Version
return node.Options.Version

Check warning on line 350 in node/oracle_node.go

View check run for this annotation

Codecov / codecov/patch

node/oracle_node.go#L350

Added line #L350 was not covered by tests
}

// LogActiveTopics logs the currently active topic names to the
Expand Down
2 changes: 1 addition & 1 deletion pkg/api/handlers_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@
}
api.sendTrackingEvent(data_types.LLMChat, bodyBytes)

cfUrl := config.GetInstance().LLMCfUrl
cfUrl := api.Node.Options.LLMCloudflareUrl

Check warning on line 784 in pkg/api/handlers_data.go

View check run for this annotation

Codecov / codecov/patch

pkg/api/handlers_data.go#L784

Added line #L784 was not covered by tests
if cfUrl == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Errorf("missing env LLM_CF_URL")})
return
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 @@

"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 @@
return
}

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

Check warning on line 183 in pkg/api/handlers_node.go

View check run for this annotation

Codecov / codecov/patch

pkg/api/handlers_node.go#L183

Added line #L183 was not covered by tests

// Set the data to be signed as the signer's Peer ID
data := []byte(api.Node.Host.ID().String())
Expand Down
1 change: 1 addition & 0 deletions pkg/config/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
instance = &AppConfig{}

instance.setDefaultConfig()
// TODO Shouldn't the env vars override the file config, instead of the other way around?

Check warning on line 94 in pkg/config/app.go

View check run for this annotation

Codecov / codecov/patch

pkg/config/app.go#L94

Added line #L94 was not covered by tests
instance.setEnvVariableConfig()

instance.setFileConfig(viper.GetString("FILE_PATH"))
Expand Down
13 changes: 3 additions & 10 deletions pkg/db/access_control.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@

import (
"encoding/hex"

libp2pCrypto "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
"github.com/sirupsen/logrus"

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

Expand All @@ -34,14 +34,7 @@
}

// Verifier checks if the given host is allowed to access to the database and verifies the signature
func Verifier(h host.Host, data []byte, signature []byte) bool {
// Load configuration instance
cfg := config.GetInstance()

// Get allowed peer ID and public key from the configuration
allowedPeerID := cfg.AllowedPeerId
allowedPeerPubKeyString := cfg.AllowedPeerPublicKey

func Verifier(h host.Host, data []byte, signature []byte, allowedPeerID string, allowedPeerPubKeyString string, isValidator bool) bool {

Check warning on line 37 in pkg/db/access_control.go

View check run for this annotation

Codecov / codecov/patch

pkg/db/access_control.go#L37

Added line #L37 was not covered by tests
if allowedPeerID == "" || allowedPeerPubKeyString == "" {
logrus.Warn("[-] Allowed peer ID or public key not found in configuration")
return false
Expand Down Expand Up @@ -81,7 +74,7 @@
return false
}

if cfg.Validator {
if isValidator {

Check warning on line 77 in pkg/db/access_control.go

View check run for this annotation

Codecov / codecov/patch

pkg/db/access_control.go#L77

Added line #L77 was not covered by tests

logrus.WithFields(logrus.Fields{
"hostID": h.ID().String(),
Expand Down
2 changes: 1 addition & 1 deletion pkg/db/operations.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// TODO Rename this to something else, this is NOT a database (it just stores data in the DHT and in a cache)
// TODO: Rename this to something else, this is NOT a database (it just stores data in the DHT and in a cache)
package db

import (
Expand Down
11 changes: 4 additions & 7 deletions pkg/db/resolver_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,10 @@
// The purpose of this function is to initialize the resolver cache and perform any necessary setup or configuration. It associates the resolver cache with the provided Masa Oracle node and key manager.
//
// Note: The specific implementation details of the `InitResolverCache` function are not provided in the given code snippet. The function signature suggests that it initializes the resolver cache, but the actual initialization logic would be present in the function body.
func InitResolverCache(node *node.OracleNode, keyManager *masacrypto.KeyManager) {
func InitResolverCache(node *node.OracleNode, keyManager *masacrypto.KeyManager, allowedPeerID string, allowedPeerPubKeyString string, isValidator bool) {

Check warning on line 46 in pkg/db/resolver_cache.go

View check run for this annotation

Codecov / codecov/patch

pkg/db/resolver_cache.go#L46

Added line #L46 was not covered by tests
var err error
cachePath := config.GetInstance().CachePath
if cachePath == "" {
cachePath = config.GetInstance().MasaDir + "/cache"
}
cache, err = leveldb.NewDatastore(cachePath, nil)

cache, err = leveldb.NewDatastore(node.Options.CachePath, nil)

Check warning on line 49 in pkg/db/resolver_cache.go

View check run for this annotation

Codecov / codecov/patch

pkg/db/resolver_cache.go#L48-L49

Added lines #L48 - L49 were not covered by tests
if err != nil {
log.Fatal(err)
}
Expand All @@ -60,7 +57,7 @@
if err != nil {
logrus.Errorf("[-] Error signing data: %v", err)
}
_ = Verifier(node.Host, data, signature)
_ = Verifier(node.Host, data, signature, allowedPeerID, allowedPeerPubKeyString, isValidator)

Check warning on line 60 in pkg/db/resolver_cache.go

View check run for this annotation

Codecov / codecov/patch

pkg/db/resolver_cache.go#L60

Added line #L60 was not covered by tests

go monitorNodeData(context.Background(), node)

Expand Down
Loading
Loading