Skip to content

Commit

Permalink
resolve build error
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremy-babylonlabs committed Oct 22, 2024
1 parent 5bb58c8 commit 0dfde9a
Show file tree
Hide file tree
Showing 16 changed files with 308 additions and 95 deletions.
2 changes: 1 addition & 1 deletion cmd/staking-api-service/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func main() {
if cli.GetReplayFlag() {
log.Info().Msg("Replay flag is set. Starting replay of unprocessable messages.")

err := scripts.ReplayUnprocessableMessages(ctx, cfg, queueClients, dbClients.DBClient)
err := scripts.ReplayUnprocessableMessages(ctx, cfg, queueClients, dbClients.SharedDBClient)
if err != nil {
log.Fatal().Err(err).Msg("error while replaying unprocessable messages")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type GenericEvent struct {
EventType queueClient.EventType `json:"event_type"`
}

func ReplayUnprocessableMessages(ctx context.Context, cfg *config.Config, queues *queueclients.QueueClients, db dbclient.DBClient) (err error) {
func ReplayUnprocessableMessages(ctx context.Context, cfg *config.Config, queues *queueclients.QueueClients, db dbclient.DBClientInterface) (err error) {
// Fetch unprocessable messages
unprocessableMessages, err := db.FindUnprocessableMessages(ctx)
if err != nil {
Expand Down
12 changes: 6 additions & 6 deletions internal/shared/api/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import (
)

type Handlers struct {
Shared *handler.Handler
V1 *v1handler.V1Handler
V2 *v2handler.V2Handler
SharedHandler *handler.Handler
V1Handler *v1handler.V1Handler
V2Handler *v2handler.V2Handler
}

func New(ctx context.Context, config *config.Config, services *services.Services) (*Handlers, error) {
Expand All @@ -31,8 +31,8 @@ func New(ctx context.Context, config *config.Config, services *services.Services
}

return &Handlers{
Shared: sharedHandler,
V1: v1Handler,
V2: v2Handler,
SharedHandler: sharedHandler,
V1Handler: v1Handler,
V2Handler: v2Handler,
}, nil
}
34 changes: 17 additions & 17 deletions internal/shared/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,35 @@ import (
func (a *Server) SetupRoutes(r *chi.Mux) {
handlers := a.handlers
// Extend on the healthcheck endpoint here
r.Get("/healthcheck", registerHandler(handlers.Shared.HealthCheck))
r.Get("/healthcheck", registerHandler(handlers.SharedHandler.HealthCheck))

r.Get("/v1/staker/delegations", registerHandler(handlers.V1.GetStakerDelegations))
r.Post("/v1/unbonding", registerHandler(handlers.V1.UnbondDelegation))
r.Get("/v1/unbonding/eligibility", registerHandler(handlers.V1.GetUnbondingEligibility))
r.Get("/v1/global-params", registerHandler(handlers.V1.GetBabylonGlobalParams))
r.Get("/v1/finality-providers", registerHandler(handlers.V1.GetFinalityProviders))
r.Get("/v1/stats", registerHandler(handlers.V1.GetOverallStats))
r.Get("/v1/stats/staker", registerHandler(handlers.V1.GetStakersStats))
r.Get("/v1/staker/delegation/check", registerHandler(handlers.V1.CheckStakerDelegationExist))
r.Get("/v1/delegation", registerHandler(handlers.V1.GetDelegationByTxHash))
r.Get("/v1/staker/delegations", registerHandler(handlers.V1Handler.GetStakerDelegations))
r.Post("/v1/unbonding", registerHandler(handlers.V1Handler.UnbondDelegation))
r.Get("/v1/unbonding/eligibility", registerHandler(handlers.V1Handler.GetUnbondingEligibility))
r.Get("/v1/global-params", registerHandler(handlers.V1Handler.GetBabylonGlobalParams))
r.Get("/v1/finality-providers", registerHandler(handlers.V1Handler.GetFinalityProviders))
r.Get("/v1/stats", registerHandler(handlers.V1Handler.GetOverallStats))
r.Get("/v1/stats/staker", registerHandler(handlers.V1Handler.GetStakersStats))
r.Get("/v1/staker/delegation/check", registerHandler(handlers.V1Handler.CheckStakerDelegationExist))
r.Get("/v1/delegation", registerHandler(handlers.V1Handler.GetDelegationByTxHash))

// Only register these routes if the asset has been configured
// The endpoints are used to check ordinals within the UTXOs
// Don't deprecate this endpoint
if a.cfg.Assets != nil {
r.Post("/v1/ordinals/verify-utxos", registerHandler(handlers.Shared.VerifyUTXOs))
r.Post("/v1/ordinals/verify-utxos", registerHandler(handlers.SharedHandler.VerifyUTXOs))
}

// Don't deprecate this endpoint
r.Get("/v1/staker/pubkey-lookup", registerHandler(handlers.V1.GetPubKeys))
r.Get("/v1/staker/pubkey-lookup", registerHandler(handlers.V1Handler.GetPubKeys))

r.Get("/swagger/*", httpSwagger.WrapHandler)

// V2 API
// TODO: Implement the handlers for the V2 API
r.Get("/v2/stats", registerHandler(handlers.V2.GetStats))
r.Get("/v2/finality-providers", registerHandler(handlers.V2.GetFinalityProviders))
r.Get("/v2/global-params", registerHandler(handlers.V2.GetGlobalParams))
r.Get("/v2/staker/delegations", registerHandler(handlers.V2.GetStakerDelegations))
r.Get("/v2/staker/stats", registerHandler(handlers.V2.GetStakerStats))
r.Get("/v2/stats", registerHandler(handlers.V2Handler.GetStats))
r.Get("/v2/finality-providers", registerHandler(handlers.V2Handler.GetFinalityProviders))
r.Get("/v2/global-params", registerHandler(handlers.V2Handler.GetGlobalParams))
r.Get("/v2/staker/delegations", registerHandler(handlers.V2Handler.GetStakerDelegations))
r.Get("/v2/staker/stats", registerHandler(handlers.V2Handler.GetStakerStats))
}
2 changes: 1 addition & 1 deletion internal/shared/db/client/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
dbmodel "github.com/babylonlabs-io/staking-api-service/internal/shared/db/model"
)

type DBClient interface {
type DBClientInterface interface {
Ping(ctx context.Context) error
// InsertPkAddressMappings inserts the btc public key and
// its corresponding btc addresses into the database.
Expand Down
16 changes: 8 additions & 8 deletions internal/shared/db/clients/db_clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import (
)

type DbClients struct {
MongoClient *mongo.Client
DBClient dbclient.DBClient
V1DBClient v1dbclient.V1DBClient
V2DBClient v2dbclient.V2DBClient
MongoClient *mongo.Client
SharedDBClient dbclient.DBClientInterface
V1DBClient v1dbclient.V1DBClientInterface
V2DBClient v2dbclient.V2DBClientInterface
}

func New(ctx context.Context, cfg *config.Config) (*DbClients, error) {
Expand All @@ -41,10 +41,10 @@ func New(ctx context.Context, cfg *config.Config) (*DbClients, error) {
}

dbClients := DbClients{
MongoClient: mongoClient,
DBClient: dbClient,
V1DBClient: v1dbClient,
V2DBClient: v2dbClient,
MongoClient: mongoClient,
SharedDBClient: dbClient,
V1DBClient: v1dbClient,
V2DBClient: v2dbClient,
}

return &dbClients, nil
Expand Down
8 changes: 4 additions & 4 deletions internal/shared/http/client/http_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ import (

var ALLOWED_METHODS = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"}

type Client interface {
type HttpClientInterface interface {
GetBaseURL() string
GetDefaultRequestTimeout() int
GetHttpClient() *http.Client
}

type ClientOptions struct {
type HttpClientOptions struct {
Timeout int
Path string
TemplatePath string // Metrics purpose
Expand All @@ -38,7 +38,7 @@ func isAllowedMethod(method string) bool {
}

func sendRequest[I any, R any](
ctx context.Context, client Client, method string, opts *ClientOptions, input *I,
ctx context.Context, client HttpClientInterface, method string, opts *HttpClientOptions, input *I,
) (*R, *types.Error) {
if !isAllowedMethod(method) {
return nil, types.NewInternalServiceError(fmt.Errorf("method %s is not allowed", method))
Expand Down Expand Up @@ -122,7 +122,7 @@ func sendRequest[I any, R any](
}

func SendRequest[I any, R any](
ctx context.Context, client Client, method string, opts *ClientOptions, input *I,
ctx context.Context, client HttpClientInterface, method string, opts *HttpClientOptions, input *I,
) (*R, *types.Error) {
timer := metrics.StartClientRequestDurationTimer(
client.GetBaseURL(), method, opts.TemplatePath,
Expand Down
2 changes: 1 addition & 1 deletion internal/shared/http/clients/ordinals/ordinals.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (c *OrdinalsClient) FetchUTXOInfos(
ctx context.Context, utxos []types.UTXOIdentifier,
) ([]OrdinalsOutputResponse, *types.Error) {
path := "/outputs"
opts := &client.ClientOptions{
opts := &client.HttpClientOptions{
Path: path,
TemplatePath: path,
Headers: c.defaultHeaders,
Expand Down
215 changes: 215 additions & 0 deletions internal/shared/utils/datagen/datagen.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
package datagen

import (
"bytes"
"encoding/hex"
"fmt"
"log"
"math/rand"
"time"

"github.com/babylonlabs-io/staking-api-service/internal/shared/types"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

func GenRandomByteArray(r *rand.Rand, length uint64) []byte {
newHeaderBytes := make([]byte, length)
r.Read(newHeaderBytes)
return newHeaderBytes
}

func RandomPk() (string, error) {
fpPirvKey, err := btcec.NewPrivateKey()
if err != nil {
return "", err
}
fpPk := fpPirvKey.PubKey()
return hex.EncodeToString(schnorr.SerializePubKey(fpPk)), nil
}

func GeneratePks(numOfKeys int) []string {
var pks []string
for i := 0; i < numOfKeys; i++ {
k, err := RandomPk()
if err != nil {
log.Fatalf("Failed to generate random pk: %v", err)
}
pks = append(pks, k)
}
return pks
}

// RandomPostiveFloat64 generates a random float64 value greater than 0.
func RandomPostiveFloat64(r *rand.Rand) float64 {
for {
f := r.Float64() // Generate a random float64
if f > 0 {
return f
}
// If f is 0 (extremely rare), regenerate
}
}

// RandomPositiveInt generates a random positive integer from 1 to max.
func RandomPositiveInt(r *rand.Rand, max int) int {
// Generate a random number from 1 to max (inclusive)
return r.Intn(max) + 1
}

// RandomString generates a random alphanumeric string of length n.
func RandomString(r *rand.Rand, n int) string {
result := make([]byte, n)
letterLen := len(letters)
for i := range result {
num := r.Int() % letterLen
result[i] = letters[num]
}
return string(result)
}

// RandomAmount generates a random BTC amount from 0.1 to 10000
// the returned value is in satoshis
func RandomAmount(r *rand.Rand) int64 {
// Generate a random value range from 0.1 to 10000 BTC
randomBTC := r.Float64()*(9999.9-0.1) + 0.1
// convert to satoshi
return int64(randomBTC*1e8) + 1
}

// GenerateRandomTx generates a random transaction with random values for each field.
func GenerateRandomTx(
r *rand.Rand,
options *struct{ DisableRbf bool },
) (*wire.MsgTx, string, error) {
sequence := r.Uint32()
if options != nil && options.DisableRbf {
sequence = wire.MaxTxInSequenceNum
}
tx := &wire.MsgTx{
Version: 1,
TxIn: []*wire.TxIn{
{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.HashH(GenRandomByteArray(r, 10)),
Index: r.Uint32(),
},
SignatureScript: []byte{},
Sequence: sequence,
},
},
TxOut: []*wire.TxOut{
{
Value: int64(r.Int31()),
PkScript: GenRandomByteArray(r, 80),
},
},
LockTime: 0,
}
var buf bytes.Buffer
if err := tx.Serialize(&buf); err != nil {
return nil, "", err
}
txHex := hex.EncodeToString(buf.Bytes())

return tx, txHex, nil
}

// GenerateRandomTxWithOutput generates a random transaction with random values
// for each field.
func RandomBytes(r *rand.Rand, n uint64) ([]byte, string) {
randomBytes := GenRandomByteArray(r, n)
return randomBytes, hex.EncodeToString(randomBytes)
}

// GenerateRandomTimestamp generates a random timestamp before the specified timestamp.
// If beforeTimestamp is 0, then the current time is used.
func GenerateRandomTimestamp(afterTimestamp, beforeTimestamp int64) int64 {
timeNow := time.Now().Unix()
if beforeTimestamp == 0 && afterTimestamp == 0 {
return timeNow
}
if beforeTimestamp == 0 {
return afterTimestamp + rand.Int63n(timeNow-afterTimestamp)
} else if afterTimestamp == 0 {
// Generate a reasonable timestamp between 1 second to 6 months in the past
sixMonthsInSeconds := int64(6 * 30 * 24 * 60 * 60)
return beforeTimestamp - rand.Int63n(sixMonthsInSeconds)
}
return afterTimestamp + rand.Int63n(beforeTimestamp-afterTimestamp)
}

// GenerateRandomFinalityProviderDetail generates a random number of finality providers
func GenerateRandomFinalityProviderDetail(r *rand.Rand, numOfFps uint64) []types.FinalityProviderDetails {
var finalityProviders []types.FinalityProviderDetails

for i := uint64(0); i < numOfFps; i++ {
fpPkInHex, err := RandomPk()
if err != nil {
log.Fatalf("failed to generate random public key: %v", err)
}

randomStr := RandomString(r, 10)
finalityProviders = append(finalityProviders, types.FinalityProviderDetails{
Description: types.FinalityProviderDescription{
Moniker: "Moniker" + randomStr,
Identity: "Identity" + randomStr,
Website: "Website" + randomStr,
SecurityContact: "SecurityContact" + randomStr,
Details: "Details" + randomStr,
},
Commission: fmt.Sprintf("%f", RandomPostiveFloat64(r)),
BtcPk: fpPkInHex,
})
}
return finalityProviders
}

func RandomFinalityProviderState(r *rand.Rand) types.FinalityProviderState {
states := []types.FinalityProviderState{types.FinalityProviderStateActive, types.FinalityProviderStateStandby}
return states[r.Intn(len(states))]
}

func GenerateRandomBabylonParams(r *rand.Rand) types.BabylonParams {
return types.BabylonParams{
Version: r.Intn(10),
CovenantPKs: GeneratePks(r.Intn(10)),
CovenantQuorum: r.Intn(10),
MaxStakingAmount: int64(r.Intn(1000000000000000000)),
MinStakingAmount: int64(r.Intn(1000000000000000000)),
MaxStakingTime: int64(r.Intn(1000000000000000000)),
MinStakingTime: int64(r.Intn(1000000000000000000)),
SlashingPKScript: RandomString(r, 10),
MinSlashingTxFee: int64(r.Intn(1000000000000000000)),
SlashingRate: RandomPostiveFloat64(r),
MinUnbondingTime: int64(r.Intn(1000000000000000000)),
UnbondingFee: int64(r.Intn(1000000000000000000)),
MinCommissionRate: RandomPostiveFloat64(r),
MaxActiveFinalityProviders: r.Intn(10),
DelegationCreationBaseGasFee: int64(r.Intn(1000000000000000000)),
}
}

func GenerateRandomBTCParams(r *rand.Rand) types.BTCParams {
return types.BTCParams{
Version: r.Intn(10),
BTCConfirmationDepth: r.Intn(10),
}
}

func RandomDelegationState(r *rand.Rand) types.DelegationState {
states := []types.DelegationState{types.Active, types.UnbondingRequested, types.Unbonding, types.Unbonded, types.Withdrawn}
return states[r.Intn(len(states))]
}

func RandomTransactionInfo(r *rand.Rand) types.TransactionInfo {
_, txHex, _ := GenerateRandomTx(r, nil)
return types.TransactionInfo{
TxHex: txHex,
OutputIndex: r.Intn(100),
}
}
Loading

0 comments on commit 0dfde9a

Please sign in to comment.