diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 7d6eaad..01af97f --- a/README.md +++ b/README.md @@ -1,25 +1,27 @@ # INTERX -INTERX is an interchain engine, proxy, load balancer & security gateway service for communication between backend and frontend. -It will connect to the node using the GRPC endpoint as well as the RPC endpoint ([`Tendermint RPC`](https://docs.tendermint.com/master/rpc/)). +INTERX is an interchain engine, proxy, load balancer & security gateway service for communication between backend and frontend. +It connects to the node using the GRPC endpoint as well as the RPC endpoint ([`Tendermint RPC`](https://docs.tendermint.com/master/rpc/)). -#### Releases +## Releases -All files in the [KIRA releases](https://github.com/KiraCore/interx/releases) are always signed with [cosign](https://github.com/sigstore/cosign/releases) and listed with a corresponding `SHA256` checksum. You should NEVER install anything on your machine unless you verified integrity of the files! +All files in the [KIRA releases](https://github.com/KiraCore/interx/releases) are always signed with [cosign](https://github.com/sigstore/cosign/releases) and listed with a corresponding `SHA256` checksum. +You should NEVER install anything on your machine unless you have verified the integrity of the files! -To learn more about how to install cosign and verify integrity of files click [here](./cosign.md) +To learn more about how to install `cosign` and verify the integrity of files, click [here](./cosign.md). ## Setup ### Prerequisites -Essential dependencies and tools required to build INTERX can be found [here](./PREREQUISITES.md). Make sure you run prerequisites-commands successfully before you continue with local development or further installation. +Essential dependencies and tools required to build INTERX can be found [here](./PREREQUISITES.md). +Make sure you run all prerequisite commands successfully before you continue with local development or further installation. ### Installation from Github -Binary (`interxd`) will be installed in the `$GOBIN` directory, please make sure to add it to your system `PATH`. +The binary (`interxd`) will be installed in the `$GOBIN` directory. Please make sure to add it to your system `PATH`. -``` +```bash cd $HOME && rm -fvr ./interx && INTERX_BRANCH="" && \ git clone https://github.com/KiraCore/interx.git -b $INTERX_BRANCH && \ cd ./interx && chmod -R 777 ./scripts && \ @@ -29,51 +31,55 @@ cd $HOME && rm -fvr ./interx && INTERX_BRANCH="" && \ ### How to start Simple start: + ```bash interxd init interxd start ``` -#### `interxd init` -Generate configuration file. +Generates the configuration file. Parameters: -- `config` - The interx configuration file path. (default = "./config.json") -- `serve_https` - https or http. (default = false) -- `grpc` - The grpc endpoint of the sekaid. (default = "dns:///0.0.0.0:9090") -- `rpc` - The tendermint rpc endpoint of the sekaid (default = "http://0.0.0.0:26657") -- `port` - The interx port. (default = "11000") -- `signing_mnemonic` - The mnemonic file path or word seeds for interx singing service. (deafult = auto generated word seeds) -- `status_sync` - The time in seconds and INTERX syncs node status. (deafult = 5) -- `cache_dir` - The interx cache directory path. (deafult = "cache") -- `max_cache_size`- The maximum cache size. (default = "2GB") -- `caching_duration` - The caching clear duration in seconds. (deafult = 5) -- `download_file_size_limitation`- The maximum download file size. (default = "10MB") -- `faucet_mnemonic` - The mnemonic file path or word seeds for faucet service. (deafult = auto generated word seeds) -- `faucet_time_limit` - The claim time limitation in seconds. (default = 20) - -#### `interxd start` + +- **`config`** - The interx configuration file path. (default = `./config.json`) +- **`serve_https`** - Use HTTPS or HTTP. (default = `false`) +- **`grpc`** - The GRPC endpoint of the `sekaid`. (default = `dns:///0.0.0.0:9090`) +- **`rpc`** - The Tendermint RPC endpoint of the `sekaid`. (default = `http://0.0.0.0:26657`) +- **`port`** - The interx port. (default = `11000`) +- **`signing_mnemonic`** - The mnemonic file path or word seeds for the interx signing service. (default = auto-generated word seeds) +- **`status_sync`** - The time interval in seconds for INTERX to sync node status. (default = `5`) +- **`cache_dir`** - The interx cache directory path. (default = `cache`) +- **`max_cache_size`** - The maximum cache size. (default = `2GB`) +- **`caching_duration`** - The caching clear duration in seconds. (default = `5`) +- **`download_file_size_limitation`** - The maximum file size allowed for downloads. (default = `10MB`) +- **`faucet_mnemonic`** - The mnemonic file path or word seeds for the faucet service. (default = auto-generated word seeds) +- **`faucet_time_limit`** - The claim time limitation in seconds. (default = `20`) + +`interxd start` + Start interx service. Parameters: + - `config` - The interx configuration file path. (default = "./config.json") -## Configuration +### Configuration Configurations are available using `config.json`. -### `mnemonic` +### mnemonic -The 24-words seed string or the file path to the mnemonic file. -This is for generating interx priv/pub keys which will be used for response signing. +The 24-word seed string or the file path to the mnemonic file. + +This is for generating interx private/public keys which will be used for response signing. -``` +```bash "mnemonic": "swap exercise equip shoot mad inside floor wheel loan visual stereo build frozen always bulb naive subway foster marine erosion shuffle flee action there" "mnemonic": "interx.mnemonic" ``` -### `cache` +### Cache Cache configurations. @@ -82,7 +88,7 @@ Cache configurations. Interx has a feature to sync node status. `status_sync` refers the time in seconds and INTERX syncs node status every `status_sync` seconds. -``` +```json "status_sync": 5 ``` @@ -91,7 +97,7 @@ Interx has a feature to sync node status. Interx has a caching feature. `cache_dir` refers the cache directory. -``` +```json "cache_dir": "cache" ``` @@ -100,7 +106,7 @@ Interx has a caching feature. Interx has a gabage collection feature. `max_cache_size` refers the maximum cache size. If cache size is over maximum cache size, it will remove random caches. (it remains 90% of maximum cache size) -``` +```json "max_cache_size": "2 GB" ``` @@ -109,7 +115,7 @@ Interx has a gabage collection feature. Interx has a gabage collection feature. `caching_duration` refers the caching clear duration in seconds -``` +```json "caching_duration": 10 ``` @@ -118,30 +124,30 @@ Interx has a gabage collection feature. Interx has a download feature. `download_file_size_limitation` refers the maximum download file size. -``` +```json "download_file_size_limitation": "10 MB" ``` -### `faucet` +#### faucet Interx has a faucet feature. -#### `mnemonic` +#### faucet_mnemonic `mnemonic` refers the 24-words seed string or the file path to the mnemonic file. It will be used to generate faucet account priv/pub keys and address. -``` +```text "mnemonic": "equip exercise shoot mad inside floor wheel loan visual stereo build frozen potato always bulb naive subway foster marine erosion shuffle flee action there" "mnemonic": "faucet.mnemonic" ``` -#### `faucet_amounts` +#### faucet_amounts `faucet_amounts` refers the faucet amount for each tokens. -``` +```json "faucet_amounts": { "stake": 100000, "validatortoken": 100000, @@ -149,11 +155,11 @@ It will be used to generate faucet account priv/pub keys and address. }, ``` -#### `faucet_minimum_amounts` +#### faucet_minimum_amounts `faucet_minimum_amounts` refers the faucet minimum amount for each tokens. -``` +```json "faucet_minimum_amounts": { "stake": 100, "validatortoken": 100, @@ -161,12 +167,12 @@ It will be used to generate faucet account priv/pub keys and address. }, ``` -#### `fee_amounts` +#### fee_amounts `fee_amounts` refers the fee amount for faucet feature. For `stake` token faucet, we can use different coins for fee. E.g. we can use `ukex` for `stake` token faucet. -``` +```json "fee_amounts": { "stake": "1000ukex", "validatortoken": "1000ukex", @@ -174,28 +180,28 @@ For `stake` token faucet, we can use different coins for fee. E.g. we can use `u } ``` -#### `time_limit` +#### time_limit `time_limit` refers the claim time limitation in seconds. Users can re-request faucet after `time_limit` seconds. -``` +```json "time_limit": 20 ``` -### `rpc` +### rpc `rpc` refers the RPC endpoint configurations. -#### `API` +### API `API` refers the configurations for each endpoint. -##### `GET` +#### GET `GET` refers the configurations for each `GET` endpoint. -``` +```json "GET": { "/api/cosmos/status": { "rate_limit": 0.1, @@ -211,53 +217,53 @@ Users can re-request faucet after `time_limit` seconds. }, ``` -###### `disable` +#### disable `disable` refers the options to disable the endpoint. -``` +```json "disable": true ``` -###### `rate_limit` +### rate_limit `rate_limit` refers the rate limit for each endpoint. -``` +```json "rate_limit": 0.1 ``` -###### `auth_rate_limit` +### auth_rate_limit `auth_rate_limit` refers the auth rate limit for each endpoint. -``` +```json "auth_rate_limit": 1 ``` -###### `caching_disable` +### caching_disable `caching_disable` refers the option to disable caching feature for each endpoint. -``` +```json "caching_disable": true ``` -###### `caching_duration` +### caching_duration `caching_duration` refers the customized caching duration time in seconds for each endpoint. -``` +```json "caching_duration": 30 ``` -##### `POST` +### POST `POST` refers the configurations for each `POST` endpoint. This is the same as `GET` configurations. -``` +```json "POST": { "/api/cosmos/txs": { "disable": false, @@ -268,14 +274,14 @@ This is the same as `GET` configurations. ## Networking -### Communication between Sekai and INTERX +### Communication Between Sekai and INTERX INTERX connects to sekai using following ports. - `9090`: Connect to the GRPC endpoint for the node. - `26657`: Connect to the Tendermint RPC endpoint for the node. -### Communication between INTERX and the frontend +### Communication Between INTERX and Frontend - INTERX uses `http` protocol by default. It's possible to config `http` setting using `SERVE_HTTP`(default = true) env variable. @@ -285,23 +291,23 @@ It's possible to config `port` setting using `PORT`(deafult = 11000) env variabl ## Communication -### `/api/kira/metadata` +### /api/kira/metadata Query functions metadata for `sekai`. -### `/api/interx/metadata` +### /api/interx/metadata Query functions metadata for `interx`. -### `/api/rpc_methods` +### /api/rpc_methods Query available RPC methods `interx` provides. -### `/api/status` +### /api/status QueryStatus is a function to query the node status. -### `/api/cosmos/auth/accounts/{address}` +### /api/cosmos/auth/accounts/{address} QueryAccount is a function to query the account info. @@ -311,173 +317,174 @@ QueryAccount is a function to query the account info. #### Example -GET http://0.0.0.0:11000/api/cosmos/auth/accounts/kira1gaadckc6g8ne62dzmscgyqkx3sd5p26wrapekd +GET -### `/api/cosmos/bank/balances/{address}` +#### /api/cosmos/bank/balances/{address} QueryBalance is a function to query the account balances. -#### Parameters +1- Parameters - `address`: (`string`) The account address. -#### Example +2- Example -GET http://0.0.0.0:11000/api/cosmos/bank/balances/kira1gaadckc6g8ne62dzmscgyqkx3sd5p26wrapekd +GET ### `/api/cosmos/txs/{hash}` QueryTransactionHash is a function to query transaction details from transaction hash. -#### Parameters +1- Parameters - `hash`: (`string`) The transaction hash. (e.g. 0x20.....) -#### Example +2- Example -GET http://0.0.0.0:11000/api/cosmos/txs/0x4A41257AC228F6CE476E9C9AD67BB98057412A22B035E1C0A4CCEB0E4E8E364D +GET ### `/api/faucet` Faucet is a function to claim tokens to the account for free. Returns the available faucet amount when 'claim' and 'token' is unset. -#### Parameters +1- Parameters - `claim`: (`string`, `optional`) The claim address. - `token`: (`string`, `optional`) The claim token. -#### Example +2- Example -GET http://0.0.0.0:11000/api/faucet -GET http://0.0.0.0:11000/api/faucet?claim=kira1kdnep4lm3z6yd3pah0rzfu3dvudgwfjejs9ans&token=stake +GET +GET ### `/api/withdraws` Withdraws is a function to query withdraw transactions of the account. -#### Parameters +1- Parameters - `account`: (`string`) The Kira account address. - `type`: (`string`, `optional`) The transaction type. - `max`: (`int`, `optional`) The maximum number of the results. (1 ~ 1000) - `last`: (`string`, `optional`) The last transaction hash. -#### Example +2- Example -GET http://0.0.0.0:11000/api/withdraws?account=kira1eyvuhkj9r28sutr6n5vxgckejz2qy3hvanjk7k&type=send&max=4 +GET ### `/api/deposits` Deposits is a function to query deposit transactions of the account. -#### Parameters +1- Parameters - `account`: (`string`) The Kira account address. - `type`: (`string`, `optional`) The transaction type. - `max`: (`int`, `optional`) The maximum number of the results. (1 ~ 1000) - `last`: (`string`, `optional`) The last transaction hash. -#### Example +2- Example -GET http://0.0.0.0:11000/api/deposits?account=kira1h9s2k2s9624kdghp5ztcdgnausg77rdj9cyat6&type=Send +GET ### `/api/kira/gov/data_keys` QueryDataReferenceKeys is a function to query data reference keys with pagination. -#### Parameters +1- Parameters - `limit`: (`number`) The limit of the query results. (like page size) - `offset`: (`number`) The offset of the query results. (like page number) - `count_total`: (`bool`, `optional`) The option to return total count of data reference keys. -#### Example +2- Example -GET http://0.0.0.0:11000/api/kira/gov/data_keys?limit=2&offset=0&count_total=true +GET ### `/api/kira/gov/data/{key}` QueryDataReference is a function to query data reference by a key. -#### Parameters +1- Parameters - `key`: (`string`) The data reference key. -#### Example +2- Example -GET http://0.0.0.0:11000/api/kira/gov/data/data_reference_key +GET ### `/download/{module}/{key}` Download is a function to download a data reference or arbitrary data. -#### Parameters +1- Parameters - `module`: (`string`) The module name. (e.g. DRR for data reference registry.) - `key`: (`string`) The reference key. (It saves reference data with hashed name. e.g. 2CEE6B1689EDDDD6F08EB1EAEC7D3C4E.) -#### Example +2- Example -GET http://0.0.0.0:11000/download/DRR/2CEE6B1689EDDDD6F08EB1EAEC7D3C4E +GET ### `/api/cosmos/txs` Broadcast is a function to broadcast signed transaction. -#### Parameters +1- Parameters - `tx`: (`object`) The signed transaction to be broadcasted. - `mode`: (`string`) The transaction broadcast mode. (block, sync, async) -#### Example +2- Example -POST http://0.0.0.0:11000/api/cosmos/txs -``` +POST + +```json { - "tx": { - "body": { - "messages": [ - { - "@type": "/cosmos.bank.v1beta1.MsgSend", - "from_address": "kira1rsgnkecqgq575ynn6rczd96kc23uwtruqx9m0m", - "to_address": "kira1h9s2k2s9624kdghp5ztcdgnausg77rdj9cyat6", - "amount": [ - { - "denom": "ukex", - "amount": "250" - } - ] - } - ], - "memo": "", - "timeout_height": "0", - "extension_options": [], - "non_critical_extension_options": [] - }, - "auth_info": { - "signer_infos": [ - { - "public_key": { - "secp256k1": "Alm0A4BIQyUWy8KXjP1BRMePguZWgFKQa5hzzwRlu3I8" - }, - "mode_info": { - "single": { - "mode": "SIGN_MODE_DIRECT" - } - }, - "sequence": "0" - } - ], - "fee": { - "amount": [], - "gas_limit": "200000" - } - }, - "signatures": [ - "0BsM4jdGj/qqgtzMaVZkhDZguX6ol6hL18KxR17yr60MqW9yMNMA8bCwonLEPjSL0PgCzVCll5V9tlfAlKak1g==" - ] - }, - "mode": "block" + "tx": { + "body": { + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "kira1rsgnkecqgq575ynn6rczd96kc23uwtruqx9m0m", + "to_address": "kira1h9s2k2s9624kdghp5ztcdgnausg77rdj9cyat6", + "amount": [ + { + "denom": "ukex", + "amount": "250" + } + ] + } + ], + "memo": "", + "timeout_height": "0", + "extension_options": [], + "non_critical_extension_options": [] + }, + "auth_info": { + "signer_infos": [ + { + "public_key": { + "secp256k1": "Alm0A4BIQyUWy8KXjP1BRMePguZWgFKQa5hzzwRlu3I8" + }, + "mode_info": { + "single": { + "mode": "SIGN_MODE_DIRECT" + } + }, + "sequence": "0" + } + ], + "fee": { + "amount": [], + "gas_limit": "200000" + } + }, + "signatures": [ + "0BsM4jdGj/qqgtzMaVZkhDZguX6ol6hL18KxR17yr60MqW9yMNMA8bCwonLEPjSL0PgCzVCll5V9tlfAlKak1g==" + ] + }, + "mode": "block" } ``` @@ -499,14 +506,16 @@ POST http://0.0.0.0:11000/api/cosmos/txs ## Caching Configurations of RPC methods ### `/api/rpc_methods` contains caching information for all endpoints + - caching_blocks: integer defining number of blocks that the response data will be preserved - caching_time: integer defining time in seconds that the response data will be preserved for - caching_enabled: boolean if caching is enabled or not Here `0` represents no caching, `-1` represents infinit caching, `positive integer` represetns the caching time or number of blocks Remember this settings when you set/update manually from `config.json`. -### Additionally `config.json` file contains `cache-size-limit` config param which represents the cache size limit in bytes. If cache reaches the limit, it will randomly delete folders/files. +### Additionally `config.json` file contains `cache-size-limit` config param which represents the cache size limit in bytes. If cache reaches the limit, it will randomly delete folders/files ### How to update caching configurations + All caching configurations are set in `config.json` file. -`config.json` file includes `rpc_methods` field and there you can set/update caching config of each endpoint. \ No newline at end of file +`config.json` file includes `rpc_methods` field and there you can set/update caching config of each endpoint. diff --git a/common/api.go b/common/api.go old mode 100644 new mode 100755 index 86775b5..c03fda0 --- a/common/api.go +++ b/common/api.go @@ -15,6 +15,7 @@ import ( "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/database" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" tmjson "github.com/cometbft/cometbft/libs/json" tmTypes "github.com/cometbft/cometbft/rpc/core/types" @@ -26,11 +27,13 @@ import ( // MakeTendermintRPCRequest is a function to make GET request func MakeTendermintRPCRequest(rpcAddr string, url string, query string) (interface{}, interface{}, int) { endpoint := fmt.Sprintf("%s%s?%s", rpcAddr, url, query) - // GetLogger().Info("[rpc-call] Entering tendermint rpc call: ", endpoint) resp, err := http.Get(endpoint) if err != nil { - GetLogger().Error("[rpc-call] Unable to connect to ", endpoint) + log.CustomLogger().Error("[MakeTendermintRPCRequest] Unable to connect to ", + "endpoint", endpoint, + "error", err, + ) return ServeError(0, "", err.Error(), http.StatusInternalServerError) } defer resp.Body.Close() @@ -38,7 +41,9 @@ func MakeTendermintRPCRequest(rpcAddr string, url string, query string) (interfa response := new(types.RPCResponse) err = json.NewDecoder(resp.Body).Decode(response) if err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: : ", err) + log.CustomLogger().Error("[MakeTendermintRPCRequest][Decode] Unable to decode response", + "error", err, + ) return nil, err.Error(), resp.StatusCode } @@ -48,11 +53,13 @@ func MakeTendermintRPCRequest(rpcAddr string, url string, query string) (interfa // MakeGetRequest is a function to make GET request func MakeGetRequest(rpcAddr string, url string, query string) (Result interface{}, Error interface{}, StatusCode int) { endpoint := fmt.Sprintf("%s%s?%s", rpcAddr, url, query) - // GetLogger().Info("[rpc-call] Entering rpc call: ", endpoint) resp, err := http.Get(endpoint) if err != nil { - GetLogger().Error("[rpc-call] Unable to connect to ", endpoint) + log.CustomLogger().Error("[MakeGetRequest] Unable to connect to ", + "endpoint", endpoint, + "error", err, + ) return ServeError(0, "", err.Error(), http.StatusInternalServerError) } defer resp.Body.Close() @@ -61,7 +68,9 @@ func MakeGetRequest(rpcAddr string, url string, query string) (Result interface{ err = json.NewDecoder(resp.Body).Decode(&Result) if err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: : ", err) + log.CustomLogger().Error("[MakeGetRequest][Decode] Unable to decode response", + "error", err, + ) Error = err.Error() } @@ -71,11 +80,13 @@ func MakeGetRequest(rpcAddr string, url string, query string) (Result interface{ // DownloadResponseToFile is a function to save GET response as a file func DownloadResponseToFile(rpcAddr string, url string, query string, filepath string) error { endpoint := fmt.Sprintf("%s%s?%s", rpcAddr, url, query) - // GetLogger().Info("[rpc-call] Entering rpc call: ", endpoint) resp, err := http.Get(endpoint) if err != nil { - GetLogger().Error("[rpc-call] Unable to connect to ", endpoint) + log.CustomLogger().Error("[DownloadResponseToFile] Unable to connect to ", + "endpoint", endpoint, + "error", err, + ) return err } defer resp.Body.Close() @@ -86,7 +97,9 @@ func DownloadResponseToFile(rpcAddr string, url string, query string, filepath s global.Mutex.Lock() _, err = io.Copy(fileout, resp.Body) if err != nil { - GetLogger().Error("[rpc-call] Unable to save response") + log.CustomLogger().Error("[DownloadResponseToFile] Unable to save response", + "error", err, + ) } global.Mutex.Unlock() @@ -98,16 +111,21 @@ func DownloadResponseToFile(rpcAddr string, url string, query string, filepath s func GetAccountBalances(gwCosmosmux *runtime.ServeMux, r *http.Request, bech32addr string) []types.Coin { _, err := sdk.AccAddressFromBech32(bech32addr) if err != nil { - GetLogger().Error("[grpc-call] Invalid bech32addr: ", bech32addr) + log.CustomLogger().Error("[GetAccountBalances][AccAddressFromBech32] Invalid bech32addr", + "address", bech32addr, + "error", err, + ) return nil } + log.CustomLogger().Info("Starting get balance request...", + "address", bech32addr, + ) + r.URL.Path = fmt.Sprintf("/cosmos/bank/v1beta1/balances/%s", bech32addr) r.URL.RawQuery = "" r.Method = "GET" - // GetLogger().Info("[grpc-call] Entering grpc call: ", r.URL.Path) - recorder := httptest.NewRecorder() gwCosmosmux.ServeHTTP(recorder, r) resp := recorder.Result() @@ -119,7 +137,9 @@ func GetAccountBalances(gwCosmosmux *runtime.ServeMux, r *http.Request, bech32ad result := BalancesResponse{} err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { - GetLogger().Error("[grpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetAccountBalances][Decode] Unable to decode response", + "error", err, + ) } return result.Balances @@ -129,16 +149,20 @@ func GetAccountBalances(gwCosmosmux *runtime.ServeMux, r *http.Request, bech32ad func GetAccountNumberSequence(gwCosmosmux *runtime.ServeMux, r *http.Request, bech32addr string) (uint64, uint64) { _, err := sdk.AccAddressFromBech32(bech32addr) if err != nil { - GetLogger().Error("[grpc-call] Invalid bech32addr: ", bech32addr) + log.CustomLogger().Error("[GetAccountNumberSequence] Invalid bech32addr", + "address", bech32addr, + ) return 0, 0 } + log.CustomLogger().Info("[GetAccountNumberSequence] Starting grpc call: ", + "url", r.URL.Path, + ) + r.URL.Path = fmt.Sprintf("/cosmos/auth/v1beta1/accounts/%s", bech32addr) r.URL.RawQuery = "" r.Method = "GET" - // GetLogger().Info("[grpc-call] Entering grpc call: ", r.URL.Path) - recorder := httptest.NewRecorder() gwCosmosmux.ServeHTTP(recorder, r) resp := recorder.Result() @@ -154,23 +178,33 @@ func GetAccountNumberSequence(gwCosmosmux *runtime.ServeMux, r *http.Request, be result := QueryAccountResponse{} err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { - GetLogger().Error("[grpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetAccountNumberSequence][Decode] Unable to decode response", + "error", err, + ) } accountNumber, _ := strconv.ParseInt(result.Account.AccountNumber, 10, 64) sequence, _ := strconv.ParseInt(result.Account.Sequence, 10, 64) + log.CustomLogger().Info("Finished 'GetAccountNumberSequence' request.") + return uint64(accountNumber), uint64(sequence) } // BroadcastTransaction is a function to post transaction, returns txHash func BroadcastTransaction(rpcAddr string, txBytes []byte) (string, error) { + endpoint := fmt.Sprintf("%s/broadcast_tx_async?tx=0x%X", rpcAddr, txBytes) - GetLogger().Info("[rpc-call] Entering rpc call: ", endpoint) + log.CustomLogger().Info("Starting `BroadcastTransaction` call", + "endpoint", endpoint, + ) resp, err := http.Get(endpoint) if err != nil { - GetLogger().Error("[rpc-call] Unable to connect to ", endpoint) + log.CustomLogger().Error("[BroadcastTransaction] Unable to connect to ", + "endpoint", endpoint, + "error", err, + ) return "", err } defer resp.Body.Close() @@ -190,15 +224,21 @@ func BroadcastTransaction(rpcAddr string, txBytes []byte) (string, error) { result := new(RPCTempResponse) err = json.NewDecoder(resp.Body).Decode(result) if err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[BroadcastTransaction] Unable to decode response", + "error", err, + ) return "", err } if resp.StatusCode != http.StatusOK { - GetLogger().Error("[rpc-call] Unable to broadcast transaction: ", result.Error.Message) + log.CustomLogger().Error("[BroadcastTransaction] Unable to broadcast transaction", + "error", result.Error.Message, + ) return "", errors.New(result.Error.Message) } + log.CustomLogger().Info("Finished 'BroadcastTransaction' request.") + return result.Result.Hash, nil } @@ -211,18 +251,23 @@ func GetPermittedTxTypes(rpcAddr string, account string) (map[string]string, err // GetBlockTime is a function to get block time func GetBlockTime(rpcAddr string, height int64) (int64, error) { - // blockTime, err := database.GetBlockTime(height) + blockTime, found := BlockTimes[height] if found { return blockTime, nil } endpoint := fmt.Sprintf("%s/block?height=%d", rpcAddr, height) - // GetLogger().Info("[rpc-call] Entering rpc call: ", endpoint) + log.CustomLogger().Info("Starting `GetBlockTime` call", + "endpoint", endpoint, + ) resp, err := http.Get(endpoint) if err != nil { - GetLogger().Error("[rpc-call] Unable to connect to ", endpoint) + log.CustomLogger().Error("[GetBlockTime] Unable to connect to ", + "endpoint", endpoint, + "error", err, + ) return 0, fmt.Errorf("block not found: %d", height) } defer resp.Body.Close() @@ -232,18 +277,25 @@ func GetBlockTime(rpcAddr string, height int64) (int64, error) { response := new(tmJsonRPCTypes.RPCResponse) if err := json.Unmarshal(respBody, response); err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetBlockTime] Unable to decode response", + "error", err, + ) return 0, err } if response.Error != nil { - GetLogger().Error("[rpc-call] Block not found: ", height) + log.CustomLogger().Error("[GetBlockTime] Block not found", + "error", response.Error, + "height", height, + ) return 0, fmt.Errorf("block not found: %d", height) } result := new(tmTypes.ResultBlock) if err := tmjson.Unmarshal(response.Result, result); err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetBlockTime] Unable to decode response", + "error", err, + ) return 0, err } @@ -263,15 +315,24 @@ func GetBlockTime(rpcAddr string, height int64) (int64, error) { func GetBlockNanoTime(rpcAddr string, height int64) (int64, error) { blockTime, err := database.GetBlockNanoTime(height) if err == nil { + log.CustomLogger().Error("[GetBlockNanoTime] Unable to fetch balance", + "error", err, + ) return blockTime, nil } endpoint := fmt.Sprintf("%s/block?height=%d", rpcAddr, height) - // GetLogger().Info("[rpc-call] Entering rpc call: ", endpoint) + log.CustomLogger().Info("Starting `GetBlockNanoTime` call", + "endpoint", endpoint, + ) resp, err := http.Get(endpoint) if err != nil { - GetLogger().Error("[rpc-call] Unable to connect to ", endpoint) + log.CustomLogger().Error("[GetBlockNanoTime] Unable to connect to ", + "endpoint", endpoint, + "height", height, + "error", err, + ) return 0, fmt.Errorf("block not found: %d", height) } defer resp.Body.Close() @@ -281,18 +342,25 @@ func GetBlockNanoTime(rpcAddr string, height int64) (int64, error) { response := new(tmJsonRPCTypes.RPCResponse) if err := json.Unmarshal(respBody, response); err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetBlockNanoTime] Unable to decode response", + "error", err, + ) return 0, err } if response.Error != nil { - GetLogger().Error("[rpc-call] Block not found: ", height) + log.CustomLogger().Error("[GetBlockNanoTime] Block not found: ", + "height", height, + "error", response.Error, + ) return 0, fmt.Errorf("block not found: %d", height) } result := new(tmTypes.ResultBlock) if err := tmjson.Unmarshal(response.Result, result); err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetBlockNanoTime] Unable to decode response", + "error", err, + ) return 0, err } @@ -319,7 +387,7 @@ func GetTokenAliases(gwCosmosmux *runtime.ServeMux, r *http.Request) ([]types.To r.URL.RawQuery = "" r.Method = "GET" - // GetLogger().Info("[grpc-call] Entering grpc call: ", r.URL.Path) + // log.CustomLogger().Info("[grpc-call] Entering grpc call: ", r.URL.Path) recorder := httptest.NewRecorder() gwCosmosmux.ServeHTTP(recorder, r) resp := recorder.Result() @@ -334,13 +402,15 @@ func GetTokenAliases(gwCosmosmux *runtime.ServeMux, r *http.Request) ([]types.To err := json.NewDecoder(resp.Body).Decode(&result) if err != nil { - GetLogger().Error("[grpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetTokenAliases][Decode] Unable to decode response", "error", err) } // save block time err = database.AddTokenAliases(result.Data) if err != nil { - GetLogger().Error("[grpc-call] Unable to save response") + log.CustomLogger().Error("[GetTokenAliases][AddTokenAliases] Unable to save response", + "error", err, + ) } return result.Data, result.DefaultDenom, result.Bech32Prefix @@ -352,7 +422,9 @@ func GetAllBalances(gwCosmosmux *runtime.ServeMux, r *http.Request, bech32Addr s r.URL.RawQuery = "pagination.limit=100000" r.Method = "GET" - // GetLogger().Info("[grpc-call] Entering grpc call: ", r.URL.Path) + log.CustomLogger().Info("Starting 'GetAllBalances' request...", + "endpoint", r.URL.Path, + ) recorder := httptest.NewRecorder() gwCosmosmux.ServeHTTP(recorder, r) @@ -365,9 +437,13 @@ func GetAllBalances(gwCosmosmux *runtime.ServeMux, r *http.Request, bech32Addr s result := AllBalancesResponse{} err := json.NewDecoder(resp.Body).Decode(&result) if err != nil { - GetLogger().Error("[grpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetAllBalances] Unable to decode response", + "error", err, + ) } + log.CustomLogger().Info("Finished 'GetAllBalances' request.") + return result.Balances } @@ -377,7 +453,9 @@ func GetTokenSupply(gwCosmosmux *runtime.ServeMux, r *http.Request) []types.Toke r.URL.RawQuery = "" r.Method = "GET" - // GetLogger().Info("[grpc-call] Entering grpc call: ", r.URL.Path) + log.CustomLogger().Info("Starting 'GetTokenSupply' request...", + "endpoint", r.URL.Path, + ) recorder := httptest.NewRecorder() gwCosmosmux.ServeHTTP(recorder, r) @@ -390,73 +468,105 @@ func GetTokenSupply(gwCosmosmux *runtime.ServeMux, r *http.Request) []types.Toke result := TokenAliasesResponse{} err := json.NewDecoder(resp.Body).Decode(&result) if err != nil { - GetLogger().Error("[grpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetTokenSupply] Unable to decode response", + "error", err, + ) } + log.CustomLogger().Info("Finished 'GetTokenSupply' request.") + return result.Supply } func GetKiraStatus(rpcAddr string) *types.KiraStatus { success, _, _ := MakeTendermintRPCRequest(rpcAddr, "/status", "") + log.CustomLogger().Info("Starting 'GetKiraStatus' request...", + "success", success, + ) + if success != nil { result := types.KiraStatus{} byteData, err := json.Marshal(success) if err != nil { - GetLogger().Error("[kira-status] Invalid response format", err) + log.CustomLogger().Error("[GetKiraStatus] Invalid response format", + "error", err, + ) } err = json.Unmarshal(byteData, &result) if err != nil { - GetLogger().Error("[kira-status] Invalid response format", err) + log.CustomLogger().Error("[GetKiraStatus] Invalid response format", + "error", err, + ) } return &result } + log.CustomLogger().Info("Finished 'GetKiraStatus' request.") + return nil } func GetInterxStatus(interxAddr string) *types.InterxStatus { success, _, _ := MakeGetRequest(interxAddr, "/api/status", "") + log.CustomLogger().Info("Starting 'GetInterxStatus' request...", + "success", success, + ) + if success != nil { result := types.InterxStatus{} byteData, err := json.Marshal(success) if err != nil { - GetLogger().Error("[interx-status] Invalid response format", err) + log.CustomLogger().Error("[GetInterxStatus][Marshal] Invalid response format", + "error", err, + ) return nil } err = json.Unmarshal(byteData, &result) if err != nil { - GetLogger().Error("[interx-status] Invalid response format", err) + log.CustomLogger().Error("[GetInterxStatus][Unmarshal] Invalid response format", + "error", err, + ) return nil } return &result } + log.CustomLogger().Info("Finished 'GetInterxStatus' request.") + return nil } func GetSnapshotInfo(interxAddr string) *types.SnapShotChecksumResponse { success, _, _ := MakeGetRequest(interxAddr, "/api/snapshot_info", "") + log.CustomLogger().Info("Starting 'GetSnapshotInfo' request...", + "success", success, + ) + if success != nil { result := types.SnapShotChecksumResponse{} byteData, err := json.Marshal(success) if err != nil { - GetLogger().Error("[interx-snapshot_info] Invalid response format", err) + log.CustomLogger().Error("[GetSnapshotInfo][interx-snapshot_info] Invalid response format", + "error", err, + ) return nil } err = json.Unmarshal(byteData, &result) if err != nil { - GetLogger().Error("[interx-snapshot_info] Invalid response format", err) + log.CustomLogger().Error("[GetSnapshotInfo][interx-snapshot_info] Invalid response format", + "error", err, + ) return nil } @@ -467,15 +577,21 @@ func GetSnapshotInfo(interxAddr string) *types.SnapShotChecksumResponse { return &result } + log.CustomLogger().Info("Finished 'GetSnapshotInfo' request.") + return nil } // GetBlockchain is a function to get block nano time func GetBlockchain(rpcAddr string) (*tmTypes.ResultBlockchainInfo, error) { endpoint := fmt.Sprintf("%s/blockchain", rpcAddr) + resp, err := http.Get(endpoint) if err != nil { - GetLogger().Error("[rpc-call] Unable to connect to ", endpoint) + log.CustomLogger().Error("[GetBlockchain] Unable to connect to ", + "endpoint", endpoint, + "error", err, + ) return nil, fmt.Errorf("blockchain query error") } defer resp.Body.Close() @@ -485,18 +601,24 @@ func GetBlockchain(rpcAddr string) (*tmTypes.ResultBlockchainInfo, error) { response := new(tmJsonRPCTypes.RPCResponse) if err := json.Unmarshal(respBody, response); err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetBlockchain][Unmarshal] Unable to decode response", + "error", err, + ) return nil, err } if response.Error != nil { - GetLogger().Error("[rpc-call] Blockchain query fail ") + log.CustomLogger().Error("[GetBlockchain] Blockchain query fail", + "error", response.Error, + ) return nil, fmt.Errorf("blockchain query error") } result := new(tmTypes.ResultBlockchainInfo) if err := tmjson.Unmarshal(response.Result, result); err != nil { - GetLogger().Error("[rpc-call] Unable to decode response: ", err) + log.CustomLogger().Error("[GetBlockchain][Unmarshal] Unable to decode response", + "error", err, + ) return nil, err } diff --git a/common/block.go b/common/block.go index ae3599b..e400904 100644 --- a/common/block.go +++ b/common/block.go @@ -5,6 +5,7 @@ import ( "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/database" + "github.com/KiraCore/interx/log" ) type BlockHeightTime struct { @@ -28,7 +29,9 @@ func GetAverageBlockTime() float64 { return 0 } - // GetLogger().Infof("[GetAverageBlockTime] %v", LatestNBlockTimes) + log.CustomLogger().Info(" `GetAverageBlockTime` Finished request.", + "LatestNBlockTimes", LatestNBlockTimes, + ) return total / float64(len(LatestNBlockTimes)) } @@ -43,9 +46,12 @@ func LoadAllBlocks() { } func AddNewBlock(height int64, timestamp int64) { + if len(LatestNBlockTimes) > 0 && LatestNBlockTimes[len(LatestNBlockTimes)-1].Height >= height { // not a new block - GetLogger().Errorf("[AddNewBlock] not a new block: %d", height) + log.CustomLogger().Error("[AddNewBlock] Failed to fetch new block.", + "height", height, + ) return } @@ -54,7 +60,9 @@ func AddNewBlock(height int64, timestamp int64) { prevBlockTimestamp, err := GetBlockNanoTime(config.Config.RPC, height-1) if err != nil { - GetLogger().Errorf("[AddNewBlock] Can't get block: %d", height-1) + log.CustomLogger().Error("[AddNewBlock][GetBlockNanoTime] Failed to fetch a block.", + "height", height-1, + ) return } @@ -62,7 +70,12 @@ func AddNewBlock(height int64, timestamp int64) { if len(LatestNBlockTimes) > 0 && timespan >= GetAverageBlockTime()*float64(config.Config.Block.HaltedAvgBlockTimes) { // a block just after a halt - GetLogger().Errorf("[AddNewBlock] block just after a halt: %d, timestamp: %f, average: %f", height, timespan, GetAverageBlockTime()) + log.CustomLogger().Error("`AddNewBlock` Block added just after a halt.", + "height", height, + "timestamp", timespan, + "average_block_time", GetAverageBlockTime(), + "halted_threshold", GetAverageBlockTime()*float64(config.Config.Block.HaltedAvgBlockTimes), + ) return } } @@ -76,6 +89,8 @@ func AddNewBlock(height int64, timestamp int64) { if len(LatestNBlockTimes) > N { LatestNBlockTimes = LatestNBlockTimes[len(LatestNBlockTimes)-N:] } + + log.CustomLogger().Info("Finished 'AddNewBlock' request.") } func UpdateN(_N int) { @@ -94,13 +109,17 @@ func UpdateN(_N int) { currentBlockTimestamp, err := GetBlockNanoTime(config.Config.RPC, current) if err != nil { - GetLogger().Errorf("[UpdateN] Can't get block: %d", current) + log.CustomLogger().Error("[UpdateN][GetBlockNanoTime] Failed to fetch a block.", + "height", current, + ) return } prevBlockTimestamp, err := GetBlockNanoTime(config.Config.RPC, current-1) if err != nil { - GetLogger().Errorf("[UpdateN] Can't get block: %d", current-1) + log.CustomLogger().Error("[UpdateN][GetBlockNanoTime] Failed to fetch a block.", + "height", current-1, + ) return } @@ -125,7 +144,9 @@ func IsConsensusStopped(validatorCount int) bool { blockTime, _ := time.Parse(time.RFC3339, NodeStatus.Blocktime) if blockHeight <= 1 { - GetLogger().Errorf("[UpdateN] block <= 1: %d", blockHeight) + log.CustomLogger().Error("[IsConsensusStopped] Failed to UpdateN block <= 1.", + "height", blockHeight, + ) return false } diff --git a/common/cache.go b/common/cache.go index 38081f8..3c6407f 100644 --- a/common/cache.go +++ b/common/cache.go @@ -7,15 +7,22 @@ import ( "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" ) // PutCache is a function to save value to cache func PutCache(chainIDHash string, endpointHash string, requestHash string, value types.InterxResponse) error { - // GetLogger().Info("[cache] Saving interx response") + + log.CustomLogger().Info("Starting 'PutCache' request...", + "endpoint", endpointHash, + ) data, err := json.Marshal(value) if err != nil { + log.CustomLogger().Error("[PutCache] Failed to marshal the response.", + "error", err, + ) return err } @@ -25,9 +32,14 @@ func PutCache(chainIDHash string, endpointHash string, requestHash string, value global.Mutex.Lock() err = os.MkdirAll(folderPath, os.ModePerm) if err != nil { + + log.CustomLogger().Error("[PutCache] Failed to create a folder.", + "error", err, + "folder_Path", folderPath, + ) + global.Mutex.Unlock() - GetLogger().Error("[cache] Unable to create a folder: ", folderPath) return err } @@ -35,14 +47,24 @@ func PutCache(chainIDHash string, endpointHash string, requestHash string, value global.Mutex.Unlock() if err != nil { - GetLogger().Error("[cache] Unable to save response: ", filePath) + log.CustomLogger().Error("[PutCache] Failed to write data to the named file.", + "error", err, + "file_Path", filePath, + ) } + log.CustomLogger().Info("Finished 'PutCache' request.") + return err } // GetCache is a function to get value from cache func GetCache(chainIDHash string, endpointHash string, requestHash string) (types.InterxResponse, error) { + + log.CustomLogger().Info("Starting 'GetCache' request...", + "endpoint", endpointHash, + ) + filePath := fmt.Sprintf("%s/%s/%s/%s", config.GetResponseCacheDir(), chainIDHash, endpointHash, requestHash) response := types.InterxResponse{} @@ -50,6 +72,10 @@ func GetCache(chainIDHash string, endpointHash string, requestHash string) (type data, err := os.ReadFile(filePath) if err != nil { + log.CustomLogger().Error("[GetCache] Failed to read data from the named file.", + "error", err, + "file_Path", filePath, + ) return response, err } diff --git a/common/gateway.go b/common/gateway.go index 69c7155..7b31d4a 100644 --- a/common/gateway.go +++ b/common/gateway.go @@ -13,6 +13,7 @@ import ( "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/database" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" "github.com/KiraCore/interx/types/rosetta" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" @@ -161,12 +162,20 @@ func (c conventionalMarshaller) MarshalAndConvert(endpoint string) ([]byte, erro // GetInterxRequest is a function to get Interx Request func GetInterxRequest(r *http.Request) types.InterxRequest { + + log.CustomLogger().Info("Starting 'GetInterxRequest' request...", + "method", r.Method, + "endpoint", r.URL.String(), + ) + request := types.InterxRequest{} request.Method = r.Method request.Endpoint = r.URL.String() request.Params, _ = ioutil.ReadAll(r.Body) + log.CustomLogger().Info("Finished 'GetInterxRequest' request.") + return request } @@ -184,6 +193,9 @@ func GetResponseFormat(request types.InterxRequest, rpcAddr string) *types.Proxy // GetResponseSignature is a function to get response signature func GetResponseSignature(response types.ProxyResponse) (string, string) { + + log.CustomLogger().Info("Starting 'GetResponseSignature' request...") + // Get Response Hash responseHash := GetBlake2bHash(response.Response) @@ -196,29 +208,45 @@ func GetResponseSignature(response types.ProxyResponse) (string, string) { sign.Response = responseHash signBytes, err := json.Marshal(sign) if err != nil { + log.CustomLogger().Error("[GetResponseSignature] Failed to create signature.", + "error", err, + ) return "", responseHash } // Get Signature signature, err := config.Config.PrivKey.Sign(signBytes) if err != nil { + log.CustomLogger().Error("[GetResponseSignature] Failed to fetch signature.", + "error", err, + ) return "", responseHash } + log.CustomLogger().Info("Finished 'GetResponseSignature' request.") + return base64.StdEncoding.EncodeToString([]byte(signature)), responseHash } // SearchCache is a function to search response in cache func SearchCache(request types.InterxRequest, response *types.ProxyResponse) (bool, interface{}, interface{}, int) { + + log.CustomLogger().Info("Starting SearchCache") + chainIDHash := GetBlake2bHash(response.Chainid) endpointHash := GetBlake2bHash(request.Endpoint) requestHash := GetBlake2bHash(request) - // GetLogger().Info(chainIDHash, endpointHash, requestHash) + log.CustomLogger().Info("`SearchCache` Config Path", "chainIDHash", chainIDHash, + "endpointHash", endpointHash, "requestHash", requestHash, + ) + result, err := GetCache(chainIDHash, endpointHash, requestHash) - // GetLogger().Info(result) if err != nil { + log.CustomLogger().Error("[SearchCache] Failed to run GetCache function.", + "error", err, + ) return false, nil, nil, -1 } @@ -226,6 +254,8 @@ func SearchCache(request types.InterxRequest, response *types.ProxyResponse) (bo return false, nil, nil, -1 } + log.CustomLogger().Info("Finished SearchCache") + return true, result.Response.Response, result.Response.Error, result.Status } @@ -235,7 +265,7 @@ func WrapResponse(w http.ResponseWriter, request types.InterxRequest, response t statusCode = 503 // Service Unavailable Error } if saveToCache { - // GetLogger().Info("[gateway] Saving in the cache") + log.CustomLogger().Info("Starting Wrap Response...") chainIDHash := GetBlake2bHash(response.Chainid) endpointHash := GetBlake2bHash(request.Endpoint) @@ -249,9 +279,10 @@ func WrapResponse(w http.ResponseWriter, request types.InterxRequest, response t CachingBlockDuration: conf.CachingBlockDuration, }) if err != nil { - GetLogger().Error("[gateway] Failed to save in the cache: ", err.Error()) + log.CustomLogger().Error("[WrapResponse] Failed to save in the cache.", + "error", err, + ) } - // GetLogger().Info("[gateway] Save finished") } } @@ -279,7 +310,9 @@ func WrapResponse(w http.ResponseWriter, request types.InterxRequest, response t case string: _, err := w.Write([]byte(v)) if err != nil { - GetLogger().Error("[gateway] Failed to make a response", err.Error()) + log.CustomLogger().Error("[WrapResponse] Failed to make a response.", + "error", err, + ) } return } @@ -287,7 +320,9 @@ func WrapResponse(w http.ResponseWriter, request types.InterxRequest, response t encoded, _ := conventionalMarshaller{response.Response}.MarshalAndConvert(request.Endpoint) _, err := w.Write(encoded) if err != nil { - GetLogger().Error("[gateway] Failed to make a response", err.Error()) + log.CustomLogger().Error("[WrapResponse] Failed to make a response.", + "error", err, + ) } } else { w.WriteHeader(statusCode) @@ -299,7 +334,9 @@ func WrapResponse(w http.ResponseWriter, request types.InterxRequest, response t encoded, _ := conventionalMarshaller{response.Error}.MarshalAndConvert(request.Endpoint) _, err := w.Write(encoded) if err != nil { - GetLogger().Error("[gateway] Failed to make a response", err.Error()) + log.CustomLogger().Error("[WrapResponse] Failed to make a response.", + "error", err, + ) } } } diff --git a/common/gov.go b/common/gov.go index 198982b..482e15c 100644 --- a/common/gov.go +++ b/common/gov.go @@ -3,6 +3,7 @@ package common import ( "encoding/json" + "github.com/KiraCore/interx/log" govTypes "github.com/KiraCore/interx/types/kira/gov" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -79,13 +80,17 @@ func QueryVotersFromGrpcResult(success interface{}) ([]govTypes.Voter, error) { byteData, err := json.Marshal(success) if err != nil { - GetLogger().Error("[query-voters] Invalid response format: ", err) + log.CustomLogger().Error("[QueryVotersFromGrpcResult] Failed to marshal response.", + "error", err, + ) return nil, err } err = json.Unmarshal(byteData, &result) if err != nil { - GetLogger().Error("[query-voters] Invalid response format: ", err) + log.CustomLogger().Error("[QueryVotersFromGrpcResult] Failed to unmarshal response.", + "error", err, + ) return nil, err } @@ -126,13 +131,17 @@ func QueryVotesFromGrpcResult(success interface{}) ([]govTypes.Vote, error) { byteData, err := json.Marshal(success) if err != nil { - GetLogger().Error("[query-votes] Invalid response format: ", err) + log.CustomLogger().Error("[QueryVotesFromGrpcResult] Failed to marshal response.", + "error", err, + ) return nil, err } err = json.Unmarshal(byteData, &result) if err != nil { - GetLogger().Error("[query-votes] Invalid response format: ", err) + log.CustomLogger().Error("[QueryVotesFromGrpcResult] Failed to unmarshal response.", + "error", err, + ) return nil, err } @@ -155,12 +164,16 @@ func QueryNetworkPropertiesFromGrpcResult(success interface{}) (NetworkPropertie result := NetworkPropertiesResponse{} byteData, err := json.Marshal(success) if err != nil { - GetLogger().Error("[query-network-properties] Invalid response format", err) + log.CustomLogger().Error("[QueryNetworkPropertiesFromGrpcResult] Failed to marshal response.", + "error", err, + ) return NetworkPropertiesResponse{}, err } err = json.Unmarshal(byteData, &result) if err != nil { - GetLogger().Error("[query-network-properties] Invalid response format", err) + log.CustomLogger().Error("[QueryNetworkPropertiesFromGrpcResult] Failed to unmarshal response.", + "error", err, + ) return NetworkPropertiesResponse{}, err } diff --git a/common/hash.go b/common/hash.go index 2aadb00..3e860b6 100644 --- a/common/hash.go +++ b/common/hash.go @@ -5,6 +5,8 @@ import ( "crypto/sha256" "encoding/json" "fmt" + + "github.com/KiraCore/interx/log" ) // GetSha256SumFromBytes is a function to get hash @@ -18,7 +20,9 @@ func GetBlake2bHash(request interface{}) string { // Calculate blake2b hash requestJSON, err := json.Marshal(request) if err != nil { - GetLogger().Error("[blake2b-hash] Unable to marshal request: ", err) + log.CustomLogger().Error("[GetBlake2bHash] Failed to marshal response.", + "error", err, + ) } return GetSha256SumFromBytes(requestJSON) @@ -29,7 +33,9 @@ func GetMD5Hash(request interface{}) string { // Calculate md5 hash requestJSON, err := json.Marshal(request) if err != nil { - GetLogger().Error("[md5-hash] Unable to marshal request: ", err) + log.CustomLogger().Error("[GetMD5Hash] Failed to marshal response.", + "error", err, + ) } hash := md5.Sum([]byte(requestJSON)) diff --git a/config/constants.go b/config/constants.go index 96d5828..ee6a213 100755 --- a/config/constants.go +++ b/config/constants.go @@ -1,8 +1,8 @@ package config const ( - InterxVersion = "v0.4.48" - SekaiVersion = "v0.3.42" + InterxVersion = "v0.4.50" + SekaiVersion = "v0.4.1" CosmosVersion = "v0.47.6" QueryDashboard = "/api/dashboard" diff --git a/config/init.go b/config/init.go index c0265ff..a1eb088 100644 --- a/config/init.go +++ b/config/init.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "strings" + "github.com/KiraCore/interx/log" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tyler-smith/go-bip39" ) @@ -295,11 +296,18 @@ func InitConfig( bytes, err := json.MarshalIndent(&configFromFile, "", " ") if err != nil { + log.CustomLogger().Error("[InitConfig] Failed to marshal config.", + "error", err, + ) panic(err) } err = ioutil.WriteFile(configFilePath, bytes, 0644) if err != nil { + log.CustomLogger().Error("[InitConfig] Failed to write to file.", + "config_File_Path", configFilePath, + "error", err, + ) panic(err) } } diff --git a/config/load.go b/config/load.go index 9e73b77..69f85af 100644 --- a/config/load.go +++ b/config/load.go @@ -9,6 +9,7 @@ import ( "os" "strings" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" sekaiapp "github.com/KiraCore/sekai/app" sekaiappparams "github.com/KiraCore/sekai/app/params" @@ -43,6 +44,9 @@ func mnemonicFromFile(filename string) string { mnemonic, err := ioutil.ReadFile(filename) if err != nil { + log.CustomLogger().Error("[mnemonicFromFile] Failed to read from file.", + "error", err, + ) panic(err) } @@ -82,20 +86,39 @@ func serveGRPC(r *http.Request, gwCosmosmux *runtime.ServeMux) (interface{}, int // LoadAddressAndDenom is a function to load addresses and migrate config using custom bech32 and denom prefixes func LoadAddressAndDenom(configFilePath string, gwCosmosmux *runtime.ServeMux, rpcAddr string, gatewayAddr string) { + + log.CustomLogger().Info("Starting 'LoadAddressAndDenom' request...") + request, _ := http.NewRequest("GET", "http://"+gatewayAddr+"/kira/gov/custom_prefixes", nil) response, failure, _ := serveGRPC(request, gwCosmosmux) + log.CustomLogger().Info("Proccessed serve GRPC for `LoadAddressAndDenom`.", + "configFilePath", configFilePath, + "gatewayAddr", gatewayAddr, + "failure", failure, + ) + if response == nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to serve GPRC.", + "failure", failure, + ) panic(failure) } byteData, err := json.Marshal(response) if err != nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to marshal response.", + "error", err, + ) panic(err) } + result := map[string]string{} err = json.Unmarshal(byteData, &result) if err != nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to unmarshal response data.", + "error", err, + ) panic(err) } @@ -110,9 +133,13 @@ func LoadAddressAndDenom(configFilePath string, gwCosmosmux *runtime.ServeMux, r sekaiappparams.ConsNodePubKeyPrefix = bech32Prefix + "valconspub" sekaiappparams.SetConfig() + file, err := ioutil.ReadFile(configFilePath) if err != nil { - fmt.Println("Invalid configuration: {}", err) + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to read configuration file.", + "configFilePath", configFilePath, + "error", err, + ) panic(err) } @@ -120,24 +147,33 @@ func LoadAddressAndDenom(configFilePath string, gwCosmosmux *runtime.ServeMux, r err = json.Unmarshal([]byte(file), &configFromFile) if err != nil { - fmt.Println("Invalid configuration: {}", err) + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to unmarshal configuration file.", + "configFilePath", configFilePath, + "error", err, + ) panic(err) } //=============== interx address =============== Config.Mnemonic = LoadMnemonic(configFromFile.MnemonicFile) if !bip39.IsMnemonicValid(Config.Mnemonic) { - fmt.Println("Invalid Interx Mnemonic: ", Config.Mnemonic) + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to load mnemonic.") panic("Invalid Interx Mnemonic") } seed, err := bip39.NewSeedWithErrorChecking(Config.Mnemonic, "") if err != nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to validate seed.", + "error", err, + ) panic(err) } master, ch := hd.ComputeMastersFromSeed(seed) priv, err := hd.DerivePrivateKeyForPath(master, ch, "44'/118'/0'/0/0") if err != nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to derive form address path.", + "error", err, + ) panic(err) } @@ -183,17 +219,19 @@ func LoadAddressAndDenom(configFilePath string, gwCosmosmux *runtime.ServeMux, r } if !bip39.IsMnemonicValid(Config.Faucet.Mnemonic) { - fmt.Println("Invalid Faucet Mnemonic: ", Config.Faucet.Mnemonic) + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to validate faucet mnemonic.") panic("Invalid Faucet Mnemonic") } seed, err = bip39.NewSeedWithErrorChecking(Config.Faucet.Mnemonic, "") if err != nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to validate new seed from mnemonic.") panic(err) } master, ch = hd.ComputeMastersFromSeed(seed) priv, err = hd.DerivePrivateKeyForPath(master, ch, "44'/118'/0'/0/0") if err != nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to derive private key from the path.") panic(err) } @@ -214,11 +252,13 @@ func LoadAddressAndDenom(configFilePath string, gwCosmosmux *runtime.ServeMux, r // save denom changes to config bytes, err := json.MarshalIndent(&configFromFile, "", " ") if err != nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to marshal config file.") panic(err) } err = ioutil.WriteFile(configFilePath, bytes, 0644) if err != nil { + log.CustomLogger().Error("[LoadAddressAndDenom] Failed to write config file to the file.") panic(err) } } @@ -229,7 +269,10 @@ func LoadConfig(configFilePath string) { file, err := ioutil.ReadFile(configFilePath) if err != nil { - fmt.Println("Invalid configuration: {}", err) + log.CustomLogger().Error("[LoadConfig] Failed to load interx configurations from a given file.", + "config_file_path", configFilePath, + "error", err, + ) panic(err) } @@ -237,7 +280,9 @@ func LoadConfig(configFilePath string) { err = json.Unmarshal([]byte(file), &configFromFile) if err != nil { - fmt.Println("Invalid configuration: {}", err) + log.CustomLogger().Error("[LoadConfig] Failed to unmarshal interx configurations file.", + "error", err, + ) panic(err) } @@ -258,6 +303,9 @@ func LoadConfig(configFilePath string) { Config.AddrBooks = strings.Split(configFromFile.AddrBooks, ",") Config.NodeKey, err = p2p.LoadOrGenNodeKey(configFromFile.NodeKey) if err != nil { + log.CustomLogger().Error("[LoadConfig] Failed to load node key fro interx configurations file.", + "error", err, + ) panic(err) } @@ -330,6 +378,8 @@ func LoadConfig(configFilePath string) { Config.Bitcoin = configFromFile.Bitcoin Config.SnapshotInterval = configFromFile.SnapshotInterval + + log.CustomLogger().Info("Finished 'LoadConfig' request.") } // GenPrivKey is a function to generate a privKey @@ -353,6 +403,9 @@ func GetDbCacheDir() string { } func LoadAddressBooks() []types.AddrBookJSON { + + log.CustomLogger().Info("Starting 'LoadAddressBooks' request...") + addrBooks := make([]types.AddrBookJSON, 0) for _, addrFile := range Config.AddrBooks { file, _ := ioutil.ReadFile(addrFile) @@ -362,16 +415,24 @@ func LoadAddressBooks() []types.AddrBookJSON { err := json.Unmarshal([]byte(file), &book) if err != nil { - fmt.Println("Failed to load addrBook: ", addrFile) + log.CustomLogger().Error(" [LoadAddressBooks] Failed to load addrBook.", + "error", err, + "addrFile", addrFile, + ) } addrBooks = append(addrBooks, book) } + log.CustomLogger().Info("Finished 'LoadAddressBooks' request.") + return addrBooks } func LoadUniqueIPAddresses() []string { + + log.CustomLogger().Info("Starting 'LoadUniqueIPAddresses' request...") + ipAddresses := make([]string, 0) flag := make(map[string]bool) @@ -383,7 +444,10 @@ func LoadUniqueIPAddresses() []string { err := json.Unmarshal([]byte(file), &book) if err != nil { - fmt.Println("Failed to load addrBook: ", addrFile) + log.CustomLogger().Error(" [LoadUniqueIPAddresses] Failed to load addrBook.", + "error", err, + "addrFile", addrFile, + ) } for _, addr := range book.Addrs { @@ -394,6 +458,8 @@ func LoadUniqueIPAddresses() []string { } } + log.CustomLogger().Info("Finished 'LoadUniqueIPAddresses' request.") + return ipAddresses } diff --git a/database/block.go b/database/block.go old mode 100644 new mode 100755 index 819a80d..a45ba6d --- a/database/block.go +++ b/database/block.go @@ -2,6 +2,7 @@ package database import ( "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/sonyarouje/simdb/db" ) @@ -28,7 +29,13 @@ func LoadBlockDbDriver() { // GetBlockTime is a function to get blockTime func GetBlockTime(height int64) (int64, error) { + + log.CustomLogger().Info("Starting 'GetBlockTime' request...") + if blockDb == nil { + log.CustomLogger().Error("[GetBlockTime] block db is null.", + "height", height, + ) panic("cache dir not set") } @@ -42,12 +49,18 @@ func GetBlockTime(height int64) (int64, error) { return 0, err } + log.CustomLogger().Info("Finished 'GetBlockTime' request.") + return data.Timestamp, nil } // GetAllBlocks is a function to get all blockTimes func GetAllBlocks() []interface{} { + + log.CustomLogger().Info("Starting 'GetAllBlocks' request...") + if blockDb == nil { + log.CustomLogger().Error("[GetBlockTime] block db is null.") panic("cache dir not set") } @@ -55,12 +68,18 @@ func GetAllBlocks() []interface{} { rawData := blockDb.Open(BlockData{}).RawArray() EnableStdout() + log.CustomLogger().Info("Finished 'GetAllBlocks' request.") + return rawData } // AddBlockTime is a function to add blockTime func AddBlockTime(height int64, timestamp int64) { + + log.CustomLogger().Info("Starting 'AddBlockTime' request...") + if blockDb == nil { + log.CustomLogger().Error("[AddBlockTime] block db is null.") panic("cache dir not set") } @@ -81,6 +100,8 @@ func AddBlockTime(height int64, timestamp int64) { } } + + log.CustomLogger().Info("Finished 'AddBlockTime' request.") } var ( diff --git a/database/blocknano.go b/database/blocknano.go old mode 100644 new mode 100755 index caf162d..d739207 --- a/database/blocknano.go +++ b/database/blocknano.go @@ -2,6 +2,7 @@ package database import ( "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/sonyarouje/simdb/db" ) @@ -28,7 +29,11 @@ func LoadBlockNanoDbDriver() { // GetBlockNanoTime is a function to get blockTime func GetBlockNanoTime(height int64) (int64, error) { + + log.CustomLogger().Info("Starting 'GetBlockNanoTime' request...") + if blockNanoDb == nil { + log.CustomLogger().Error("[GetBlockNanoTime] block Nano Db is null.") panic("cache dir not set") } @@ -42,12 +47,18 @@ func GetBlockNanoTime(height int64) (int64, error) { return 0, err } + log.CustomLogger().Info("Finished 'GetBlockNanoTime' request.") + return data.Timestamp, nil } // AddBlockNanoTime is a function to add blockTime func AddBlockNanoTime(height int64, timestamp int64) { + + log.CustomLogger().Info("Starting 'AddBlockNanoTime' request...") + if blockNanoDb == nil { + log.CustomLogger().Error("[AddBlockNanoTime] block Nano Db is null.") panic("cache dir not set") } @@ -68,6 +79,8 @@ func AddBlockNanoTime(height int64, timestamp int64) { } } + + log.CustomLogger().Info("Finished 'AddBlockNanoTime' request.") } var ( diff --git a/database/faucet.go b/database/faucet.go old mode 100644 new mode 100755 index 4b4cc56..acb7c03 --- a/database/faucet.go +++ b/database/faucet.go @@ -4,6 +4,7 @@ import ( "time" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/sonyarouje/simdb/db" ) @@ -29,6 +30,9 @@ func LoadFaucetDbDriver() { } func isClaimExist(address string) bool { + + log.CustomLogger().Info("Starting 'isClaimExist' request...") + if faucetDb == nil { panic("cache dir not set") } @@ -39,10 +43,15 @@ func isClaimExist(address string) bool { err := faucetDb.Open(FaucetClaim{}).Where("address", "=", address).First().AsEntity(&data) EnableStdout() + log.CustomLogger().Info("Finished 'isClaimExist' request.") + return err == nil } func getClaim(address string) time.Time { + + log.CustomLogger().Info("Starting 'getClaim' request...") + if faucetDb == nil { panic("cache dir not set") } @@ -51,18 +60,26 @@ func getClaim(address string) time.Time { DisableStdout() err := faucetDb.Open(FaucetClaim{}).Where("address", "=", address).First().AsEntity(&data) + EnableStdout() if err != nil { + log.CustomLogger().Error(err.Error()) panic(err) } + log.CustomLogger().Info("Finished 'getClaim' request.") + return data.Claim } // GetClaimTimeLeft is a function to get left time for next claim func GetClaimTimeLeft(address string) int64 { + + log.CustomLogger().Info("Starting 'GetClaimTimeLeft' request...") + if faucetDb == nil { + log.CustomLogger().Error("[GetClaimTimeLeft] faucet Db is null.") panic("cache dir not set") } @@ -76,12 +93,18 @@ func GetClaimTimeLeft(address string) int64 { return 0 } + log.CustomLogger().Info("Finished 'GetClaimTimeLeft' request.") + return config.Config.Faucet.TimeLimit - diff } // AddNewClaim is a function to add current claim time func AddNewClaim(address string, claim time.Time) { + + log.CustomLogger().Info("Starting 'AddNewClaim' request...") + if faucetDb == nil { + log.CustomLogger().Error("[AddNewClaim] faucet Db is null.") panic("cache dir not set") } @@ -98,6 +121,7 @@ func AddNewClaim(address string, claim time.Time) { EnableStdout() if err != nil { + log.CustomLogger().Error(err.Error()) panic(err) } } else { @@ -106,9 +130,12 @@ func AddNewClaim(address string, claim time.Time) { EnableStdout() if err != nil { + log.CustomLogger().Error(err.Error()) panic(err) } } + + log.CustomLogger().Info("Finished 'AddNewClaim' request.") } var ( diff --git a/database/proposals.go b/database/proposals.go old mode 100644 new mode 100755 index 70a4dcb..1f98597 --- a/database/proposals.go +++ b/database/proposals.go @@ -8,6 +8,7 @@ import ( "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" govTypes "github.com/KiraCore/interx/types/kira/gov" ) @@ -68,7 +69,11 @@ func SaveProposals(propsData []govTypes.CachedProposal) error { if err != nil { global.Mutex.Unlock() - fmt.Println("[cache] Unable to create a folder: ", folderPath) + log.CustomLogger().Error("[SaveProposals] Unable to create a folder", + "folder path", folderPath, + "error", err, + ) + return err } @@ -76,7 +81,9 @@ func SaveProposals(propsData []govTypes.CachedProposal) error { global.Mutex.Unlock() if err != nil { - fmt.Println("[cache] Unable to save response: ", filePath) + fmt.Println("[SaveProposals] Unable to save response", "file path", filePath, + "error", err, + ) } return err diff --git a/database/transactions.go b/database/transactions.go old mode 100644 new mode 100755 index 5b0dbf0..17b363d --- a/database/transactions.go +++ b/database/transactions.go @@ -8,6 +8,7 @@ import ( "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" tmTypes "github.com/cometbft/cometbft/rpc/core/types" ) @@ -75,9 +76,13 @@ func SaveTransactions(address string, txsData tmTypes.ResultTxSearch, isWithdraw global.Mutex.Lock() err = os.MkdirAll(folderPath, os.ModePerm) if err != nil { + global.Mutex.Unlock() + log.CustomLogger().Error("[SaveTransactions][cache] Unable to create a folder", + "folder path", folderPath, + "error", err, + ) - fmt.Println("[cache] Unable to create a folder: ", folderPath) return err } @@ -85,7 +90,12 @@ func SaveTransactions(address string, txsData tmTypes.ResultTxSearch, isWithdraw global.Mutex.Unlock() if err != nil { - fmt.Println("[cache] Unable to save response: ", filePath) + + log.CustomLogger().Error("[SaveTransactions][cache] Unable to save response", + "file path", filePath, + "error", err, + ) + } return err diff --git a/gateway/bitcoin/accounts.go b/gateway/bitcoin/accounts.go index 07f26f0..6dc9bf4 100644 --- a/gateway/bitcoin/accounts.go +++ b/gateway/bitcoin/accounts.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" @@ -110,7 +111,11 @@ func QueryBtcAccountsRequest(rpcAddr string) http.HandlerFunc { response := common.GetResponseFormat(request, rpcAddr) statusCode := http.StatusOK - common.GetLogger().Info("[query-btc-accounts] Entering accounts query: ", chain) + log.CustomLogger().Info("Starting QueryBtcAccountsRequest", + "chain", chain, + "address", address, + "statusCode", statusCode, + ) if !common.RPCMethods["GET"][config.QueryBitcoinAccounts].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -121,7 +126,10 @@ func QueryBtcAccountsRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-btc-accounts] Returning from the cache: ", chain) + log.CustomLogger().Info("Returning Btc Account from the cache", + "chain", chain, + ) + return } } diff --git a/gateway/bitcoin/balances.go b/gateway/bitcoin/balances.go index 9b8320c..f4145db 100644 --- a/gateway/bitcoin/balances.go +++ b/gateway/bitcoin/balances.go @@ -8,6 +8,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/btcsuite/btcd/btcjson" "github.com/gorilla/mux" @@ -361,7 +362,11 @@ func QueryBtcBalancesRequest(rpcAddr string) http.HandlerFunc { response := common.GetResponseFormat(request, rpcAddr) statusCode := http.StatusOK - common.GetLogger().Info("[query-btc-balances] Entering balances query: ", chain) + log.CustomLogger().Info("Starting QueryBtcBalancesRequest", + "chain", chain, + "address", address, + "statusCode", statusCode, + ) if !common.RPCMethods["GET"][config.QueryBitcoinBalances].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -372,7 +377,9 @@ func QueryBtcBalancesRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-btc-balances] Returning from the cache: ", chain) + log.CustomLogger().Info("Returning Btc Balances from the cache", + "chain", chain, + ) return } } diff --git a/gateway/bitcoin/block.go b/gateway/bitcoin/block.go index c2ace6a..4a2200f 100644 --- a/gateway/bitcoin/block.go +++ b/gateway/bitcoin/block.go @@ -7,6 +7,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" @@ -133,7 +134,9 @@ func QueryBitcoinBlockRequest(rpcAddr string) http.HandlerFunc { response := common.GetResponseFormat(request, rpcAddr) statusCode := http.StatusOK - common.GetLogger().Info("[query-bitcoin-block] Entering block query: ", chain) + log.CustomLogger().Info("Starting QueryBitcoinBlockRequest ...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryBitcoinBlock].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -144,7 +147,9 @@ func QueryBitcoinBlockRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-bitcoin-block] Returning from the cache: ", chain) + log.CustomLogger().Info("Returning Bitcoin Block from the cache", + "chain", chain, + ) return } } diff --git a/gateway/bitcoin/faucet.go b/gateway/bitcoin/faucet.go index 073f0ad..ecca59b 100644 --- a/gateway/bitcoin/faucet.go +++ b/gateway/bitcoin/faucet.go @@ -7,6 +7,7 @@ import ( jsonrpc2 "github.com/KeisukeYamashita/go-jsonrpc" "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" ) @@ -72,7 +73,9 @@ func BitcoinFaucetRequest(rpcAddr string) http.HandlerFunc { queries := r.URL.Query() claimAddr := queries["claim"] - common.GetLogger().Info("[bitcoin-faucet] Entering faucet request: ", chain) + log.CustomLogger().Info(" Starting BitcoinFaucetRequest request...", + "chain", chain, + ) if len(claimAddr) != 0 { response.Response, response.Error, statusCode = bitcoinFaucetHandle(r, chain, claimAddr[0]) diff --git a/gateway/bitcoin/status.go b/gateway/bitcoin/status.go index c132457..ac3e233 100644 --- a/gateway/bitcoin/status.go +++ b/gateway/bitcoin/status.go @@ -10,6 +10,7 @@ import ( jsonrpc2 "github.com/KeisukeYamashita/go-jsonrpc" "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" "github.com/btcsuite/btcd/btcjson" @@ -151,7 +152,9 @@ func QueryBitcoinStatusRequest(rpcAddr string) http.HandlerFunc { response := common.GetResponseFormat(request, rpcAddr) statusCode := http.StatusOK - common.GetLogger().Info("[query-bitcoin-status] Entering status query: ", chain) + log.CustomLogger().Info(" Starting QueryBitcoinStatusRequest request...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryBitcoinStatus].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -162,7 +165,9 @@ func QueryBitcoinStatusRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-bitcoin-status] Returning from the cache: ", chain) + log.CustomLogger().Info(" Returning Bitcoin Status from the cache", + "chain", chain, + ) return } } diff --git a/gateway/bitcoin/transactions.go b/gateway/bitcoin/transactions.go index 54d205e..491e52a 100644 --- a/gateway/bitcoin/transactions.go +++ b/gateway/bitcoin/transactions.go @@ -7,6 +7,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/btcsuite/btcd/btcjson" "github.com/gorilla/mux" @@ -129,7 +130,9 @@ func QueryBtcTransactionRequest(rpcAddr string) http.HandlerFunc { response := common.GetResponseFormat(request, rpcAddr) statusCode := http.StatusOK - common.GetLogger().Info("[query-btc-transaction] Entering transaction query: ", chain) + log.CustomLogger().Info(" Starting QueryBtcTransactionRequest request...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryBitcoinTransaction].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -140,7 +143,10 @@ func QueryBtcTransactionRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-btc-transaction] Returning from the cache: ", chain) + log.CustomLogger().Info(" Returning Btc Transaction from the cache.", + "chain", chain, + ) + return } } diff --git a/gateway/bitcoin/transfer.go b/gateway/bitcoin/transfer.go index 0b044d2..90afbc2 100644 --- a/gateway/bitcoin/transfer.go +++ b/gateway/bitcoin/transfer.go @@ -7,6 +7,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/btcsuite/btcd/btcjson" "github.com/gorilla/mux" @@ -183,7 +184,9 @@ func QueryBtcTransferRequest(rpcAddr string) http.HandlerFunc { response := common.GetResponseFormat(request, rpcAddr) statusCode := http.StatusOK - common.GetLogger().Info("[query-btc-transfer] Entering transfer execute: ", chain) + log.CustomLogger().Info(" Starting QueryBtcTransferRequest request...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryBitcoinTransfer].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -194,7 +197,10 @@ func QueryBtcTransferRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-btc-transfer] Returning from the cache: ", chain) + log.CustomLogger().Info(" Returning Btc Transfer from the cache.", + "chain", chain, + ) + return } } diff --git a/gateway/cosmos/auth.go b/gateway/cosmos/auth.go index ab65eb2..68b82a3 100755 --- a/gateway/cosmos/auth.go +++ b/gateway/cosmos/auth.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" ) @@ -31,7 +32,9 @@ func QueryAccountsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-account] Entering account query: ", bech32addr) + log.CustomLogger().Info(" Starting QueryAccountsRequest request...", + "bech32addr", bech32addr, + ) if !common.RPCMethods["GET"][config.QueryAccounts].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -42,7 +45,10 @@ func QueryAccountsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-account] Returning from the cache: ", bech32addr) + log.CustomLogger().Info(" Returning Account from the cache.", + "bech32addr", bech32addr, + ) + return } } diff --git a/gateway/cosmos/bank.go b/gateway/cosmos/bank.go index 4683593..f70f8b9 100755 --- a/gateway/cosmos/bank.go +++ b/gateway/cosmos/bank.go @@ -8,6 +8,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" @@ -34,7 +35,7 @@ func QuerySupplyRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Hand request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-supply] Entering total supply query") + log.CustomLogger().Info(" Starting QuerySupplyRequest request...") if !common.RPCMethods["GET"][config.QueryTotalSupply].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -45,7 +46,8 @@ func QuerySupplyRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Hand response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-supply] Returning from the cache") + log.CustomLogger().Info(" Returning Supply from the cache.") + return } } @@ -184,7 +186,9 @@ func QueryBalancesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-balances] Entering balances query: ", bech32addr) + log.CustomLogger().Info(" Starting QueryBalancesRequest request...", + "address", bech32addr, + ) if !common.RPCMethods["GET"][config.QueryBalances].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -195,7 +199,10 @@ func QueryBalancesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-balances] Returning from the cache: ", bech32addr) + log.CustomLogger().Info(" Returning Balances from the cache", + "address", bech32addr, + ) + return } } diff --git a/gateway/cosmos/tx.go b/gateway/cosmos/tx.go index 2673806..244c316 100644 --- a/gateway/cosmos/tx.go +++ b/gateway/cosmos/tx.go @@ -9,6 +9,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" legacytx "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" "github.com/gorilla/mux" @@ -36,7 +37,9 @@ func postTxHandle(r *http.Request, request types.InterxRequest, rpcAddr string) var req PostTxReq err := json.Unmarshal(request.Params, &req) if err != nil { - common.GetLogger().Error("[post-transaction] Failed to unmarshal request: ", err) + log.CustomLogger().Error("[postTxHandle] Failed to unmarshal request.", + "error", err, + ) return common.ServeError(0, "failed to unmarshal", err.Error(), http.StatusBadRequest) } @@ -49,7 +52,9 @@ func postTxHandle(r *http.Request, request types.InterxRequest, rpcAddr string) } if !txModeAllowed { - common.GetLogger().Error("[post-transaction] Invalid transaction mode") + log.CustomLogger().Error("[postTxHandle] Invalid transaction mode.", + "tx mode", req.Mode, + ) return common.ServeError(0, "invalid transaction mode: ", req.Mode, http.StatusBadRequest) } @@ -61,25 +66,33 @@ func postTxHandle(r *http.Request, request types.InterxRequest, rpcAddr string) } else if req.Mode == "async" { url = "/broadcast_tx_async" } else { - common.GetLogger().Error("[post-transaction] Invalid mode: ", req.Mode) + log.CustomLogger().Error("[postTxHandle] Invalid transaction mode.", + "tx mode", req.Mode, + ) return common.ServeError(0, "", "invalid mode", http.StatusBadRequest) } signedTx, err := config.EncodingCg.TxConfig.TxJSONDecoder()(req.Tx) if err != nil { - common.GetLogger().Error("[post-transaction] Failed to decode tx request: ", err) + log.CustomLogger().Error("[postTxHandle] Failed to decode tx request.", + "error", err, + ) return common.ServeError(0, "failed to get signed TX", err.Error(), http.StatusBadRequest) } txBuilder, err := config.EncodingCg.TxConfig.WrapTxBuilder(signedTx) if err != nil { - common.GetLogger().Error("[post-transaction] Failed to get tx builder: ", err) + log.CustomLogger().Error("[postTxHandle] Failed to get tx builder.", + "error", err, + ) return common.ServeError(0, "failed to get TX builder", err.Error(), http.StatusBadRequest) } txBytes, err := config.EncodingCg.TxConfig.TxEncoder()(txBuilder.GetTx()) if err != nil { - common.GetLogger().Error("[post-transaction] Failed to get tx bytes: ", err) + log.CustomLogger().Error("[postTxHandle] Failed to get tx bytes.", + "error", err, + ) return common.ServeError(0, "failed to get TX bytes", err.Error(), http.StatusBadRequest) } @@ -93,7 +106,7 @@ func PostTxRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[post-transaction] Entering transaction broadcast: ") + log.CustomLogger().Info("`PostTxRequest` Starting Request...") if !common.RPCMethods["POST"][config.PostTransaction].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -121,7 +134,7 @@ func QueryTxHashRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-txhash] Entering transaction hash query: ", hash) + log.CustomLogger().Info("`QueryTxHashRequest` Transaction Hash Request...", "hash", hash) if !common.RPCMethods["GET"][config.QueryTransactionHash].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -132,7 +145,8 @@ func QueryTxHashRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-txhash] Returning from the cache: ", hash) + log.CustomLogger().Info("`QueryTxHashRequest` Returning from the cache", "hash", hash) + return } } @@ -156,7 +170,7 @@ func encodeTransactionHandle(r *http.Request, request types.InterxRequest, rpcAd err := config.EncodingCg.Amino.UnmarshalJSON(request.Params, &req) if err != nil { - common.GetLogger().Error("[encode-transaction] Failed to decode tx request: ", err) + log.CustomLogger().Error("[EncodeTransactionHandle] Failed encode transaction", "error", err) return common.ServeError(0, "failed to unmarshal", err.Error(), http.StatusBadRequest) } @@ -179,7 +193,7 @@ func EncodeTransaction(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[encode-transaction] Entering transaction request encoding") + log.CustomLogger().Info("`EncodeTransaction` Starting encoding transaction request...") if !common.RPCMethods["POST"][config.EncodeTransaction].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -190,7 +204,8 @@ func EncodeTransaction(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[encode-transaction] Returning from the cache") + log.CustomLogger().Info("`EncodeTransaction` Returning from the cache") + return } } diff --git a/gateway/evm/abi.go b/gateway/evm/abi.go index c4f7d7f..9106a21 100755 --- a/gateway/evm/abi.go +++ b/gateway/evm/abi.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" ) @@ -29,7 +30,6 @@ func queryAbiHandle(r *http.Request, chain string, contract string) (interface{} } abi := new(interface{}) - common.GetLogger().Info(result.(map[string]interface{})["result"]) err = json.Unmarshal([]byte(result.(map[string]interface{})["result"].(string)), abi) if err != nil { return common.ServeError(0, "", "failed to decode result", http.StatusInternalServerError) @@ -53,7 +53,9 @@ func QueryAbiRequests(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-abi] Entering abi query: ", chain) + log.CustomLogger().Info("`QueryAbiRequests` Starting Abi request...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryABI].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -64,7 +66,10 @@ func QueryAbiRequests(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-abi] Returning from the cache: ", chain) + log.CustomLogger().Info("`QueryAbiRequests` Returning from the cache", + "chain", chain, + ) + return } } diff --git a/gateway/evm/accounts.go b/gateway/evm/accounts.go index 4c0617b..68764e7 100755 --- a/gateway/evm/accounts.go +++ b/gateway/evm/accounts.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" @@ -104,7 +105,9 @@ func RegisterEVMAccountsRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-accounts] Entering transactions execute: ", chain) + log.CustomLogger().Info("`RegisterEVMAccountsRequest` Starting EVM Account request...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryEVMAccounts].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -115,7 +118,10 @@ func RegisterEVMAccountsRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-accounts] Returning from the cache: ", chain) + log.CustomLogger().Info("`RegisterEVMAccountsRequest` Returning from the cache...", + "chain", chain, + ) + return } } diff --git a/gateway/evm/balances.go b/gateway/evm/balances.go index 634dca7..ac9f1dd 100755 --- a/gateway/evm/balances.go +++ b/gateway/evm/balances.go @@ -10,6 +10,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" "github.com/holiman/uint256" @@ -162,7 +163,9 @@ func RegisterEVMBalancesRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-balances] Entering transactions execute: ", chain) + log.CustomLogger().Info("`RegisterEVMBalancesRequest` Starting EVM balance request...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryEVMBalances].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -173,7 +176,10 @@ func RegisterEVMBalancesRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-balances] Returning from the cache: ", chain) + log.CustomLogger().Info("`RegisterEVMBalancesRequest` Returning from the cache...", + "chain", chain, + ) + return } } diff --git a/gateway/evm/block.go b/gateway/evm/block.go index cc5388d..50a3326 100755 --- a/gateway/evm/block.go +++ b/gateway/evm/block.go @@ -8,6 +8,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" @@ -87,7 +88,9 @@ func QueryEVMBlockRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-block] Entering block query: ", chain) + log.CustomLogger().Info("`QueryEVMBlockRequest` Starting EVM block request...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryEVMBlock].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -98,7 +101,10 @@ func QueryEVMBlockRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-block] Returning from the cache: ", chain) + log.CustomLogger().Info("`QueryEVMBlockRequest` Returning from the cache", + "chain", chain, + ) + return } } diff --git a/gateway/evm/contract.go b/gateway/evm/contract.go index e3d99b1..26daf9c 100755 --- a/gateway/evm/contract.go +++ b/gateway/evm/contract.go @@ -13,6 +13,7 @@ import ( jsonrpc2 "github.com/KeisukeYamashita/go-jsonrpc" "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/gorilla/mux" @@ -208,7 +209,9 @@ func QueryReadContractRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-read-contract] Entering read smart contract: ", chain) + log.CustomLogger().Info("`QueryReadContractRequest` Starting reading contract request...", + "chain", chain, + ) if !common.RPCMethods["GET"][config.QueryReadContract].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -219,7 +222,9 @@ func QueryReadContractRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-read-contract] Returning from the cache: ", chain) + log.CustomLogger().Info("`QueryReadContractRequest` Returning from the cache", + "chain", chain, + ) return } } @@ -299,7 +304,7 @@ func WriteContractCall(nodeInfo config.EVMNodeConfig, from string, contract stri transactionCall.GasPrice = gasPrice transactionCall.Value = "0x" + hex.EncodeToString([]byte(value)) transactionCall.Data = data - common.GetLogger().Info(transactionCall) + log.CustomLogger().Info("transaction", transactionCall) result, err = client.Call("eth_estimateGas", transactionCall, "latest") if err != nil { @@ -414,7 +419,7 @@ func QueryWriteContractRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-write-contract] Entering write smart contract: ", chain) + log.CustomLogger().Info("[query-evm-write-contract] Entering write smart contract: ", chain) if !common.RPCMethods["GET"][config.QueryWriteContract].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -425,7 +430,7 @@ func QueryWriteContractRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-write-contract] Returning from the cache: ", chain) + log.CustomLogger().Info("[query-evm-write-contract] Returning from the cache: ", chain) return } } diff --git a/gateway/evm/faucet.go b/gateway/evm/faucet.go index 6a8964a..b896c3a 100755 --- a/gateway/evm/faucet.go +++ b/gateway/evm/faucet.go @@ -12,6 +12,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/database" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" @@ -374,7 +375,7 @@ func RegisterEVMFaucetRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-faucet] Entering transactions execute: ", chain) + log.CustomLogger().Info("[query-evm-faucet] Entering transactions execute: ", chain) if !common.RPCMethods["GET"][config.QueryEVMFaucet].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -385,7 +386,7 @@ func RegisterEVMFaucetRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-faucet] Returning from the cache: ", chain) + log.CustomLogger().Info("[query-evm-faucet] Returning from the cache: ", chain) return } } diff --git a/gateway/evm/status.go b/gateway/evm/status.go index 105be55..c4c5bff 100755 --- a/gateway/evm/status.go +++ b/gateway/evm/status.go @@ -7,6 +7,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" @@ -180,7 +181,7 @@ func QueryEVMStatusRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-status] Entering status query: ", chain) + log.CustomLogger().Info("[query-evm-status] Entering status query: ", chain) if !common.RPCMethods["GET"][config.QueryEVMStatus].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -191,7 +192,7 @@ func QueryEVMStatusRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-status] Returning from the cache: ", chain) + log.CustomLogger().Info("[query-evm-status] Returning from the cache: ", chain) return } } diff --git a/gateway/evm/transaction.go b/gateway/evm/transaction.go index 2f8898f..928c794 100755 --- a/gateway/evm/transaction.go +++ b/gateway/evm/transaction.go @@ -5,6 +5,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" @@ -80,7 +81,7 @@ func QueryEVMTransactionRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-transaction] Entering transaction query: ", chain) + log.CustomLogger().Info("[query-evm-transaction] Entering transaction query: ", chain) if !common.RPCMethods["GET"][config.QueryEVMTransaction].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -91,7 +92,7 @@ func QueryEVMTransactionRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-transaction] Returning from the cache: ", chain) + log.CustomLogger().Info("[query-evm-transaction] Returning from the cache: ", chain) return } } diff --git a/gateway/evm/transfer.go b/gateway/evm/transfer.go index 6be0aab..96adc9a 100755 --- a/gateway/evm/transfer.go +++ b/gateway/evm/transfer.go @@ -9,6 +9,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + interxLog "github.com/KiraCore/interx/log" "github.com/gorilla/mux" // "github.com/powerman/rpc-codec/jsonrpc2" @@ -156,7 +157,7 @@ func QueryEVMTransferRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-evm-transfer] Entering transactions execute: ", chain) + interxLog.CustomLogger().Info("[query-evm-transfer] Entering transactions execute: ", chain) if !common.RPCMethods["GET"][config.QueryEVMTransfer].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -167,7 +168,7 @@ func QueryEVMTransferRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-evm-transfer] Returning from the cache: ", chain) + interxLog.CustomLogger().Info("[query-evm-transfer] Returning from the cache: ", chain) return } } diff --git a/gateway/interx/block.go b/gateway/interx/block.go old mode 100644 new mode 100755 index a4c6942..c6d5bf0 --- a/gateway/interx/block.go +++ b/gateway/interx/block.go @@ -9,6 +9,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" kiratypes "github.com/KiraCore/sekai/types" multistaking "github.com/KiraCore/sekai/x/multistaking/types" @@ -61,12 +62,19 @@ func queryBlocksHandle(rpcAddr string, r *http.Request) (interface{}, interface{ func QueryBlocksRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var statusCode int + + log.CustomLogger().Info("Starting 'QueryBlocksRequest' request...") + request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-blocks] Entering Blocks query") - if !common.RPCMethods["GET"][config.QueryBlocks].Enabled { + + log.CustomLogger().Error(" `QueryBlocksRequest` is disabled.", + "method", request.Method, + "endpoint", request.Endpoint, + ) + response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) } else { if common.RPCMethods["GET"][config.QueryBlocks].CachingEnabled { @@ -75,7 +83,13 @@ func QueryBlocksRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Hand response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-blocks] Returning from the cache") + log.CustomLogger().Info("Cache hit for 'QueryBlocksRequest' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + return } } @@ -83,7 +97,16 @@ func QueryBlocksRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Hand response.Response, response.Error, statusCode = queryBlocksHandle(rpcAddr, r) } + log.CustomLogger().Info("Processed 'QueryBlocksRequest' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + common.WrapResponse(w, request, *response, statusCode, common.RPCMethods["GET"][config.QueryBlocks].CachingEnabled) + + log.CustomLogger().Info("Finished 'QueryBlocksRequest' request.") } } @@ -91,6 +114,11 @@ func queryBlockByHeightOrHashHandle(rpcAddr string, height string) (interface{}, success, err, statusCode := common.MakeTendermintRPCRequest(rpcAddr, "/block", fmt.Sprintf("height=%s", height)) if err != nil { + log.CustomLogger().Error(" `queryBlockByHeightOrHashHandle` failed to execute.", + "height", height, + "method", "/block", + "err", err, + ) success, err, statusCode = common.MakeTendermintRPCRequest(rpcAddr, "/block_by_hash", fmt.Sprintf("hash=%s", height)) } @@ -106,9 +134,17 @@ func QueryBlockByHeightOrHashRequest(gwCosmosmux *runtime.ServeMux, rpcAddr stri request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-blocks-by-height] Entering Block query by height: ", height) + log.CustomLogger().Info("Starting `QueryBlockByHeightOrHashRequest` request...") if !common.RPCMethods["GET"][config.QueryBlockByHeightOrHash].Enabled { + + log.CustomLogger().Error("Query `QueryBlockByHeightOrHashRequest` is disabled.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) } else { if common.RPCMethods["GET"][config.QueryBlockByHeightOrHash].CachingEnabled { @@ -117,7 +153,13 @@ func QueryBlockByHeightOrHashRequest(gwCosmosmux *runtime.ServeMux, rpcAddr stri response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-blocks-by-height] Returning from the cache: ", height) + log.CustomLogger().Info("Cache hit for `QueryBlockByHeightOrHashRequest` request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + return } } @@ -125,13 +167,25 @@ func QueryBlockByHeightOrHashRequest(gwCosmosmux *runtime.ServeMux, rpcAddr stri response.Response, response.Error, statusCode = queryBlockByHeightOrHashHandle(rpcAddr, height) } + log.CustomLogger().Info("Processed `QueryBlockByHeightOrHashRequest` request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + common.WrapResponse(w, request, *response, statusCode, common.RPCMethods["GET"][config.QueryBlockByHeightOrHash].CachingEnabled) + + log.CustomLogger().Info("Finished `QueryBlockByHeightOrHashRequest` request.") + } } func getTransactionsFromLog(attributes []abciTypes.EventAttribute) []sdk.Coin { feeTxs := []sdk.Coin{} + log.CustomLogger().Info("Starting `getTransactionsFromLog` request...") + var evMap = make(map[string]string) for _, attribute := range attributes { key := string(attribute.GetKey()) @@ -164,15 +218,26 @@ func getTransactionsFromLog(attributes []abciTypes.EventAttribute) []sdk.Coin { } } + log.CustomLogger().Info("Finished `getTransactionsFromLog` request.") + return feeTxs } func parseTransaction(rpcAddr string, transaction tmTypes.ResultTx) (types.TransactionResult, error) { txResult := types.TransactionResult{} + log.CustomLogger().Info("Starting `parseTransaction` request...") + tx, err := config.EncodingCg.TxConfig.TxDecoder()(transaction.Tx) if err != nil { - common.GetLogger().Error("[query-transactions] Failed to decode transaction: ", err) + + log.CustomLogger().Error("Failed to decode transaction.", + "method", "TxDecoder", + "transaction", tx, + "error", err, + "result", txResult, + ) + return txResult, err } @@ -185,8 +250,14 @@ func parseTransaction(rpcAddr string, transaction tmTypes.ResultTx) (types.Trans txResult.BlockHeight = transaction.Height txResult.BlockTimestamp, err = common.GetBlockTime(rpcAddr, transaction.Height) if err != nil { - common.GetLogger().Error("[query-transactions] Block not found: ", transaction.Height) - return txResult, fmt.Errorf("block not found: %d", transaction.Height) + + log.CustomLogger().Error("Failed to find block.", + "method", "GetBlockTime", + "RPC", rpcAddr, + "height", transaction.Height, + "error", err, + ) + } txResult.Confirmation = common.NodeStatus.Block - transaction.Height + 1 txResult.GasWanted = transaction.TxResult.GetGasWanted() @@ -205,6 +276,11 @@ func parseTransaction(rpcAddr string, transaction tmTypes.ResultTx) (types.Trans }) } + log.CustomLogger().Info("Signing tx successfully done.", + "method", "signing.Tx", + "signed tx", txSigning, + ) + txResult.Transactions = []types.Transaction{} txResult.Fees = []sdk.Coin{} @@ -413,8 +489,11 @@ func parseTransaction(rpcAddr string, transaction tmTypes.ResultTx) (types.Trans } txResult.Transactions = append(txResult.Transactions, transfers...) + } + log.CustomLogger().Info("Finished `parseTransaction` request.") + return txResult, nil } @@ -423,6 +502,11 @@ func QueryBlockTransactionsHandle(rpcAddr string, height string) (interface{}, i blockHeight, _ := strconv.Atoi(height) response, err := SearchTxHashHandle(rpcAddr, "", "", "", 0, 0, int64(blockHeight), int64(blockHeight), "") if err != nil { + log.CustomLogger().Error("`QueryBlockTransactionsHandle` failed to execute.", + "block_height", height, + "error", err, + "response_data", response, + ) return common.ServeError(0, "transaction query failed", "", http.StatusBadRequest) } @@ -449,12 +533,27 @@ func QueryBlockTransactionsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string var statusCode int queries := mux.Vars(r) height := queries["height"] + + log.CustomLogger().Info("Starting `QueryBlockTransactionsRequest`.", + "block_height", height, + ) + request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-block-transactions-by-height] Entering Block query by height: ", height) + log.CustomLogger().Info("Attempting to fetch transactions from block.", + "block_height", height, + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + ) if !common.RPCMethods["GET"][config.QueryBlockTransactions].Enabled { + + log.CustomLogger().Error("`QueryBlockTransactionsRequest` is disabled.", + "block_height", height, + ) + response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) } else { if common.RPCMethods["GET"][config.QueryBlockTransactions].CachingEnabled { @@ -463,7 +562,10 @@ func QueryBlockTransactionsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-block-transactions-by-height] Returning from the cache: %s", height) + log.CustomLogger().Info("Cache hit for `QueryBlockTransactionsRequest`.", + "block_height", height, + ) + return } } @@ -471,7 +573,17 @@ func QueryBlockTransactionsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string response.Response, response.Error, statusCode = QueryBlockTransactionsHandle(rpcAddr, height) } + log.CustomLogger().Info("Fetched transaction from block (no cache used).", + "block_height", height, + "transaction_response", response.Response, + "error_details", response.Error, + ) common.WrapResponse(w, request, *response, statusCode, common.RPCMethods["GET"][config.QueryBlockTransactions].CachingEnabled) + + log.CustomLogger().Info("Completed `QueryBlockTransactionsRequest`.", + "block_height", height, + "status_code", statusCode, + ) } } @@ -481,6 +593,11 @@ func QueryTransactionResultHandle(rpcAddr string, txHash string) (interface{}, i response, err := SearchTxHashHandle(rpcAddr, "", "", "", 0, 0, 0, 0, txHash) if err != nil { + log.CustomLogger().Error("`QueryTransactionResultHandle` failed to execute.", + "tx_Hash", txHash, + "error", err, + "response_data", response, + ) return common.ServeError(0, "transaction query failed", "", http.StatusBadRequest) } @@ -489,6 +606,11 @@ func QueryTransactionResultHandle(rpcAddr string, txHash string) (interface{}, i for _, transaction := range response.Txs { txResult, err = parseTransaction(rpcAddr, *transaction) if err != nil { + log.CustomLogger().Error("`parseTransaction` failed to execute.", + "tx_Result", txResult, + "error", err, + "response_data", response.Txs, + ) return common.ServeError(0, "", err.Error(), http.StatusBadRequest) } } @@ -502,12 +624,25 @@ func QueryTransactionResultRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string var statusCode int queries := mux.Vars(r) txHash := queries["txHash"] + + log.CustomLogger().Info("Starting `QueryTransactionResultRequest` request...") + request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-transaction-by-hash] Entering transaction query by hash: %s", txHash) + log.CustomLogger().Info("Attempting to fetch transactions by hash.", + "tx_Hash", txHash, + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + ) if !common.RPCMethods["GET"][config.QueryTransactionResult].Enabled { + + log.CustomLogger().Error("`QueryTransactionResultRequest` is disabled.", + "tx_Hash", txHash, + ) + response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) } else { if common.RPCMethods["GET"][config.QueryTransactionResult].CachingEnabled { @@ -516,14 +651,26 @@ func QueryTransactionResultRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-transaction-by-hash] Returning from the cache: %s", txHash) + log.CustomLogger().Info("Cache hit for `QueryTransactionResultRequest`.", + "tx_Hash", txHash, + ) return } } response.Response, response.Error, statusCode = QueryTransactionResultHandle(rpcAddr, txHash) + log.CustomLogger().Info("Fetched transaction by hash (no cache used).", + "tx_Hash", txHash, + "transaction_response", response.Response, + "error_details", response.Error, + ) } common.WrapResponse(w, request, *response, statusCode, common.RPCMethods["GET"][config.QueryTransactionResult].CachingEnabled) + + log.CustomLogger().Info("Completed `QueryBlockTransactionsRequest`.", + "tx_Hash", txHash, + "status_code", statusCode, + ) } } diff --git a/gateway/interx/download.go b/gateway/interx/download.go index 573c282..be893a1 100644 --- a/gateway/interx/download.go +++ b/gateway/interx/download.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" ) @@ -22,7 +23,7 @@ func DownloadReference() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { filename := strings.TrimPrefix(r.URL.Path, config.Download+"/") - common.GetLogger().Info("[download] Entering reference download: ", filename) + log.CustomLogger().Info("[download] Entering reference download: ", filename) if len(filename) != 0 { http.ServeFile(w, r, config.GetReferenceCacheDir()+"/"+filename) diff --git a/gateway/interx/faucet.go b/gateway/interx/faucet.go index 94892a3..d17e734 100644 --- a/gateway/interx/faucet.go +++ b/gateway/interx/faucet.go @@ -9,6 +9,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/database" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx" @@ -48,21 +49,21 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I // check address faucetAccAddr, err := sdk.AccAddressFromBech32(config.Config.Faucet.Address) if err != nil { - common.GetLogger().Error("[faucet] Invalid bech32addr: ", config.Config.Faucet.Address) + log.CustomLogger().Error("[faucet] Invalid bech32addr: ", config.Config.Faucet.Address) return common.ServeError(0, "", fmt.Sprintf("internal server error: %s", err), http.StatusInternalServerError) } // check address claimAccAddr, err := sdk.AccAddressFromBech32(bech32addr) if err != nil { - common.GetLogger().Error("[faucet] Invalid bech32addr: ", claimAccAddr) + log.CustomLogger().Error("[faucet] Invalid bech32addr: ", claimAccAddr) return common.ServeError(100, "", fmt.Sprintf("invalid address: %s", err), http.StatusBadRequest) } // check claim limit timeLeft := database.GetClaimTimeLeft(bech32addr) if timeLeft > 0 { - common.GetLogger().Error("[faucet] Claim time left: ", timeLeft) + log.CustomLogger().Error("[faucet] Claim time left: ", timeLeft) return common.ServeError(101, "", fmt.Sprintf("claim limit: %d second(s) left", timeLeft), http.StatusBadRequest) } @@ -89,7 +90,7 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I faucetAmountString, ok := config.Config.Faucet.FaucetAmounts[token] // X if !ok { - common.GetLogger().Error("[faucet] Failed to get faucet amount from the configuration") + log.CustomLogger().Error("[faucet] Failed to get faucet amount from the configuration") return common.ServeError(102, "", "invalid token", http.StatusBadRequest) } @@ -99,7 +100,7 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I faucetMininumAmountString, ok := config.Config.Faucet.FaucetMinimumAmounts[token] // M if !ok { - common.GetLogger().Error("[faucet] Failed to get faucet minimum amount from the configuration") + log.CustomLogger().Error("[faucet] Failed to get faucet minimum amount from the configuration") return common.ServeError(102, "", "invalid token", http.StatusBadRequest) } @@ -108,24 +109,24 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I coinStr, ok := config.Config.Faucet.FeeAmounts[token] if !ok { - common.GetLogger().Error("[faucet] Failed to get fee amount from the configuration") + log.CustomLogger().Error("[faucet] Failed to get fee amount from the configuration") return common.ServeError(102, "", "invalid token", http.StatusBadRequest) } feeAmount, err := sdk.ParseCoinNormalized(coinStr) if err != nil { - common.GetLogger().Error("[faucet] Failed to parse fee amount from the configuration: ", coinStr) + log.CustomLogger().Error("[faucet] Failed to parse fee amount from the configuration: ", coinStr) return common.ServeError(102, "", "invalid token", http.StatusBadRequest) } - // common.GetLogger().Info("[faucet] Available amount: ", availableAmount) - // common.GetLogger().Info("[faucet] Claim amount: ", claimAmount) - // common.GetLogger().Info("[faucet] Faucet amount: ", faucetAmount) - // common.GetLogger().Info("[faucet] Faucet minimum amount: ", faucetMininumAmount) + // log.CustomLogger().Info("[faucet] Available amount: ", availableAmount) + // log.CustomLogger().Info("[faucet] Claim amount: ", claimAmount) + // log.CustomLogger().Info("[faucet] Faucet amount: ", faucetAmount) + // log.CustomLogger().Info("[faucet] Faucet minimum amount: ", faucetMininumAmount) if faucetAmount.Cmp(claimAmount) <= 0 { - common.GetLogger().Error("[faucet] No need to send tokens: faucetAmount <= claimAmount") + log.CustomLogger().Error("[faucet] No need to send tokens: faucetAmount <= claimAmount") return common.ServeError(103, "", "no need to send tokens", http.StatusBadRequest) } @@ -133,7 +134,7 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I claimingAmount.SetString("0", 10) claimingAmount = claimingAmount.Sub(faucetAmount, claimAmount) if claimingAmount.Cmp(faucetMininumAmount) <= 0 { - common.GetLogger().Error("[faucet] Less than minimum amount: faucetAmount-claimAmount <= faucetMininumAmount") + log.CustomLogger().Error("[faucet] Less than minimum amount: faucetAmount-claimAmount <= faucetMininumAmount") return common.ServeError(104, "", "can't send tokens, less than minimum amount", http.StatusBadRequest) } @@ -141,14 +142,14 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I remainingAmount.SetString("0", 10) remainingAmount = remainingAmount.Sub(availableAmount, faucetMininumAmount) if claimingAmount.Cmp(remainingAmount) > 0 { - common.GetLogger().Error("[faucet] Not enough tokens: faucetAmount-claimAmount > availableAmount-faucetMininumAmount") + log.CustomLogger().Error("[faucet] Not enough tokens: faucetAmount-claimAmount > availableAmount-faucetMininumAmount") return common.ServeError(105, "", "not enough tokens", http.StatusBadRequest) } // GET AccountNumber and Sequence accountNumber, sequence := common.GetAccountNumberSequence(gwCosmosmux, r.Clone(r.Context()), config.Config.Faucet.Address) - // common.GetLogger().Info("[faucet] accountNumber: ", accountNumber) - // common.GetLogger().Info("[faucet] sequence: ", sequence) + // log.CustomLogger().Info("[faucet] accountNumber: ", accountNumber) + // log.CustomLogger().Info("[faucet] sequence: ", sequence) msgSend := &bank.MsgSend{ FromAddress: faucetAccAddr.String(), @@ -166,7 +167,7 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I sig, err := config.Config.Faucet.PrivKey.Sign(signBytes) if err != nil { - common.GetLogger().Error("[faucet] Failed to sign transaction: ", err) + log.CustomLogger().Error("[faucet] Failed to sign transaction: ", err) panic(err) } @@ -177,13 +178,13 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I txBuilder := config.EncodingCg.TxConfig.NewTxBuilder() err = txBuilder.SetMsgs(stdTx.GetMsgs()...) if err != nil { - common.GetLogger().Error("[faucet] Failed to set tx msgs: ", err) + log.CustomLogger().Error("[faucet] Failed to set tx msgs: ", err) return common.ServeError(1, "failed to set TX Msgs", err.Error(), http.StatusInternalServerError) } sigV2, err := stdTx.GetSignaturesV2() if err != nil { - common.GetLogger().Error("[faucet] Failed to get SignatureV2: ", err) + log.CustomLogger().Error("[faucet] Failed to get SignatureV2: ", err) return common.ServeError(1, "failed to get SignaturesV2", err.Error(), http.StatusInternalServerError) } @@ -191,7 +192,7 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I err = txBuilder.SetSignatures(sigV2...) if err != nil { - common.GetLogger().Error("[faucet] Failed to set SignatureV2: ", err) + log.CustomLogger().Error("[faucet] Failed to set SignatureV2: ", err) return common.ServeError(1, "failed to set Signatures", err.Error(), http.StatusInternalServerError) } @@ -201,14 +202,14 @@ func serveFaucet(r *http.Request, gwCosmosmux *runtime.ServeMux, request types.I txBytes, err := config.EncodingCg.TxConfig.TxEncoder()(txBuilder.GetTx()) if err != nil { - common.GetLogger().Error("[faucet] Failed to get tx bytes: ", err) + log.CustomLogger().Error("[faucet] Failed to get tx bytes: ", err) return common.ServeError(1, "failed to get TX bytes", err.Error(), http.StatusBadRequest) } // send tokens txHash, err := common.BroadcastTransaction(rpcAddr, txBytes) if err != nil { - common.GetLogger().Error("[faucet] Failed to broadcast transaction: ", err) + log.CustomLogger().Error("[faucet] Failed to broadcast transaction: ", err) return common.ServeError(1, "", err.Error(), http.StatusInternalServerError) } @@ -233,13 +234,13 @@ func FaucetRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.HandlerFu tokens := queries["token"] if len(claims) == 0 && len(tokens) == 0 { - // common.GetLogger().Info("[faucet] Entering faucet info") + // log.CustomLogger().Info("[faucet] Entering faucet info") response.Response, response.Error, statusCode = serveFaucetInfo(r, gwCosmosmux) } else if len(claims) == 1 && len(tokens) == 1 { - // common.GetLogger().Info("[faucet] Entering faucet: claim = ", claims[0], ", token = ", tokens[0]) + // log.CustomLogger().Info("[faucet] Entering faucet: claim = ", claims[0], ", token = ", tokens[0]) response.Response, response.Error, statusCode = serveFaucet(r, gwCosmosmux, request, rpcAddr, claims[0], tokens[0]) } else { - common.GetLogger().Error("[faucet] Invalid parameters") + log.CustomLogger().Error("[faucet] Invalid parameters") response.Response, response.Error, statusCode = common.ServeError(0, "", "invalid query parameters", http.StatusBadRequest) } diff --git a/gateway/interx/genesis.go b/gateway/interx/genesis.go index 6d3ad62..97bcde5 100644 --- a/gateway/interx/genesis.go +++ b/gateway/interx/genesis.go @@ -10,6 +10,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" tmjson "github.com/cometbft/cometbft/libs/json" tmtypes "github.com/cometbft/cometbft/types" "github.com/gorilla/mux" @@ -39,6 +40,9 @@ func JSONRemarshal(bytes []byte) ([]byte, error) { } func getChunkedGenesisData(rpcAddr string, chunkedNum int) ([]byte, int, error) { + + log.CustomLogger().Info("Starting `getChunkedGenesisData` request...") + data, _, _ := common.MakeTendermintRPCRequest(rpcAddr, "/genesis_chunked", fmt.Sprintf("chunk=%d", chunkedNum)) type GenesisChunkedResponse struct { @@ -55,25 +59,43 @@ func getChunkedGenesisData(rpcAddr string, chunkedNum int) ([]byte, int, error) err = json.Unmarshal(byteData, &genesis) if err != nil { + log.CustomLogger().Error("`getChunkedGenesisData` Failed to unmarshal genesisi data.", + "chunked_Num", chunkedNum, + ) return nil, 0, err } total, err := strconv.Atoi(genesis.Total) if err != nil { + log.CustomLogger().Error("`getChunkedGenesisData` Failed to unmarshal genesisi data.", + "chunked_Num", chunkedNum, + "error", err, + ) return nil, 0, err } + log.CustomLogger().Info("Completed `getChunkedGenesisData`.") + return genesis.Data, total, nil } func saveGenesis(rpcAddr string) error { + + log.CustomLogger().Info("Starting `saveGenesis` request...") + _, err := getGenesisCheckSum() if err == nil { + log.CustomLogger().Error("[saveGenesis][getGenesisCheckSum] Failed to fetch genesis checksum.", + "error", err, + ) return nil } cBytes, cTotal, err := getChunkedGenesisData(rpcAddr, 0) if err != nil { + log.CustomLogger().Error("[saveGenesis][getChunkedGenesisData] Failed to fetch genesis chunked data.", + "error", err, + ) return err } @@ -92,6 +114,9 @@ func saveGenesis(rpcAddr string) error { err = genesis.ValidateAndComplete() if err != nil { + log.CustomLogger().Error("[saveGenesis][ValidateAndComplete] Failed to validate genesis data.", + "error", err, + ) return err } @@ -99,6 +124,8 @@ func saveGenesis(rpcAddr string) error { err = os.WriteFile(genesisPath(), cBytes, 0644) global.Mutex.Unlock() + log.CustomLogger().Info("Completed `saveGenesis`.") + return err } @@ -108,6 +135,10 @@ func getGenesisCheckSum() (string, error) { global.Mutex.Unlock() if err != nil { + log.CustomLogger().Error("[getGenesisCheckSum][ReadFile] Failed to read from genesis file.", + "genesis_Path", genesisPath, + "error", err, + ) return "", err } @@ -130,6 +161,9 @@ func GetGenesisResults(rpcAddr string) (*tmtypes.GenesisDoc, string, error) { genesis := tmtypes.GenesisDoc{} err = tmjson.Unmarshal(data, &genesis) + log.CustomLogger().Error("[GetGenesisResults][Unmarshal] Failed to unmarshal genesis doc.", + "error", err, + ) return &genesis, common.GetSha256SumFromBytes(data), err } @@ -138,15 +172,28 @@ func GetGenesisResults(rpcAddr string) (*tmtypes.GenesisDoc, string, error) { func QueryGenesis(rpcAddr string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var statusCode int + + log.CustomLogger().Info("Starting 'QueryGenesis' request...") + request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) if saveGenesis(rpcAddr) != nil { + + log.CustomLogger().Info("Processed 'QueryGenesis' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + response.Response, response.Error, statusCode = common.ServeError(0, "", "interx error", http.StatusInternalServerError) common.WrapResponse(w, request, *response, statusCode, false) } else { http.ServeFile(w, r, genesisPath()) } + + log.CustomLogger().Info("Finished 'QueryGenesis' request.") } } @@ -175,11 +222,23 @@ func queryGenesisSumHandler(rpcAddr string) (interface{}, interface{}, int) { func QueryGenesisSum(rpcAddr string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var statusCode int + + log.CustomLogger().Info("Starting 'QueryGenesisSum' request...") + request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) response.Response, response.Error, statusCode = queryGenesisSumHandler(rpcAddr) + log.CustomLogger().Info("Processed 'QueryGenesis' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + common.WrapResponse(w, request, *response, statusCode, false) + + log.CustomLogger().Info("Finished 'QueryGenesisSum' request.") } } diff --git a/gateway/interx/interx.tx.go b/gateway/interx/interx.tx.go index 7d72a49..c584f46 100644 --- a/gateway/interx/interx.tx.go +++ b/gateway/interx/interx.tx.go @@ -15,6 +15,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/database" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" kiratypes "github.com/KiraCore/sekai/types" tmjson "github.com/cometbft/cometbft/libs/json" @@ -47,17 +48,33 @@ func GetTransactionsWithSync(rpcAddr string, address string, isOutbound bool) (* var limit = 100 var limitPages = 100 + log.CustomLogger().Info("Starting 'GetTransactionsWithSync' request...", + "rpc_address", rpcAddr, + "address", address, + "is_outbound", isOutbound, + ) + if address == "" { + log.CustomLogger().Info("Address is empty, returning empty ResultTxSearch.") return &tmTypes.ResultTxSearch{}, nil } lastBlock := database.GetLastBlockFetched(address, isOutbound) + log.CustomLogger().Info("Fetched last block request `GetLastBlockFetched`", + "last_block", lastBlock, + "address", address, + ) + totalResult := tmTypes.ResultTxSearch{ Txs: []*tmTypes.ResultTx{}, TotalCount: 0, } for page < limitPages { + log.CustomLogger().Info("Processing page of transactions...", + "page", page, + "limit", limit, + ) var events = make([]string, 0, 5) if isOutbound { events = append(events, fmt.Sprintf("message.sender='%s'", address)) @@ -68,11 +85,16 @@ func GetTransactionsWithSync(rpcAddr string, address string, isOutbound bool) (* // search transactions endpoint := fmt.Sprintf("%s/tx_search?query=\"%s\"&page=%d&per_page=%d&order_by=\"desc\"", rpcAddr, strings.Join(events, "%20AND%20"), page, limit) - common.GetLogger().Info("[query-transaction] Entering transaction search: ", endpoint) + log.CustomLogger().Info("Constructed endpoint for transaction query.", + "endpoint", endpoint, + ) resp, err := http.Get(endpoint) if err != nil { - common.GetLogger().Error("[query-transaction] Unable to connect to ", endpoint) + log.CustomLogger().Error("[GetTransactionsWithSync][http.Get] Failed to connect to endpoint.", + "endpoint", endpoint, + "error", err, + ) return nil, err } defer resp.Body.Close() @@ -82,24 +104,40 @@ func GetTransactionsWithSync(rpcAddr string, address string, isOutbound bool) (* response := new(tmJsonRPCTypes.RPCResponse) if err := json.Unmarshal(respBody, response); err != nil { - common.GetLogger().Error("[query-transaction] Unable to decode response: ", err) + log.CustomLogger().Error("[GetTransactionsWithSync] Failed to unmarshal RPC response.", + "error", err, + "response_body", string(respBody), + ) break } if response.Error != nil { + log.CustomLogger().Error("[GetTransactionsWithSync] RPC response contains an error.", + "rpc_error", response.Error, + ) break } result := new(tmTypes.ResultTxSearch) if err := tmjson.Unmarshal(response.Result, result); err != nil { - common.GetLogger().Error("[query-transaction] Failed to unmarshal result:", err) + log.CustomLogger().Error("[GetTransactionsWithSync][Unmarshal] Failed to unmarshal transaction search result.", + "error", err, + ) break } if result.TotalCount == 0 { + log.CustomLogger().Info("No more transactions found, exiting loop.", + "page", page, + ) break } + log.CustomLogger().Info("Transactions retrieved for current page.", + "transaction_count", len(result.Txs), + "page", page, + ) + totalResult.Txs = append(totalResult.Txs, result.Txs...) if result.TotalCount < limit { @@ -108,11 +146,19 @@ func GetTransactionsWithSync(rpcAddr string, address string, isOutbound bool) (* page++ } totalResult.TotalCount = len(totalResult.Txs) + log.CustomLogger().Info("Total transactions fetched.", + "total_count", totalResult.TotalCount, + ) + err := database.SaveTransactions(address, totalResult, isOutbound) if err != nil { - common.GetLogger().Error("[query-transaction] Failed to save cache result:", err) + log.CustomLogger().Error("[GetTransactionsWithSync][SaveTransactions] Failed to save transactions to database.", + "error", err, + ) } + log.CustomLogger().Info("Finished 'GetTransactionsWithSync' request.") + return database.GetTransactions(address, isOutbound) } @@ -163,7 +209,7 @@ func GetFilteredTransactions(rpcAddr string, address string, txtypes []string, d // Filter by time txTime, err := common.GetBlockTime(rpcAddr, cachedTx.Height) if err != nil { - common.GetLogger().Error("[query-transactions] Block not found: ", cachedTx.Height) + log.CustomLogger().Error("[query-transactions] Block not found: ", cachedTx.Height) continue } @@ -174,7 +220,7 @@ func GetFilteredTransactions(rpcAddr string, address string, txtypes []string, d // Filter by msg tx, err := config.EncodingCg.TxConfig.TxDecoder()(cachedTx.Tx) if err != nil { - common.GetLogger().Error("[query-transactions] Failed to decode transaction: ", err) + log.CustomLogger().Error("[query-transactions] Failed to decode transaction: ", err) continue } @@ -274,11 +320,11 @@ func SearchTxHashHandle(rpcAddr string, sender string, recipient string, txType if page == 0 { endpoint = fmt.Sprintf("%s/tx_search?query=\"%s\"&per_page=%d&order_by=\"desc\"", rpcAddr, strings.Join(events, "%20AND%20"), limit) } - common.GetLogger().Info("[query-transaction] Entering transaction search: ", endpoint) + log.CustomLogger().Info("[query-transaction] Entering transaction search: ", endpoint) resp, err := http.Get(endpoint) if err != nil { - common.GetLogger().Error("[query-transaction] Unable to connect to ", endpoint) + log.CustomLogger().Error("[query-transaction] Unable to connect to ", endpoint) return nil, err } defer resp.Body.Close() @@ -288,18 +334,18 @@ func SearchTxHashHandle(rpcAddr string, sender string, recipient string, txType response := new(tmJsonRPCTypes.RPCResponse) if err := json.Unmarshal(respBody, response); err != nil { - common.GetLogger().Error("[query-transaction] Unable to decode response: ", err) + log.CustomLogger().Error("[query-transaction] Unable to decode response: ", err) return nil, err } if response.Error != nil { - common.GetLogger().Error("[query-transaction] Error response:", response.Error.Message) + log.CustomLogger().Error("[query-transaction] Error response:", response.Error.Message) return nil, errors.New(response.Error.Message) } result := new(tmTypes.ResultTxSearch) if err := tmjson.Unmarshal(response.Result, result); err != nil { - common.GetLogger().Error("[query-transaction] Failed to unmarshal result:", err) + log.CustomLogger().Error("[query-transaction] Failed to unmarshal result:", err) return nil, fmt.Errorf("error unmarshalling result: %w", err) } @@ -309,11 +355,11 @@ func SearchTxHashHandle(rpcAddr string, sender string, recipient string, txType // Get block height for tx hash from cache or tendermint func getBlockHeight(rpcAddr string, hash string) (int64, error) { endpoint := fmt.Sprintf("%s/tx?hash=%s", rpcAddr, hash) - common.GetLogger().Info("[query-block] Entering block query: ", endpoint) + log.CustomLogger().Info("[query-block] Entering block query: ", endpoint) resp, err := http.Get(endpoint) if err != nil { - common.GetLogger().Error("[query-block] Unable to connect to ", endpoint) + log.CustomLogger().Error("[query-block] Unable to connect to ", endpoint) return 0, err } defer resp.Body.Close() @@ -322,17 +368,17 @@ func getBlockHeight(rpcAddr string, hash string) (int64, error) { response := new(tmJsonRPCTypes.RPCResponse) if err := json.Unmarshal(respBody, response); err != nil { - common.GetLogger().Error("[query-block] Unable to decode response: ", err) + log.CustomLogger().Error("[query-block] Unable to decode response: ", err) return 0, err } if response.Error != nil { - common.GetLogger().Error("[query-block] Error response:", response.Error.Message) + log.CustomLogger().Error("[query-block] Error response:", response.Error.Message) return 0, errors.New(response.Error.Message) } result := new(tmTypes.ResultTx) if err := tmjson.Unmarshal(response.Result, result); err != nil { - common.GetLogger().Error("[query-block] Failed to unmarshal result:", err) + log.CustomLogger().Error("[query-block] Failed to unmarshal result:", err) return 0, fmt.Errorf("error unmarshalling result: %w", err) } @@ -342,7 +388,7 @@ func getBlockHeight(rpcAddr string, hash string) (int64, error) { func QueryBlockTransactionsHandler(rpcAddr string, r *http.Request) (interface{}, interface{}, int) { err := r.ParseForm() if err != nil { - common.GetLogger().Error("[query-transactions] Failed to parse query parameters:", err) + log.CustomLogger().Error("[query-transactions] Failed to parse query parameters:", err) return common.ServeError(0, "failed to parse query parameters", err.Error(), http.StatusBadRequest) } @@ -372,7 +418,7 @@ func QueryBlockTransactionsHandler(rpcAddr string, r *http.Request) (interface{} //------------ Address ------------ account = r.FormValue("address") if account == "" { - common.GetLogger().Error("[query-transactions] 'address' is not set") + log.CustomLogger().Error("[query-transactions] 'address' is not set") return common.ServeError(0, "'address' is not set", "", http.StatusBadRequest) } @@ -408,7 +454,7 @@ func QueryBlockTransactionsHandler(rpcAddr string, r *http.Request) (interface{} layout := "01/02/2006 3:04:05 PM" t, err1 := time.Parse(layout, dateStStr+" 12:00:00 AM") if err1 != nil { - common.GetLogger().Error("[query-transactions] Failed to parse parameter 'dateStart': ", err1) + log.CustomLogger().Error("[query-transactions] Failed to parse parameter 'dateStart': ", err1) return common.ServeError(0, "failed to parse parameter 'dateStart'", err.Error(), http.StatusBadRequest) } @@ -421,7 +467,7 @@ func QueryBlockTransactionsHandler(rpcAddr string, r *http.Request) (interface{} layout := "01/02/2006 3:04:05 PM" t, err1 := time.Parse(layout, dateEdStr+" 12:00:00 AM") if err1 != nil { - common.GetLogger().Error("[query-transactions] Failed to parse parameter 'dateEnd': ", err1) + log.CustomLogger().Error("[query-transactions] Failed to parse parameter 'dateEnd': ", err1) return common.ServeError(0, "failed to parse parameter 'dateEnd'", err.Error(), http.StatusBadRequest) } @@ -432,18 +478,18 @@ func QueryBlockTransactionsHandler(rpcAddr string, r *http.Request) (interface{} //------------ Pagination ------------ if pageSizeStr := r.FormValue("page_size"); pageSizeStr != "" { if pageSize, err = strconv.Atoi(pageSizeStr); err != nil { - common.GetLogger().Error("[query-transactions] Failed to parse parameter 'page_size': ", err) + log.CustomLogger().Error("[query-transactions] Failed to parse parameter 'page_size': ", err) return common.ServeError(0, "failed to parse parameter 'page_size'", err.Error(), http.StatusBadRequest) } if pageSize < 1 || pageSize > 100 { - common.GetLogger().Error("[query-transactions] Invalid 'page_size' range: ", pageSize) + log.CustomLogger().Error("[query-transactions] Invalid 'page_size' range: ", pageSize) return common.ServeError(0, "'page_size' should be 1 ~ 100", "", http.StatusBadRequest) } } if pageStr := r.FormValue("page"); pageStr != "" { if page, err = strconv.Atoi(pageStr); err != nil { - common.GetLogger().Error("[query-transactions] Failed to parse parameter 'page': ", err) + log.CustomLogger().Error("[query-transactions] Failed to parse parameter 'page': ", err) return common.ServeError(0, "failed to parse parameter 'page'", err.Error(), http.StatusBadRequest) } } @@ -460,19 +506,19 @@ func QueryBlockTransactionsHandler(rpcAddr string, r *http.Request) (interface{} } else { if limitStr := r.FormValue("limit"); limitStr != "" { if limit, err = strconv.Atoi(limitStr); err != nil { - common.GetLogger().Error("[query-transactions] Failed to parse parameter 'limit': ", err) + log.CustomLogger().Error("[query-transactions] Failed to parse parameter 'limit': ", err) return common.ServeError(0, "failed to parse parameter 'limit'", err.Error(), http.StatusBadRequest) } if limit < 1 || limit > 100 { - common.GetLogger().Error("[query-transactions] Invalid 'limit' range: ", limit) + log.CustomLogger().Error("[query-transactions] Invalid 'limit' range: ", limit) return common.ServeError(0, "'limit' should be 1 ~ 100", "", http.StatusBadRequest) } } if offsetStr := r.FormValue("offset"); offsetStr != "" { if offset, err = strconv.Atoi(offsetStr); err != nil { - common.GetLogger().Error("[query-transactions] Failed to parse parameter 'offset': ", err) + log.CustomLogger().Error("[query-transactions] Failed to parse parameter 'offset': ", err) return common.ServeError(0, "failed to parse parameter 'offset'", err.Error(), http.StatusBadRequest) } } @@ -524,7 +570,7 @@ func QueryTransactions(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-transactions] Entering transactions query") + log.CustomLogger().Info("[query-transactions] Entering transactions query") if !common.RPCMethods["GET"][config.QueryTransactions].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -535,7 +581,7 @@ func QueryTransactions(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-transactions] Returning from the cache") + log.CustomLogger().Info("[query-transactions] Returning from the cache") return } } @@ -549,11 +595,11 @@ func QueryTransactions(rpcAddr string) http.HandlerFunc { func searchUnconfirmed(rpcAddr string, limit string) (*tmTypes.ResultUnconfirmedTxs, error) { endpoint := fmt.Sprintf("%s/unconfirmed_txs?limit=%s", rpcAddr, limit) - common.GetLogger().Info("[query-unconfirmed-txs] Entering transaction search: ", endpoint) + log.CustomLogger().Info("[query-unconfirmed-txs] Entering transaction search: ", endpoint) resp, err := http.Get(endpoint) if err != nil { - common.GetLogger().Error("[query-unconfirmed-txs] Unable to connect to ", endpoint) + log.CustomLogger().Error("[query-unconfirmed-txs] Unable to connect to ", endpoint) return nil, err } defer resp.Body.Close() @@ -563,18 +609,18 @@ func searchUnconfirmed(rpcAddr string, limit string) (*tmTypes.ResultUnconfirmed response := new(tmJsonRPCTypes.RPCResponse) if err := json.Unmarshal(respBody, response); err != nil { - common.GetLogger().Error("[query-unconfirmed-txs] Unable to decode response: ", err) + log.CustomLogger().Error("[query-unconfirmed-txs] Unable to decode response: ", err) return nil, err } if response.Error != nil { - common.GetLogger().Error("[query-unconfirmed-txs] Error response:", response.Error.Message) + log.CustomLogger().Error("[query-unconfirmed-txs] Error response:", response.Error.Message) return nil, errors.New(response.Error.Message) } result := new(tmTypes.ResultUnconfirmedTxs) if err := tmjson.Unmarshal(response.Result, result); err != nil { - common.GetLogger().Error("[query-unconfirmed-txs] Failed to unmarshal result:", err) + log.CustomLogger().Error("[query-unconfirmed-txs] Failed to unmarshal result:", err) return nil, fmt.Errorf("error unmarshalling result: %w", err) } @@ -585,7 +631,7 @@ func queryUnconfirmedTransactionsHandler(rpcAddr string, r *http.Request) (inter limit := r.FormValue("limit") result, err := searchUnconfirmed(rpcAddr, limit) if err != nil { - common.GetLogger().Error("[query-unconfirmed-txs] Failed to query unconfirmed txs: %w ", err) + log.CustomLogger().Error("[query-unconfirmed-txs] Failed to query unconfirmed txs: %w ", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -604,14 +650,14 @@ func queryUnconfirmedTransactionsHandler(rpcAddr string, r *http.Request) (inter for _, tx := range result.Txs { decodedTx, err := config.EncodingCg.TxConfig.TxDecoder()(tx) if err != nil { - common.GetLogger().Error("[post-unconfirmed-txs] Failed to decode transaction: ", err) + log.CustomLogger().Error("[post-unconfirmed-txs] Failed to decode transaction: ", err) return common.ServeError(0, "failed to decode signed TX", err.Error(), http.StatusBadRequest) } txResult, ok := decodedTx.(signing.Tx) if !ok { - common.GetLogger().Error("[post-unconfirmed-txs] Failed to decode transaction") - return common.ServeError(0, "failed to decode signed TX", err.Error(), http.StatusBadRequest) + log.CustomLogger().Error("[post-unconfirmed-txs] Failed to decode transaction") + return common.ServeError(0, "failed to decode signed TX", "", http.StatusBadRequest) } signature, _ := txResult.GetSignaturesV2() @@ -644,7 +690,7 @@ func QueryUnconfirmedTxs(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Error("[query-unconfirmed-txs] Entering query") + log.CustomLogger().Error("[query-unconfirmed-txs] Entering query") if !common.RPCMethods["GET"][config.QueryUnconfirmedTxs].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) diff --git a/gateway/interx/nodelist.go b/gateway/interx/nodelist.go index 082bb75..a758366 100644 --- a/gateway/interx/nodelist.go +++ b/gateway/interx/nodelist.go @@ -10,6 +10,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/tasks" "github.com/KiraCore/interx/types" "github.com/gorilla/mux" @@ -132,7 +133,7 @@ func QueryPubP2PNodeList(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Han request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-pub-node-list] Entering pub p2p node lists query") + log.CustomLogger().Info("[query-pub-node-list] Entering pub p2p node lists query") if !common.RPCMethods["GET"][config.QueryPubP2PList].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -143,7 +144,7 @@ func QueryPubP2PNodeList(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Han response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-pub-node-list] Returning from the cache") + log.CustomLogger().Info("[query-pub-node-list] Returning from the cache") return } } @@ -258,7 +259,7 @@ func QueryPrivP2PNodeList(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-priv-node-list] Entering priv p2p node lists query") + log.CustomLogger().Info("[query-priv-node-list] Entering priv p2p node lists query") if !common.RPCMethods["GET"][config.QueryPrivP2PList].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -269,7 +270,7 @@ func QueryPrivP2PNodeList(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-priv-node-list] Returning from the cache") + log.CustomLogger().Info("[query-priv-node-list] Returning from the cache") return } } @@ -336,7 +337,7 @@ func QueryInterxList(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Handler request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-interx-list] Entering interx lists query") + log.CustomLogger().Info("[query-interx-list] Entering interx lists query") if !common.RPCMethods["GET"][config.QueryInterxList].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -347,7 +348,7 @@ func QueryInterxList(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Handler response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-interx-list] Returning from the cache") + log.CustomLogger().Info("[query-interx-list] Returning from the cache") return } } @@ -414,7 +415,7 @@ func QuerySnapList(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.HandlerFu request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-snap-list] Entering snap lists query") + log.CustomLogger().Info("[query-snap-list] Entering snap lists query") if !common.RPCMethods["GET"][config.QuerySnapList].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -425,7 +426,7 @@ func QuerySnapList(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.HandlerFu response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-snap-list] Returning from the cache") + log.CustomLogger().Info("[query-snap-list] Returning from the cache") return } } diff --git a/gateway/interx/query.go b/gateway/interx/query.go index 8e53080..6690343 100644 --- a/gateway/interx/query.go +++ b/gateway/interx/query.go @@ -9,6 +9,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" functions "github.com/KiraCore/interx/functions" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/tasks" "github.com/KiraCore/interx/types" "github.com/KiraCore/interx/types/kira" @@ -34,17 +35,30 @@ func RegisterInterxQueryRoutes(r *mux.Router, gwCosmosmux *runtime.ServeMux, rpc // QueryRPCMethods is a function to query RPC methods. func QueryRPCMethods(rpcAddr string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + log.CustomLogger().Info("Starting 'QueryRPCMethods' request...") + request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) statusCode := http.StatusOK + log.CustomLogger().Info("Processed 'QueryRPCMethods' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "statusCode", statusCode, + "error", response.Error, + ) + response.Response = common.RPCMethods common.WrapResponse(w, request, *response, statusCode, false) + + log.CustomLogger().Info("Finished 'QueryRPCMethods' request.") } } -func queryInterxFunctionsHandle(rpcAddr string) (interface{}, interface{}, int) { +func queryInterxFunctionsHandle(_ string) (interface{}, interface{}, int) { metadata := functions.GetInterxMetadata() return metadata, nil, http.StatusOK @@ -53,13 +67,26 @@ func queryInterxFunctionsHandle(rpcAddr string) (interface{}, interface{}, int) // QueryInterxFunctions is a function to list functions and metadata. func QueryInterxFunctions(rpcAddr string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + log.CustomLogger().Info("Starting 'QueryInterxFunctions' request...") + var statusCode int request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) response.Response, response.Error, statusCode = queryInterxFunctionsHandle(rpcAddr) + log.CustomLogger().Info("Processed 'QueryInterxFunctions' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "statusCode", statusCode, + "error", response.Error, + ) + common.WrapResponse(w, request, *response, statusCode, false) + + log.CustomLogger().Info("Finished 'QueryInterxFunctions' request.") } } @@ -70,13 +97,13 @@ func queryStatusHandle(rpcAddr string) (interface{}, interface{}, int) { pubkeyBytes, err := config.EncodingCg.Amino.MarshalJSON(&config.Config.PubKey) if err != nil { - common.GetLogger().Error("[query-status] Failed to marshal interx pubkey", err) + log.CustomLogger().Error("[query-status] Failed to marshal interx pubkey", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(pubkeyBytes, &result.InterxInfo.PubKey) if err != nil { - common.GetLogger().Error("[query-status] Failed to add interx pubkey to status response", err) + log.CustomLogger().Error("[query-status] Failed to add interx pubkey to status response", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -85,7 +112,7 @@ func queryStatusHandle(rpcAddr string) (interface{}, interface{}, int) { // Handle Genesis genesis, checksum, err := GetGenesisResults(rpcAddr) if err != nil { - common.GetLogger().Error("[query-status] Failed to query genesis ", err) + log.CustomLogger().Error("[query-status] Failed to query genesis ", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -120,13 +147,22 @@ func queryStatusHandle(rpcAddr string) (interface{}, interface{}, int) { // QueryStatusRequest is a function to query status. func QueryStatusRequest(rpcAddr string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + log.CustomLogger().Info("Starting `QueryStatus` request...") + var statusCode int request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-status] Entering status query") - if !common.RPCMethods["GET"][config.QueryStatus].Enabled { + + log.CustomLogger().Error("Query `QueryStatus` is disabled.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) } else { if common.RPCMethods["GET"][config.QueryStatus].CachingEnabled { @@ -135,7 +171,13 @@ func QueryStatusRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-status] Returning from the cache") + log.CustomLogger().Info("Cache hit for `QueryStatus` request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + return } } @@ -143,24 +185,45 @@ func QueryStatusRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = queryStatusHandle(rpcAddr) } + log.CustomLogger().Info("Processed `QueryStatus` request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + common.WrapResponse(w, request, *response, statusCode, common.RPCMethods["GET"][config.QueryStatus].CachingEnabled) + + log.CustomLogger().Info("Finished `QueryStatus` request.") } } -func queryAddrBookHandler(rpcAddr string) (interface{}, interface{}, int) { +func queryAddrBookHandler(_ string) (interface{}, interface{}, int) { return config.LoadAddressBooks(), nil, http.StatusOK } // QueryAddrBook is a function to query address book. func QueryAddrBook(rpcAddr string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + log.CustomLogger().Info("Starting 'QueryAddrBook' request...") + var statusCode int request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) response.Response, response.Error, statusCode = queryAddrBookHandler(rpcAddr) + log.CustomLogger().Info("Processed 'QueryAddrBook' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + common.WrapResponse(w, request, *response, statusCode, false) + + log.CustomLogger().Info("Finished 'QueryAddrBook' request.") } } @@ -176,13 +239,25 @@ func queryNetInfoHandler(rpcAddr string) (interface{}, interface{}, int) { // QueryNetInfo is a function to query net info. func QueryNetInfo(rpcAddr string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + log.CustomLogger().Info("Starting 'QueryNetInfo' request...") + var statusCode int request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) response.Response, response.Error, statusCode = queryNetInfoHandler(rpcAddr) + log.CustomLogger().Info("Processed 'QueryNetInfo' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + common.WrapResponse(w, request, *response, statusCode, false) + + log.CustomLogger().Info("Finished 'QueryNetInfo' request.") } } @@ -290,12 +365,24 @@ func queryDashboardHandler(rpcAddr string, r *http.Request, gwCosmosmux *runtime // QueryDashboard is a function to query dashboard info. func QueryDashboard(rpcAddr string, gwCosmosmux *runtime.ServeMux) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + log.CustomLogger().Info("Starting 'QueryDashboard' request...") + var statusCode int request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) response.Response, response.Error, statusCode = queryDashboardHandler(rpcAddr, r, gwCosmosmux) + log.CustomLogger().Info("Processed 'QueryDashboard' request.", + "method", request.Method, + "endpoint", request.Endpoint, + "params", request.Params, + "error", response.Error, + ) + common.WrapResponse(w, request, *response, statusCode, false) + + log.CustomLogger().Info("Finished 'QueryDashboard' request.") } } diff --git a/gateway/interx/validators.go b/gateway/interx/validators.go index aa9eea4..45fe0f4 100644 --- a/gateway/interx/validators.go +++ b/gateway/interx/validators.go @@ -10,6 +10,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/tasks" "github.com/KiraCore/interx/types" "github.com/KiraCore/interx/types/kira" @@ -134,7 +135,7 @@ func QueryValidators(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Handler response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-validators] Returning from the cache") + log.CustomLogger().Info("[query-validators] Returning from the cache") return } } @@ -194,7 +195,7 @@ func QueryValidatorInfos(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Han response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-validator-info] Returning from the cache") + log.CustomLogger().Info("[query-validator-info] Returning from the cache") return } } @@ -231,13 +232,13 @@ func queryConsensusHandle(r *http.Request, gwCosmosmux *runtime.ServeMux, rpcAdd byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-consensus] Invalid response format", err) + log.CustomLogger().Error("[query-consensus] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[query-consensus] Invalid response format", err) + log.CustomLogger().Error("[query-consensus] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -253,13 +254,13 @@ func queryConsensusHandle(r *http.Request, gwCosmosmux *runtime.ServeMux, rpcAdd byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-consensus] Invalid response format: ", err) + log.CustomLogger().Error("[query-consensus] Invalid response format: ", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &consensus) if err != nil { - common.GetLogger().Error("[query-consensus] Invalid response format: ", err) + log.CustomLogger().Error("[query-consensus] Invalid response format: ", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -267,7 +268,7 @@ func queryConsensusHandle(r *http.Request, gwCosmosmux *runtime.ServeMux, rpcAdd err = json.Unmarshal(consensus.RoundState, &roundState) if err != nil { - common.GetLogger().Error("[query-consensus] Invalid round state: ", err) + log.CustomLogger().Error("[query-consensus] Invalid round state: ", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -346,7 +347,7 @@ func QueryConsensus(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.HandlerF response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-consensus] Returning from the cache") + log.CustomLogger().Info("[query-consensus] Returning from the cache") return } } @@ -378,7 +379,7 @@ func QueryDumpConsensusState(gwCosmosmux *runtime.ServeMux, rpcAddr string) http response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-dump-consensus-state] Returning from the cache") + log.CustomLogger().Info("[query-dump-consensus-state] Returning from the cache") return } } diff --git a/gateway/kira/gov.go b/gateway/kira/gov.go index 3bd710f..2de80aa 100755 --- a/gateway/kira/gov.go +++ b/gateway/kira/gov.go @@ -11,6 +11,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" database "github.com/KiraCore/interx/database" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" @@ -66,7 +67,7 @@ func QueryDataReferenceKeysRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-reference-keys] Entering data reference keys query") + log.CustomLogger().Info("[query-reference-keys] Entering data reference keys query") if !common.RPCMethods["GET"][config.QueryDataReferenceKeys].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -77,7 +78,7 @@ func QueryDataReferenceKeysRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-reference-keys] Returning from the cache") + log.CustomLogger().Info("[query-reference-keys] Returning from the cache") return } } @@ -101,13 +102,13 @@ func queryDataReferenceHandle(r *http.Request, gwCosmosmux *runtime.ServeMux, ke byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-reference] Invalid response format", err) + log.CustomLogger().Error("[query-reference] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[query-reference] Invalid response format", err) + log.CustomLogger().Error("[query-reference] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -130,7 +131,7 @@ func QueryDataReferenceRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-reference] Entering data reference query by key: ", key) + log.CustomLogger().Info("[query-reference] Entering data reference query by key: ", key) if !common.RPCMethods["GET"][config.QueryDataReference].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -141,7 +142,7 @@ func QueryDataReferenceRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-reference] Returning from the cache") + log.CustomLogger().Info("[query-reference] Returning from the cache") return } } @@ -159,7 +160,7 @@ func QueryNetworkPropertiesHandle(r *http.Request, gwCosmosmux *runtime.ServeMux if success != nil { result, err := common.QueryNetworkPropertiesFromGrpcResult(success) if err != nil { - common.GetLogger().Error("[query-network-properties] Invalid response format", err) + log.CustomLogger().Error("[query-network-properties] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -175,7 +176,7 @@ func QueryNetworkPropertiesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-network-properties] Entering network properties query") + log.CustomLogger().Info("[query-network-properties] Entering network properties query") if !common.RPCMethods["GET"][config.QueryNetworkProperties].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -186,7 +187,7 @@ func QueryNetworkPropertiesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-network-properties] Returning from the cache") + log.CustomLogger().Info("[query-network-properties] Returning from the cache") return } } @@ -216,7 +217,7 @@ func QueryExecutionFeeRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) htt request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-execution-fee] Entering execution fee query") + log.CustomLogger().Info("[query-execution-fee] Entering execution fee query") if !common.RPCMethods["GET"][config.QueryExecutionFee].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -227,7 +228,7 @@ func QueryExecutionFeeRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) htt response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-execution-fee] Returning from the cache") + log.CustomLogger().Info("[query-execution-fee] Returning from the cache") return } } @@ -251,7 +252,7 @@ func QueryExecutionFeesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-execution-fees] Entering execution fees query") + log.CustomLogger().Info("[query-execution-fees] Entering execution fees query") if !common.RPCMethods["GET"][config.QueryExecutionFees].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -262,7 +263,7 @@ func QueryExecutionFeesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-execution-fees] Returning from the cache") + log.CustomLogger().Info("[query-execution-fees] Returning from the cache") return } } diff --git a/gateway/kira/identity_registrar.go b/gateway/kira/identity_registrar.go index 8fc4940..ae45dab 100644 --- a/gateway/kira/identity_registrar.go +++ b/gateway/kira/identity_registrar.go @@ -9,6 +9,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types/kira/gov" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/gorilla/mux" @@ -44,7 +45,7 @@ func QueryIdentityRecordRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) h request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-identity-record] entering query") + log.CustomLogger().Info("[query-identity-record] entering query") if !common.RPCMethods["GET"][config.QueryIdentityRecord].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -55,7 +56,7 @@ func QueryIdentityRecordRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) h response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-identity-record] returning from the cache") + log.CustomLogger().Info("[query-identity-record] returning from the cache") return } } @@ -84,7 +85,7 @@ func QueryIdentityRecordsByAddressRequest(gwCosmosmux *runtime.ServeMux, rpcAddr request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-identity-records-by-address] entering query") + log.CustomLogger().Info("[query-identity-records-by-address] entering query") if !common.RPCMethods["GET"][config.QueryIdentityRecordsByAddress].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -95,7 +96,7 @@ func QueryIdentityRecordsByAddressRequest(gwCosmosmux *runtime.ServeMux, rpcAddr response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-identity-records-by-address] returning from the cache") + log.CustomLogger().Info("[query-identity-records-by-address] returning from the cache") return } } @@ -140,7 +141,7 @@ func QueryAllIdentityRecordsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr strin request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-all-identity-records] entering query") + log.CustomLogger().Info("[query-all-identity-records] entering query") if !common.RPCMethods["GET"][config.QueryAllIdentityRecords].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -151,7 +152,7 @@ func QueryAllIdentityRecordsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr strin response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-all-identity-records] returning from the cache") + log.CustomLogger().Info("[query-all-identity-records] returning from the cache") return } } @@ -174,7 +175,7 @@ func QueryIdentityRecordVerifyRequest(gwCosmosmux *runtime.ServeMux, rpcAddr str request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-identity-record-verify-request] entering query") + log.CustomLogger().Info("[query-identity-record-verify-request] entering query") if !common.RPCMethods["GET"][config.QueryIdentityRecordVerifyRequest].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -185,7 +186,7 @@ func QueryIdentityRecordVerifyRequest(gwCosmosmux *runtime.ServeMux, rpcAddr str response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-identity-record-verify-request] returning from the cache") + log.CustomLogger().Info("[query-identity-record-verify-request] returning from the cache") return } } @@ -231,13 +232,13 @@ func QueryIdentityRecordVerifyRequestsByRequesterHandler(r *http.Request, gwCosm res := gov.IdVerifyRequests{} bz, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-identity-record-verify-requests-by-requester] Invalid response format", err) + log.CustomLogger().Error("[query-identity-record-verify-requests-by-requester] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(bz, &res) if err != nil { - common.GetLogger().Error("[query-identity-record-verify-requests-by-requester] Invalid response format", err) + log.CustomLogger().Error("[query-identity-record-verify-requests-by-requester] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -256,7 +257,7 @@ func QueryIdentityRecordVerifyRequestsByRequester(gwCosmosmux *runtime.ServeMux, request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-identity-record-verify-request-by-requester] entering query") + log.CustomLogger().Info("[query-identity-record-verify-request-by-requester] entering query") if !common.RPCMethods["GET"][config.QueryIdentityRecordVerifyRequestsByRequester].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -267,7 +268,7 @@ func QueryIdentityRecordVerifyRequestsByRequester(gwCosmosmux *runtime.ServeMux, response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-identity-record-verify-request-by-requester] returning from the cache") + log.CustomLogger().Info("[query-identity-record-verify-request-by-requester] returning from the cache") return } } @@ -314,13 +315,13 @@ func QueryIdentityRecordVerifyRequestsByApproverHandler(r *http.Request, gwCosmo res := gov.IdVerifyRequests{} bz, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-identity-record-verify-requests-by-approver] Invalid response format", err) + log.CustomLogger().Error("[query-identity-record-verify-requests-by-approver] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(bz, &res) if err != nil { - common.GetLogger().Error("[query-identity-record-verify-requests-by-approver] Invalid response format", err) + log.CustomLogger().Error("[query-identity-record-verify-requests-by-approver] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -339,7 +340,7 @@ func QueryIdentityRecordVerifyRequestsByApprover(gwCosmosmux *runtime.ServeMux, request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-identity-record-verify-request-by-approver] entering query") + log.CustomLogger().Info("[query-identity-record-verify-request-by-approver] entering query") if !common.RPCMethods["GET"][config.QueryIdentityRecordVerifyRequestsByApprover].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -350,7 +351,7 @@ func QueryIdentityRecordVerifyRequestsByApprover(gwCosmosmux *runtime.ServeMux, response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-identity-record-verify-request-by-approver] returning from the cache") + log.CustomLogger().Info("[query-identity-record-verify-request-by-approver] returning from the cache") return } } @@ -395,7 +396,7 @@ func QueryAllIdentityRecordVerifyRequests(gwCosmosmux *runtime.ServeMux, rpcAddr request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-all-identity-record-verify-requests] entering query") + log.CustomLogger().Info("[query-all-identity-record-verify-requests] entering query") if !common.RPCMethods["GET"][config.QueryAllIdentityRecords].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -406,7 +407,7 @@ func QueryAllIdentityRecordVerifyRequests(gwCosmosmux *runtime.ServeMux, rpcAddr response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-all-identity-record-verify-requests] returning from the cache") + log.CustomLogger().Info("[query-all-identity-record-verify-requests] returning from the cache") return } } diff --git a/gateway/kira/multistaking.go b/gateway/kira/multistaking.go index acdb8df..6b334f9 100644 --- a/gateway/kira/multistaking.go +++ b/gateway/kira/multistaking.go @@ -11,6 +11,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/tasks" "github.com/KiraCore/interx/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -95,12 +96,12 @@ func queryStakingPoolHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (in byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-staking-pool] Invalid response format", err) + log.CustomLogger().Error("[query-staking-pool] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[query-staking-pool] Invalid response format", err) + log.CustomLogger().Error("[query-staking-pool] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -128,7 +129,7 @@ func QueryStakingPoolRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-staking-pool] Entering staking pool query") + log.CustomLogger().Info("[query-staking-pool] Entering staking pool query") if !common.RPCMethods["GET"][config.QueryStakingPool].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -139,7 +140,7 @@ func QueryStakingPoolRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-staking-pool] Returning from the cache") + log.CustomLogger().Info("[query-staking-pool] Returning from the cache") return } } @@ -170,7 +171,7 @@ func queryUndelegationsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) ( response := QueryUndelegationsResponse{} if len(account) == 0 { - common.GetLogger().Error("[query-undelegations] 'undelegator address' is not set") + log.CustomLogger().Error("[query-undelegations] 'undelegator address' is not set") return common.ServeError(0, "'delegator address' is not set", "", http.StatusBadRequest) } @@ -189,13 +190,13 @@ func queryUndelegationsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) ( // parse user balance data and generate delegation responses from pool tokens byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-undelegations] Invalid response format", err) + log.CustomLogger().Error("[query-undelegations] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[query-undelegations] Invalid response format", err) + log.CustomLogger().Error("[query-undelegations] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -232,14 +233,14 @@ func queryUndelegationsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) ( if len(offset) == 1 { from, err = strconv.Atoi(offset[0]) if err != nil { - common.GetLogger().Error("[query-undelegation] Failed to parse parameter 'offset': ", err) + log.CustomLogger().Error("[query-undelegation] Failed to parse parameter 'offset': ", err) return common.ServeError(0, "failed to parse parameter 'offset'", err.Error(), http.StatusBadRequest) } } if len(limit) == 1 { count, err = strconv.Atoi(limit[0]) if err != nil { - common.GetLogger().Error("[query-undelegation] Failed to parse parameter 'limit': ", err) + log.CustomLogger().Error("[query-undelegation] Failed to parse parameter 'limit': ", err) return common.ServeError(0, "failed to parse parameter 'limit'", err.Error(), http.StatusBadRequest) } } @@ -259,7 +260,7 @@ func QueryUndelegationsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-undelegations] Entering undelegations query") + log.CustomLogger().Info("[query-undelegations] Entering undelegations query") if !common.RPCMethods["GET"][config.QueryUndelegations].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -270,7 +271,7 @@ func QueryUndelegationsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-undelegations] Returning from the cache") + log.CustomLogger().Info("[query-undelegations] Returning from the cache") return } } @@ -303,12 +304,12 @@ func queryDelegationsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (in // parse user balance data and generate delegation responses from pool tokens byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-staking-pool] Invalid response format", err) + log.CustomLogger().Error("[query-staking-pool] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[query-staking-pool] Invalid response format", err) + log.CustomLogger().Error("[query-staking-pool] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -361,14 +362,14 @@ func queryDelegationsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (in if len(offset) == 1 { from, err = strconv.Atoi(offset[0]) if err != nil { - common.GetLogger().Error("[query-staking-pool] Failed to parse parameter 'offset': ", err) + log.CustomLogger().Error("[query-staking-pool] Failed to parse parameter 'offset': ", err) return common.ServeError(0, "failed to parse parameter 'offset'", err.Error(), http.StatusBadRequest) } } if len(limit) == 1 { count, err = strconv.Atoi(limit[0]) if err != nil { - common.GetLogger().Error("[query-staking-pool] Failed to parse parameter 'limit': ", err) + log.CustomLogger().Error("[query-staking-pool] Failed to parse parameter 'limit': ", err) return common.ServeError(0, "failed to parse parameter 'limit'", err.Error(), http.StatusBadRequest) } } @@ -388,7 +389,7 @@ func QueryDelegationsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-delegations] Entering delegations query") + log.CustomLogger().Info("[query-delegations] Entering delegations query") if !common.RPCMethods["GET"][config.QueryDelegations].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -399,7 +400,7 @@ func QueryDelegationsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-staking-pool] Returning from the cache") + log.CustomLogger().Info("[query-staking-pool] Returning from the cache") return } } diff --git a/gateway/kira/permission.go b/gateway/kira/permission.go index 2f4c91b..73bd073 100644 --- a/gateway/kira/permission.go +++ b/gateway/kira/permission.go @@ -7,6 +7,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" @@ -25,7 +26,7 @@ func queryPermissionsByAddressHandler(r *http.Request, gwCosmosmux *runtime.Serv _, err := sdk.AccAddressFromBech32(bech32addr) if err != nil { - common.GetLogger().Error("[query-account] Invalid bech32addr: ", bech32addr) + log.CustomLogger().Error("[query-account] Invalid bech32addr: ", bech32addr) return common.ServeError(0, "", err.Error(), http.StatusBadRequest) } @@ -42,7 +43,7 @@ func QueryPermissionsByAddressRequest(gwCosmosmux *runtime.ServeMux, rpcAddr str request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-permissions-by-address] Entering permissions by address query") + log.CustomLogger().Info("[query-permissions-by-address] Entering permissions by address query") if !common.RPCMethods["GET"][config.QueryPermissionsByAddress].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -53,7 +54,7 @@ func QueryPermissionsByAddressRequest(gwCosmosmux *runtime.ServeMux, rpcAddr str response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-permissions-by-address] Returning from the cache") + log.CustomLogger().Info("[query-permissions-by-address] Returning from the cache") return } } diff --git a/gateway/kira/proposal.go b/gateway/kira/proposal.go index ca35313..269d03a 100644 --- a/gateway/kira/proposal.go +++ b/gateway/kira/proposal.go @@ -11,6 +11,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/tasks" govTypes "github.com/KiraCore/interx/types/kira/gov" sekaitypes "github.com/KiraCore/sekai/types" @@ -60,7 +61,7 @@ func queryProposalsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (inte //------------ Offset ------------ if offsetStr := r.FormValue("offset"); offsetStr != "" { if offset, err = strconv.Atoi(offsetStr); err != nil { - common.GetLogger().Error("[query-proposals] Failed to parse parameter 'offset': ", err) + log.CustomLogger().Error("[query-proposals] Failed to parse parameter 'offset': ", err) return common.ServeError(0, "failed to parse parameter 'offset'", err.Error(), http.StatusBadRequest) } } @@ -68,12 +69,12 @@ func queryProposalsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (inte //------------ Limit ------------ if limitStr := r.FormValue("limit"); limitStr != "" { if limit, err = strconv.Atoi(limitStr); err != nil { - common.GetLogger().Error("[query-proposals] Failed to parse parameter 'limit': ", err) + log.CustomLogger().Error("[query-proposals] Failed to parse parameter 'limit': ", err) return common.ServeError(0, "failed to parse parameter 'limit'", err.Error(), http.StatusBadRequest) } if limit < 1 || limit > 100 { - common.GetLogger().Error("[query-proposals] Invalid 'limit' range: ", limit) + log.CustomLogger().Error("[query-proposals] Invalid 'limit' range: ", limit) return common.ServeError(0, "'limit' should be 1 ~ 100", "", http.StatusBadRequest) } } @@ -108,7 +109,7 @@ func queryProposalsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (inte layout := "01/02/2006 3:04:05 PM" t, err1 := time.Parse(layout, dateStStr+" 12:00:00 AM") if err1 != nil { - common.GetLogger().Error("[query-proposals] Failed to parse parameter 'dateStart': ", err1) + log.CustomLogger().Error("[query-proposals] Failed to parse parameter 'dateStart': ", err1) return common.ServeError(0, "failed to parse parameter 'dateStart'", err1.Error(), http.StatusBadRequest) } @@ -121,7 +122,7 @@ func queryProposalsHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (inte layout := "01/02/2006 3:04:05 PM" t, err1 := time.Parse(layout, dateEdStr+" 12:00:00 AM") if err1 != nil { - common.GetLogger().Error("[query-proposals] Failed to parse parameter 'dateEnd': ", err1) + log.CustomLogger().Error("[query-proposals] Failed to parse parameter 'dateEnd': ", err1) return common.ServeError(0, "failed to parse parameter 'dateEnd'", err.Error(), http.StatusBadRequest) } @@ -246,7 +247,7 @@ func QueryProposalsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.H request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-proposals] Entering proposals query") + log.CustomLogger().Info("[query-proposals] Entering proposals query") if !common.RPCMethods["GET"][config.QueryProposals].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -257,7 +258,7 @@ func QueryProposalsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.H response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-proposals] Returning from the cache") + log.CustomLogger().Info("[query-proposals] Returning from the cache") return } } @@ -278,13 +279,13 @@ func queryProposalHandler(r *http.Request, gwCosmosmux *runtime.ServeMux, propos result := make(map[string]interface{}) byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-proposal] Invalid response format", err) + log.CustomLogger().Error("[query-proposal] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[query-proposal] Invalid response format", err) + log.CustomLogger().Error("[query-proposal] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } propResult := tasks.ProposalsMap[proposalID] @@ -309,7 +310,7 @@ func QueryProposalRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-proposal] Entering proposal query by proposal_id: ", proposalID) + log.CustomLogger().Info("[query-proposal] Entering proposal query by proposal_id: ", proposalID) if !common.RPCMethods["GET"][config.QueryProposal].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -320,7 +321,7 @@ func QueryProposalRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-proposal] Returning from the cache") + log.CustomLogger().Info("[query-proposal] Returning from the cache") return } } @@ -339,7 +340,7 @@ func queryVotersHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (interfa if success != nil { voters, err := common.QueryVotersFromGrpcResult(success) if err != nil { - common.GetLogger().Error("[query-voters] Invalid response format: ", err) + log.CustomLogger().Error("[query-voters] Invalid response format: ", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -358,7 +359,7 @@ func QueryVotersRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Hand request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-voters] Entering proposal query by proposal_id: ", proposalID) + log.CustomLogger().Info("[query-voters] Entering proposal query by proposal_id: ", proposalID) if !common.RPCMethods["GET"][config.QueryVoters].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -369,7 +370,7 @@ func QueryVotersRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Hand response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-voters] Returning from the cache") + log.CustomLogger().Info("[query-voters] Returning from the cache") return } } @@ -388,7 +389,7 @@ func queryVotesHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) (interfac if success != nil { votes, err := common.QueryVotesFromGrpcResult(success) if err != nil { - common.GetLogger().Error("[query-votes] Invalid response format: ", err) + log.CustomLogger().Error("[query-votes] Invalid response format: ", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -407,7 +408,7 @@ func QueryVotesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Handl request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-votes] Entering proposal query by proposal_id: ", proposalID) + log.CustomLogger().Info("[query-votes] Entering proposal query by proposal_id: ", proposalID) if !common.RPCMethods["GET"][config.QueryVotes].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -418,7 +419,7 @@ func QueryVotesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Handl response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-votes] Returning from the cache") + log.CustomLogger().Info("[query-votes] Returning from the cache") return } } diff --git a/gateway/kira/query.go b/gateway/kira/query.go index 9a46af6..5643536 100644 --- a/gateway/kira/query.go +++ b/gateway/kira/query.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" functions "github.com/KiraCore/interx/functions" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" ) @@ -45,7 +46,7 @@ func QueryKiraStatusRequest(rpcAddr string) http.HandlerFunc { request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-kira-status] Entering status query") + log.CustomLogger().Info("[query-kira-status] Entering status query") if !common.RPCMethods["GET"][config.QueryKiraStatus].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -56,7 +57,7 @@ func QueryKiraStatusRequest(rpcAddr string) http.HandlerFunc { response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-kira-status] Returning from the cache") + log.CustomLogger().Info("[query-kira-status] Returning from the cache") return } } diff --git a/gateway/kira/role.go b/gateway/kira/role.go index fae9130..8b6e794 100644 --- a/gateway/kira/role.go +++ b/gateway/kira/role.go @@ -7,6 +7,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" @@ -33,7 +34,7 @@ func QueryRolesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Handl request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-roles] Entering roles query") + log.CustomLogger().Info("[query-roles] Entering roles query") if !common.RPCMethods["GET"][config.QueryRoles].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -44,7 +45,7 @@ func QueryRolesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Handl response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-roles] Returning from the cache") + log.CustomLogger().Info("[query-roles] Returning from the cache") return } } @@ -62,7 +63,7 @@ func queryRolesByAddressHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) _, err := sdk.AccAddressFromBech32(bech32addr) if err != nil { - common.GetLogger().Error("[query-account] Invalid bech32addr: ", bech32addr) + log.CustomLogger().Error("[query-account] Invalid bech32addr: ", bech32addr) return common.ServeError(0, "", err.Error(), http.StatusBadRequest) } @@ -79,7 +80,7 @@ func QueryRolesByAddressRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) h request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-roles-by-address] Entering roles by address query") + log.CustomLogger().Info("[query-roles-by-address] Entering roles by address query") if !common.RPCMethods["GET"][config.QueryRolesByAddress].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -90,7 +91,7 @@ func QueryRolesByAddressRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) h response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-roles-by-address] Returning from the cache") + log.CustomLogger().Info("[query-roles-by-address] Returning from the cache") return } } diff --git a/gateway/kira/spending.go b/gateway/kira/spending.go index 74d17ac..a88a24e 100644 --- a/gateway/kira/spending.go +++ b/gateway/kira/spending.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" ) @@ -45,7 +46,7 @@ func QuerySpendingPoolsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-spending-pool-names] Entering upgrade plan query") + log.CustomLogger().Info("[query-spending-pool-names] Entering upgrade plan query") if !common.RPCMethods["GET"][config.QuerySpendingPools].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -56,7 +57,7 @@ func QuerySpendingPoolsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-spending-pool-names] Returning from the cache") + log.CustomLogger().Info("[query-spending-pool-names] Returning from the cache") return } } @@ -87,7 +88,7 @@ func QuerySpendingPoolProposalsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr st request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-spending-pool-proposals] Entering upgrade plan query") + log.CustomLogger().Info("[query-spending-pool-proposals] Entering upgrade plan query") if !common.RPCMethods["GET"][config.QuerySpendingPoolProposals].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -98,7 +99,7 @@ func QuerySpendingPoolProposalsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr st response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-spending-pool-proposals] Returning from the cache") + log.CustomLogger().Info("[query-spending-pool-proposals] Returning from the cache") return } } diff --git a/gateway/kira/tokens.go b/gateway/kira/tokens.go index feb5b17..49e8d70 100644 --- a/gateway/kira/tokens.go +++ b/gateway/kira/tokens.go @@ -10,6 +10,7 @@ import ( "cosmossdk.io/math" "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/gorilla/mux" @@ -137,7 +138,7 @@ func QueryKiraTokensAliasesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-tokens-aliases] Entering token aliases query") + log.CustomLogger().Info("[query-tokens-aliases] Entering token aliases query") if !common.RPCMethods["GET"][config.QueryKiraTokensAliases].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -148,7 +149,7 @@ func QueryKiraTokensAliasesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-tokens-aliases] Returning from the cache") + log.CustomLogger().Info("[query-tokens-aliases] Returning from the cache") return } } @@ -172,12 +173,12 @@ func queryKiraTokensRatesHandler(r *http.Request, gwCosmosmux *runtime.ServeMux) byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[query-token-rates] Invalid response format", err) + log.CustomLogger().Error("[query-token-rates] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[query-token-rates] Invalid response format", err) + log.CustomLogger().Error("[query-token-rates] Invalid response format", err) return common.ServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -200,7 +201,7 @@ func QueryKiraTokensRatesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-tokens-rates] Entering token rates query") + log.CustomLogger().Info("[query-tokens-rates] Entering token rates query") if !common.RPCMethods["GET"][config.QueryKiraTokensRates].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -211,7 +212,7 @@ func QueryKiraTokensRatesRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-tokens-rates] Returning from the cache") + log.CustomLogger().Info("[query-tokens-rates] Returning from the cache") return } } diff --git a/gateway/kira/ubi.go b/gateway/kira/ubi.go index 380fb0e..b81e121 100644 --- a/gateway/kira/ubi.go +++ b/gateway/kira/ubi.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" ) @@ -39,7 +40,7 @@ func QueryUBIRecordsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http. request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-ubi-records] Entering upgrade plan query") + log.CustomLogger().Info("[query-ubi-records] Entering upgrade plan query") if !common.RPCMethods["GET"][config.QueryUBIRecords].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -50,7 +51,7 @@ func QueryUBIRecordsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http. response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-ubi-records] Returning from the cache") + log.CustomLogger().Info("[query-ubi-records] Returning from the cache") return } } diff --git a/gateway/kira/upgrade.go b/gateway/kira/upgrade.go index 6865026..89b29d6 100644 --- a/gateway/kira/upgrade.go +++ b/gateway/kira/upgrade.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" ) @@ -31,7 +32,7 @@ func QueryCurrentPlanRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-current-upgrade-plan] Entering upgrade plan query") + log.CustomLogger().Info("[query-current-upgrade-plan] Entering upgrade plan query") if !common.RPCMethods["GET"][config.QueryCurrentPlan].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -42,7 +43,7 @@ func QueryCurrentPlanRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-current-upgrade-plan] Returning from the cache") + log.CustomLogger().Info("[query-current-upgrade-plan] Returning from the cache") return } } @@ -66,7 +67,7 @@ func QueryNextPlanRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[query-next-upgrade-plan] Entering upgrade plan query") + log.CustomLogger().Info("[query-next-upgrade-plan] Entering upgrade plan query") if !common.RPCMethods["GET"][config.QueryNextPlan].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -77,7 +78,7 @@ func QueryNextPlanRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http.Ha response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[query-next-upgrade-plan] Returning from the cache") + log.CustomLogger().Info("[query-next-upgrade-plan] Returning from the cache") return } } diff --git a/gateway/rosetta/data/account.go b/gateway/rosetta/data/account.go index 78f7239..8fa226f 100644 --- a/gateway/rosetta/data/account.go +++ b/gateway/rosetta/data/account.go @@ -6,6 +6,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" "github.com/KiraCore/interx/types/rosetta" "github.com/KiraCore/interx/types/rosetta/dataapi" @@ -25,7 +26,7 @@ func queryAccountBalanceHandler(r *http.Request, request types.InterxRequest, rp err := json.Unmarshal(request.Params, &req) if err != nil { - common.GetLogger().Error("[rosetta-query-accountbalance] Failed to decode the request: ", err) + log.CustomLogger().Error("[rosetta-query-accountbalance] Failed to decode the request: ", err) return common.RosettaServeError(0, "failed to unmarshal", err.Error(), http.StatusBadRequest) } @@ -62,7 +63,7 @@ func QueryAccountBalanceRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) h request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[rosetta-query-accountbalance] Entering account balance query") + log.CustomLogger().Info("[rosetta-query-accountbalance] Entering account balance query") if !common.RPCMethods["POST"][config.QueryRosettaAccountBalance].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -73,7 +74,7 @@ func QueryAccountBalanceRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) h response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[rosetta-query-accountbalance] Returning from the cache") + log.CustomLogger().Info("[rosetta-query-accountbalance] Returning from the cache") return } } diff --git a/gateway/rosetta/data/network.go b/gateway/rosetta/data/network.go index 9e75ec3..db55459 100644 --- a/gateway/rosetta/data/network.go +++ b/gateway/rosetta/data/network.go @@ -7,6 +7,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" "github.com/KiraCore/interx/types/rosetta" "github.com/KiraCore/interx/types/rosetta/dataapi" @@ -30,7 +31,7 @@ func queryNetworkListHandler(r *http.Request, request types.InterxRequest, rpcAd err := json.Unmarshal(request.Params, &req) if err != nil { - common.GetLogger().Error("[rosetta-query-networklist] Failed to decode the request: ", err) + log.CustomLogger().Error("[rosetta-query-networklist] Failed to decode the request: ", err) return common.RosettaServeError(0, "failed to unmarshal", err.Error(), http.StatusBadRequest) } @@ -48,13 +49,13 @@ func queryNetworkListHandler(r *http.Request, request types.InterxRequest, rpcAd byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[rosetta-query-networklist] Invalid response format", err) + log.CustomLogger().Error("[rosetta-query-networklist] Invalid response format", err) return common.RosettaServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[rosetta-query-networklist] Invalid response format", err) + log.CustomLogger().Error("[rosetta-query-networklist] Invalid response format", err) return common.RosettaServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -77,7 +78,7 @@ func QueryNetworkListRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[rosetta-query-networklist] Entering network list query") + log.CustomLogger().Info("[rosetta-query-networklist] Entering network list query") if !common.RPCMethods["POST"][config.QueryRosettaNetworkList].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -88,7 +89,7 @@ func QueryNetworkListRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) http response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[rosetta-query-networklist] Returning from the cache") + log.CustomLogger().Info("[rosetta-query-networklist] Returning from the cache") return } } @@ -118,7 +119,7 @@ func QueryNetworkOptionsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) h request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[rosetta-query-networkoptions] Entering network list query") + log.CustomLogger().Info("[rosetta-query-networkoptions] Entering network list query") if !common.RPCMethods["POST"][config.QueryRosettaNetworkOptions].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -129,7 +130,7 @@ func QueryNetworkOptionsRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) h response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[rosetta-query-networkoptions] Returning from the cache") + log.CustomLogger().Info("[rosetta-query-networkoptions] Returning from the cache") return } } @@ -146,7 +147,7 @@ func queryNetworkStatusHandler(r *http.Request, request types.InterxRequest, rpc err := json.Unmarshal(request.Params, &req) if err != nil { - common.GetLogger().Error("[rosetta-query-networkstatus] Failed to decode the request: ", err) + log.CustomLogger().Error("[rosetta-query-networkstatus] Failed to decode the request: ", err) return common.RosettaServeError(0, "failed to unmarshal", err.Error(), http.StatusBadRequest) } @@ -176,13 +177,13 @@ func queryNetworkStatusHandler(r *http.Request, request types.InterxRequest, rpc byteData, err := json.Marshal(success) if err != nil { - common.GetLogger().Error("[rosetta-query-networkstatus] Invalid response format", err) + log.CustomLogger().Error("[rosetta-query-networkstatus] Invalid response format", err) return common.RosettaServeError(0, "", err.Error(), http.StatusInternalServerError) } err = json.Unmarshal(byteData, &result) if err != nil { - common.GetLogger().Error("[rosetta-query-networkstatus] Invalid response format", err) + log.CustomLogger().Error("[rosetta-query-networkstatus] Invalid response format", err) return common.RosettaServeError(0, "", err.Error(), http.StatusInternalServerError) } @@ -224,7 +225,7 @@ func QueryNetworkStatusRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht request := common.GetInterxRequest(r) response := common.GetResponseFormat(request, rpcAddr) - common.GetLogger().Info("[rosetta-query-networkstatus] Entering network list query") + log.CustomLogger().Info("[rosetta-query-networkstatus] Entering network list query") if !common.RPCMethods["POST"][config.QueryRosettaNetworkStatus].Enabled { response.Response, response.Error, statusCode = common.ServeError(0, "", "API disabled", http.StatusForbidden) @@ -235,7 +236,7 @@ func QueryNetworkStatusRequest(gwCosmosmux *runtime.ServeMux, rpcAddr string) ht response.Response, response.Error, statusCode = cacheResponse, cacheError, cacheStatus common.WrapResponse(w, request, *response, statusCode, false) - common.GetLogger().Info("[rosetta-query-networkstatus] Returning from the cache") + log.CustomLogger().Info("[rosetta-query-networkstatus] Returning from the cache") return } } diff --git a/go.mod b/go.mod index 3664ca9..b23d2c4 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,8 @@ module github.com/KiraCore/interx go 1.19 require ( + cosmossdk.io/log v1.2.1 + cosmossdk.io/math v1.2.0 github.com/KeisukeYamashita/go-jsonrpc v1.0.1 github.com/KiraCore/sekai v0.3.38 github.com/btcsuite/btcd v0.22.1 @@ -20,6 +22,8 @@ require ( github.com/inhies/go-bytesize v0.0.0-20200716184324-4fe85e9b81b2 github.com/rakyll/statik v0.1.7 github.com/rs/cors v1.8.2 + github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible + github.com/sirupsen/logrus v1.9.0 github.com/sonyarouje/simdb v0.0.0-20181202125413-c2488dfc374a github.com/stretchr/testify v1.8.4 github.com/tyler-smith/go-bip39 v1.0.2 @@ -34,8 +38,6 @@ require ( cosmossdk.io/core v0.5.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.4 // indirect cosmossdk.io/errors v1.0.0 // indirect - cosmossdk.io/log v1.2.1 // indirect - cosmossdk.io/math v1.2.0 // indirect cosmossdk.io/tools/rosetta v0.2.1 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect @@ -136,7 +138,6 @@ require ( github.com/rs/zerolog v1.30.0 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/satori/go.uuid v1.2.0 // indirect - github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect github.com/spf13/afero v1.9.2 // indirect github.com/spf13/cast v1.5.0 // indirect github.com/spf13/cobra v1.6.1 // indirect diff --git a/go.sum b/go.sum index 7fef56c..be4d27f 100644 --- a/go.sum +++ b/go.sum @@ -729,6 +729,7 @@ github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6Mwd github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= @@ -1029,6 +1030,7 @@ golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/log/logger.go b/log/logger.go new file mode 100755 index 0000000..a78beb9 --- /dev/null +++ b/log/logger.go @@ -0,0 +1,31 @@ +package log + +import ( + "fmt" + "os" + "strconv" + "time" + + cosmosLog "cosmossdk.io/log" +) + +func CustomLogger() cosmosLog.Logger { + + printLogs, err := strconv.ParseBool(os.Getenv("PrintLogs")) + if err != nil { + fmt.Println("[CustomLogger] Error parsing PrintLogs environment variable:", err) + } + + if !printLogs { + return cosmosLog.NewNopLogger() + } + + // Initialize a new `cosmosLog` logger instance + logger := cosmosLog.NewLogger(os.Stderr) + + logger = logger.With( + "timestamp", time.Now().UTC().Format(time.RFC3339), + ) + + return logger +} diff --git a/log/monitor.go b/log/monitor.go new file mode 100755 index 0000000..68288d0 --- /dev/null +++ b/log/monitor.go @@ -0,0 +1,54 @@ +package log + +import ( + "fmt" + "os" + "runtime" + "strconv" + "time" + + "github.com/shirou/gopsutil/cpu" + "github.com/shirou/gopsutil/load" + "github.com/shirou/gopsutil/mem" + "github.com/sirupsen/logrus" +) + +var log = logrus.New() + +// Monitor will continuously collect system information +func Monitor(interval time.Duration) { + + printLogs, err := strconv.ParseBool(os.Getenv("PrintLogs")) + + if err != nil { + fmt.Println("[CustomLogger] Error parsing PrintLogs environment variable:", err) + } + + if printLogs { + for { + var memStats runtime.MemStats + runtime.ReadMemStats(&memStats) + + v, _ := mem.VirtualMemory() + cpuPercent, _ := cpu.Percent(0, true) + loadAvg, _ := load.Avg() + + log.Printf("Timestamp: %v", time.Now().Format(time.RFC3339)) + + log.Printf("Memory Total: %v, Free: %v, Used Percent: %.2f%%, Active: %v", + v.Total, v.Free, v.UsedPercent, v.Active) + + log.Printf("CPU Usage Percentage: %v%%, CPU Usage: %v", cpuPercent, runtime.NumCPU()) + + // It logs the system load average for 1, 5, and 15 minutes. + log.Printf("Load Average: 1m: %.2f, 5m: %.2f, 15m: %.2f", + loadAvg.Load1, loadAvg.Load5, loadAvg.Load15) + + log.Printf("Memory Alloc: %v, Total Memory Alloc: %v, System Memory: %v", + memStats.Alloc, memStats.TotalAlloc, memStats.Sys) + + time.Sleep(interval) + } + } + +} diff --git a/log/recover.go b/log/recover.go new file mode 100755 index 0000000..d87cd61 --- /dev/null +++ b/log/recover.go @@ -0,0 +1,14 @@ +package log + +import ( + "github.com/sirupsen/logrus" +) + +var logger = logrus.New() + +// Recovery function to handle panics +func RecoverFromPanic() { + if r := recover(); r != nil { + logger.Errorf("Application crashed: %v", r) + } +} diff --git a/logs/logger.go b/logs/logger.go new file mode 100755 index 0000000..a78beb9 --- /dev/null +++ b/logs/logger.go @@ -0,0 +1,31 @@ +package log + +import ( + "fmt" + "os" + "strconv" + "time" + + cosmosLog "cosmossdk.io/log" +) + +func CustomLogger() cosmosLog.Logger { + + printLogs, err := strconv.ParseBool(os.Getenv("PrintLogs")) + if err != nil { + fmt.Println("[CustomLogger] Error parsing PrintLogs environment variable:", err) + } + + if !printLogs { + return cosmosLog.NewNopLogger() + } + + // Initialize a new `cosmosLog` logger instance + logger := cosmosLog.NewLogger(os.Stderr) + + logger = logger.With( + "timestamp", time.Now().UTC().Format(time.RFC3339), + ) + + return logger +} diff --git a/logs/monitor.go b/logs/monitor.go new file mode 100755 index 0000000..68288d0 --- /dev/null +++ b/logs/monitor.go @@ -0,0 +1,54 @@ +package log + +import ( + "fmt" + "os" + "runtime" + "strconv" + "time" + + "github.com/shirou/gopsutil/cpu" + "github.com/shirou/gopsutil/load" + "github.com/shirou/gopsutil/mem" + "github.com/sirupsen/logrus" +) + +var log = logrus.New() + +// Monitor will continuously collect system information +func Monitor(interval time.Duration) { + + printLogs, err := strconv.ParseBool(os.Getenv("PrintLogs")) + + if err != nil { + fmt.Println("[CustomLogger] Error parsing PrintLogs environment variable:", err) + } + + if printLogs { + for { + var memStats runtime.MemStats + runtime.ReadMemStats(&memStats) + + v, _ := mem.VirtualMemory() + cpuPercent, _ := cpu.Percent(0, true) + loadAvg, _ := load.Avg() + + log.Printf("Timestamp: %v", time.Now().Format(time.RFC3339)) + + log.Printf("Memory Total: %v, Free: %v, Used Percent: %.2f%%, Active: %v", + v.Total, v.Free, v.UsedPercent, v.Active) + + log.Printf("CPU Usage Percentage: %v%%, CPU Usage: %v", cpuPercent, runtime.NumCPU()) + + // It logs the system load average for 1, 5, and 15 minutes. + log.Printf("Load Average: 1m: %.2f, 5m: %.2f, 15m: %.2f", + loadAvg.Load1, loadAvg.Load5, loadAvg.Load15) + + log.Printf("Memory Alloc: %v, Total Memory Alloc: %v, System Memory: %v", + memStats.Alloc, memStats.TotalAlloc, memStats.Sys) + + time.Sleep(interval) + } + } + +} diff --git a/logs/recover.go b/logs/recover.go new file mode 100755 index 0000000..d87cd61 --- /dev/null +++ b/logs/recover.go @@ -0,0 +1,14 @@ +package log + +import ( + "github.com/sirupsen/logrus" +) + +var logger = logrus.New() + +// Recovery function to handle panics +func RecoverFromPanic() { + if r := recover(); r != nil { + logger.Errorf("Application crashed: %v", r) + } +} diff --git a/main.go b/main.go old mode 100644 new mode 100755 index 9ab2f62..cd91247 --- a/main.go +++ b/main.go @@ -4,15 +4,20 @@ import ( "flag" "fmt" "os" + "time" "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/gateway" + "github.com/KiraCore/interx/log" _ "github.com/KiraCore/interx/statik" "github.com/tyler-smith/go-bip39" "google.golang.org/grpc/grpclog" ) +// Enable or disable logging by setting the environment variable +const ENABLE_LOGS = "true" + func printUsage() { fmt.Println("Interx Daemon (server)") fmt.Println() @@ -35,6 +40,16 @@ func printUsage() { } func main() { + // Set the "PrintLogs" environment variable based on the logging configuration + os.Setenv("PrintLogs", ENABLE_LOGS) + + log.CustomLogger().Info("Starting INTERX server.") + + defer log.RecoverFromPanic() // Ensure we recover from any panic + + // Monitor system resources + go log.Monitor(25 * time.Second) + initCommand := flag.NewFlagSet("init", flag.ExitOnError) startCommand := flag.NewFlagSet("start", flag.ExitOnError) versionCommand := flag.NewFlagSet("version", flag.ExitOnError) @@ -98,8 +113,12 @@ func main() { // os.Args[2:] will be all arguments starting after the subcommand at os.Args[1] switch os.Args[1] { case "init": + + log.CustomLogger().Info("Initializing server with 'interxd init' command.") + err := initCommand.Parse(os.Args[2:]) if err != nil { + log.CustomLogger().Error("Failed to initialize server with 'interxd init' command.") panic(err) } @@ -159,12 +178,16 @@ func main() { *initSnapShotInterval, ) - fmt.Printf("Created interx configuration file: %s\n", *initHomePtr+"/config.json") + log.CustomLogger().Info("Created interx configuration file.", "Config File Path", *initHomePtr+"/config.json") return } case "start": + + log.CustomLogger().Info("Starting server with 'interxd start' command.") + err := startCommand.Parse(os.Args[2:]) if err != nil { + log.CustomLogger().Error("Failed to start INTERX server.") panic(err) } @@ -172,7 +195,7 @@ func main() { // Check which subcommand was Parsed using the FlagSet.Parsed() function. Handle each case accordingly. // FlagSet.Parse() will evaluate to false if no flags were parsed (i.e. the user did not provide any flags) configFilePath := *startHomePtr + "/config.json" - fmt.Println("configFilePath", configFilePath) + log.CustomLogger().Info("Config Path", configFilePath) // Adds gRPC internal logs. This is quite verbose, so adjust as desired! log := common.GetLogger() @@ -184,8 +207,12 @@ func main() { return } case "version": + + log.CustomLogger().Info("Starting server with 'interxd version' command.") + err := versionCommand.Parse(os.Args[2:]) if err != nil { + log.CustomLogger().Error("Failed to find INTERX version.") panic(err) } @@ -194,7 +221,7 @@ func main() { return } default: - fmt.Println("init or start command is available.") + log.CustomLogger().Error("Server did not initialized and started.") os.Exit(1) } } diff --git a/tasks/cache_data_check.go b/tasks/cache_data_check.go index b64d4e3..6d2e33d 100644 --- a/tasks/cache_data_check.go +++ b/tasks/cache_data_check.go @@ -3,7 +3,6 @@ package tasks import ( "encoding/json" "io/ioutil" - "log" "os" "path/filepath" "time" @@ -11,6 +10,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" ) @@ -51,7 +51,7 @@ func CacheDataCheck(rpcAddr string, isLog bool) { if path != config.GetResponseCacheDir() && delete { if isLog { - common.GetLogger().Info("[cache] Deleting file: ", path) + log.CustomLogger().Info("[cache] Deleting file: ", path) } global.Mutex.Lock() @@ -65,7 +65,7 @@ func CacheDataCheck(rpcAddr string, isLog bool) { if err != nil { if isLog { - common.GetLogger().Error("[cache] Error deleting file: ", err) + log.CustomLogger().Error("[cache] Error deleting file: ", err) } return err } @@ -77,7 +77,9 @@ func CacheDataCheck(rpcAddr string, isLog bool) { }) if err != nil { - log.Println(err) + log.CustomLogger().Error("[CacheDataCheck] Failed to check cache data ", + "error", err, + ) } time.Sleep(2 * time.Second) diff --git a/tasks/cache_header_check.go b/tasks/cache_header_check.go index 427cc26..17b5c33 100644 --- a/tasks/cache_header_check.go +++ b/tasks/cache_header_check.go @@ -2,14 +2,13 @@ package tasks import ( "io/ioutil" - "log" "os" "path/filepath" "time" - common "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" ) // CacheHeaderCheck is a function to check cache headers if it's expired. @@ -39,7 +38,7 @@ func CacheHeaderCheck(rpcAddr string, isLog bool) { if path != config.GetResponseCacheDir() && delete { if isLog { - common.GetLogger().Info("[cache] Deleting file: ", path) + log.CustomLogger().Info("[cache] Deleting file: ", path) } global.Mutex.Lock() @@ -53,7 +52,7 @@ func CacheHeaderCheck(rpcAddr string, isLog bool) { if err != nil { if isLog { - common.GetLogger().Error("[cache] Error deleting file: ", err) + log.CustomLogger().Error("[cache] Error deleting file: ", err) } return err } @@ -65,7 +64,9 @@ func CacheHeaderCheck(rpcAddr string, isLog bool) { }) if err != nil { - log.Println(err) + log.CustomLogger().Error("[CacheHeaderCheck] Failed to check cache headers", + "error", err, + ) } time.Sleep(2 * time.Second) diff --git a/tasks/cache_max_size_check.go b/tasks/cache_max_size_check.go index 6ed936c..7117fc7 100644 --- a/tasks/cache_max_size_check.go +++ b/tasks/cache_max_size_check.go @@ -6,9 +6,9 @@ import ( "path/filepath" "time" - common "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" ) // CacheMaxSizeCheck is a function to check if cache reached the maximum size. @@ -27,7 +27,7 @@ func CacheMaxSizeCheck(isLog bool) { if cacheSize >= config.Config.Cache.MaxCacheSize { if isLog { - common.GetLogger().Info("[cache] Reached the maximum size") + log.CustomLogger().Info("[cache] Reached the maximum size") } for { @@ -43,7 +43,7 @@ func CacheMaxSizeCheck(isLog bool) { cacheSize -= info.Size() if isLog { - common.GetLogger().Info("[cache] Deleting file: ", path) + log.CustomLogger().Info("[cache] Deleting file: ", path) } global.Mutex.Lock() @@ -57,7 +57,7 @@ func CacheMaxSizeCheck(isLog bool) { if err != nil { if isLog { - common.GetLogger().Error("[cache] Error deleting file: ", err) + log.CustomLogger().Error("[cache] Error deleting file: ", err) } return err } diff --git a/tasks/data_reference_check.go b/tasks/data_reference_check.go index b5a4e56..386fc8d 100644 --- a/tasks/data_reference_check.go +++ b/tasks/data_reference_check.go @@ -8,10 +8,10 @@ import ( "strconv" "time" - common "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" database "github.com/KiraCore/interx/database" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" ) // RefMeta is a struct to be used for reference metadata @@ -103,9 +103,9 @@ func DataReferenceCheck(isLog bool) { } if isLog { - common.GetLogger().Info("[cache] Data reference updated") - common.GetLogger().Info("[cache] Key = ", v.Key) - common.GetLogger().Info("[cache] Ref = ", v.URL) + log.CustomLogger().Info("[cache] Data reference updated") + log.CustomLogger().Info("[cache] Key = ", v.Key) + log.CustomLogger().Info("[cache] Ref = ", v.URL) } database.AddReference(v.Key, v.URL, ref.ContentLength, ref.LastModified, v.FilePath) diff --git a/tasks/node_discover.go b/tasks/node_discover.go index 3817439..0dd2210 100644 --- a/tasks/node_discover.go +++ b/tasks/node_discover.go @@ -16,6 +16,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/ed25519" @@ -231,7 +232,7 @@ func getBlock(rpcAddr string, height string) (*struct { Time string `json:"time"` }, error) { url := fmt.Sprintf("%s/block?height=%s", rpcAddr, height) - common.GetLogger().Info("getBlock", url) + log.CustomLogger().Info("getBlock", url) resp, err := http.Get(url) if err != nil { return nil, err @@ -257,7 +258,7 @@ func getBlock(rpcAddr string, height string) (*struct { }) err = json.NewDecoder(resp.Body).Decode(result) if err != nil { - common.GetLogger().Error("[node-status] Unexpected response: ", url) + log.CustomLogger().Error("[node-status] Unexpected response: ", url) return nil, err } @@ -317,7 +318,7 @@ func getBlockFromInterx(rpcAddr string, height string) (*struct { Time string `json:"time"` }, error) { url := fmt.Sprintf("%s/api/block/%s", rpcAddr, height) - common.GetLogger().Info("getBlockFromInterx", url) + log.CustomLogger().Info("getBlockFromInterx", url) resp, err := http.Get(url) if err != nil { return nil, err @@ -343,7 +344,7 @@ func getBlockFromInterx(rpcAddr string, height string) (*struct { }) err = json.NewDecoder(resp.Body).Decode(result) if err != nil { - common.GetLogger().Error("[node-status] Unexpected response: ", url) + log.CustomLogger().Error("[node-status] Unexpected response: ", url) return nil, err } @@ -385,20 +386,20 @@ func getGeoData(ipAddr string) GeoData { geoApiEndpoint := "http://ip-api.com/json/" + ipAddr res, err := http.Get(geoApiEndpoint) if err != nil { - common.GetLogger().Error("failed to query geo info", err) + log.CustomLogger().Error("failed to query geo info", err) return geodata } defer res.Body.Close() resBody, err := io.ReadAll(res.Body) if err != nil { - common.GetLogger().Error("failed to read response body", err) + log.CustomLogger().Error("failed to read response body", err) return geodata } err = json.Unmarshal(resBody, &geodata) if err != nil { - common.GetLogger().Error("failed to unmarshal geodata", err) + log.CustomLogger().Error("failed to unmarshal geodata", err) return geodata } return geodata @@ -468,7 +469,7 @@ func NodeDiscover(rpcAddr string, isLog bool) { index++ if isLog { - common.GetLogger().Info("[node-discovery] ", ipAddr) + log.CustomLogger().Info("[node-discovery] ", ipAddr) } kiraStatus, err := QueryStatus(ipAddr) @@ -688,7 +689,7 @@ func NodeDiscover(rpcAddr string, isLog bool) { global.Mutex.Unlock() if isLog { - common.GetLogger().Info("[node-discovery] finished!") + log.CustomLogger().Info("[node-discovery] finished!") } time.Sleep(10 * time.Second) @@ -747,7 +748,7 @@ func getHostname(listenAddr string) (string, error) { if err == nil { return u.Hostname(), nil } - common.GetLogger().Error("[node-discovery] unexpected listen addr: ", listenAddr) + log.CustomLogger().Error("[node-discovery] unexpected listen addr: ", listenAddr) return "", err } diff --git a/tasks/proposals.go b/tasks/proposals.go index eb81a5d..a861152 100644 --- a/tasks/proposals.go +++ b/tasks/proposals.go @@ -13,6 +13,7 @@ import ( "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/database" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types/kira/gov" tmjson "github.com/cometbft/cometbft/libs/json" tmTypes "github.com/cometbft/cometbft/rpc/core/types" @@ -261,7 +262,7 @@ func GetCachedProposals(gwCosmosmux *runtime.ServeMux, gatewayAddr string, rpcAd txTime, err := common.GetBlockTime(rpcAddr, propTx.Height) if err != nil { - common.GetLogger().Error("[query-transactions] Block not found: ", propTx.Height) + log.CustomLogger().Error("[query-transactions] Block not found: ", propTx.Height) continue } @@ -270,7 +271,7 @@ func GetCachedProposals(gwCosmosmux *runtime.ServeMux, gatewayAddr string, rpcAd // grab metadata from the transaction tx, err := config.EncodingCg.TxConfig.TxDecoder()(propTx.Tx) if err != nil { - common.GetLogger().Error("[query-transactions] Failed to decode transaction: ", err) + log.CustomLogger().Error("[query-transactions] Failed to decode transaction: ", err) continue } @@ -328,7 +329,7 @@ func SyncProposals(gwCosmosmux *runtime.ServeMux, gatewayAddr string, rpcAddr st err := QueryProposals(gwCosmosmux, gatewayAddr, rpcAddr) if err != nil && isLog { - common.GetLogger().Error("[sync-proposals] Failed to query proposals: ", err) + log.CustomLogger().Error("[sync-proposals] Failed to query proposals: ", err) } lastBlock = common.NodeStatus.Block diff --git a/tasks/snapshot_checksum.go b/tasks/snapshot_checksum.go index d4bc101..3fac6c6 100644 --- a/tasks/snapshot_checksum.go +++ b/tasks/snapshot_checksum.go @@ -7,8 +7,8 @@ import ( "os" "time" - "github.com/KiraCore/interx/common" "github.com/KiraCore/interx/config" + "github.com/KiraCore/interx/log" ) var ( @@ -22,12 +22,12 @@ func calcChecksum(isLog bool) { SnapshotChecksumAvailable = false SnapshotLength = 0 - common.GetLogger().Info("[cache] calculating snapshot checksum: ") + log.CustomLogger().Info("[cache] calculating snapshot checksum: ") f, err := os.Open(config.SnapshotPath()) if err != nil { if isLog { - common.GetLogger().Error("[cache] can't read snapshot file: ", err) + log.CustomLogger().Error("[cache] can't read snapshot file: ", err) } return @@ -46,7 +46,7 @@ func calcChecksum(isLog bool) { if err != nil { if err != io.EOF { if isLog { - common.GetLogger().Error("[cache] failed to read snapshot: ", err) + log.CustomLogger().Error("[cache] failed to read snapshot: ", err) } return } @@ -64,7 +64,7 @@ func calcChecksum(isLog bool) { SnapshotChecksumAvailable = true SnapshotChecksum = hex.EncodeToString(h.Sum(nil)) SnapshotLength = totalRead - common.GetLogger().Info("[cache] snapshot checksum: ", SnapshotChecksum) + log.CustomLogger().Info("[cache] snapshot checksum: ", SnapshotChecksum) } // CalcSnapshotChecksum is a function for syncing sekaid status. @@ -76,7 +76,7 @@ func CalcSnapshotChecksum(isLog bool) { if err != nil { if available != 1 && isLog { - common.GetLogger().Error("[cache] can't read snapshot file: ", err) + log.CustomLogger().Error("[cache] can't read snapshot file: ", err) available = 1 } diff --git a/tasks/sync_status.go b/tasks/sync_status.go index 6bc459d..18703c1 100644 --- a/tasks/sync_status.go +++ b/tasks/sync_status.go @@ -11,13 +11,21 @@ import ( "github.com/KiraCore/interx/config" "github.com/KiraCore/interx/database" "github.com/KiraCore/interx/global" + "github.com/KiraCore/interx/log" ) func getStatus(rpcAddr string, isLog bool) { + + log.CustomLogger().Info("Starting `getStatus` request...", + "rpc Addr", rpcAddr, + ) + url := fmt.Sprintf("%s/block", rpcAddr) resp, err := http.Get(url) if err != nil { - common.GetLogger().Error("[node-status] Unable to connect to ", url) + log.CustomLogger().Error(" [getStatus] Unable to connect to", + "url", url, + ) return } defer resp.Body.Close() @@ -39,7 +47,9 @@ func getStatus(rpcAddr string, isLog bool) { result := new(RPCTempResponse) if json.NewDecoder(resp.Body).Decode(result) != nil { - common.GetLogger().Error("[node-status] Unexpected response: ", url) + log.CustomLogger().Error(" [getStatus] Unable to connect to", + "url", url, + ) return } @@ -50,7 +60,11 @@ func getStatus(rpcAddr string, isLog bool) { global.Mutex.Unlock() if isLog { - common.GetLogger().Info("[node-status] (new block) height: ", common.NodeStatus.Block, " time: ", common.NodeStatus.Blocktime) + + log.CustomLogger().Info("Processed `getStatus` (new block) height", + "block", common.NodeStatus.Block, + "time", common.NodeStatus.Blocktime, + ) } // save block height/time @@ -68,10 +82,11 @@ func SyncStatus(rpcAddr string, isLog bool) { getStatus(rpcAddr, isLog) if isLog { - common.GetLogger().Info("[node-status] Syncing node status") - common.GetLogger().Info("[node-status] Chain_id = ", common.NodeStatus.Chainid) - common.GetLogger().Info("[node-status] Block = ", common.NodeStatus.Block) - common.GetLogger().Info("[node-status] Blocktime = ", common.NodeStatus.Blocktime) + log.CustomLogger().Info("Processed `getStatus` Syncing node status", + "Chain_id", common.NodeStatus.Chainid, + "Block", common.NodeStatus.Block, + "Blocktime", common.NodeStatus.Blocktime, + ) } time.Sleep(time.Duration(config.Config.Block.StatusSync) * time.Second) diff --git a/tasks/validators.go b/tasks/validators.go index 170985c..ceedf9e 100644 --- a/tasks/validators.go +++ b/tasks/validators.go @@ -10,6 +10,7 @@ import ( "time" "github.com/KiraCore/interx/common" + "github.com/KiraCore/interx/log" "github.com/KiraCore/interx/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" @@ -278,8 +279,6 @@ func QueryValidators(gwCosmosmux *runtime.ServeMux, gatewayAddr string) error { AllValidators = allValidators - // common.GetLogger().Info(AllValidators) - return nil } @@ -290,7 +289,9 @@ func SyncValidators(gwCosmosmux *runtime.ServeMux, gatewayAddr string, isLog boo err := QueryValidators(gwCosmosmux, gatewayAddr) if err != nil && isLog { - common.GetLogger().Error("[sync-validators] Failed to query validators: ", err) + log.CustomLogger().Error("[SyncValidators] Failed to fetch validators.", + "error", err, + ) } lastBlock = common.NodeStatus.Block