Skip to content

Commit

Permalink
testutil and supply checker
Browse files Browse the repository at this point in the history
  • Loading branch information
lumtis committed Apr 15, 2024
1 parent 3cbd10e commit 9a63d23
Show file tree
Hide file tree
Showing 9 changed files with 171 additions and 154 deletions.
6 changes: 5 additions & 1 deletion zetaclient/interfaces/signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ import (

type TSSSigner interface {
Pubkey() []byte
// Sign: Specify optionalPubkey to use a different pubkey than the current pubkey set during keygen

// Sign signs the data
// Note: it specifies optionalPubkey to use a different pubkey than the current pubkey set during keygen
Sign(data []byte, height uint64, nonce uint64, chain *chains.Chain, optionalPubkey string) ([65]byte, error)

EVMAddress() ethcommon.Address
BTCAddress() string
BTCAddressWitnessPubkeyHash() *btcutil.AddressWitnessPubKeyHash
Expand Down Expand Up @@ -90,6 +93,7 @@ func (s TestSigner) BTCAddressWitnessPubkeyHash() *btcutil.AddressWitnessPubKeyH
fmt.Printf("error parsing pubkey: %v", err)
return nil
}

// witness program: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#Witness_program
// The HASH160 of the public key must match the 20-byte witness program.
addrWPKH, err := btcutil.NewAddressWitnessPubKeyHash(btcutil.Hash160(pk.SerializeCompressed()), &chaincfg.TestNet3Params)
Expand Down
48 changes: 24 additions & 24 deletions zetaclient/keys/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,25 +86,6 @@ func GetKeyringKeybase(cfg config.Config, hotkeyPassword string) (ckeys.Keyring,
return kb, pubkeyBech32, nil
}

// getKeybase will create an instance of Keybase
func getKeybase(zetaCoreHome string, reader io.Reader, keyringBackend config.KeyringBackend) (ckeys.Keyring, error) {
cliDir := zetaCoreHome
if len(zetaCoreHome) == 0 {
return nil, fmt.Errorf("zetaCoreHome is empty")
}
registry := codectypes.NewInterfaceRegistry()
cryptocodec.RegisterInterfaces(registry)
cdc := codec.NewProtoCodec(registry)

// create a new keybase based on the selected backend
backend := ckeys.BackendTest
if keyringBackend == config.KeyringBackendFile {
backend = ckeys.BackendFile
}

return ckeys.New(sdk.KeyringServiceName(), backend, cliDir, reader, cdc)
}

// GetSignerInfo return signer info
func (k *Keys) GetSignerInfo() *ckeys.Record {
signer := GetGranteeKeyName(k.signerName)
Expand Down Expand Up @@ -184,13 +165,32 @@ func (k *Keys) GetHotkeyPassword() string {
}

func SetupConfigForTest() {
config := sdk.GetConfig()
config.SetBech32PrefixForAccount(cmd.Bech32PrefixAccAddr, cmd.Bech32PrefixAccPub)
config.SetBech32PrefixForValidator(cmd.Bech32PrefixValAddr, cmd.Bech32PrefixValPub)
config.SetBech32PrefixForConsensusNode(cmd.Bech32PrefixConsAddr, cmd.Bech32PrefixConsPub)
testConfig := sdk.GetConfig()
testConfig.SetBech32PrefixForAccount(cmd.Bech32PrefixAccAddr, cmd.Bech32PrefixAccPub)
testConfig.SetBech32PrefixForValidator(cmd.Bech32PrefixValAddr, cmd.Bech32PrefixValPub)
testConfig.SetBech32PrefixForConsensusNode(cmd.Bech32PrefixConsAddr, cmd.Bech32PrefixConsPub)
//config.SetCoinType(cmd.MetaChainCoinType)
config.SetFullFundraiserPath(cmd.ZetaChainHDPath)
testConfig.SetFullFundraiserPath(cmd.ZetaChainHDPath)
sdk.SetCoinDenomRegex(func() string {
return cmd.DenomRegex
})
}

// getKeybase will create an instance of Keybase
func getKeybase(zetaCoreHome string, reader io.Reader, keyringBackend config.KeyringBackend) (ckeys.Keyring, error) {
cliDir := zetaCoreHome
if len(zetaCoreHome) == 0 {
return nil, fmt.Errorf("zetaCoreHome is empty")
}
registry := codectypes.NewInterfaceRegistry()
cryptocodec.RegisterInterfaces(registry)
cdc := codec.NewProtoCodec(registry)

// create a new keybase based on the selected backend
backend := ckeys.BackendTest
if keyringBackend == config.KeyringBackendFile {
backend = ckeys.BackendFile
}

return ckeys.New(sdk.KeyringServiceName(), backend, cliDir, reader, cdc)
}
17 changes: 9 additions & 8 deletions zetaclient/metrics/burn_rate.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
sdkmath "cosmossdk.io/math"
)

// BurnRate calculates the average burn rate for a range of blocks.
type BurnRate struct {
blockLow int64
blockHigh int64
Expand All @@ -14,6 +15,7 @@ type BurnRate struct {
queue []int64
}

// NewBurnRate creates a new BurnRate instance with a window size.
func NewBurnRate(windowSize int64) *BurnRate {
return &BurnRate{
blockLow: 1,
Expand All @@ -24,9 +26,8 @@ func NewBurnRate(windowSize int64) *BurnRate {
}
}

// AddFee - adds fee amount spent on a tx for a particular block. It is added to a queue which is used to calculate
//
// the average burn rate for a range of blocks determined by the window size.
// AddFee adds fee amount spent on a tx for a particular block. It is added to a queue which is used to calculate
// the average burn rate for a range of blocks determined by the window size.
func (br *BurnRate) AddFee(amount int64, block int64) error {
// Check if block is in range of the window
if block < br.blockLow {
Expand Down Expand Up @@ -58,9 +59,8 @@ func (br *BurnRate) AddFee(amount int64, block int64) error {
return nil
}

// enqueueEntry - add fee entry into queue if is in range of the window. A padding is added if the block height is
//
// more than one block greater than the highest range.
// enqueueEntry adds fee entry into queue if is in range of the window. A padding is added if the block height is
// more than one block greater than the highest range.
func (br *BurnRate) enqueueEntry(block int64, amount int64) error {
diff := block - br.blockHigh
if diff < 1 {
Expand All @@ -82,7 +82,8 @@ func (br *BurnRate) enqueueEntry(block int64, amount int64) error {
return nil
}

// dequeueOldEntries - when the window slides forward, older entries in the queue need to be cleared.
// dequeueOldEntries dequeues old entries
// when the window slides forward, older entries in the queue need to be cleared.
func (br *BurnRate) dequeueOldEntries() error {
diff := br.blockHigh - br.blockLow
if diff < br.windowSize {
Expand All @@ -102,7 +103,7 @@ func (br *BurnRate) dequeueOldEntries() error {
return nil
}

// GetBurnRate - calculate current burn rate and return the value.
// GetBurnRate calculates current burn rate and return the value.
func (br *BurnRate) GetBurnRate() sdkmath.Int {
if br.blockHigh < br.windowSize {
return sdkmath.NewInt(br.total).QuoRaw(br.blockHigh)
Expand Down
46 changes: 22 additions & 24 deletions zetaclient/metrics/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,32 +39,35 @@ func NewTelemetryServer() *TelemetryServer {
return hs
}

// setter/getter for p2pid
// SetP2PID sets p2pid
func (t *TelemetryServer) SetP2PID(p2pid string) {
t.mu.Lock()
t.p2pid = p2pid
t.mu.Unlock()
}

// GetP2PID gets p2pid
func (t *TelemetryServer) GetP2PID() string {
t.mu.Lock()
defer t.mu.Unlock()
return t.p2pid
}

// setter/getter for p2pid
// SetIPAddress sets p2pid
func (t *TelemetryServer) SetIPAddress(ip string) {
t.mu.Lock()
t.ipAddress = ip
t.mu.Unlock()
}

// GetIPAddress gets p2pid
func (t *TelemetryServer) GetIPAddress() string {
t.mu.Lock()
defer t.mu.Unlock()
return t.ipAddress
}

// AddFeeEntry adds fee entry
func (t *TelemetryServer) AddFeeEntry(block int64, amount int64) {
t.mu.Lock()
err := t.HotKeyBurnRate.AddFee(amount, block)
Expand All @@ -74,21 +77,16 @@ func (t *TelemetryServer) AddFeeEntry(block int64, amount int64) {
t.mu.Unlock()
}

// NewHandler registers the API routes and returns a new HTTP handler
// Handlers registers the API routes and returns a new HTTP handler
func (t *TelemetryServer) Handlers() http.Handler {
router := mux.NewRouter()
router.Handle("/ping", http.HandlerFunc(t.pingHandler)).Methods(http.MethodGet)
router.Handle("/p2p", http.HandlerFunc(t.p2pHandler)).Methods(http.MethodGet)
router.Handle("/ip", http.HandlerFunc(t.ipHandler)).Methods(http.MethodGet)
router.Handle("/hotkeyburnrate", http.HandlerFunc(t.hotKeyFeeBurnRate)).Methods(http.MethodGet)

// router.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
// router.Handle("/debug/pprof/heap", pprof.Handler("heap"))
// router.HandleFunc("/debug/pprof/", pprof.Index)
// router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)

//router.Handle("/pending", http.HandlerFunc(t.pendingHandler)).Methods(http.MethodGet)
router.Use(logMiddleware())

return router
}

Expand All @@ -97,28 +95,14 @@ func (t *TelemetryServer) Start() error {
return errors.New("invalid http server instance")
}
if err := t.s.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
if !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("fail to start http server: %w", err)
}
}

return nil
}

func logMiddleware() mux.MiddlewareFunc {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Debug().
Str("route", r.URL.Path).
Str("port", r.URL.Port()).
Str("method", r.Method).
Msg("HTTP request received")

handler.ServeHTTP(w, r)
})
}
}

func (t *TelemetryServer) Stop() error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
Expand Down Expand Up @@ -153,3 +137,17 @@ func (t *TelemetryServer) hotKeyFeeBurnRate(w http.ResponseWriter, _ *http.Reque
defer t.mu.Unlock()
fmt.Fprintf(w, "%v", t.HotKeyBurnRate.GetBurnRate())
}

func logMiddleware() mux.MiddlewareFunc {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Debug().
Str("route", r.URL.Path).
Str("port", r.URL.Port()).
Str("method", r.Method).
Msg("HTTP request received")

handler.ServeHTTP(w, r)
})
}
}
29 changes: 29 additions & 0 deletions zetaclient/supplychecker/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package supplychecker

import (
sdkmath "cosmossdk.io/math"
"github.com/rs/zerolog"
"github.com/zeta-chain/zetacore/zetaclient/bitcoin"
)

// ZetaSupplyCheckLogs is a struct to log the output of the ZetaSupplyChecker
type ZetaSupplyCheckLogs struct {
Logger zerolog.Logger
AbortedTxAmounts sdkmath.Int `json:"aborted_tx_amounts"`
ZetaInTransit sdkmath.Int `json:"zeta_in_transit"`
ExternalChainTotalSupply sdkmath.Int `json:"external_chain_total_supply"`
ZetaTokenSupplyOnNode sdkmath.Int `json:"zeta_token_supply_on_node"`
EthLockedAmount sdkmath.Int `json:"eth_locked_amount"`
NodeAmounts sdkmath.Int `json:"node_amounts"`
LHS sdkmath.Int `json:"LHS"`
RHS sdkmath.Int `json:"RHS"`
SupplyCheckSuccess bool `json:"supply_check_success"`
}

func (z ZetaSupplyCheckLogs) LogOutput() {
output, err := bitcoin.PrettyPrintStruct(z)
if err != nil {
z.Logger.Error().Err(err).Msgf("error pretty printing struct")
}
z.Logger.Info().Msgf(output)
}
34 changes: 34 additions & 0 deletions zetaclient/supplychecker/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package supplychecker

import (
sdkmath "cosmossdk.io/math"
"github.com/rs/zerolog"
)

func ValidateZetaSupply(logger zerolog.Logger, abortedTxAmounts, zetaInTransit, genesisAmounts, externalChainTotalSupply, zetaTokenSupplyOnNode, ethLockedAmount sdkmath.Int) bool {
lhs := ethLockedAmount.Sub(abortedTxAmounts)
rhs := zetaTokenSupplyOnNode.Add(zetaInTransit).Add(externalChainTotalSupply).Sub(genesisAmounts)

copyZetaTokenSupplyOnNode := zetaTokenSupplyOnNode
copyGenesisAmounts := genesisAmounts
nodeAmounts := copyZetaTokenSupplyOnNode.Sub(copyGenesisAmounts)
logs := ZetaSupplyCheckLogs{
Logger: logger,
AbortedTxAmounts: abortedTxAmounts,
ZetaInTransit: zetaInTransit,
ExternalChainTotalSupply: externalChainTotalSupply,
NodeAmounts: nodeAmounts,
ZetaTokenSupplyOnNode: zetaTokenSupplyOnNode,
EthLockedAmount: ethLockedAmount,
LHS: lhs,
RHS: rhs,
}
defer logs.LogOutput()
if !lhs.Equal(rhs) {
logs.SupplyCheckSuccess = false
return false
}

logs.SupplyCheckSuccess = true
return true
}
Loading

0 comments on commit 9a63d23

Please sign in to comment.