mirror of
https://github.com/sonr-io/sonr.git
synced 2026-08-02 17:31:39 +00:00
@@ -0,0 +1,214 @@
|
||||
package context
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/client"
|
||||
"github.com/cosmos/cosmos-sdk/client/tx"
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
|
||||
"github.com/cosmos/cosmos-sdk/types/tx/signing"
|
||||
)
|
||||
|
||||
// BroadcastTx broadcasts a transaction to the blockchain using the stored client context
|
||||
func (sc *SonrContext) BroadcastTx(txBytes []byte) error {
|
||||
clientCtx, err := sc.GetClientContext()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get client context: %w", err)
|
||||
}
|
||||
|
||||
// Create broadcast request
|
||||
txReq := &txtypes.BroadcastTxRequest{
|
||||
TxBytes: txBytes,
|
||||
Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC,
|
||||
}
|
||||
|
||||
// Get the gRPC client connection
|
||||
grpcConn := clientCtx.GRPCClient
|
||||
|
||||
// Create transaction service client
|
||||
txClient := txtypes.NewServiceClient(grpcConn)
|
||||
|
||||
// Broadcast the transaction
|
||||
res, err := txClient.BroadcastTx(context.Background(), txReq)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to broadcast transaction: %w", err)
|
||||
}
|
||||
|
||||
// Check if transaction was accepted
|
||||
if res.TxResponse.Code != 0 {
|
||||
return fmt.Errorf(
|
||||
"transaction failed with code %d: %s",
|
||||
res.TxResponse.Code,
|
||||
res.TxResponse.RawLog,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// BroadcastTxWithResponse broadcasts a transaction and returns the response
|
||||
func (sc *SonrContext) BroadcastTxWithResponse(
|
||||
txBytes []byte,
|
||||
) (*txtypes.BroadcastTxResponse, error) {
|
||||
clientCtx, err := sc.GetClientContext()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get client context: %w", err)
|
||||
}
|
||||
|
||||
// Create broadcast request
|
||||
txReq := &txtypes.BroadcastTxRequest{
|
||||
TxBytes: txBytes,
|
||||
Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC,
|
||||
}
|
||||
|
||||
// Get the gRPC client connection
|
||||
grpcConn := clientCtx.GRPCClient
|
||||
|
||||
// Create transaction service client
|
||||
txClient := txtypes.NewServiceClient(grpcConn)
|
||||
|
||||
// Broadcast the transaction
|
||||
res, err := txClient.BroadcastTx(context.Background(), txReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to broadcast transaction: %w", err)
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// SignAndBroadcastTx signs a transaction and broadcasts it
|
||||
func (sc *SonrContext) SignAndBroadcastTx(txBuilder client.TxBuilder) error {
|
||||
clientCtx, err := sc.GetClientContext()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get client context: %w", err)
|
||||
}
|
||||
|
||||
// Sign the transaction
|
||||
txFactory, err := tx.NewFactoryCLI(clientCtx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create tx factory: %w", err)
|
||||
}
|
||||
err = tx.Sign(clientCtx.CmdContext, txFactory, clientCtx.GetFromName(), txBuilder, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to sign transaction: %w", err)
|
||||
}
|
||||
|
||||
// Encode the transaction
|
||||
txBytes, err := clientCtx.TxConfig.TxEncoder()(txBuilder.GetTx())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encode transaction: %w", err)
|
||||
}
|
||||
|
||||
// Broadcast the transaction
|
||||
return sc.BroadcastTx(txBytes)
|
||||
}
|
||||
|
||||
// CreateUnsignedTx creates an unsigned transaction from messages
|
||||
func (sc *SonrContext) CreateUnsignedTx(msgs ...sdk.Msg) (client.TxBuilder, error) {
|
||||
clientCtx, err := sc.GetClientContext()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get client context: %w", err)
|
||||
}
|
||||
|
||||
// Create transaction builder
|
||||
txBuilder := clientCtx.TxConfig.NewTxBuilder()
|
||||
|
||||
// Set messages
|
||||
err = txBuilder.SetMsgs(msgs...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to set messages: %w", err)
|
||||
}
|
||||
|
||||
// Set gas limit and fees (these should be estimated or configured)
|
||||
txBuilder.SetGasLimit(200000) // Default gas limit
|
||||
|
||||
// Set fee amount (you may want to make this configurable)
|
||||
feeAmount := sdk.NewCoins(sdk.NewInt64Coin("usonr", 1000))
|
||||
txBuilder.SetFeeAmount(feeAmount)
|
||||
|
||||
return txBuilder, nil
|
||||
}
|
||||
|
||||
// EstimateGas estimates gas for a transaction
|
||||
func (sc *SonrContext) EstimateGas(txBuilder client.TxBuilder) (uint64, error) {
|
||||
clientCtx, err := sc.GetClientContext()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to get client context: %w", err)
|
||||
}
|
||||
|
||||
// Simulate the transaction to estimate gas
|
||||
simReq, err := sc.buildSimTx(clientCtx, txBuilder)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to build simulation request: %w", err)
|
||||
}
|
||||
|
||||
// Get the gRPC client connection
|
||||
grpcConn := clientCtx.GRPCClient
|
||||
|
||||
// Create transaction service client
|
||||
txClient := txtypes.NewServiceClient(grpcConn)
|
||||
|
||||
// Simulate the transaction
|
||||
simRes, err := txClient.Simulate(context.Background(), simReq)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to simulate transaction: %w", err)
|
||||
}
|
||||
|
||||
// Return estimated gas with some buffer
|
||||
return simRes.GasInfo.GasUsed + 10000, nil
|
||||
}
|
||||
|
||||
// buildSimTx builds a simulation request from a transaction builder
|
||||
func (sc *SonrContext) buildSimTx(
|
||||
clientCtx client.Context,
|
||||
txBuilder client.TxBuilder,
|
||||
) (*txtypes.SimulateRequest, error) {
|
||||
// Create a copy of the transaction builder for simulation
|
||||
simBuilder := clientCtx.TxConfig.NewTxBuilder()
|
||||
err := simBuilder.SetMsgs(txBuilder.GetTx().GetMsgs()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Get account info for signature
|
||||
fromAddr := clientCtx.GetFromAddress()
|
||||
if fromAddr.Empty() {
|
||||
return nil, fmt.Errorf("from address is empty")
|
||||
}
|
||||
|
||||
// Set dummy signature for simulation - we need a public key from the keyring
|
||||
keyInfo, err := clientCtx.Keyring.Key(clientCtx.GetFromName())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get key info: %w", err)
|
||||
}
|
||||
pubKey, err := keyInfo.GetPubKey()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get public key: %w", err)
|
||||
}
|
||||
|
||||
sigV2 := signing.SignatureV2{
|
||||
PubKey: pubKey,
|
||||
Data: &signing.SingleSignatureData{
|
||||
SignMode: signing.SignMode_SIGN_MODE_DIRECT,
|
||||
Signature: nil,
|
||||
},
|
||||
Sequence: 0,
|
||||
}
|
||||
|
||||
err = simBuilder.SetSignatures(sigV2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Encode the simulation transaction
|
||||
simTxBytes, err := clientCtx.TxConfig.TxEncoder()(simBuilder.GetTx())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &txtypes.SimulateRequest{
|
||||
TxBytes: simTxBytes,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// Package context provides the Sonr context system for managing node-specific state.
|
||||
package context
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"cosmossdk.io/log"
|
||||
"github.com/cosmos/cosmos-sdk/client"
|
||||
|
||||
"github.com/sonr-io/sonr/crypto/vrf"
|
||||
)
|
||||
|
||||
// SonrContext manages node-specific state and configuration
|
||||
type SonrContext struct {
|
||||
logger log.Logger
|
||||
|
||||
// VRF keypair for the node
|
||||
vrfPrivateKey vrf.PrivateKey
|
||||
vrfPublicKey vrf.PublicKey
|
||||
|
||||
// Client context for transaction operations
|
||||
clientCtx client.Context
|
||||
|
||||
// Synchronization for thread-safe access
|
||||
mu sync.RWMutex
|
||||
|
||||
// Initialization state
|
||||
initialized bool
|
||||
}
|
||||
|
||||
// NewSonrContext creates a new SonrContext instance
|
||||
func NewSonrContext(logger log.Logger) *SonrContext {
|
||||
if logger == nil {
|
||||
logger = log.NewNopLogger()
|
||||
}
|
||||
|
||||
return &SonrContext{
|
||||
logger: logger.With("component", "sonr-context"),
|
||||
initialized: false,
|
||||
}
|
||||
}
|
||||
|
||||
// SetClientContext sets the client context for transaction operations (thread-safe)
|
||||
func (sc *SonrContext) SetClientContext(clientCtx client.Context) {
|
||||
sc.mu.Lock()
|
||||
defer sc.mu.Unlock()
|
||||
|
||||
sc.clientCtx = clientCtx
|
||||
}
|
||||
|
||||
// GetClientContext returns the client context (thread-safe)
|
||||
func (sc *SonrContext) GetClientContext() (client.Context, error) {
|
||||
sc.mu.RLock()
|
||||
defer sc.mu.RUnlock()
|
||||
|
||||
if sc.clientCtx.Codec == nil {
|
||||
return client.Context{}, fmt.Errorf("client context not initialized")
|
||||
}
|
||||
|
||||
return sc.clientCtx, nil
|
||||
}
|
||||
|
||||
// Initialize loads the VRF keypair from storage
|
||||
func (sc *SonrContext) Initialize() error {
|
||||
sc.mu.Lock()
|
||||
defer sc.mu.Unlock()
|
||||
|
||||
if sc.initialized {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Load VRF private key from storage
|
||||
// Use hardcoded default path to avoid import cycle
|
||||
defaultNodeHome := os.ExpandEnv("$HOME/.sonr")
|
||||
vrfKeyPath := filepath.Join(defaultNodeHome, "vrf_secret.key")
|
||||
|
||||
// #nosec G304 - vrfKeyPath is constructed from trusted DefaultNodeHome constant
|
||||
vrfKeyData, err := os.ReadFile(vrfKeyPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read VRF secret key from %s: %w\n"+
|
||||
"VRF keys are required for multi-validator encryption features.\n"+
|
||||
"To generate VRF keys:\n"+
|
||||
" 1. For new nodes: Run 'snrd init <moniker>' to initialize with VRF keys\n"+
|
||||
" 2. For existing nodes: VRF keys should have been generated during init\n"+
|
||||
" 3. If encryption is not needed, disable it in DWN module params",
|
||||
vrfKeyPath, err)
|
||||
}
|
||||
|
||||
// Validate key size
|
||||
if len(vrfKeyData) != vrf.PrivateKeySize {
|
||||
return fmt.Errorf(
|
||||
"invalid VRF private key size: expected %d, got %d",
|
||||
vrf.PrivateKeySize,
|
||||
len(vrfKeyData),
|
||||
)
|
||||
}
|
||||
|
||||
sc.vrfPrivateKey = vrf.PrivateKey(vrfKeyData)
|
||||
|
||||
// Derive public key
|
||||
publicKey, ok := sc.vrfPrivateKey.Public()
|
||||
if !ok {
|
||||
return fmt.Errorf("failed to derive VRF public key from private key")
|
||||
}
|
||||
|
||||
sc.vrfPublicKey = publicKey
|
||||
sc.initialized = true
|
||||
|
||||
sc.logger.Info("SonrContext initialized successfully",
|
||||
"vrf_key_path", vrfKeyPath,
|
||||
"public_key_size", len(sc.vrfPublicKey),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetVRFPrivateKey returns the VRF private key (thread-safe)
|
||||
func (sc *SonrContext) GetVRFPrivateKey() (vrf.PrivateKey, error) {
|
||||
sc.mu.RLock()
|
||||
defer sc.mu.RUnlock()
|
||||
|
||||
if !sc.initialized {
|
||||
return nil, fmt.Errorf("SonrContext not initialized")
|
||||
}
|
||||
|
||||
return sc.vrfPrivateKey, nil
|
||||
}
|
||||
|
||||
// GetVRFPublicKey returns the VRF public key (thread-safe)
|
||||
func (sc *SonrContext) GetVRFPublicKey() (vrf.PublicKey, error) {
|
||||
sc.mu.RLock()
|
||||
defer sc.mu.RUnlock()
|
||||
|
||||
if !sc.initialized {
|
||||
return nil, fmt.Errorf("SonrContext not initialized")
|
||||
}
|
||||
|
||||
return sc.vrfPublicKey, nil
|
||||
}
|
||||
|
||||
// IsInitialized returns whether the context has been initialized (thread-safe)
|
||||
func (sc *SonrContext) IsInitialized() bool {
|
||||
sc.mu.RLock()
|
||||
defer sc.mu.RUnlock()
|
||||
|
||||
return sc.initialized
|
||||
}
|
||||
|
||||
// ComputeVRF generates VRF output for the given input using the loaded private key
|
||||
func (sc *SonrContext) ComputeVRF(input []byte) ([]byte, error) {
|
||||
sc.mu.RLock()
|
||||
defer sc.mu.RUnlock()
|
||||
|
||||
if !sc.initialized {
|
||||
return nil, fmt.Errorf("SonrContext not initialized")
|
||||
}
|
||||
|
||||
if len(input) == 0 {
|
||||
return nil, fmt.Errorf("VRF input cannot be empty")
|
||||
}
|
||||
|
||||
return sc.vrfPrivateKey.Compute(input), nil
|
||||
}
|
||||
|
||||
// ProveVRF generates VRF output with proof for the given input
|
||||
func (sc *SonrContext) ProveVRF(input []byte) (vrf []byte, proof []byte, err error) {
|
||||
sc.mu.RLock()
|
||||
defer sc.mu.RUnlock()
|
||||
|
||||
if !sc.initialized {
|
||||
return nil, nil, fmt.Errorf("SonrContext not initialized")
|
||||
}
|
||||
|
||||
if len(input) == 0 {
|
||||
return nil, nil, fmt.Errorf("VRF input cannot be empty")
|
||||
}
|
||||
|
||||
vrf, proof = sc.vrfPrivateKey.Prove(input)
|
||||
return vrf, proof, nil
|
||||
}
|
||||
|
||||
// Global context instance (initialized by the node)
|
||||
var globalSonrContext *SonrContext
|
||||
|
||||
// SetGlobalSonrContext sets the global SonrContext instance
|
||||
func SetGlobalSonrContext(ctx *SonrContext) {
|
||||
globalSonrContext = ctx
|
||||
}
|
||||
|
||||
// GetGlobalSonrContext returns the global SonrContext instance
|
||||
func GetGlobalSonrContext() *SonrContext {
|
||||
return globalSonrContext
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package context
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cosmossdk.io/log"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/sonr-io/sonr/crypto/vrf"
|
||||
)
|
||||
|
||||
// TestSonrContextInitialization tests SonrContext initialization with VRF keys
|
||||
func TestSonrContextInitialization(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
// Create temporary directory for test
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Test initialization without VRF keys
|
||||
t.Setenv("HOME", tmpDir)
|
||||
logger := log.NewNopLogger()
|
||||
ctx := NewSonrContext(logger)
|
||||
|
||||
err := ctx.Initialize()
|
||||
require.Error(err, "Should fail to initialize without VRF keys")
|
||||
require.False(ctx.IsInitialized(), "Context should not be initialized without VRF keys")
|
||||
}
|
||||
|
||||
// TestSonrContextWithValidKeys tests SonrContext with valid VRF keys
|
||||
func TestSonrContextWithValidKeys(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
// Create temporary directory for test
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("HOME", tmpDir)
|
||||
|
||||
// Create .sonr directory
|
||||
sonrDir := filepath.Join(tmpDir, ".sonr")
|
||||
err := os.MkdirAll(sonrDir, 0o750)
|
||||
require.NoError(err)
|
||||
|
||||
// Generate VRF keys
|
||||
privateKey, err := vrf.GenerateKey(nil)
|
||||
require.NoError(err)
|
||||
|
||||
// Write VRF keys
|
||||
vrfKeyPath := filepath.Join(sonrDir, "vrf_secret.key")
|
||||
err = os.WriteFile(vrfKeyPath, privateKey, 0o600)
|
||||
require.NoError(err)
|
||||
|
||||
// Test initialization with valid VRF keys
|
||||
logger := log.NewNopLogger()
|
||||
ctx := NewSonrContext(logger)
|
||||
|
||||
err = ctx.Initialize()
|
||||
require.NoError(err, "Should initialize successfully with valid VRF keys")
|
||||
require.True(ctx.IsInitialized(), "Context should be initialized")
|
||||
|
||||
// Test VRF key retrieval
|
||||
privKey, err := ctx.GetVRFPrivateKey()
|
||||
require.NoError(err)
|
||||
require.Len(privKey, vrf.PrivateKeySize)
|
||||
|
||||
pubKey, err := ctx.GetVRFPublicKey()
|
||||
require.NoError(err)
|
||||
require.Len(pubKey, vrf.PublicKeySize)
|
||||
}
|
||||
|
||||
// TestSonrContextInvalidKeySize tests handling of invalid key size
|
||||
func TestSonrContextInvalidKeySize(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
// Create temporary directory for test
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("HOME", tmpDir)
|
||||
|
||||
// Create .sonr directory
|
||||
sonrDir := filepath.Join(tmpDir, ".sonr")
|
||||
err := os.MkdirAll(sonrDir, 0o750)
|
||||
require.NoError(err)
|
||||
|
||||
// Write invalid VRF key (wrong size)
|
||||
vrfKeyPath := filepath.Join(sonrDir, "vrf_secret.key")
|
||||
invalidKey := make([]byte, 32) // Should be 64 bytes
|
||||
err = os.WriteFile(vrfKeyPath, invalidKey, 0o600)
|
||||
require.NoError(err)
|
||||
|
||||
// Test initialization with invalid key size
|
||||
logger := log.NewNopLogger()
|
||||
ctx := NewSonrContext(logger)
|
||||
|
||||
err = ctx.Initialize()
|
||||
require.Error(err, "Should fail to initialize with invalid key size")
|
||||
require.Contains(err.Error(), "invalid VRF private key size")
|
||||
require.False(ctx.IsInitialized(), "Context should not be initialized with invalid keys")
|
||||
}
|
||||
|
||||
// TestSonrContextThreadSafety tests thread-safe access to VRF keys
|
||||
func TestSonrContextThreadSafety(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
// Create temporary directory for test
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("HOME", tmpDir)
|
||||
|
||||
// Create .sonr directory with valid keys
|
||||
sonrDir := filepath.Join(tmpDir, ".sonr")
|
||||
err := os.MkdirAll(sonrDir, 0o750)
|
||||
require.NoError(err)
|
||||
|
||||
privateKey, err := vrf.GenerateKey(nil)
|
||||
require.NoError(err)
|
||||
|
||||
vrfKeyPath := filepath.Join(sonrDir, "vrf_secret.key")
|
||||
err = os.WriteFile(vrfKeyPath, privateKey, 0o600)
|
||||
require.NoError(err)
|
||||
|
||||
// Initialize context
|
||||
logger := log.NewNopLogger()
|
||||
ctx := NewSonrContext(logger)
|
||||
err = ctx.Initialize()
|
||||
require.NoError(err)
|
||||
|
||||
// Test concurrent access (simple check - not exhaustive)
|
||||
done := make(chan bool, 10)
|
||||
for i := 0; i < 10; i++ {
|
||||
go func() {
|
||||
_, err := ctx.GetVRFPrivateKey()
|
||||
require.NoError(err)
|
||||
_, err = ctx.GetVRFPublicKey()
|
||||
require.NoError(err)
|
||||
done <- true
|
||||
}()
|
||||
}
|
||||
|
||||
// Wait for all goroutines
|
||||
for i := 0; i < 10; i++ {
|
||||
<-done
|
||||
}
|
||||
}
|
||||
|
||||
// TestSonrContextErrorMessages tests that error messages are helpful
|
||||
func TestSonrContextErrorMessages(t *testing.T) {
|
||||
require := require.New(t)
|
||||
|
||||
// Create temporary directory for test
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("HOME", tmpDir)
|
||||
|
||||
logger := log.NewNopLogger()
|
||||
ctx := NewSonrContext(logger)
|
||||
|
||||
err := ctx.Initialize()
|
||||
require.Error(err)
|
||||
require.Contains(err.Error(), "failed to read VRF secret key")
|
||||
require.Contains(err.Error(), "VRF keys are required")
|
||||
require.Contains(err.Error(), "snrd init")
|
||||
}
|
||||
Reference in New Issue
Block a user