From 052915a1d599f415dd519c5d83ce2bddb95f6d18 Mon Sep 17 00:00:00 2001 From: Yohan Nelson Date: Mon, 31 Jul 2023 18:51:59 +0530 Subject: [PATCH] Releasing 1.0.6 (#1102) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Merged `v1.3.0-alpha` into `v1.0.5` (#973) * Merged `v1` into `v1.3.0-aplha` with hotfixes (#966) * Hotfix-proposed data (#913) * Updated propose data global variables correctly * Fixed tests * Returned correct waitForBlockCompletion error * coverage increase * GetLocalData returns type types.ProposeFileData * fixed benchmark * Fetched Last proposed from contracts (#917) * fetched getLastProposedEpoch from contracts and tests for it * typo fix * V1 propose hotfix (#918) * Change propose.go to get sorted proposed block ids. * Fix sorted proposed block issue. Signed-off-by: Ashish Kumar Mishra * allow stakers to addStake < minSafeRazor (#928) * Call claimStakerReward only if there reward to claim (#926) * Make contract call only if there is commission to claim * Add tests for claimCommission file * update check * Hotfix-giveSorted (#921) * ResetDispute only done after FinalizeDispute * Fixed tests * Update README (#931) * Update README * Update logs path * Fix home dir path * Add logs to vote.go and commit.go Signed-off-by: Ashish Kumar Mishra * Add logs for dispute and propose. Signed-off-by: Ashish Kumar Mishra * Fix tests. Signed-off-by: Ashish Kumar Mishra * Suppress unneccessary error logs. (#935) Signed-off-by: Ashish Kumar Mishra * changed http timeout to 30 sec (#943) * saving commit data only after successfull commit (#947) * Added password flag (#946) * added password flag * README updated * Hotfix-giveSorted (new implementation) (#953) * GiveSorted linear recursion * Added backupNode flag * Compilation success for tests * Fixed tests * removed recusrsion, called giveSorted linearly * fixed tests * Added leafId to giveSortedLeafIds[] on successful giveSorted * Hotfix-sortedProposedBlocks (#957) * Shuffled copied slice instead of original slice * returned error from giveSorted when len(sortedValues)=0 * Fixed dispute tests * Changed pending nonce at to nonce at. (#948) * Changed pending nonce at to nonce at. * Update mockery Signed-off-by: Ashish Kumar Mishra * Hotfix -RPCTimeout (#955) * Added a generic function with timeout for contract calls * Moved generic function to utils and implemented to all contract getter calls * Implemented timeout for contract setter functions * rpc timeout custom error * type asserting structs from contract mappings * Shifted timeout to constants * passed timeout in int in constants.go * Added rpcTimeout as config * Removed errorIndex paramter from CheckIfAnyError() * Function renamed * Fixed tests * Unrequired change * Added backup node info in readme (#963) * Passed a initialized varible instead of nil value as a parameter Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Updated `v1.3.0` branch to staging parameters for v1.3.0-alpha version (#967) * Updated contract addresses and chainId to staging * Updated razor-go version to v1.3.0-alpha * Fixed `CheckIfAnyError()` on RPCTimeout. (#974) * Added errorIndexInReturnedValues as a parameter in function * Fixed comparios of error data type from returned values * Added a check if config key is present in yaml file before fetching value (#975) * Added default values for config parameters * Checked if config key is present in yaml file before fetching * Fixed tests * returned default values uniformly Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * updated version to v1.0.5-alpha (#978) * Reduced wait for block completion to 1 second (#984) * changed tolerance flag type to uint32 (#983) * Removed ethBalanceCheck (#982) * Moved constant values to constants.go (#987) * moved gasLimitMultiplier as constant in constants.go * Moved path.go strings to constants.go * Replaced common.Hash{0x00} with core.NilHash * Update geth version to v1.10.25 and updated depreciated bindings (#985) * Updated geth version * Updated depriciated bindings * updated go.sum to fix tests * Replaced errors package * Validate contract calls (Changes from v1-audit) (#981) * Added retry mechanism for fetchBalance * Added ETA for unlockWithdraw * Added check of staker is slashed for stake * Added valid ERC20 check for addresses * Changed name from IsValidErc20Address to IsValidAddress * Functions Refactor (#989) * changed state name to Buffer instead of -1 * CalculateBlockNumberAtEpochBeginning cleanup * Renamed functions in array.go * ApproveUnstake sends StakerTokenAddress instead of StakerStruct * Returned error from getMerkleTree() * Returned error from getMerkleRoot() * Removed unused functions * Added tree is nil condition in GetMerkleRoot() * fixed BenchmarkGenerateTreeRevealData * Code CleanUp (Issues from v1-audit) (#990) * Renamed getDelayedState to getBufferedState * remove uint64 from block time * Renamed handleRevealState to CheckForLastCommitted * CalculateBlockNumberAtEpochBeginning renamed to EstimateBlockNumberAtEpochBeginning * Renamed claimStakeReward to ClaimStakerReward * Renamed GetStatesAllowed to GetFormattedStateNames * GetSalt clean up * changed int64 to uint64 in constants * Used block.Time directly instead of blockTime variable * Txn hash made consistent in logging * remove redundant uint64 typecast from GetEpoch() * Rename coinContract to erc20contract * Updated mocks after renaming coinContract to erc20Contract * Removed redundant code in logger.go * Removed space from xhtml job result (#991) * Log changes from v1-audit (#994) * Renamed eth balance to sFuel balance * used log.Info instead of fmt.Println for contractAddresses * Added do not mopdify note in constants.go * Added a warning for low ethBalance * replaced path.join with filepath.join (#992) * Removed redundant cmd/utilsInterface (#997) * Removed UtilsInterface in cmd package * Compilation successful for tests * replaced utils.UtilsInterface with razorUtils * Included CheckAmountAndBalance in utils/utilsInterface * Fixed tests * Fixed benchmark * Fixed MakeBlock benchmark * Moved waitForAppropriateState after epoch check (#1008) * Implemented timeout for logger on fetching blockNumber (#1009) * Implemented timeout for logger on fethcing blockNumber * Added comments * updated dockerfile and readme for non-root user (#1014) * Moved Lumberjack constants to config (#1011) * Added logFile parameters to config * Initialised logger with getting parameters from config * Added logFile paramters in config set up script * Added config as a parameter in AssignLogFile() * Fixed tests * Avoided passing nil types.Configurations{] * Passed types.Configuations{} for setConfig * updated readme for expose metric and running cmd in background (#1015) * Cached API Response (#1016) * Added cache package containing caching utils * Used cache to get data from API * Fixed tests * Fixed test * minor fixes * removed unwanted test * Added condition to fetch value only if the key is present in json (#1028) * Added support for Post Requests (#1020) * Added POST request support * datasource URL struct support * Updated createJob command and new format for assets.json file * Fixed tests * Fixed URlStruct in test * Removed unwanted comment * Backwards compatible * Removed unwanted logs * Merge `v1.0.5`into `v1.0.6` (#1031) * Changes Requested in v1.0.5 Review (#1006) * updated logs and readMe for v1.0.5 * Canges string formater for errors to %v * Inserted Logs in the entire codebase (#1018) * Inserted Logs * Corrected logs * Modified lumberJack constants * V1.0.5-alpha-patch1 Ready (#1022) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Log corrections * updated release * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Calculated blockNumber in a separate go-routine for logging (#1025) * Cached block number in logger * Revert "Cached block number in logger" This reverts commit 760e3adf38f106bd444ef2d64494565d9bd6dae1. * Added block/block.go for calculating latestBlock in a seperate goroutine * Fetched block number from block package * log corrections * Increased max size of file to 182MB (#1027) * renamed variable correctly Co-authored-by: Shrikant upadhyay * Refactor utilsInterface (#1024) * FileUtils, GasUtils, ClientUtils * Added test_utils.go to initialiase all the mocked interface * test_utils.go support for all tests * Initialised new utils interfaces * Fetched v1.0.5 updates to v1.0.6 (#1045) * Fetched the updated changes from v1.0.5 * Staging deployement parameters (#1046) * Added http timeout as a config parameter (#1055) * added http timeout as a config parameter * Fixed and Added tests * added httpTimeout in config * Added logFile config parameters to readMe * Fixed comments * Fetched API key from env file (#1048) * Added dot env file utils * Fetched API key from .env file when required * updated dependencies * Changed API key regex * Added name field in customJob struct * Replaced content-type field with headers in dataSourceURLStruct * Updated post request creation * picked API Regex from constants.go * Removed unwanted field from header * returned error as well from GetkeywordAndAPIKey * replaces regexp.Match() with strings.Contains() * support for headers in GET requests * Refactored GetDataFromAPI * Added processRequest retry constants * Added condition to check if there was a value in previous block (#1056) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Merge v1.0.5 to main (#1038) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Merged `v1.3.0-alpha` into `v1.0.5` (#973) * Merged `v1` into `v1.3.0-aplha` with hotfixes (#966) * Hotfix-proposed data (#913) * Updated propose data global variables correctly * Fixed tests * Returned correct waitForBlockCompletion error * coverage increase * GetLocalData returns type types.ProposeFileData * fixed benchmark * Fetched Last proposed from contracts (#917) * fetched getLastProposedEpoch from contracts and tests for it * typo fix * V1 propose hotfix (#918) * Change propose.go to get sorted proposed block ids. * Fix sorted proposed block issue. Signed-off-by: Ashish Kumar Mishra * allow stakers to addStake < minSafeRazor (#928) * Call claimStakerReward only if there reward to claim (#926) * Make contract call only if there is commission to claim * Add tests for claimCommission file * update check * Hotfix-giveSorted (#921) * ResetDispute only done after FinalizeDispute * Fixed tests * Update README (#931) * Update README * Update logs path * Fix home dir path * Add logs to vote.go and commit.go Signed-off-by: Ashish Kumar Mishra * Add logs for dispute and propose. Signed-off-by: Ashish Kumar Mishra * Fix tests. Signed-off-by: Ashish Kumar Mishra * Suppress unneccessary error logs. (#935) Signed-off-by: Ashish Kumar Mishra * changed http timeout to 30 sec (#943) * saving commit data only after successfull commit (#947) * Added password flag (#946) * added password flag * README updated * Hotfix-giveSorted (new implementation) (#953) * GiveSorted linear recursion * Added backupNode flag * Compilation success for tests * Fixed tests * removed recusrsion, called giveSorted linearly * fixed tests * Added leafId to giveSortedLeafIds[] on successful giveSorted * Hotfix-sortedProposedBlocks (#957) * Shuffled copied slice instead of original slice * returned error from giveSorted when len(sortedValues)=0 * Fixed dispute tests * Changed pending nonce at to nonce at. (#948) * Changed pending nonce at to nonce at. * Update mockery Signed-off-by: Ashish Kumar Mishra * Hotfix -RPCTimeout (#955) * Added a generic function with timeout for contract calls * Moved generic function to utils and implemented to all contract getter calls * Implemented timeout for contract setter functions * rpc timeout custom error * type asserting structs from contract mappings * Shifted timeout to constants * passed timeout in int in constants.go * Added rpcTimeout as config * Removed errorIndex paramter from CheckIfAnyError() * Function renamed * Fixed tests * Unrequired change * Added backup node info in readme (#963) * Passed a initialized varible instead of nil value as a parameter Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Updated `v1.3.0` branch to staging parameters for v1.3.0-alpha version (#967) * Updated contract addresses and chainId to staging * Updated razor-go version to v1.3.0-alpha * Fixed `CheckIfAnyError()` on RPCTimeout. (#974) * Added errorIndexInReturnedValues as a parameter in function * Fixed comparios of error data type from returned values * Added a check if config key is present in yaml file before fetching value (#975) * Added default values for config parameters * Checked if config key is present in yaml file before fetching * Fixed tests * returned default values uniformly Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * updated version to v1.0.5-alpha (#978) * Changes Requested in v1.0.5 Review (#1006) * updated logs and readMe for v1.0.5 * Canges string formater for errors to %v * Inserted Logs in the entire codebase (#1018) * Inserted Logs * Corrected logs * Modified lumberJack constants * V1.0.5-alpha-patch1 Ready (#1022) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Log corrections * updated release * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Calculated blockNumber in a separate go-routine for logging (#1025) * Cached block number in logger * Revert "Cached block number in logger" This reverts commit 760e3adf38f106bd444ef2d64494565d9bd6dae1. * Added block/block.go for calculating latestBlock in a seperate goroutine * Fetched block number from block package * log corrections * Increased max size of file to 182MB (#1027) * V1.0.5 beta ready (#1032) * Production support * Updated release version * Updated maxSize of log file to 200MB * Added mutex lock in blockNumber calculation (#1035) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Added mutex lock in blockNumber calculation * Added new staging addresses and chainId * updated version Co-authored-by: Shrikant upadhyay * v1.0.5-beta-patch1 (#1037) * Updated depolyment paramters to prod * updated version to v1.0.5-beta-patch1 * Updated version to v1.0.5 (#1033) * Made v1.0.5 branch in sync with main branch (#1039) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Deleted password file (#1040) Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay * Releases/v1.0.5 (#1043) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Merged `v1.3.0-alpha` into `v1.0.5` (#973) * Merged `v1` into `v1.3.0-aplha` with hotfixes (#966) * Hotfix-proposed data (#913) * Updated propose data global variables correctly * Fixed tests * Returned correct waitForBlockCompletion error * coverage increase * GetLocalData returns type types.ProposeFileData * fixed benchmark * Fetched Last proposed from contracts (#917) * fetched getLastProposedEpoch from contracts and tests for it * typo fix * V1 propose hotfix (#918) * Change propose.go to get sorted proposed block ids. * Fix sorted proposed block issue. Signed-off-by: Ashish Kumar Mishra * allow stakers to addStake < minSafeRazor (#928) * Call claimStakerReward only if there reward to claim (#926) * Make contract call only if there is commission to claim * Add tests for claimCommission file * update check * Hotfix-giveSorted (#921) * ResetDispute only done after FinalizeDispute * Fixed tests * Update README (#931) * Update README * Update logs path * Fix home dir path * Add logs to vote.go and commit.go Signed-off-by: Ashish Kumar Mishra * Add logs for dispute and propose. Signed-off-by: Ashish Kumar Mishra * Fix tests. Signed-off-by: Ashish Kumar Mishra * Suppress unneccessary error logs. (#935) Signed-off-by: Ashish Kumar Mishra * changed http timeout to 30 sec (#943) * saving commit data only after successfull commit (#947) * Added password flag (#946) * added password flag * README updated * Hotfix-giveSorted (new implementation) (#953) * GiveSorted linear recursion * Added backupNode flag * Compilation success for tests * Fixed tests * removed recusrsion, called giveSorted linearly * fixed tests * Added leafId to giveSortedLeafIds[] on successful giveSorted * Hotfix-sortedProposedBlocks (#957) * Shuffled copied slice instead of original slice * returned error from giveSorted when len(sortedValues)=0 * Fixed dispute tests * Changed pending nonce at to nonce at. (#948) * Changed pending nonce at to nonce at. * Update mockery Signed-off-by: Ashish Kumar Mishra * Hotfix -RPCTimeout (#955) * Added a generic function with timeout for contract calls * Moved generic function to utils and implemented to all contract getter calls * Implemented timeout for contract setter functions * rpc timeout custom error * type asserting structs from contract mappings * Shifted timeout to constants * passed timeout in int in constants.go * Added rpcTimeout as config * Removed errorIndex paramter from CheckIfAnyError() * Function renamed * Fixed tests * Unrequired change * Added backup node info in readme (#963) * Passed a initialized varible instead of nil value as a parameter Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Updated `v1.3.0` branch to staging parameters for v1.3.0-alpha version (#967) * Updated contract addresses and chainId to staging * Updated razor-go version to v1.3.0-alpha * Fixed `CheckIfAnyError()` on RPCTimeout. (#974) * Added errorIndexInReturnedValues as a parameter in function * Fixed comparios of error data type from returned values * Added a check if config key is present in yaml file before fetching value (#975) * Added default values for config parameters * Checked if config key is present in yaml file before fetching * Fixed tests * returned default values uniformly Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * updated version to v1.0.5-alpha (#978) * Changes Requested in v1.0.5 Review (#1006) * updated logs and readMe for v1.0.5 * Canges string formater for errors to %v * Inserted Logs in the entire codebase (#1018) * Inserted Logs * Corrected logs * Modified lumberJack constants * V1.0.5-alpha-patch1 Ready (#1022) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Log corrections * updated release * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Calculated blockNumber in a separate go-routine for logging (#1025) * Cached block number in logger * Revert "Cached block number in logger" This reverts commit 760e3adf38f106bd444ef2d64494565d9bd6dae1. * Added block/block.go for calculating latestBlock in a seperate goroutine * Fetched block number from block package * log corrections * Increased max size of file to 182MB (#1027) * V1.0.5 beta ready (#1032) * Production support * Updated release version * Updated maxSize of log file to 200MB * Added mutex lock in blockNumber calculation (#1035) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Added mutex lock in blockNumber calculation * Added new staging addresses and chainId * updated version Co-authored-by: Shrikant upadhyay * v1.0.5-beta-patch1 (#1037) * Updated depolyment paramters to prod * updated version to v1.0.5-beta-patch1 * Updated version to v1.0.5 (#1033) * Made v1.0.5 branch in sync with main branch (#1039) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Deleted password file (#1040) * Added sleep time to reduce amount of RPC calls to get blockNumber (#1042) add sleep after client call to get blockNumber Signed-off-by: Ashish Kumar Mishra Co-authored-by: Yashk767 <76935991+Yashk767@users.noreply.github.com> Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay Co-authored-by: YashK * updated CI for dockerhub token. (#1052) * added condition to check if there was a value in previous block * changed error messaged --------- Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shrikant upadhyay Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Checked password is correct at the immediate start of command (#1069) * Added function CheckPassword() * Checked password at immediate start of command * Added CheckPassword in UtilsInterface * fixed tests * Fetch `main` branch into `v1.0.6` (#1076) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Merge v1.0.5 to main (#1038) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Merged `v1.3.0-alpha` into `v1.0.5` (#973) * Merged `v1` into `v1.3.0-aplha` with hotfixes (#966) * Hotfix-proposed data (#913) * Updated propose data global variables correctly * Fixed tests * Returned correct waitForBlockCompletion error * coverage increase * GetLocalData returns type types.ProposeFileData * fixed benchmark * Fetched Last proposed from contracts (#917) * fetched getLastProposedEpoch from contracts and tests for it * typo fix * V1 propose hotfix (#918) * Change propose.go to get sorted proposed block ids. * Fix sorted proposed block issue. Signed-off-by: Ashish Kumar Mishra * allow stakers to addStake < minSafeRazor (#928) * Call claimStakerReward only if there reward to claim (#926) * Make contract call only if there is commission to claim * Add tests for claimCommission file * update check * Hotfix-giveSorted (#921) * ResetDispute only done after FinalizeDispute * Fixed tests * Update README (#931) * Update README * Update logs path * Fix home dir path * Add logs to vote.go and commit.go Signed-off-by: Ashish Kumar Mishra * Add logs for dispute and propose. Signed-off-by: Ashish Kumar Mishra * Fix tests. Signed-off-by: Ashish Kumar Mishra * Suppress unneccessary error logs. (#935) Signed-off-by: Ashish Kumar Mishra * changed http timeout to 30 sec (#943) * saving commit data only after successfull commit (#947) * Added password flag (#946) * added password flag * README updated * Hotfix-giveSorted (new implementation) (#953) * GiveSorted linear recursion * Added backupNode flag * Compilation success for tests * Fixed tests * removed recusrsion, called giveSorted linearly * fixed tests * Added leafId to giveSortedLeafIds[] on successful giveSorted * Hotfix-sortedProposedBlocks (#957) * Shuffled copied slice instead of original slice * returned error from giveSorted when len(sortedValues)=0 * Fixed dispute tests * Changed pending nonce at to nonce at. (#948) * Changed pending nonce at to nonce at. * Update mockery Signed-off-by: Ashish Kumar Mishra * Hotfix -RPCTimeout (#955) * Added a generic function with timeout for contract calls * Moved generic function to utils and implemented to all contract getter calls * Implemented timeout for contract setter functions * rpc timeout custom error * type asserting structs from contract mappings * Shifted timeout to constants * passed timeout in int in constants.go * Added rpcTimeout as config * Removed errorIndex paramter from CheckIfAnyError() * Function renamed * Fixed tests * Unrequired change * Added backup node info in readme (#963) * Passed a initialized varible instead of nil value as a parameter Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Updated `v1.3.0` branch to staging parameters for v1.3.0-alpha version (#967) * Updated contract addresses and chainId to staging * Updated razor-go version to v1.3.0-alpha * Fixed `CheckIfAnyError()` on RPCTimeout. (#974) * Added errorIndexInReturnedValues as a parameter in function * Fixed comparios of error data type from returned values * Added a check if config key is present in yaml file before fetching value (#975) * Added default values for config parameters * Checked if config key is present in yaml file before fetching * Fixed tests * returned default values uniformly Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * updated version to v1.0.5-alpha (#978) * Changes Requested in v1.0.5 Review (#1006) * updated logs and readMe for v1.0.5 * Canges string formater for errors to %v * Inserted Logs in the entire codebase (#1018) * Inserted Logs * Corrected logs * Modified lumberJack constants * V1.0.5-alpha-patch1 Ready (#1022) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Log corrections * updated release * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Calculated blockNumber in a separate go-routine for logging (#1025) * Cached block number in logger * Revert "Cached block number in logger" This reverts commit 760e3adf38f106bd444ef2d64494565d9bd6dae1. * Added block/block.go for calculating latestBlock in a seperate goroutine * Fetched block number from block package * log corrections * Increased max size of file to 182MB (#1027) * V1.0.5 beta ready (#1032) * Production support * Updated release version * Updated maxSize of log file to 200MB * Added mutex lock in blockNumber calculation (#1035) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Added mutex lock in blockNumber calculation * Added new staging addresses and chainId * updated version Co-authored-by: Shrikant upadhyay * v1.0.5-beta-patch1 (#1037) * Updated depolyment paramters to prod * updated version to v1.0.5-beta-patch1 * Updated version to v1.0.5 (#1033) * Made v1.0.5 branch in sync with main branch (#1039) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Deleted password file (#1040) Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay * Releases/v1.0.5 (#1043) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Merged `v1.3.0-alpha` into `v1.0.5` (#973) * Merged `v1` into `v1.3.0-aplha` with hotfixes (#966) * Hotfix-proposed data (#913) * Updated propose data global variables correctly * Fixed tests * Returned correct waitForBlockCompletion error * coverage increase * GetLocalData returns type types.ProposeFileData * fixed benchmark * Fetched Last proposed from contracts (#917) * fetched getLastProposedEpoch from contracts and tests for it * typo fix * V1 propose hotfix (#918) * Change propose.go to get sorted proposed block ids. * Fix sorted proposed block issue. Signed-off-by: Ashish Kumar Mishra * allow stakers to addStake < minSafeRazor (#928) * Call claimStakerReward only if there reward to claim (#926) * Make contract call only if there is commission to claim * Add tests for claimCommission file * update check * Hotfix-giveSorted (#921) * ResetDispute only done after FinalizeDispute * Fixed tests * Update README (#931) * Update README * Update logs path * Fix home dir path * Add logs to vote.go and commit.go Signed-off-by: Ashish Kumar Mishra * Add logs for dispute and propose. Signed-off-by: Ashish Kumar Mishra * Fix tests. Signed-off-by: Ashish Kumar Mishra * Suppress unneccessary error logs. (#935) Signed-off-by: Ashish Kumar Mishra * changed http timeout to 30 sec (#943) * saving commit data only after successfull commit (#947) * Added password flag (#946) * added password flag * README updated * Hotfix-giveSorted (new implementation) (#953) * GiveSorted linear recursion * Added backupNode flag * Compilation success for tests * Fixed tests * removed recusrsion, called giveSorted linearly * fixed tests * Added leafId to giveSortedLeafIds[] on successful giveSorted * Hotfix-sortedProposedBlocks (#957) * Shuffled copied slice instead of original slice * returned error from giveSorted when len(sortedValues)=0 * Fixed dispute tests * Changed pending nonce at to nonce at. (#948) * Changed pending nonce at to nonce at. * Update mockery Signed-off-by: Ashish Kumar Mishra * Hotfix -RPCTimeout (#955) * Added a generic function with timeout for contract calls * Moved generic function to utils and implemented to all contract getter calls * Implemented timeout for contract setter functions * rpc timeout custom error * type asserting structs from contract mappings * Shifted timeout to constants * passed timeout in int in constants.go * Added rpcTimeout as config * Removed errorIndex paramter from CheckIfAnyError() * Function renamed * Fixed tests * Unrequired change * Added backup node info in readme (#963) * Passed a initialized varible instead of nil value as a parameter Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Updated `v1.3.0` branch to staging parameters for v1.3.0-alpha version (#967) * Updated contract addresses and chainId to staging * Updated razor-go version to v1.3.0-alpha * Fixed `CheckIfAnyError()` on RPCTimeout. (#974) * Added errorIndexInReturnedValues as a parameter in function * Fixed comparios of error data type from returned values * Added a check if config key is present in yaml file before fetching value (#975) * Added default values for config parameters * Checked if config key is present in yaml file before fetching * Fixed tests * returned default values uniformly Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * updated version to v1.0.5-alpha (#978) * Changes Requested in v1.0.5 Review (#1006) * updated logs and readMe for v1.0.5 * Canges string formater for errors to %v * Inserted Logs in the entire codebase (#1018) * Inserted Logs * Corrected logs * Modified lumberJack constants * V1.0.5-alpha-patch1 Ready (#1022) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Log corrections * updated release * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Calculated blockNumber in a separate go-routine for logging (#1025) * Cached block number in logger * Revert "Cached block number in logger" This reverts commit 760e3adf38f106bd444ef2d64494565d9bd6dae1. * Added block/block.go for calculating latestBlock in a seperate goroutine * Fetched block number from block package * log corrections * Increased max size of file to 182MB (#1027) * V1.0.5 beta ready (#1032) * Production support * Updated release version * Updated maxSize of log file to 200MB * Added mutex lock in blockNumber calculation (#1035) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Added mutex lock in blockNumber calculation * Added new staging addresses and chainId * updated version Co-authored-by: Shrikant upadhyay * v1.0.5-beta-patch1 (#1037) * Updated depolyment paramters to prod * updated version to v1.0.5-beta-patch1 * Updated version to v1.0.5 (#1033) * Made v1.0.5 branch in sync with main branch (#1039) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Deleted password file (#1040) * Added sleep time to reduce amount of RPC calls to get blockNumber (#1042) add sleep after client call to get blockNumber Signed-off-by: Ashish Kumar Mishra Co-authored-by: Yashk767 <76935991+Yashk767@users.noreply.github.com> Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay Co-authored-by: YashK * updated CI for dockerhub token. (#1052) * updated CI for tests (#1075) * updated CI for tests * removed docker from test ci * Merge `v1.0.5-patch2` to main (#1073) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Merged `v1.3.0-alpha` into `v1.0.5` (#973) * Merged `v1` into `v1.3.0-aplha` with hotfixes (#966) * Hotfix-proposed data (#913) * Updated propose data global variables correctly * Fixed tests * Returned correct waitForBlockCompletion error * coverage increase * GetLocalData returns type types.ProposeFileData * fixed benchmark * Fetched Last proposed from contracts (#917) * fetched getLastProposedEpoch from contracts and tests for it * typo fix * V1 propose hotfix (#918) * Change propose.go to get sorted proposed block ids. * Fix sorted proposed block issue. Signed-off-by: Ashish Kumar Mishra * allow stakers to addStake < minSafeRazor (#928) * Call claimStakerReward only if there reward to claim (#926) * Make contract call only if there is commission to claim * Add tests for claimCommission file * update check * Hotfix-giveSorted (#921) * ResetDispute only done after FinalizeDispute * Fixed tests * Update README (#931) * Update README * Update logs path * Fix home dir path * Add logs to vote.go and commit.go Signed-off-by: Ashish Kumar Mishra * Add logs for dispute and propose. Signed-off-by: Ashish Kumar Mishra * Fix tests. Signed-off-by: Ashish Kumar Mishra * Suppress unneccessary error logs. (#935) Signed-off-by: Ashish Kumar Mishra * changed http timeout to 30 sec (#943) * saving commit data only after successfull commit (#947) * Added password flag (#946) * added password flag * README updated * Hotfix-giveSorted (new implementation) (#953) * GiveSorted linear recursion * Added backupNode flag * Compilation success for tests * Fixed tests * removed recusrsion, called giveSorted linearly * fixed tests * Added leafId to giveSortedLeafIds[] on successful giveSorted * Hotfix-sortedProposedBlocks (#957) * Shuffled copied slice instead of original slice * returned error from giveSorted when len(sortedValues)=0 * Fixed dispute tests * Changed pending nonce at to nonce at. (#948) * Changed pending nonce at to nonce at. * Update mockery Signed-off-by: Ashish Kumar Mishra * Hotfix -RPCTimeout (#955) * Added a generic function with timeout for contract calls * Moved generic function to utils and implemented to all contract getter calls * Implemented timeout for contract setter functions * rpc timeout custom error * type asserting structs from contract mappings * Shifted timeout to constants * passed timeout in int in constants.go * Added rpcTimeout as config * Removed errorIndex paramter from CheckIfAnyError() * Function renamed * Fixed tests * Unrequired change * Added backup node info in readme (#963) * Passed a initialized varible instead of nil value as a parameter Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Updated `v1.3.0` branch to staging parameters for v1.3.0-alpha version (#967) * Updated contract addresses and chainId to staging * Updated razor-go version to v1.3.0-alpha * Fixed `CheckIfAnyError()` on RPCTimeout. (#974) * Added errorIndexInReturnedValues as a parameter in function * Fixed comparios of error data type from returned values * Added a check if config key is present in yaml file before fetching value (#975) * Added default values for config parameters * Checked if config key is present in yaml file before fetching * Fixed tests * returned default values uniformly Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * updated version to v1.0.5-alpha (#978) * Changes Requested in v1.0.5 Review (#1006) * updated logs and readMe for v1.0.5 * Canges string formater for errors to %v * Inserted Logs in the entire codebase (#1018) * Inserted Logs * Corrected logs * Modified lumberJack constants * V1.0.5-alpha-patch1 Ready (#1022) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Log corrections * updated release * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Calculated blockNumber in a separate go-routine for logging (#1025) * Cached block number in logger * Revert "Cached block number in logger" This reverts commit 760e3adf38f106bd444ef2d64494565d9bd6dae1. * Added block/block.go for calculating latestBlock in a seperate goroutine * Fetched block number from block package * log corrections * Increased max size of file to 182MB (#1027) * V1.0.5 beta ready (#1032) * Production support * Updated release version * Updated maxSize of log file to 200MB * Added mutex lock in blockNumber calculation (#1035) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Added mutex lock in blockNumber calculation * Added new staging addresses and chainId * updated version Co-authored-by: Shrikant upadhyay * v1.0.5-beta-patch1 (#1037) * Updated depolyment paramters to prod * updated version to v1.0.5-beta-patch1 * Updated version to v1.0.5 (#1033) * Made v1.0.5 branch in sync with main branch (#1039) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Deleted password file (#1040) * Added sleep time to reduce amount of RPC calls to get blockNumber (#1042) add sleep after client call to get blockNumber * Merge `V1.0.5-gasLimitFix` to `releases/v1.0.5` (#1062) * Hardcoded gas limit for reveal (#1060) * Updated version to v1.0.5-patch2 (#1061) * Added gasLimit to override as a config parameter (#1063) * Added gasLimitOverride config parameter * Taking the gas limit value from config if present * Added tests * Added default gas limit override value * Added gas limit overridr in readMe * Updated deployment parameters to staging for `v1.0.5-patch2-alpha` (#1065) * Updated deployment parameters to staging * updated version * Updated to v1.0.5-patch2-beta (#1066) * Updated version to v1.0.5-patch2-beta * Updated deployement parameters to prod * Updated version to `v1.0.5-patch2` release (#1067) * Merge v1.0.5 to main (#1038) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Merged `v1.3.0-alpha` into `v1.0.5` (#973) * Merged `v1` into `v1.3.0-aplha` with hotfixes (#966) * Hotfix-proposed data (#913) * Updated propose data global variables correctly * Fixed tests * Returned correct waitForBlockCompletion error * coverage increase * GetLocalData returns type types.ProposeFileData * fixed benchmark * Fetched Last proposed from contracts (#917) * fetched getLastProposedEpoch from contracts and tests for it * typo fix * V1 propose hotfix (#918) * Change propose.go to get sorted proposed block ids. * Fix sorted proposed block issue. Signed-off-by: Ashish Kumar Mishra * allow stakers to addStake < minSafeRazor (#928) * Call claimStakerReward only if there reward to claim (#926) * Make contract call only if there is commission to claim * Add tests for claimCommission file * update check * Hotfix-giveSorted (#921) * ResetDispute only done after FinalizeDispute * Fixed tests * Update README (#931) * Update README * Update logs path * Fix home dir path * Add logs to vote.go and commit.go Signed-off-by: Ashish Kumar Mishra * Add logs for dispute and propose. Signed-off-by: Ashish Kumar Mishra * Fix tests. Signed-off-by: Ashish Kumar Mishra * Suppress unneccessary error logs. (#935) Signed-off-by: Ashish Kumar Mishra * changed http timeout to 30 sec (#943) * saving commit data only after successfull commit (#947) * Added password flag (#946) * added password flag * README updated * Hotfix-giveSorted (new implementation) (#953) * GiveSorted linear recursion * Added backupNode flag * Compilation success for tests * Fixed tests * removed recusrsion, called giveSorted linearly * fixed tests * Added leafId to giveSortedLeafIds[] on successful giveSorted * Hotfix-sortedProposedBlocks (#957) * Shuffled copied slice instead of original slice * returned error from giveSorted when len(sortedValues)=0 * Fixed dispute tests * Changed pending nonce at to nonce at. (#948) * Changed pending nonce at to nonce at. * Update mockery Signed-off-by: Ashish Kumar Mishra * Hotfix -RPCTimeout (#955) * Added a generic function with timeout for contract calls * Moved generic function to utils and implemented to all contract getter calls * Implemented timeout for contract setter functions * rpc timeout custom error * type asserting structs from contract mappings * Shifted timeout to constants * passed timeout in int in constants.go * Added rpcTimeout as config * Removed errorIndex paramter from CheckIfAnyError() * Function renamed * Fixed tests * Unrequired change * Added backup node info in readme (#963) * Passed a initialized varible instead of nil value as a parameter Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Updated `v1.3.0` branch to staging parameters for v1.3.0-alpha version (#967) * Updated contract addresses and chainId to staging * Updated razor-go version to v1.3.0-alpha * Fixed `CheckIfAnyError()` on RPCTimeout. (#974) * Added errorIndexInReturnedValues as a parameter in function * Fixed comparios of error data type from returned values * Added a check if config key is present in yaml file before fetching value (#975) * Added default values for config parameters * Checked if config key is present in yaml file before fetching * Fixed tests * returned default values uniformly Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * updated version to v1.0.5-alpha (#978) * Changes Requested in v1.0.5 Review (#1006) * updated logs and readMe for v1.0.5 * Canges string formater for errors to %v * Inserted Logs in the entire codebase (#1018) * Inserted Logs * Corrected logs * Modified lumberJack constants * V1.0.5-alpha-patch1 Ready (#1022) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Log corrections * updated release * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Calculated blockNumber in a separate go-routine for logging (#1025) * Cached block number in logger * Revert "Cached block number in logger" This reverts commit 760e3adf38f106bd444ef2d64494565d9bd6dae1. * Added block/block.go for calculating latestBlock in a seperate goroutine * Fetched block number from block package * log corrections * Increased max size of file to 182MB (#1027) * V1.0.5 beta ready (#1032) * Production support * Updated release version * Updated maxSize of log file to 200MB * Added mutex lock in blockNumber calculation (#1035) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Added mutex lock in blockNumber calculation * Added new staging addresses and chainId * updated version Co-authored-by: Shrikant upadhyay * v1.0.5-beta-patch1 (#1037) * Updated depolyment paramters to prod * updated version to v1.0.5-beta-patch1 * Updated version to v1.0.5 (#1033) * Made v1.0.5 branch in sync with main branch (#1039) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Deleted password file (#1040) Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay * Releases/v1.0.5 (#1043) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Merged `v1.3.0-alpha` into `v1.0.5` (#973) * Merged `v1` into `v1.3.0-aplha` with hotfixes (#966) * Hotfix-proposed data (#913) * Updated propose data global variables correctly * Fixed tests * Returned correct waitForBlockCompletion error * coverage increase * GetLocalData returns type types.ProposeFileData * fixed benchmark * Fetched Last proposed from contracts (#917) * fetched getLastProposedEpoch from contracts and tests for it * typo fix * V1 propose hotfix (#918) * Change propose.go to get sorted proposed block ids. * Fix sorted proposed block issue. Signed-off-by: Ashish Kumar Mishra * allow stakers to addStake < minSafeRazor (#928) * Call claimStakerReward only if there reward to claim (#926) * Make contract call only if there is commission to claim * Add tests for claimCommission file * update check * Hotfix-giveSorted (#921) * ResetDispute only done after FinalizeDispute * Fixed tests * Update README (#931) * Update README * Update logs path * Fix home dir path * Add logs to vote.go and commit.go Signed-off-by: Ashish Kumar Mishra * Add logs for dispute and propose. Signed-off-by: Ashish Kumar Mishra * Fix tests. Signed-off-by: Ashish Kumar Mishra * Suppress unneccessary error logs. (#935) Signed-off-by: Ashish Kumar Mishra * changed http timeout to 30 sec (#943) * saving commit data only after successfull commit (#947) * Added password flag (#946) * added password flag * README updated * Hotfix-giveSorted (new implementation) (#953) * GiveSorted linear recursion * Added backupNode flag * Compilation success for tests * Fixed tests * removed recusrsion, called giveSorted linearly * fixed tests * Added leafId to giveSortedLeafIds[] on successful giveSorted * Hotfix-sortedProposedBlocks (#957) * Shuffled copied slice instead of original slice * returned error from giveSorted when len(sortedValues)=0 * Fixed dispute tests * Changed pending nonce at to nonce at. (#948) * Changed pending nonce at to nonce at. * Update mockery Signed-off-by: Ashish Kumar Mishra * Hotfix -RPCTimeout (#955) * Added a generic function with timeout for contract calls * Moved generic function to utils and implemented to all contract getter calls * Implemented timeout for contract setter functions * rpc timeout custom error * type asserting structs from contract mappings * Shifted timeout to constants * passed timeout in int in constants.go * Added rpcTimeout as config * Removed errorIndex paramter from CheckIfAnyError() * Function renamed * Fixed tests * Unrequired change * Added backup node info in readme (#963) * Passed a initialized varible instead of nil value as a parameter Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Updated `v1.3.0` branch to staging parameters for v1.3.0-alpha version (#967) * Updated contract addresses and chainId to staging * Updated razor-go version to v1.3.0-alpha * Fixed `CheckIfAnyError()` on RPCTimeout. (#974) * Added errorIndexInReturnedValues as a parameter in function * Fixed comparios of error data type from returned values * Added a check if config key is present in yaml file before fetching value (#975) * Added default values for config parameters * Checked if config key is present in yaml file before fetching * Fixed tests * returned default values uniformly Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * updated version to v1.0.5-alpha (#978) * Changes Requested in v1.0.5 Review (#1006) * updated logs and readMe for v1.0.5 * Canges string formater for errors to %v * Inserted Logs in the entire codebase (#1018) * Inserted Logs * Corrected logs * Modified lumberJack constants * V1.0.5-alpha-patch1 Ready (#1022) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Log corrections * updated release * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Calculated blockNumber in a separate go-routine for logging (#1025) * Cached block number in logger * Revert "Cached block number in logger" This reverts commit 760e3adf38f106bd444ef2d64494565d9bd6dae1. * Added block/block.go for calculating latestBlock in a seperate goroutine * Fetched block number from block package * log corrections * Increased max size of file to 182MB (#1027) * V1.0.5 beta ready (#1032) * Production support * Updated release version * Updated maxSize of log file to 200MB * Added mutex lock in blockNumber calculation (#1035) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. * Added mutex lock in blockNumber calculation * Added new staging addresses and chainId * updated version Co-authored-by: Shrikant upadhyay * v1.0.5-beta-patch1 (#1037) * Updated depolyment paramters to prod * updated version to v1.0.5-beta-patch1 * Updated version to v1.0.5 (#1033) * Made v1.0.5 branch in sync with main branch (#1039) * Merge `v1.0.4` release to main branch (#977) * v1.2.0 (#965) * Hotfix-logImprovements (#952) * Set up blocknumber and epoch in logs * updated blocknumber and epoch logger info in every command * Hotfix-getDataFromAPI (#951) * Changed numm of retry attempts * removed redundant retry attempts * corrected tests * changed http timeout and logged time elapsed to fetch data (#954) * Updated version (#960) * Updated version * updated version to v1.2.0 * version update (#972) * Updated user in dockerfile (#1012) * updating user in dockerfile * updating readme for non-root user * Revert "Updated user in dockerfile (#1012)" (#1021) This reverts commit 7f95edbdc1c2963077805a9da6b0b5aa7e4c0f22. Co-authored-by: Shrikant upadhyay * Deleted password file (#1040) * Added sleep time to reduce amount of RPC calls to get blockNumber (#1042) add sleep after client call to get blockNumber Signed-off-by: Ashish Kumar Mishra Co-authored-by: Yashk767 <76935991+Yashk767@users.noreply.github.com> Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay Co-authored-by: YashK * updated CI for dockerhub token. (#1052) * updated version to * Revert import change --------- Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay --------- Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay --------- Signed-off-by: Ashish Kumar Mishra Co-authored-by: Shrikant upadhyay Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat * Added support for jobs returning hex values (#1058) * Removed method called for GetDataFromAPI() * Added returnType support in dataSource struct * Fixed tests * Fixed hex conversion * Added a post Job test * removed unrequired comment * Replaced alchemy RPC * Used free RPC for tests * Remove hardcoded gas limit (#1078) * Fetched gasLimit from config * Removed harcoded gasLimit value * Added a generic function for retry mechanism (#1071) * Added generic function to implement retry mechanism on top of a function * Used InvokeFunctionWithRetryAttempts() for retry mechanism * Moved GetStakerSRZRBalance() from stake.go to stakedToken.go * Fixed tests * Added alternate RPC support * Added alternateProvider as a config paramter * Added GetAlternateProvider() in GetConfig() * Fixed GetStringAlternateProvider() usage in setConfig() * Fixed tests * Used alternateProvider from config * Requested changes * Revert API changes and other API features from v1.0.6 (#1080) * revert Added support for jobs returning hex values * Revert "Fetched API key from env file (#1048)" This reverts commit 3bc7983cec34ba37a6b0ca92ac9c823b757cb378. * Revert Added support for Post Requests * revert Cached API Response * compilation fixes * Revert "revert Cached API Response" This reverts commit cc800a85794ec87e01466b433c5ecf3460b0afdc. * revert updated dockerfile and readme for non-root user (#1083) * Common local cache instance used for all collections (#1082) * Removed data struct * Created a common cache for all the collections * updated version to 1.0.6-alpha.2 (#1084) * updated version to v1.0.6-alpha-patch3 * updated version * Revert "Reduced wait for block completion to 1 second (#984)" (#1087) This reverts commit b804122099123ffcdf3ac674254d7ab4c0c3f54b. * Changed err to waitForBlockCompletionErr in error log (#1088) * updated version to 1.0.6-alpha.3 (#1089) * Updated readme with v1.0.6 changes (#1079) * Added v1.0.6 changes in readME * Added debug log for gas limit override * Updated selector for API test * Returned error if provider is not set in config (#1094) * Shifted SetLogLevel() * Returned error if provider is not set * Alternate provider fix (#1092) * Assigned alternateProvider a empty string value * fixed tests * Fixed typo * Added alternateProvider in config.sh (#1095) * updated version to 1.0.6-alpha.4 (#1096) * Updated deployed contract addresses and chaind to mainnet ones for 1.0.6-beta release (#1099) * v1.0.6-beta ready * updated contract addresses * Updated version to v1.0.6 (#1101) --------- Signed-off-by: Ashish Kumar Mishra Co-authored-by: Yashk767 <76935991+Yashk767@users.noreply.github.com> Co-authored-by: Shekhar Gaur <65169767+shekhar2807@users.noreply.github.com> Co-authored-by: Ashish Kumar Mishra Co-authored-by: Shyam Patel Co-authored-by: Raj Kharvar Co-authored-by: Skanda Bhat Co-authored-by: Shrikant upadhyay Co-authored-by: YashK --- README.md | 125 ++++-- block/block.go | 7 +- cache/cache.go | 93 +++++ client/alternateClient.go | 63 +++ cmd/addStake.go | 33 +- cmd/addStake_test.go | 77 ++-- cmd/approve.go | 13 +- cmd/approve_test.go | 21 +- cmd/claimBounty.go | 28 +- cmd/claimBounty_test.go | 67 ++- cmd/claimCommission.go | 14 +- cmd/claimCommission_test.go | 38 +- cmd/cmd-utils.go | 14 +- cmd/cmd-utils_test.go | 51 +-- cmd/collectionList.go | 11 +- cmd/collectionList_test.go | 15 +- cmd/commit.go | 47 ++- cmd/commit_test.go | 70 ++-- cmd/config-utils.go | 156 ++++++- cmd/config-utils_test.go | 290 ++++++++++--- cmd/confirm.go | 5 +- cmd/confirm_test.go | 12 +- cmd/contractAddresses.go | 18 +- cmd/contractAddresses_test.go | 11 +- cmd/create.go | 16 +- cmd/createCollection.go | 16 +- cmd/createCollection_test.go | 49 +-- cmd/createJob.go | 14 +- cmd/createJob_test.go | 49 +-- cmd/create_test.go | 32 +- cmd/delegate.go | 20 +- cmd/delegate_test.go | 44 +- cmd/dispute.go | 87 ++-- cmd/dispute_test.go | 177 +++----- cmd/import.go | 17 +- cmd/import_test.go | 36 +- cmd/initiateWithdraw.go | 37 +- cmd/initiateWithdraw_test.go | 153 +++---- cmd/interface.go | 104 +---- cmd/jobList_test.go | 14 +- cmd/listAccounts.go | 15 +- cmd/listAccounts_test.go | 22 +- cmd/mocks/flag_set_interface.go | 231 ++++++++++- cmd/mocks/stake_manager_interface.go | 21 +- cmd/mocks/utils_cmd_interface.go | 163 ++++++-- cmd/modifyCollectionStatus.go | 16 +- cmd/modifyCollectionStatus_test.go | 55 +-- cmd/propose.go | 36 +- cmd/propose_test.go | 164 ++------ cmd/resetUnstakeLock.go | 15 +- cmd/resetUnstakeLock_test.go | 37 +- cmd/reveal.go | 38 +- cmd/reveal_test.go | 102 ++--- cmd/root.go | 41 +- cmd/setConfig.go | 60 ++- cmd/setConfig_test.go | 264 ++++++------ cmd/setDelegation.go | 16 +- cmd/setDelegation_test.go | 10 +- cmd/stakerInfo_test.go | 9 +- cmd/struct-utils.go | 547 ++++++------------------- cmd/test_utils.go | 170 ++++++++ cmd/transfer.go | 18 +- cmd/transfer_test.go | 39 +- cmd/unlockWithdraw.go | 23 +- cmd/unlockWithdraw_test.go | 53 +-- cmd/unstake.go | 31 +- cmd/unstake_test.go | 69 +--- cmd/updateCollection.go | 23 +- cmd/updateCollection_test.go | 49 +-- cmd/updateCommission.go | 14 +- cmd/updateCommission_test.go | 30 +- cmd/updateJob.go | 16 +- cmd/updateJob_test.go | 50 +-- cmd/vote.go | 79 ++-- cmd/vote_test.go | 150 ++++--- config.sh | 23 +- core/constants.go | 36 +- core/types/configurations.go | 5 + core/version.go | 8 +- go.mod | 24 +- go.sum | 27 ++ logger/logger.go | 21 +- password.txt | 0 path/path.go | 25 +- path/path_test.go | 8 +- utils/api.go | 53 ++- utils/api_test.go | 11 +- utils/array.go | 20 +- utils/array_test.go | 26 +- utils/asset.go | 108 +++-- utils/asset_test.go | 53 ++- utils/block.go | 152 ++----- utils/client_methods.go | 112 +---- utils/client_methods_test.go | 39 +- utils/common.go | 115 ++++-- utils/common_test.go | 274 +++++++++---- utils/contract-manager.go | 4 +- utils/interface.go | 89 ++-- utils/math.go | 4 +- utils/math_test.go | 6 +- utils/merkle.go | 17 +- utils/merkle_test.go | 63 ++- utils/mocks/bufio_utils.go | 46 --- utils/mocks/client_utils.go | 134 ++++++ utils/mocks/coin_utils.go | 10 +- utils/mocks/file_utils.go | 140 +++++++ utils/mocks/gas_utils.go | 92 +++++ utils/mocks/merkle_tree_interface.go | 22 +- utils/mocks/staked_token_utils.go | 18 +- utils/mocks/utils.go | 584 ++++++++------------------- utils/options.go | 26 +- utils/options_test.go | 54 ++- utils/password.go | 13 +- utils/stake.go | 176 ++------ utils/stake_test.go | 70 +--- utils/stakedToken.go | 22 + utils/stakedToken_test.go | 74 ++++ utils/struct-utils.go | 70 +++- utils/vote.go | 170 ++------ utils/vote_test.go | 59 +-- 120 files changed, 4102 insertions(+), 3821 deletions(-) create mode 100644 cache/cache.go create mode 100644 client/alternateClient.go create mode 100644 cmd/test_utils.go create mode 100644 password.txt delete mode 100644 utils/mocks/bufio_utils.go create mode 100644 utils/mocks/file_utils.go create mode 100644 utils/mocks/gas_utils.go create mode 100644 utils/stakedToken.go create mode 100644 utils/stakedToken_test.go diff --git a/README.md b/README.md index 66faadd6..8d4fe270 100644 --- a/README.md +++ b/README.md @@ -93,33 +93,38 @@ Go to the `build/bin` directory where the razor binary is generated. There are a set of parameters that are configurable. These include: - Provider: The RPC URL of the provider you are using to connect to the blockchain. +- Alternate Provider: This is the secondary RPC URL of the provider used to connect to the blockchain if the primary one is not working. - Gas Multiplier: The value with which the gas price will be multiplied while sending every transaction. - Buffer Size: Buffer size determines, out of all blocks in a state, in how many blocks the voting or any other operation can be performed. - Wait Time: This is the number of seconds the system will wait while voting. - Gas Price: The value of gas price if you want to set manually. If you don't provide any value or simply keep it to 1, the razor client will automatically calculate the optimum gas price and send it. - Log Level: Normally debug logs are not logged into the log file. But if you want you can set `logLevel` to `debug` and fetch the debug logs. - Gas Limit: The value with which the gas limit will be multiplied while sending every transaction. -- Gas Limit Override: This value would be used as a gas limit for all the transactions instead of estimating for each transaction. +- Gas Limit Override: This value would be used as a gas limit for all the transactions instead of estimating for each transaction. - RPC Timeout: This is the threshold number of seconds after which any contract and client calls will time out. +- HTTP Timeout: This is the threshold number of seconds after which an HTTP request for a job will time out. +- Maximum size of log file: This is the maximum size of log file in MB +- Maximum number of backups of log file: This is the maximum number of old log files to retain. +- Maximum age of log file: This is the maximum number of days to retain old log files. The config is set while the build is generated, but if you need to change any of the above parameter, you can use the `setConfig` command. razor cli ``` -$ ./razor setConfig --provider --gasmultiplier --buffer --wait --gasprice --logLevel --gasLimit --rpcTimeout +$ ./razor setConfig --provider --gasmultiplier --buffer --wait --gasprice --logLevel --gasLimit --rpcTimeout --httpTimeout --logFileMaxSize --logFileMaxBackups --logFileMaxAge ``` docker ``` -docker exec -it razor-go razor setConfig --provider --gasmultiplier --buffer --wait --gasprice --logLevel --gasLimit --rpcTimeout +docker exec -it razor-go razor setConfig --provider --alternateProvider --gasmultiplier --buffer --wait --gasprice --logLevel --gasLimit --rpcTimeout --httpTimeout --logFileMaxSize --logFileMaxBackups --logFileMaxAge ``` Example: ``` -$ ./razor setConfig --provider https://mainnet.skalenodes.com/v1/turbulent-unique-scheat --gasmultiplier 1 --buffer 20 --wait 30 --gasprice 0 --logLevel debug --gasLimit 2 --rpcTimeout 10 +$ ./razor setConfig --provider https://mainnet.skalenodes.com/v1/turbulent-unique-scheat --alternateProvider https://ce2m-skale.chainode.tech:10200/ --gasmultiplier 1 --buffer 20 --wait 30 --gasprice 0 --logLevel debug --gasLimit 2 --rpcTimeout 10 --httpTimeout 10 --logFileMaxSize 200 --logFileMaxBackups 52 --logFileMaxAge 365 ``` Other than setting these parameters in the config, you can use different values of these parameters in different command. Just add the same flag to any command you want to use and the new config changes will appear for that command. @@ -352,12 +357,14 @@ docker docker exec -it razor-go razor vote --address
``` -run vote command in background +> **Note**: _To run vote command in background you can use `tmux` for that._ +> +> 1. Run: `tmux new -s razor-go` +> 2. Run vote command +> 3. To exit from tmux session: press `ctrl+b`, release those keys and press `d` +> 4. To list your session: `tmux ls` +> 5. To attach Session back: `tmux attach-session -t razor-go` -``` -docker exec -it -d razor-go razor vote --address
--password /root/.razor/ -``` ->**_NOTE:_** To run command with password flag with the help of docker, password file should present in $HOME/.razor/ directory Example: @@ -693,17 +700,13 @@ Note : _All the commands have an additional --password flag that you can provide Expose Prometheus-based metrics for monitoring -Example: - -razor cli - -Without TLS +#### Without TLS ``` $ ./razor setConfig --exposeMetrics 2112 ``` -With TLS +#### With TLS ``` $ ./razor setConfig --exposeMetrics 2112 --certFile /cert/file/path/certfile.crt --certKey key/file/path/keyfile.key @@ -711,15 +714,15 @@ $ ./razor setConfig --exposeMetrics 2112 --certFile /cert/file/path/certfile.crt docker -``` -# Create docker network - -docker network create razor_network +#### Expose Metrics without TLS -# Expose Metrics without TLS +``` docker exec -it razor-go razor setConfig --exposeMetrics 2112 +``` + +#### Expose Metrics with TLS -# Expose Metrics with TLS +``` docker exec -it razor-go razor setConfig --exposeMetrics 2112 --certFile /cert/file/path/certfile.crt --certKey key/file/path/keyfile.key ``` @@ -734,18 +737,70 @@ cd monitoring - If your staker is running via binary, then - 1. In `./configs/prometheus.yml`, replace `"razor-go:2112"` with `":2112"` + 1. In `./configs/prometheus.yml`, replace `"razor-go:2112"` with `":2112"` - For alerting you can add webhook in `./configs/alertmanager.yml`, replace `http://127.0.0.1:5001/` with your webhook URL. This will send you an alert in every 5min if metrics stops. - If you are running multiple stakers and want to monitor via single grafana dashboard - 1. You need to update `./config/prometheus.yml`, add new target block where `job_name: "razor-go"` - ``` - - targets: [":2112"] - labels: - staker: "" - ``` - 2. Restart vmagent service `docker-compose restart vmagent` + + 1. You need to update `./config/prometheus.yml`, add new target block where `job_name: "razor-go"` + ``` + - targets: [":2112"] + labels: + staker: "" + ``` + 2. Restart vmagent service `docker-compose restart vmagent` +#### Start monitoring stack +- You can spin all agents at once via + + ``` + docker-compose up -d + ``` + Can check the status of each service via + ``` + docker-compose ps + ``` + +- You can open grafana at `:3000`, and get + 1. Can checkout `Razor` dashboard to monitor your staker. + 2. Insight of host metrics at `Node Exporter Full` dashboard. + 3. Containers Insight at `Docker and OS metrics ( cadvisor, node_exporter )` dashboard. + 4. Can monitor alerts at `Alertmanager` dashboard. + +>**_NOTE:_** Configure firewall for port `3000` on your host to access grafana. + +#### Troubleshoot Alerting + +1. In `docker-compose.yml` uncomment ports for `alertmanager` and `vmalert`. +2. Configure firewall to allow access to ports `8880` and `9093`. + +3. Check you get alerts on vmalert via `http://:8880/vmalert/alerts`. vmalert is configured to scrap in every 2min. + +4. If you see alert in vmalert then look into alertmanager `http://:9093/#/alerts?`, if you see alerts in there but you didn't get one then probably you need to check your weebhook. + +#### Configuration + +Clone repo and setup monitoring and alerting using Prometheus/Grafana + +``` +git clone https://github.com/razor-network/monitoring.git +cd monitoring +``` + +- If your staker is running via binary, then + + 1. In `./configs/prometheus.yml`, replace `"razor-go:2112"` with `":2112"` + +- For alerting you can add webhook in `./configs/alertmanager.yml`, replace `http://127.0.0.1:5001/` with your webhook URL. This will send you an alert in every 5min if metrics stops. + +- If you are running multiple stakers and want to monitor via single grafana dashboard + 1. You need to update `./config/prometheus.yml`, add new target block where `job_name: "razor-go"` + ``` + - targets: [":2112"] + labels: + staker: "" + ``` + 2. Restart vmagent service `docker-compose restart vmagent` #### Start monitoring stack @@ -762,10 +817,10 @@ cd monitoring ``` - You can open grafana at `:3000`, and get - 1. Can checkout `Razor` dashboard to monitor your staker. - 2. Insight of host metrics at `Node Exporter Full` dashboard. - 3. Containers Insight at `Docker and OS metrics ( cadvisor, node_exporter )` dashboard. - 4. Can monitor alerts at `Alertmanager` dashboard. + 1. Can checkout `Razor` dashboard to monitor your staker. + 2. Insight of host metrics at `Node Exporter Full` dashboard. + 3. Containers Insight at `Docker and OS metrics ( cadvisor, node_exporter )` dashboard. + 4. Can monitor alerts at `Alertmanager` dashboard. > **_NOTE:_** Configure firewall for port `3000` on your host to access grafana. @@ -785,7 +840,7 @@ You can override the existing job and also add your custom jobs by adding `asset Shown below is an example of how your `assets.json` file should be - -``` +``` json { "assets": { "collection": { @@ -951,7 +1006,7 @@ $ ./razor contractAddresses 9. To Start **Voting**, - 1. Provide password through **CLI** + 1. Provide password through **CLI** ```bash # Run process in foreground and provide password through cli diff --git a/block/block.go b/block/block.go index 35598d22..bd12e70d 100644 --- a/block/block.go +++ b/block/block.go @@ -2,12 +2,13 @@ package block import ( "context" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/sirupsen/logrus" "razor/core" "sync" "time" + + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/sirupsen/logrus" ) var latestBlock *types.Header diff --git a/cache/cache.go b/cache/cache.go new file mode 100644 index 00000000..4f6683c4 --- /dev/null +++ b/cache/cache.go @@ -0,0 +1,93 @@ +package cache + +import ( + "errors" + "sync" + "time" +) + +var ( + errDataNotInCache = errors.New("data not present in cache") +) + +type cachedData struct { + Result []byte + expireAtTimestamp int64 +} + +type LocalCache struct { + stop chan struct{} + + wg sync.WaitGroup + mu sync.RWMutex + URLs map[string]cachedData //URLs +} + +func NewLocalCache(cleanupInterval time.Duration) *LocalCache { + lc := &LocalCache{ + URLs: make(map[string]cachedData), + stop: make(chan struct{}), + } + + lc.wg.Add(1) + go func(cleanupInterval time.Duration) { + defer lc.wg.Done() + lc.cleanupLoop(cleanupInterval) + }(cleanupInterval) + + return lc +} + +func (lc *LocalCache) cleanupLoop(interval time.Duration) { + t := time.NewTicker(interval) + defer t.Stop() + + for { + select { + case <-lc.stop: + return + case <-t.C: + lc.mu.Lock() + for url, cu := range lc.URLs { + if cu.expireAtTimestamp <= time.Now().Unix() { + delete(lc.URLs, url) + } + } + lc.mu.Unlock() + } + } +} + +func (lc *LocalCache) StopCleanup() { + close(lc.stop) + lc.wg.Wait() +} + +func (lc *LocalCache) Update(data []byte, url string, expireAtTimestamp int64) { + lc.mu.Lock() + defer lc.mu.Unlock() + + lc.URLs[url] = cachedData{ + Result: data, + expireAtTimestamp: expireAtTimestamp, + } +} + +func (lc *LocalCache) Read(url string) ([]byte, error) { + lc.mu.RLock() + defer lc.mu.RUnlock() + + cacheData, ok := lc.URLs[url] + if !ok { + return []byte{}, errDataNotInCache + } + + return cacheData.Result, nil +} + +func (lc *LocalCache) Delete(url string) { + lc.mu.Lock() + defer lc.mu.Unlock() + + delete(lc.URLs, url) +} diff --git a/client/alternateClient.go b/client/alternateClient.go new file mode 100644 index 00000000..7d2394ff --- /dev/null +++ b/client/alternateClient.go @@ -0,0 +1,63 @@ +package client + +import ( + "github.com/ethereum/go-ethereum/ethclient" + "razor/logger" + "reflect" + "time" +) + +var ( + log = logger.NewLogger() + alternateClientStruct AlternateClientStruct +) + +type AlternateClientStruct struct { + switchToAlternateClient bool + alternateProvider string +} + +func StartTimerForAlternateClient(switchClientAfterTime uint64) { + log.Infof("StartTimerForAlternateClient: Alternate client will be switched back to primary client in %v seconds!", switchClientAfterTime) + time.Sleep(time.Duration(switchClientAfterTime) * time.Second) + log.Info("Switching back to primary RPC..") + SetSwitchToAlternateClientStatus(false) +} + +//ReplaceClientWithAlternateClient will replace the primary client(client from primary RPC) with secondary client which would be created using alternate RPC +func ReplaceClientWithAlternateClient(arguments []reflect.Value) []reflect.Value { + clientDataType := reflect.TypeOf((*ethclient.Client)(nil)).Elem() + for i := range arguments { + argument := arguments[i] + argumentDataType := reflect.TypeOf(argument.Interface()).Elem() + if argumentDataType != nil { + if argumentDataType == clientDataType { + alternateProvider := GetAlternateProvider() + alternateClient, dialErr := ethclient.Dial(alternateProvider) + if dialErr != nil { + log.Errorf("Error in connecting using alternate RPC %v: %v", alternateProvider, dialErr) + return arguments + } + arguments[i] = reflect.ValueOf(alternateClient) + return arguments + } + } + } + return arguments +} + +func GetSwitchToAlternateClientStatus() bool { + return alternateClientStruct.switchToAlternateClient +} + +func SetSwitchToAlternateClientStatus(status bool) { + alternateClientStruct.switchToAlternateClient = status +} + +func GetAlternateProvider() string { + return alternateClientStruct.alternateProvider +} + +func SetAlternateProvider(alternateProvider string) { + alternateClientStruct.alternateProvider = alternateProvider +} diff --git a/cmd/addStake.go b/cmd/addStake.go index 4b02e5d3..9ae55fcd 100644 --- a/cmd/addStake.go +++ b/cmd/addStake.go @@ -44,11 +44,14 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { logger.SetLoggerParameters(client, address) log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + balance, err := razorUtils.FetchBalance(client, address) utils.CheckError("Error in fetching razor balance for account: "+address, err) log.Debug("Getting amount in wei...") @@ -62,7 +65,7 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { log.Debug("Checking whether sFuel balance is not 0...") razorUtils.CheckEthBalanceIsZero(client, address) - minSafeRazor, err := utils.UtilsInterface.GetMinSafeRazor(client) + minSafeRazor, err := razorUtils.GetMinSafeRazor(client) utils.CheckError("Error in getting minimum safe razor amount: ", err) log.Debug("ExecuteStake: Minimum razor that you can stake for first time: ", minSafeRazor) @@ -74,6 +77,15 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { log.Fatal("The amount of razors entered is below min safe value.") } + if stakerId != 0 { + staker, err := razorUtils.GetStaker(client, stakerId) + utils.CheckError("Error in getting staker: ", err) + + if staker.IsSlashed { + log.Fatal("Staker is slashed, cannot stake") + } + } + txnArgs := types.TransactionOptions{ Client: client, AccountAddress: address, @@ -88,7 +100,7 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { utils.CheckError("Approve error: ", err) if approveTxnHash != core.NilHash { - err = razorUtils.WaitForBlockCompletion(txnArgs.Client, approveTxnHash.String()) + err = razorUtils.WaitForBlockCompletion(txnArgs.Client, approveTxnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for approve: ", err) } @@ -96,7 +108,7 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { stakeTxnHash, err := cmdUtils.StakeCoins(txnArgs) utils.CheckError("Stake error: ", err) - err = razorUtils.WaitForBlockCompletion(txnArgs.Client, stakeTxnHash.String()) + err = razorUtils.WaitForBlockCompletion(txnArgs.Client, stakeTxnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for stake: ", err) } @@ -104,22 +116,23 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { func (*UtilsStruct) StakeCoins(txnArgs types.TransactionOptions) (common.Hash, error) { epoch, err := razorUtils.GetEpoch(txnArgs.Client) if err != nil { - return common.Hash{0x00}, err + return core.NilHash, err } log.Debug("StakeCoins: Epoch: ", epoch) txnArgs.ContractAddress = core.StakeManagerAddress txnArgs.MethodName = "stake" txnArgs.Parameters = []interface{}{epoch, txnArgs.Amount} - txnArgs.ABI = bindings.StakeManagerABI + txnArgs.ABI = bindings.StakeManagerMetaData.ABI txnOpts := razorUtils.GetTxnOpts(txnArgs) log.Debugf("Executing Stake transaction with epoch = %d, amount = %d", epoch, txnArgs.Amount) - tx, err := stakeManagerUtils.Stake(txnArgs.Client, txnOpts, epoch, txnArgs.Amount) + txn, err := stakeManagerUtils.Stake(txnArgs.Client, txnOpts, epoch, txnArgs.Amount) if err != nil { - return common.Hash{0x00}, err + return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(tx).Hex()) - return transactionUtils.Hash(tx), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/addStake_test.go b/cmd/addStake_test.go index f2cd062f..ee89f30c 100644 --- a/cmd/addStake_test.go +++ b/cmd/addStake_test.go @@ -5,19 +5,18 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core" + "razor/core/types" + "razor/pkg/bindings" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core" - "razor/core/types" - "razor/utils" - mocks2 "razor/utils/mocks" - "testing" ) func TestStakeCoins(t *testing.T) { @@ -95,19 +94,11 @@ func TestStakeCoins(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock - + SetUpMockInterfaces() utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.getEpochErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) - stakeManagerUtilsMock.On("Stake", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakeTxn, tt.args.stakeErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) + stakeManagerMock.On("Stake", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakeTxn, tt.args.stakeErr) utils := &UtilsStruct{} @@ -149,6 +140,8 @@ func TestExecuteStake(t *testing.T) { minSafeRazorErr error stakerId uint32 stakerIdErr error + staker bindings.StructsStaker + stakerErr error stakeTxn common.Hash stakeErr error } @@ -167,6 +160,7 @@ func TestExecuteStake(t *testing.T) { balance: big.NewInt(10000), minSafeRazor: big.NewInt(0), stakerId: 1, + staker: bindings.StructsStaker{IsSlashed: false}, approveTxn: common.BigToHash(big.NewInt(1)), stakeTxn: common.BigToHash(big.NewInt(2)), }, @@ -294,6 +288,35 @@ func TestExecuteStake(t *testing.T) { }, expectedFatal: false, }, + { + name: "Test 10: When the staker is slashed before", + args: args{ + config: config, + password: "test", + address: "0x000000000000000000000000000000000000dead", + amount: big.NewInt(20), + balance: big.NewInt(10000), + minSafeRazor: big.NewInt(100), + stakerId: 1, + staker: bindings.StructsStaker{IsSlashed: true}, + }, + expectedFatal: true, + }, + { + name: "Test 9: When stake value is less than minSafeRazor and staker's stake is more than the minSafeRazor already", + args: args{ + config: config, + password: "test", + address: "0x000000000000000000000000000000000000dead", + amount: big.NewInt(20), + balance: big.NewInt(10000), + minSafeRazor: big.NewInt(100), + stakerId: 1, + approveTxn: common.BigToHash(big.NewInt(1)), + stakeTxn: common.BigToHash(big.NewInt(2)), + }, + expectedFatal: false, + }, } defer func() { log.ExitFunc = nil }() @@ -302,28 +325,22 @@ func TestExecuteStake(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(mocks2.Utils) - - razorUtils = utilsMock - flagSetUtils = flagSetUtilsMock - cmdUtils = cmdUtilsMock - utils.UtilsInterface = utilsPkgMock + SetUpMockInterfaces() - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.password) - flagSetUtilsMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) utilsMock.On("FetchBalance", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.balance, tt.args.balanceErr) cmdUtilsMock.On("AssignAmountInWei", flagSet).Return(tt.args.amount, tt.args.amountErr) utilsMock.On("CheckAmountAndBalance", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("*big.Int")).Return(tt.args.amount) utilsMock.On("CheckEthBalanceIsZero", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return() - utilsPkgMock.On("GetMinSafeRazor", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minSafeRazor, tt.args.minSafeRazorErr) + utilsMock.On("GetMinSafeRazor", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minSafeRazor, tt.args.minSafeRazorErr) utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStaker", mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) cmdUtilsMock.On("Approve", mock.Anything).Return(tt.args.approveTxn, tt.args.approveErr) cmdUtilsMock.On("StakeCoins", mock.Anything).Return(tt.args.stakeTxn, tt.args.stakeErr) diff --git a/cmd/approve.go b/cmd/approve.go index 2f35ae63..1a8cf1b8 100644 --- a/cmd/approve.go +++ b/cmd/approve.go @@ -13,25 +13,26 @@ func (*UtilsStruct) Approve(txnArgs types.TransactionOptions) (common.Hash, erro opts := razorUtils.GetOptions() allowance, err := tokenManagerUtils.Allowance(txnArgs.Client, &opts, common.HexToAddress(txnArgs.AccountAddress), common.HexToAddress(core.StakeManagerAddress)) if err != nil { - return common.Hash{0x00}, err + return core.NilHash, err } log.Debugf("Approve: Allowance amount: %d, Amount to get approved: %d", allowance, txnArgs.Amount) if allowance.Cmp(txnArgs.Amount) >= 0 { log.Debug("Sufficient allowance, no need to increase") - return common.Hash{0x00}, nil + return core.NilHash, nil } else { log.Info("Sending Approve transaction...") txnArgs.ContractAddress = core.RAZORAddress txnArgs.MethodName = "approve" - txnArgs.ABI = bindings.RAZORABI + txnArgs.ABI = bindings.RAZORMetaData.ABI txnArgs.Parameters = []interface{}{common.HexToAddress(core.StakeManagerAddress), txnArgs.Amount} txnOpts := razorUtils.GetTxnOpts(txnArgs) log.Debug("Executing Approve transaction with amount: ", txnArgs.Amount) txn, err := tokenManagerUtils.Approve(txnArgs.Client, txnOpts, common.HexToAddress(core.StakeManagerAddress), txnArgs.Amount) if err != nil { - return common.Hash{0x00}, err + return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } } diff --git a/cmd/approve_test.go b/cmd/approve_test.go index b249b510..860dfac2 100644 --- a/cmd/approve_test.go +++ b/cmd/approve_test.go @@ -11,7 +11,7 @@ import ( Types "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/mock" "math/big" - "razor/cmd/mocks" + "razor/core" "razor/core/types" "testing" ) @@ -79,7 +79,7 @@ func TestApprove(t *testing.T) { approveError: nil, hash: common.BigToHash(big.NewInt(1)), }, - want: common.Hash{0x00}, + want: core.NilHash, wantErr: nil, }, { @@ -101,7 +101,7 @@ func TestApprove(t *testing.T) { approveError: nil, hash: common.BigToHash(big.NewInt(1)), }, - want: common.Hash{0x00}, + want: core.NilHash, wantErr: errors.New("allowance error"), }, @@ -130,20 +130,13 @@ func TestApprove(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - tokenManagerUtilsMock := new(mocks.TokenManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - tokenManagerUtils = tokenManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetOptions").Return(tt.args.callOpts) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) - tokenManagerUtilsMock.On("Allowance", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.allowanceAmount, tt.args.allowanceError) - tokenManagerUtilsMock.On("Approve", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.approveTxn, tt.args.approveError) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) + tokenManagerMock.On("Allowance", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.allowanceAmount, tt.args.allowanceError) + tokenManagerMock.On("Approve", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.approveTxn, tt.args.approveError) utils := &UtilsStruct{} diff --git a/cmd/claimBounty.go b/cmd/claimBounty.go index a4b46efb..e4513cd6 100644 --- a/cmd/claimBounty.go +++ b/cmd/claimBounty.go @@ -46,13 +46,17 @@ func (*UtilsStruct) ExecuteClaimBounty(flagSet *pflag.FlagSet) { log.Debug("ExecuteClaimBounty: Address: ", address) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) - if utilsInterface.IsFlagPassed("bountyId") { + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + + if razorUtils.IsFlagPassed("bountyId") { bountyId, err := flagSetUtils.GetUint32BountyId(flagSet) utils.CheckError("Error in getting bountyId: ", err) log.Debug("ExecuteClaimBounty: BountyId: ", bountyId) @@ -68,7 +72,7 @@ func (*UtilsStruct) ExecuteClaimBounty(flagSet *pflag.FlagSet) { utils.CheckError("ClaimBounty error: ", err) if txn != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for claimBounty: ", err) } } else { @@ -84,14 +88,14 @@ func (*UtilsStruct) ExecuteClaimBounty(flagSet *pflag.FlagSet) { //This function handles claimBounty by picking bountyid's from disputeData file and if there is any error it returns the error func (*UtilsStruct) HandleClaimBounty(client *ethclient.Client, config types.Configurations, account types.Account) error { - disputeFilePath, err := razorUtils.GetDisputeDataFileName(account.Address) + disputeFilePath, err := pathUtils.GetDisputeDataFileName(account.Address) if err != nil { return err } log.Debug("HandleClaimBounty: Dispute data file path: ", disputeFilePath) if _, err := path.OSUtilsInterface.Stat(disputeFilePath); !errors.Is(err, os.ErrNotExist) { log.Debug("Fetching the dispute data from dispute data file...") - disputeData, err = razorUtils.ReadFromDisputeJsonFile(disputeFilePath) + disputeData, err = fileUtils.ReadFromDisputeJsonFile(disputeFilePath) if err != nil { return err } @@ -119,7 +123,7 @@ func (*UtilsStruct) HandleClaimBounty(client *ethclient.Client, config types.Con return err } if claimBountyTxn != core.NilHash { - claimBountyErr := utilsInterface.WaitForBlockCompletion(client, claimBountyTxn.String()) + claimBountyErr := razorUtils.WaitForBlockCompletion(client, claimBountyTxn.Hex()) if claimBountyErr == nil { if len(disputeData.BountyIdQueue) > 1 { //Removing the bountyId from the queue as the bounty is being claimed @@ -132,7 +136,7 @@ func (*UtilsStruct) HandleClaimBounty(client *ethclient.Client, config types.Con } log.Debug("Saving the updated dispute data to dispute data file...") - err = razorUtils.SaveDataToDisputeJsonFile(disputeFilePath, disputeData.BountyIdQueue) + err = fileUtils.SaveDataToDisputeJsonFile(disputeFilePath, disputeData.BountyIdQueue) if err != nil { return err } @@ -148,14 +152,14 @@ func (*UtilsStruct) ClaimBounty(config types.Configurations, client *ethclient.C ChainId: core.ChainId, Config: config, ContractAddress: core.StakeManagerAddress, - ABI: bindings.StakeManagerABI, + ABI: bindings.StakeManagerMetaData.ABI, MethodName: "redeemBounty", Parameters: []interface{}{redeemBountyInput.BountyId}, } epoch, err := razorUtils.GetEpoch(txnArgs.Client) if err != nil { log.Error("Error in getting epoch: ", err) - return common.Hash{0x00}, err + return core.NilHash, err } log.Debug("ClaimBounty: Epoch: ", epoch) @@ -178,7 +182,7 @@ func (*UtilsStruct) ClaimBounty(config types.Configurations, client *ethclient.C if waitFor > 0 { log.Debug("Waiting for lock period to get over....") - timeRemaining := int64(waitFor) * core.EpochLength + timeRemaining := uint64(waitFor) * core.EpochLength if waitFor == 1 { log.Infof("Cannot claim bounty now. Please wait for %d epoch! (approximately %s)", waitFor, razorUtils.SecondsToReadableTime(int(timeRemaining))) } else { @@ -194,7 +198,9 @@ func (*UtilsStruct) ClaimBounty(config types.Configurations, client *ethclient.C if err != nil { return core.NilHash, err } - return transactionUtils.Hash(tx), nil + txnHash := transactionUtils.Hash(tx) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/claimBounty_test.go b/cmd/claimBounty_test.go index 05f23f8f..4d2520e7 100644 --- a/cmd/claimBounty_test.go +++ b/cmd/claimBounty_test.go @@ -5,22 +5,20 @@ import ( "crypto/elliptic" "crypto/rand" "errors" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/spf13/pflag" - "github.com/stretchr/testify/mock" "io/fs" "math/big" "razor/cmd/mocks" "razor/core" "razor/core/types" - "razor/path" - pathMocks "razor/path/mocks" - "razor/utils" - mocks2 "razor/utils/mocks" + utilsPkgMocks "razor/utils/mocks" "testing" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + Types "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/spf13/pflag" + "github.com/stretchr/testify/mock" ) func TestExecuteClaimBounty(t *testing.T) { @@ -123,24 +121,16 @@ func TestExecuteClaimBounty(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(mocks2.Utils) - - razorUtils = utilsMock - flagSetUtils = flagSetUtilsMock - cmdUtils = cmdUtilsMock - utilsInterface = utilsPkgMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.password) - flagSetUtilsMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) - flagSetUtilsMock.On("GetUint32BountyId", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.bountyId, tt.args.bountyIdErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetUint32BountyId", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.bountyId, tt.args.bountyIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsPkgMock.On("IsFlagPassed", mock.Anything).Return(tt.args.isFlagPassed) + utilsMock.On("IsFlagPassed", mock.Anything).Return(tt.args.isFlagPassed) cmdUtilsMock.On("HandleClaimBounty", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.handleClaimBountyErr) cmdUtilsMock.On("ClaimBounty", mock.Anything, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.claimBountyTxn, tt.args.claimBountyErr) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) @@ -269,13 +259,13 @@ func TestClaimBounty(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { stakeManagerMock := new(mocks.StakeManagerInterface) - utilsMock := new(mocks.UtilsInterface) - trasactionUtilsMock := new(mocks.TransactionInterface) + utilsMock := new(utilsPkgMocks.Utils) + transactionUtilsMock := new(mocks.TransactionInterface) timeMock := new(mocks.TimeInterface) razorUtils = utilsMock stakeManagerUtils = stakeManagerMock - transactionUtils = trasactionUtilsMock + transactionUtils = transactionUtilsMock timeUtils = timeMock utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) @@ -286,7 +276,7 @@ func TestClaimBounty(t *testing.T) { utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) stakeManagerMock.On("RedeemBounty", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32")).Return(tt.args.redeemBountyTxn, tt.args.redeemBountyErr) utilsMock.On("SecondsToReadableTime", mock.AnythingOfType("int")).Return(tt.args.time) - trasactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} got, err := utils.ClaimBounty(config, client, bountyInput) @@ -390,23 +380,14 @@ func TestHandleClaimBounty(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(mocks2.Utils) - osUtilsMock := new(pathMocks.OSInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - utils.UtilsInterface = utilsPkgMock - utilsInterface = utilsPkgMock - path.OSUtilsInterface = osUtilsMock + SetUpMockInterfaces() - utilsMock.On("GetDisputeDataFileName", mock.AnythingOfType("string")).Return(tt.args.disputeFilePath, tt.args.disputeFilePathErr) - osUtilsMock.On("Stat", mock.Anything).Return(fileInfo, tt.args.statErr) - utilsMock.On("ReadFromDisputeJsonFile", mock.Anything).Return(tt.args.disputeData, tt.args.disputeDataErr) + pathMock.On("GetDisputeDataFileName", mock.AnythingOfType("string")).Return(tt.args.disputeFilePath, tt.args.disputeFilePathErr) + osPathMock.On("Stat", mock.Anything).Return(fileInfo, tt.args.statErr) + fileUtilsMock.On("ReadFromDisputeJsonFile", mock.Anything).Return(tt.args.disputeData, tt.args.disputeDataErr) cmdUtilsMock.On("ClaimBounty", mock.Anything, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.claimBountyTxn, tt.args.claimBountyTxnErr) - utilsPkgMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) - utilsMock.On("SaveDataToDisputeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) + utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + fileUtilsMock.On("SaveDataToDisputeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) ut := &UtilsStruct{} if err := ut.HandleClaimBounty(client, config, account); (err != nil) != tt.wantErr { diff --git a/cmd/claimCommission.go b/cmd/claimCommission.go index 155d4aee..e79b71db 100644 --- a/cmd/claimCommission.go +++ b/cmd/claimCommission.go @@ -38,13 +38,15 @@ func (*UtilsStruct) ClaimCommission(flagSet *pflag.FlagSet) { log.Debug("ClaimCommission: Address: ", address) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) - razorUtils.CheckEthBalanceIsZero(client, address) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) stakerId, err := razorUtils.GetStakerId(client, address) utils.CheckError("Error in getting stakerId: ", err) @@ -65,16 +67,18 @@ func (*UtilsStruct) ClaimCommission(flagSet *pflag.FlagSet) { ContractAddress: core.StakeManagerAddress, MethodName: "claimStakerReward", Parameters: []interface{}{}, - ABI: bindings.StakeManagerABI, + ABI: bindings.StakeManagerMetaData.ABI, }) log.Info("Claiming commission...") log.Debug("Executing ClaimStakeReward transaction...") - txn, err := stakeManagerUtils.ClaimStakeReward(client, txnOpts) + txn, err := stakeManagerUtils.ClaimStakerReward(client, txnOpts) utils.CheckError("Error in claiming stake reward: ", err) - err = razorUtils.WaitForBlockCompletion(client, transactionUtils.Hash(txn).String()) + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for claimCommission: ", err) } else { log.Error("no commission to claim") diff --git a/cmd/claimCommission_test.go b/cmd/claimCommission_test.go index 1db00526..59b1f8bd 100644 --- a/cmd/claimCommission_test.go +++ b/cmd/claimCommission_test.go @@ -5,19 +5,19 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core/types" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core/types" - "testing" ) -func TestUtilsStruct_ClaimCommission(t *testing.T) { +func TestClaimCommission(t *testing.T) { var client *ethclient.Client var flagSet *pflag.FlagSet var callOpts bind.CallOpts @@ -46,7 +46,7 @@ func TestUtilsStruct_ClaimCommission(t *testing.T) { expectedFatal bool }{ { - name: "Test 1: When ClaimStakeReward runs successfully", + name: "Test 1: When ClaimStakerReward runs successfully", args: args{ config: types.Configurations{}, stakerId: 1, @@ -200,36 +200,24 @@ func TestUtilsStruct_ClaimCommission(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - + SetUpMockInterfaces() fatal = false - utilsMock := new(mocks.UtilsInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - flagSetUtils = flagSetUtilsMock - cmdUtils = cmdUtilsMock - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) utilsMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("GetOptions").Return(callOpts) utilsMock.On("AssignPassword", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.password) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsMock.On("CheckEthBalanceIsZero", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return() utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(nil) - stakeManagerUtilsMock.On("StakerInfo", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.CallOpts"), mock.AnythingOfType("uint32")).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) - stakeManagerUtilsMock.On("ClaimStakeReward", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.txn, tt.args.err) + stakeManagerMock.On("StakerInfo", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.CallOpts"), mock.AnythingOfType("uint32")).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) + stakeManagerMock.On("ClaimStakerReward", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.txn, tt.args.err) - flagSetUtilsMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} utils.ClaimCommission(flagSet) diff --git a/cmd/cmd-utils.go b/cmd/cmd-utils.go index 6c105446..30a84e1c 100644 --- a/cmd/cmd-utils.go +++ b/cmd/cmd-utils.go @@ -23,18 +23,18 @@ func (*UtilsStruct) GetEpochAndState(client *ethclient.Client) (uint32, int64, e if err != nil { return 0, 0, err } - state, err := razorUtils.GetDelayedState(client, bufferPercent) + state, err := razorUtils.GetBufferedState(client, bufferPercent) if err != nil { return 0, 0, err } log.Debug("Epoch ", epoch) - log.Debug("State ", utils.UtilsInterface.GetStateName(state)) + log.Debug("State ", utils.GetStateName(state)) return epoch, state, nil } //This function waits for the appropriate states which are required func (*UtilsStruct) WaitForAppropriateState(client *ethclient.Client, action string, states ...int) (uint32, error) { - statesAllowed := GetStatesAllowed(states) + statesAllowed := GetFormattedStateNames(states) for { epoch, state, err := cmdUtils.GetEpochAndState(client) if err != nil { @@ -92,19 +92,19 @@ func (*UtilsStruct) AssignAmountInWei(flagSet *pflag.FlagSet) (*big.Int, error) amountInWei = _amount } } else { - amountInWei = razorUtils.GetAmountInWei(_amount) + amountInWei = utils.GetAmountInWei(_amount) } return amountInWei, nil } //This function returns the states which are allowed -func GetStatesAllowed(states []int) string { +func GetFormattedStateNames(states []int) string { var statesAllowed string for i := 0; i < len(states); i++ { if i == len(states)-1 { - statesAllowed = statesAllowed + strconv.Itoa(states[i]) + ":" + utils.UtilsInterface.GetStateName(int64(states[i])) + statesAllowed = statesAllowed + strconv.Itoa(states[i]) + ":" + utils.GetStateName(int64(states[i])) } else { - statesAllowed = statesAllowed + strconv.Itoa(states[i]) + ":" + utils.UtilsInterface.GetStateName(int64(states[i])) + ", " + statesAllowed = statesAllowed + strconv.Itoa(states[i]) + ":" + utils.GetStateName(int64(states[i])) + ", " } } return statesAllowed diff --git a/cmd/cmd-utils_test.go b/cmd/cmd-utils_test.go index 8ed96f65..63f54361 100644 --- a/cmd/cmd-utils_test.go +++ b/cmd/cmd-utils_test.go @@ -6,9 +6,6 @@ import ( "github.com/spf13/pflag" "github.com/stretchr/testify/mock" "math/big" - "razor/cmd/mocks" - "razor/utils" - mocks2 "razor/utils/mocks" "testing" ) @@ -81,19 +78,11 @@ func TestGetEpochAndState(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(mocks2.Utils) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - utils.UtilsInterface = utilsPkgMock + SetUpMockInterfaces() utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) cmdUtilsMock.On("GetBufferPercent").Return(tt.args.bufferPercent, tt.args.bufferPercentErr) - utilsMock.On("GetDelayedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) - utilsPkgMock.On("GetStateName", mock.AnythingOfType("int64")).Return(tt.args.stateName) + utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) utils := &UtilsStruct{} gotEpoch, gotState, err := utils.GetEpochAndState(client) @@ -178,12 +167,7 @@ func TestWaitForAppropriateState(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - timeMock := new(mocks.TimeInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - timeUtils = timeMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() cmdUtilsMock.On("GetEpochAndState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.epoch, tt.args.state, tt.args.epochOrStateErr) timeMock.On("Sleep", mock.Anything).Return() @@ -240,12 +224,7 @@ func TestWaitIfCommitState(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - cmdUtilsMock := new(mocks.UtilsCmdInterface) - timeMock := new(mocks.TimeInterface) - - cmdUtils = cmdUtilsMock - timeUtils = timeMock + SetUpMockInterfaces() cmdUtilsMock.On("GetEpochAndState", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.state, tt.args.epochOrStateErr) timeMock.On("Sleep", mock.Anything).Return() @@ -344,14 +323,10 @@ func TestAssignAmountInWei1(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - flagsetUtilsMock := new(mocks.FlagSetInterface) + SetUpMockInterfaces() - razorUtils = utilsMock - flagSetUtils = flagsetUtilsMock - - flagsetUtilsMock.On("GetStringValue", flagSet).Return(tt.args.amount, tt.args.amountErr) - flagsetUtilsMock.On("GetBoolWeiRazor", flagSet).Return(tt.args.weiRazor, tt.args.weiRazorErr) + flagSetMock.On("GetStringValue", flagSet).Return(tt.args.amount, tt.args.amountErr) + flagSetMock.On("GetBoolWeiRazor", flagSet).Return(tt.args.weiRazor, tt.args.weiRazorErr) utilsMock.On("IsFlagPassed", mock.AnythingOfType("string")).Return(tt.args.isFlagPassed) utilsMock.On("GetAmountInWei", mock.AnythingOfType("*big.Int")).Return(tt.args.amountInWei) @@ -373,7 +348,7 @@ func TestAssignAmountInWei1(t *testing.T) { } } -func TestGetStatesAllowed(t *testing.T) { +func TestGetFormattedStateNames(t *testing.T) { type args struct { states []int stateName string @@ -409,13 +384,11 @@ func TestGetStatesAllowed(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsPkgMock := new(mocks2.Utils) - - utils.UtilsInterface = utilsPkgMock + SetUpMockInterfaces() - utilsPkgMock.On("GetStateName", mock.AnythingOfType("int64")).Return(tt.args.stateName) - if got := GetStatesAllowed(tt.args.states); got != tt.want { - t.Errorf("GetStatesAllowed() = %v, want %v", got, tt.want) + utilsMock.On("GetStateName", mock.AnythingOfType("int64")).Return(tt.args.stateName) + if got := GetFormattedStateNames(tt.args.states); got != tt.want { + t.Errorf("GetFormattedStateNames() = %v, want %v", got, tt.want) } }) } diff --git a/cmd/collectionList.go b/cmd/collectionList.go index 239dc9a2..2918d779 100644 --- a/cmd/collectionList.go +++ b/cmd/collectionList.go @@ -3,15 +3,16 @@ package cmd import ( "encoding/json" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/olekukonko/tablewriter" - "github.com/spf13/cobra" - "github.com/spf13/pflag" "os" "razor/logger" "razor/utils" "strconv" "strings" + + "github.com/ethereum/go-ethereum/ethclient" + "github.com/olekukonko/tablewriter" + "github.com/spf13/cobra" + "github.com/spf13/pflag" ) // collectionListCmd represents the collectionList command @@ -45,7 +46,7 @@ func (*UtilsStruct) ExecuteCollectionList(flagSet *pflag.FlagSet) { //This function provides the list of all collections with their name, power, ID etc. func (*UtilsStruct) GetCollectionList(client *ethclient.Client) error { - collections, err := razorUtils.GetCollections(client) + collections, err := razorUtils.GetAllCollections(client) log.Debugf("GetCollectionList: Collections: %+v", collections) if err != nil { diff --git a/cmd/collectionList_test.go b/cmd/collectionList_test.go index 665070ed..bd9f8747 100644 --- a/cmd/collectionList_test.go +++ b/cmd/collectionList_test.go @@ -5,7 +5,6 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "razor/cmd/mocks" "razor/core/types" "razor/pkg/bindings" "testing" @@ -71,10 +70,9 @@ func TestGetCollectionList(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - razorUtils = utilsMock + SetUpMockInterfaces() - utilsMock.On("GetCollections", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.collectionList, tt.args.collectionListErr) + utilsMock.On("GetAllCollections", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.collectionList, tt.args.collectionListErr) utils := &UtilsStruct{} err := utils.GetCollectionList(tt.args.client) @@ -141,14 +139,9 @@ func TestExecuteCollectionList(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("GetCollectionList", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.collectionListErr) diff --git a/cmd/commit.go b/cmd/commit.go index b190a118..6e0252bb 100644 --- a/cmd/commit.go +++ b/cmd/commit.go @@ -4,14 +4,17 @@ package cmd import ( "encoding/hex" "errors" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" - solsha3 "github.com/miguelmota/go-solidity-sha3" "math/big" + "razor/cache" "razor/core" "razor/core/types" "razor/pkg/bindings" "razor/utils" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient" + solsha3 "github.com/miguelmota/go-solidity-sha3" ) /* @@ -21,31 +24,31 @@ If the previous epoch doesn't contain any medians, then the value is fetched fro func (*UtilsStruct) GetSalt(client *ethclient.Client, epoch uint32) ([32]byte, error) { previousEpoch := epoch - 1 log.Debug("GetSalt: Previous epoch: ", previousEpoch) - numProposedBlock, err := utils.UtilsInterface.GetNumberOfProposedBlocks(client, previousEpoch) + numProposedBlock, err := razorUtils.GetNumberOfProposedBlocks(client, previousEpoch) if err != nil { return [32]byte{}, err } log.Debug("GetSalt: Number of proposed blocks: ", numProposedBlock) - blockIndexedToBeConfirmed, err := utils.UtilsInterface.GetBlockIndexToBeConfirmed(client) + blockIndexToBeConfirmed, err := razorUtils.GetBlockIndexToBeConfirmed(client) if err != nil { return [32]byte{}, err } - log.Debug("GetSalt: Block Index to be confirmed: ", blockIndexedToBeConfirmed) - if numProposedBlock == 0 || (numProposedBlock > 0 && blockIndexedToBeConfirmed < 0) { + log.Debug("GetSalt: Block Index to be confirmed: ", blockIndexToBeConfirmed) + if numProposedBlock == 0 || (numProposedBlock > 0 && blockIndexToBeConfirmed < 0) { return utils.VoteManagerInterface.GetSaltFromBlockchain(client) } - blockId, err := utils.UtilsInterface.GetSortedProposedBlockId(client, previousEpoch, big.NewInt(int64(blockIndexedToBeConfirmed))) + blockId, err := razorUtils.GetSortedProposedBlockId(client, previousEpoch, big.NewInt(int64(blockIndexToBeConfirmed))) if err != nil { return [32]byte{}, errors.New("Error in getting blockId: " + err.Error()) } log.Debug("GetSalt: Block Id: ", blockId) - previousBlock, err := utils.UtilsInterface.GetProposedBlock(client, previousEpoch, blockId) + previousBlock, err := razorUtils.GetProposedBlock(client, previousEpoch, blockId) if err != nil { return [32]byte{}, errors.New("Error in getting previous block: " + err.Error()) } log.Debug("GetSalt: PreviousBlock: ", previousBlock) log.Debugf("GetSalt: Calling CalculateSalt() with arguments previous epoch = %d, previous block medians = %s", previousEpoch, previousBlock.Medians) - return utils.UtilsInterface.CalculateSalt(previousEpoch, previousBlock.Medians), nil + return razorUtils.CalculateSalt(previousEpoch, previousBlock.Medians), nil } /* @@ -53,28 +56,32 @@ HandleCommitState fetches the collections assigned to the staker and creates the Values for only the collections assigned to the staker is fetched for others, 0 is added to the leaves of tree. */ func (*UtilsStruct) HandleCommitState(client *ethclient.Client, epoch uint32, seed []byte, rogueData types.Rogue) (types.CommitData, error) { - numActiveCollections, err := utils.UtilsInterface.GetNumActiveCollections(client) + numActiveCollections, err := razorUtils.GetNumActiveCollections(client) if err != nil { return types.CommitData{}, err } log.Debug("HandleCommitState: Number of active collections: ", numActiveCollections) log.Debugf("HandleCommitState: Calling GetAssignedCollections() with arguments number of active collections = %d, seed = %v", numActiveCollections, seed) - assignedCollections, seqAllottedCollections, err := utils.UtilsInterface.GetAssignedCollections(client, numActiveCollections, seed) + assignedCollections, seqAllottedCollections, err := razorUtils.GetAssignedCollections(client, numActiveCollections, seed) if err != nil { return types.CommitData{}, err } var leavesOfTree []*big.Int + + log.Debug("Creating a local cache which will store API result and expire at the end of commit state") + localCache := cache.NewLocalCache(time.Second * time.Duration(core.StateLength)) + log.Debug("Iterating over all the collections...") for i := 0; i < int(numActiveCollections); i++ { log.Debug("HandleCommitState: Iterating index: ", i) log.Debug("HandleCommitState: Is the collection assigned: ", assignedCollections[i]) if assignedCollections[i] { - collectionId, err := utils.UtilsInterface.GetCollectionIdFromIndex(client, uint16(i)) + collectionId, err := razorUtils.GetCollectionIdFromIndex(client, uint16(i)) if err != nil { return types.CommitData{}, err } - collectionData, err := utils.UtilsInterface.GetAggregatedDataOfCollection(client, collectionId, epoch) + collectionData, err := razorUtils.GetAggregatedDataOfCollection(client, collectionId, epoch, localCache) if err != nil { return types.CommitData{}, err } @@ -92,6 +99,9 @@ func (*UtilsStruct) HandleCommitState(client *ethclient.Client, epoch uint32, se log.Debug("HandleCommitState: Assigned Collections: ", assignedCollections) log.Debug("HandleCommitState: SeqAllottedCollections: ", seqAllottedCollections) log.Debug("HandleCommitState: Leaves: ", leavesOfTree) + + localCache.StopCleanup() + return types.CommitData{ AssignedCollections: assignedCollections, SeqAllottedCollections: seqAllottedCollections, @@ -103,7 +113,7 @@ func (*UtilsStruct) HandleCommitState(client *ethclient.Client, epoch uint32, se Commit finally commits the data to the smart contract. It calculates the commitment to send using the merkle tree root and the seed. */ func (*UtilsStruct) Commit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, seed []byte, root [32]byte) (common.Hash, error) { - if state, err := razorUtils.GetDelayedState(client, config.BufferPercent); err != nil || state != 0 { + if state, err := razorUtils.GetBufferedState(client, config.BufferPercent); err != nil || state != 0 { log.Error("Not commit state") return core.NilHash, err } @@ -118,7 +128,7 @@ func (*UtilsStruct) Commit(client *ethclient.Client, config types.Configurations ChainId: core.ChainId, Config: config, ContractAddress: core.VoteManagerAddress, - ABI: bindings.VoteManagerABI, + ABI: bindings.VoteManagerMetaData.ABI, MethodName: "commit", Parameters: []interface{}{epoch, commitmentToSend}, }) @@ -131,6 +141,7 @@ func (*UtilsStruct) Commit(client *ethclient.Client, config types.Configurations if err != nil { return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } diff --git a/cmd/commit_test.go b/cmd/commit_test.go index bc27485b..983d084e 100644 --- a/cmd/commit_test.go +++ b/cmd/commit_test.go @@ -4,20 +4,17 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" + "errors" "fmt" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" - "github.com/syndtr/goleveldb/leveldb/errors" "math/big" - "razor/cmd/mocks" "razor/core" "razor/core/types" "razor/pkg/bindings" - "razor/utils" - mocks2 "razor/utils/mocks" "reflect" "testing" ) @@ -89,19 +86,12 @@ func TestCommit(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - voteManagerUtilsMock := new(mocks.VoteManagerInterface) - - razorUtils = utilsMock - transactionUtils = transactionUtilsMock - voteManagerUtils = voteManagerUtilsMock - - utilsMock.On("GetDelayedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) + utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(tt.args.txnOpts) - voteManagerUtilsMock.On("Commit", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.commitTxn, tt.args.commitErr) - transactionUtilsMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) + voteManagerMock.On("Commit", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.commitTxn, tt.args.commitErr) + transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) utils := &UtilsStruct{} got, err := utils.Commit(client, config, account, epoch, seed, tt.args.root) @@ -128,7 +118,7 @@ func TestHandleCommitState(t *testing.T) { seed []byte ) - rogueValue := utils.GetRogueRandomValue(100000) + rogueValue := big.NewInt(1111) type args struct { numActiveCollections uint16 @@ -227,16 +217,12 @@ func TestHandleCommitState(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsPkgMock := new(mocks2.Utils) - utilsMock := new(mocks.UtilsInterface) - - utils.UtilsInterface = utilsPkgMock - razorUtils = utilsMock + SetUpMockInterfaces() - utilsPkgMock.On("GetNumActiveCollections", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.numActiveCollections, tt.args.numActiveCollectionsErr) - utilsPkgMock.On("GetAssignedCollections", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.assignedCollections, tt.args.seqAllottedCollections, tt.args.assignedCollectionsErr) - utilsPkgMock.On("GetCollectionIdFromIndex", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.collectionId, tt.args.collectionIdErr) - utilsPkgMock.On("GetAggregatedDataOfCollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.collectionData, tt.args.collectionDataErr) + utilsMock.On("GetNumActiveCollections", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.numActiveCollections, tt.args.numActiveCollectionsErr) + utilsMock.On("GetAssignedCollections", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.assignedCollections, tt.args.seqAllottedCollections, tt.args.assignedCollectionsErr) + utilsMock.On("GetCollectionIdFromIndex", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.collectionId, tt.args.collectionIdErr) + utilsMock.On("GetAggregatedDataOfCollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionData, tt.args.collectionDataErr) utilsMock.On("GetRogueRandomValue", mock.Anything).Return(rogueValue) utils := &UtilsStruct{} @@ -349,18 +335,14 @@ func TestGetSalt(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsPkgMock := new(mocks2.Utils) - utilsVoteManagerMock := new(mocks2.VoteManagerUtils) + SetUpMockInterfaces() - utils.UtilsInterface = utilsPkgMock - utils.VoteManagerInterface = utilsVoteManagerMock - - utilsPkgMock.On("GetNumberOfProposedBlocks", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.numProposedBlocks, tt.args.numProposedBlocksErr) - utilsPkgMock.On("GetBlockIndexToBeConfirmed", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.blockIndexedToBeConfirmed, tt.args.blockIndexedToBeConfirmedErr) - utilsVoteManagerMock.On("GetSaltFromBlockchain", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.saltFromBlockChain, tt.args.saltFromBlockChainErr) - utilsPkgMock.On("GetSortedProposedBlockId", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.blockId, tt.args.blockIdErr) - utilsPkgMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.previousBlock, tt.args.previousBlockErr) - utilsPkgMock.On("CalculateSalt", mock.Anything, mock.Anything).Return(tt.args.salt) + utilsMock.On("GetNumberOfProposedBlocks", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.numProposedBlocks, tt.args.numProposedBlocksErr) + utilsMock.On("GetBlockIndexToBeConfirmed", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.blockIndexedToBeConfirmed, tt.args.blockIndexedToBeConfirmedErr) + voteManagerUtilsMock.On("GetSaltFromBlockchain", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.saltFromBlockChain, tt.args.saltFromBlockChainErr) + utilsMock.On("GetSortedProposedBlockId", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.blockId, tt.args.blockIdErr) + utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.previousBlock, tt.args.previousBlockErr) + utilsMock.On("CalculateSalt", mock.Anything, mock.Anything).Return(tt.args.salt) ut := &UtilsStruct{} got, err := ut.GetSalt(client, tt.args.epoch) @@ -387,7 +369,7 @@ func BenchmarkHandleCommitState(b *testing.B) { seed []byte ) - rogueValue := utils.GetRogueRandomValue(100000) + rogueValue := big.NewInt(1111) var table = []struct { numActiveCollections uint16 @@ -400,16 +382,12 @@ func BenchmarkHandleCommitState(b *testing.B) { for _, v := range table { b.Run(fmt.Sprintf("Number_Of_Active_Collections%d", v.numActiveCollections), func(b *testing.B) { for i := 0; i < b.N; i++ { - utilsPkgMock := new(mocks2.Utils) - utilsMock := new(mocks.UtilsInterface) - - utils.UtilsInterface = utilsPkgMock - razorUtils = utilsMock + SetUpMockInterfaces() - utilsPkgMock.On("GetNumActiveCollections", mock.AnythingOfType("*ethclient.Client")).Return(v.numActiveCollections, nil) - utilsPkgMock.On("GetAssignedCollections", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(v.assignedCollections, nil, nil) - utilsPkgMock.On("GetCollectionIdFromIndex", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(uint16(1), nil) - utilsPkgMock.On("GetAggregatedDataOfCollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(big.NewInt(1000), nil) + utilsMock.On("GetNumActiveCollections", mock.AnythingOfType("*ethclient.Client")).Return(v.numActiveCollections, nil) + utilsMock.On("GetAssignedCollections", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(v.assignedCollections, nil, nil) + utilsMock.On("GetCollectionIdFromIndex", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(uint16(1), nil) + utilsMock.On("GetAggregatedDataOfCollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(big.NewInt(1000), nil) utilsMock.On("GetRogueRandomValue", mock.Anything).Return(rogueValue) ut := &UtilsStruct{} diff --git a/cmd/config-utils.go b/cmd/config-utils.go index 7b424645..7ad7073e 100644 --- a/cmd/config-utils.go +++ b/cmd/config-utils.go @@ -2,29 +2,42 @@ package cmd import ( - "github.com/spf13/viper" + "errors" + "github.com/sirupsen/logrus" + "razor/client" "razor/core" "razor/core/types" "razor/utils" "strings" + + "github.com/spf13/viper" ) //This function returns the config data func (*UtilsStruct) GetConfigData() (types.Configurations, error) { config := types.Configurations{ Provider: "", + AlternateProvider: "", GasMultiplier: 0, BufferPercent: 0, WaitTime: 0, LogLevel: "", GasLimitMultiplier: 0, RPCTimeout: 0, + HTTPTimeout: 0, + LogFileMaxSize: 0, + LogFileMaxBackups: 0, + LogFileMaxAge: 0, } provider, err := cmdUtils.GetProvider() if err != nil { return config, err } + alternateProvider, err := cmdUtils.GetAlternateProvider() + if err != nil { + return config, err + } gasMultiplier, err := cmdUtils.GetMultiplier() if err != nil { return config, err @@ -57,7 +70,25 @@ func (*UtilsStruct) GetConfigData() (types.Configurations, error) { if err != nil { return config, err } + httpTimeout, err := cmdUtils.GetHTTPTimeout() + if err != nil { + return config, err + } + logFileMaxSize, err := cmdUtils.GetLogFileMaxSize() + if err != nil { + return config, err + } + logFileMaxBackups, err := cmdUtils.GetLogFileMaxBackups() + if err != nil { + return config, err + } + logFileMaxAge, err := cmdUtils.GetLogFileMaxAge() + if err != nil { + return config, err + } config.Provider = provider + config.AlternateProvider = alternateProvider + client.SetAlternateProvider(alternateProvider) config.GasMultiplier = gasMultiplier config.BufferPercent = bufferPercent config.WaitTime = waitTime @@ -67,6 +98,13 @@ func (*UtilsStruct) GetConfigData() (types.Configurations, error) { config.GasLimitOverride = gasLimitOverride config.RPCTimeout = rpcTimeout utils.RPCTimeout = rpcTimeout + config.HTTPTimeout = httpTimeout + utils.HTTPTimeout = httpTimeout + config.LogFileMaxSize = logFileMaxSize + config.LogFileMaxBackups = logFileMaxBackups + config.LogFileMaxAge = logFileMaxAge + + setLogLevel(config) return config, nil } @@ -75,14 +113,14 @@ func (*UtilsStruct) GetConfigData() (types.Configurations, error) { func (*UtilsStruct) GetProvider() (string, error) { provider, err := flagSetUtils.GetRootStringProvider() if err != nil { - return core.DefaultProvider, err + return "", err } if provider == "" { if viper.IsSet("provider") { provider = viper.GetString("provider") } else { - provider = core.DefaultProvider - log.Debug("Provider is not set, taking its default value ", provider) + log.Error("Provider is not set in config file") + return "", errors.New("provider is not set") } } if !strings.HasPrefix(provider, "https") { @@ -91,6 +129,26 @@ func (*UtilsStruct) GetProvider() (string, error) { return provider, nil } +//This function returns the alternate provider +func (*UtilsStruct) GetAlternateProvider() (string, error) { + alternateProvider, err := flagSetUtils.GetRootStringAlternateProvider() + if err != nil { + return "", err + } + if alternateProvider == "" { + if viper.IsSet("alternateProvider") { + alternateProvider = viper.GetString("alternateProvider") + } else { + alternateProvider = "" + log.Debug("alternate provider is not set, taking its nil value ", alternateProvider) + } + } + if !strings.HasPrefix(alternateProvider, "https") { + log.Warn("You are not using a secure RPC URL. Switch to an https URL instead to be safe.") + } + return alternateProvider, nil +} + //This function returns the multiplier func (*UtilsStruct) GetMultiplier() (float32, error) { gasMultiplier, err := flagSetUtils.GetRootFloat32GasMultiplier() @@ -227,3 +285,93 @@ func (*UtilsStruct) GetRPCTimeout() (int64, error) { } return rpcTimeout, nil } + +func (*UtilsStruct) GetHTTPTimeout() (int64, error) { + httpTimeout, err := flagSetUtils.GetRootInt64HTTPTimeout() + if err != nil { + return int64(core.DefaultHTTPTimeout), err + } + if httpTimeout == 0 { + if viper.IsSet("httpTimeout") { + httpTimeout = viper.GetInt64("httpTimeout") + } else { + httpTimeout = int64(core.DefaultRPCTimeout) + log.Debug("HTTPTimeout is not set, taking its default value ", httpTimeout) + } + } + return httpTimeout, nil +} + +func (*UtilsStruct) GetLogFileMaxSize() (int, error) { + logFileMaxSize, err := flagSetUtils.GetRootIntLogFileMaxSize() + if err != nil { + return core.DefaultLogFileMaxSize, err + } + if logFileMaxSize == 0 { + if viper.IsSet("logFileMaxSize") { + logFileMaxSize = viper.GetInt("logFileMaxSize") + } else { + logFileMaxSize = core.DefaultLogFileMaxSize + log.Debug("logFileMaxSize is not set, taking its default value ", logFileMaxSize) + } + } + return logFileMaxSize, nil +} + +func (*UtilsStruct) GetLogFileMaxBackups() (int, error) { + logFileMaxBackups, err := flagSetUtils.GetRootIntLogFileMaxBackups() + if err != nil { + return core.DefaultLogFileMaxBackups, err + } + if logFileMaxBackups == 0 { + if viper.IsSet("logFileMaxBackups") { + logFileMaxBackups = viper.GetInt("logFileMaxBackups") + } else { + logFileMaxBackups = core.DefaultLogFileMaxBackups + log.Debug("logFileMaxBackups is not set, taking its default value ", logFileMaxBackups) + } + } + return logFileMaxBackups, nil +} + +func (*UtilsStruct) GetLogFileMaxAge() (int, error) { + logFileMaxAge, err := flagSetUtils.GetRootIntLogFileMaxAge() + if err != nil { + return core.DefaultLogFileMaxAge, err + } + if logFileMaxAge == 0 { + if viper.IsSet("logFileMaxAge") { + logFileMaxAge = viper.GetInt("logFileMaxAge") + } else { + logFileMaxAge = core.DefaultLogFileMaxAge + log.Debug("logFileMaxAge is not set, taking its default value ", logFileMaxAge) + } + } + return logFileMaxAge, nil +} + +//This function sets the log level +func setLogLevel(config types.Configurations) { + if config.LogLevel == "debug" { + log.SetLevel(logrus.DebugLevel) + } + + log.Debug("Config details: ") + log.Debugf("Provider: %s", config.Provider) + log.Debugf("Alternate Provider: %s", config.AlternateProvider) + log.Debugf("Gas Multiplier: %.2f", config.GasMultiplier) + log.Debugf("Buffer Percent: %d", config.BufferPercent) + log.Debugf("Wait Time: %d", config.WaitTime) + log.Debugf("Gas Price: %d", config.GasPrice) + log.Debugf("Log Level: %s", config.LogLevel) + log.Debugf("Gas Limit: %.2f", config.GasLimitMultiplier) + log.Debugf("Gas Limit Override: %d", config.GasLimitOverride) + log.Debugf("RPC Timeout: %d", config.RPCTimeout) + log.Debugf("HTTP Timeout: %d", config.HTTPTimeout) + + if razorUtils.IsFlagPassed("logFile") { + log.Debugf("Log File Max Size: %d MB", config.LogFileMaxSize) + log.Debugf("Log File Max Backups (max number of old log files to retain): %d", config.LogFileMaxBackups) + log.Debugf("Log File Max Age (max number of days to retain old log files): %d", config.LogFileMaxAge) + } +} diff --git a/cmd/config-utils_test.go b/cmd/config-utils_test.go index 4dfff5e3..6250ddaf 100644 --- a/cmd/config-utils_test.go +++ b/cmd/config-utils_test.go @@ -2,6 +2,7 @@ package cmd import ( "errors" + "github.com/stretchr/testify/mock" "razor/cmd/mocks" "razor/core/types" "reflect" @@ -9,18 +10,24 @@ import ( ) func TestGetConfigData(t *testing.T) { - config := types.Configurations{ + nilConfig := types.Configurations{ Provider: "", + AlternateProvider: "", GasMultiplier: 0, BufferPercent: 0, WaitTime: 0, LogLevel: "", GasLimitMultiplier: 0, RPCTimeout: 0, + HTTPTimeout: 0, + LogFileMaxSize: 0, + LogFileMaxBackups: 0, + LogFileMaxAge: 0, } configData := types.Configurations{ Provider: "", + AlternateProvider: "", GasMultiplier: 1, BufferPercent: 20, WaitTime: 1, @@ -28,27 +35,41 @@ func TestGetConfigData(t *testing.T) { GasLimitMultiplier: 3, GasLimitOverride: 1000000, RPCTimeout: 10, + HTTPTimeout: 10, + LogFileMaxSize: 5, + LogFileMaxBackups: 10, + LogFileMaxAge: 30, } type args struct { - provider string - providerErr error - gasMultiplier float32 - gasMultiplierErr error - bufferPercent int32 - bufferPercentErr error - waitTime int32 - waitTimeErr error - gasPrice int32 - gasPriceErr error - logLevel string - logLevelErr error - gasLimit float32 - gasLimitOverride uint64 - gasLimitOverrideErr error - rpcTimeout int64 - rpcTimeoutErr error - gasLimitErr error + provider string + providerErr error + alternateProvider string + alternateProviderErr error + gasMultiplier float32 + gasMultiplierErr error + bufferPercent int32 + bufferPercentErr error + waitTime int32 + waitTimeErr error + gasPrice int32 + gasPriceErr error + logLevel string + logLevelErr error + gasLimit float32 + gasLimitOverride uint64 + gasLimitOverrideErr error + rpcTimeout int64 + rpcTimeoutErr error + httpTimeout int64 + httpTimeoutErr error + gasLimitErr error + logFileMaxSize int + logFileMaxSizeErr error + logFileMaxBackups int + logFileMaxBackupsErr error + logFileMaxAge int + logFileMaxAgeErr error } tests := []struct { name string @@ -59,14 +80,19 @@ func TestGetConfigData(t *testing.T) { { name: "Test 1: When GetConfigData function executes successfully", args: args{ - provider: "", - gasMultiplier: 1, - bufferPercent: 20, - waitTime: 1, - logLevel: "debug", - gasLimit: 3, - gasLimitOverride: 1000000, - rpcTimeout: 10, + provider: "", + alternateProvider: "", + gasMultiplier: 1, + bufferPercent: 20, + waitTime: 1, + logLevel: "debug", + gasLimit: 3, + gasLimitOverride: 1000000, + rpcTimeout: 10, + httpTimeout: 10, + logFileMaxSize: 5, + logFileMaxBackups: 10, + logFileMaxAge: 30, }, want: configData, wantErr: nil, @@ -76,7 +102,7 @@ func TestGetConfigData(t *testing.T) { args: args{ providerErr: errors.New("provider error"), }, - want: config, + want: nilConfig, wantErr: errors.New("provider error"), }, { @@ -84,7 +110,7 @@ func TestGetConfigData(t *testing.T) { args: args{ gasMultiplierErr: errors.New("gasMultiplier error"), }, - want: config, + want: nilConfig, wantErr: errors.New("gasMultiplier error"), }, { @@ -92,7 +118,7 @@ func TestGetConfigData(t *testing.T) { args: args{ bufferPercentErr: errors.New("bufferPercent error"), }, - want: config, + want: nilConfig, wantErr: errors.New("bufferPercent error"), }, { @@ -100,7 +126,7 @@ func TestGetConfigData(t *testing.T) { args: args{ waitTimeErr: errors.New("waitTime error"), }, - want: config, + want: nilConfig, wantErr: errors.New("waitTime error"), }, { @@ -108,7 +134,7 @@ func TestGetConfigData(t *testing.T) { args: args{ gasPriceErr: errors.New("gasPrice error"), }, - want: config, + want: nilConfig, wantErr: errors.New("gasPrice error"), }, { @@ -116,7 +142,7 @@ func TestGetConfigData(t *testing.T) { args: args{ logLevelErr: errors.New("logLevel error"), }, - want: config, + want: nilConfig, wantErr: errors.New("logLevel error"), }, { @@ -124,7 +150,7 @@ func TestGetConfigData(t *testing.T) { args: args{ gasLimitErr: errors.New("gasLimit error"), }, - want: config, + want: nilConfig, wantErr: errors.New("gasLimit error"), }, { @@ -132,24 +158,32 @@ func TestGetConfigData(t *testing.T) { args: args{ rpcTimeoutErr: errors.New("rpcTimeout error"), }, - want: config, + want: nilConfig, wantErr: errors.New("rpcTimeout error"), }, { - name: "When there is an error in getitng gasLimitOverride", + name: "Test 10: When there is an error in getting httpTimeout", args: args{ - gasLimitOverrideErr: errors.New("gasLimitOverride error"), + httpTimeoutErr: errors.New("httpTimeout error"), }, - want: config, - wantErr: errors.New("gasLimitOverride error"), + want: nilConfig, + wantErr: errors.New("httpTimeout error"), + }, + { + name: "Test 11: When there is an error in getting alternate provider", + args: args{ + alternateProviderErr: errors.New("alternate provider error"), + }, + want: nilConfig, + wantErr: errors.New("alternate provider error"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - cmdUtilsMock := new(mocks.UtilsCmdInterface) - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() cmdUtilsMock.On("GetProvider").Return(tt.args.provider, tt.args.providerErr) + cmdUtilsMock.On("GetAlternateProvider").Return(tt.args.alternateProvider, tt.args.alternateProviderErr) cmdUtilsMock.On("GetMultiplier").Return(tt.args.gasMultiplier, tt.args.gasMultiplierErr) cmdUtilsMock.On("GetWaitTime").Return(tt.args.waitTime, tt.args.waitTimeErr) cmdUtilsMock.On("GetGasPrice").Return(tt.args.gasPrice, tt.args.gasPriceErr) @@ -158,7 +192,11 @@ func TestGetConfigData(t *testing.T) { cmdUtilsMock.On("GetGasLimitOverride").Return(tt.args.gasLimitOverride, tt.args.gasLimitOverrideErr) cmdUtilsMock.On("GetBufferPercent").Return(tt.args.bufferPercent, tt.args.bufferPercentErr) cmdUtilsMock.On("GetRPCTimeout").Return(tt.args.rpcTimeout, tt.args.rpcTimeoutErr) - + cmdUtilsMock.On("GetHTTPTimeout").Return(tt.args.httpTimeout, tt.args.httpTimeoutErr) + cmdUtilsMock.On("GetLogFileMaxSize").Return(tt.args.logFileMaxSize, tt.args.logFileMaxSizeErr) + cmdUtilsMock.On("GetLogFileMaxBackups").Return(tt.args.logFileMaxBackups, tt.args.logFileMaxBackupsErr) + cmdUtilsMock.On("GetLogFileMaxAge").Return(tt.args.logFileMaxAge, tt.args.logFileMaxAgeErr) + utilsMock.On("IsFlagPassed", mock.AnythingOfType("string")).Return(true) utils := &UtilsStruct{} got, err := utils.GetConfigData() @@ -217,10 +255,9 @@ func TestGetBufferPercent(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - flagSetUtilsMock := new(mocks.FlagSetInterface) - flagSetUtils = flagSetUtilsMock + SetUpMockInterfaces() - flagSetUtilsMock.On("GetRootInt32Buffer").Return(tt.args.bufferPercent, tt.args.bufferPercentErr) + flagSetMock.On("GetRootInt32Buffer").Return(tt.args.bufferPercent, tt.args.bufferPercentErr) utils := &UtilsStruct{} got, err := utils.GetBufferPercent() if got != tt.want { @@ -277,10 +314,9 @@ func TestGetGasLimit(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - flagSetUtilsMock := new(mocks.FlagSetInterface) - flagSetUtils = flagSetUtilsMock + SetUpMockInterfaces() - flagSetUtilsMock.On("GetRootFloat32GasLimit").Return(tt.args.gasLimit, tt.args.gasLimitErr) + flagSetMock.On("GetRootFloat32GasLimit").Return(tt.args.gasLimit, tt.args.gasLimitErr) utils := &UtilsStruct{} got, err := utils.GetGasLimit() @@ -460,10 +496,9 @@ func TestGetLogLevel(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - flagSetUtilsMock := new(mocks.FlagSetInterface) - flagSetUtils = flagSetUtilsMock + SetUpMockInterfaces() - flagSetUtilsMock.On("GetRootStringLogLevel").Return(tt.args.logLevel, tt.args.logLevelErr) + flagSetMock.On("GetRootStringLogLevel").Return(tt.args.logLevel, tt.args.logLevelErr) utils := &UtilsStruct{} got, err := utils.GetLogLevel() @@ -521,10 +556,9 @@ func TestGetMultiplier(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - flagSetUtilsMock := new(mocks.FlagSetInterface) - flagSetUtils = flagSetUtilsMock + SetUpMockInterfaces() - flagSetUtilsMock.On("GetRootFloat32GasMultiplier").Return(tt.args.gasMultiplier, tt.args.gasMultiplierErr) + flagSetMock.On("GetRootFloat32GasMultiplier").Return(tt.args.gasMultiplier, tt.args.gasMultiplierErr) utils := &UtilsStruct{} got, err := utils.GetMultiplier() @@ -576,7 +610,7 @@ func TestGetProvider(t *testing.T) { args: args{ providerErr: errors.New("provider error"), }, - want: "http://127.0.0.1:8545", + want: "", wantErr: errors.New("provider error"), }, { @@ -584,16 +618,15 @@ func TestGetProvider(t *testing.T) { args: args{ provider: "", }, - want: "http://127.0.0.1:8545", - wantErr: nil, + want: "", + wantErr: errors.New("provider is not set"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - flagSetUtilsMock := new(mocks.FlagSetInterface) - flagSetUtils = flagSetUtilsMock + SetUpMockInterfaces() - flagSetUtilsMock.On("GetRootStringProvider").Return(tt.args.provider, tt.args.providerErr) + flagSetMock.On("GetRootStringProvider").Return(tt.args.provider, tt.args.providerErr) utils := &UtilsStruct{} got, err := utils.GetProvider() @@ -613,6 +646,74 @@ func TestGetProvider(t *testing.T) { } } +func TestGetAlternateProvider(t *testing.T) { + type args struct { + alternateProvider string + alternateProviderErr error + } + tests := []struct { + name string + args args + want string + wantErr error + }{ + { + name: "Test 1: When getAlternateProvider function execute successfully", + args: args{ + alternateProvider: "https://polygon-mumbai.g.alchemy.com/v2/-Re1lE3oDIVTWchuKMfRIECn0I", + }, + want: "https://polygon-mumbai.g.alchemy.com/v2/-Re1lE3oDIVTWchuKMfRIECn0I", + wantErr: nil, + }, + { + name: "Test 2: When alternate provider has prefix https", + args: args{ + alternateProvider: "127.0.0.1:8545", + }, + want: "127.0.0.1:8545", + wantErr: nil, + }, + { + name: "Test 3: When there is an error in getting alternate provider", + args: args{ + alternateProviderErr: errors.New("alternateProvider error"), + }, + want: "", + wantErr: errors.New("alternateProvider error"), + }, + { + name: "Test 4: When alternate provider is nil", + args: args{ + alternateProvider: "", + }, + want: "", + wantErr: nil, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() + + flagSetMock.On("GetRootStringAlternateProvider").Return(tt.args.alternateProvider, tt.args.alternateProviderErr) + utils := &UtilsStruct{} + + got, err := utils.GetAlternateProvider() + if got != tt.want { + t.Errorf("getAlternateProvider() got = %v, want %v", got, tt.want) + } + if err == nil || tt.wantErr == nil { + if err != tt.wantErr { + t.Errorf("Error for getAlternateProvider function, got = %v, want = %v", err, tt.wantErr) + } + } else { + if err.Error() != tt.wantErr.Error() { + t.Errorf("Error for getAlternateProvider function, got = %v, want = %v", err, tt.wantErr) + } + } + }) + } +} + func TestGetWaitTime(t *testing.T) { type args struct { waitTime int32 @@ -651,10 +752,9 @@ func TestGetWaitTime(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - flagSetUtilsMock := new(mocks.FlagSetInterface) - flagSetUtils = flagSetUtilsMock + SetUpMockInterfaces() - flagSetUtilsMock.On("GetRootInt32Wait").Return(tt.args.waitTime, tt.args.waitTimeErr) + flagSetMock.On("GetRootInt32Wait").Return(tt.args.waitTime, tt.args.waitTimeErr) utils := &UtilsStruct{} got, err := utils.GetWaitTime() if got != tt.want { @@ -711,10 +811,9 @@ func TestGetRPCTimeout(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - flagSetUtilsMock := new(mocks.FlagSetInterface) - flagSetUtils = flagSetUtilsMock + SetUpMockInterfaces() - flagSetUtilsMock.On("GetRootInt64RPCTimeout").Return(tt.args.rpcTimeout, tt.args.rpcTimeoutErr) + flagSetMock.On("GetRootInt64RPCTimeout").Return(tt.args.rpcTimeout, tt.args.rpcTimeoutErr) utils := &UtilsStruct{} got, err := utils.GetRPCTimeout() if got != tt.want { @@ -732,3 +831,62 @@ func TestGetRPCTimeout(t *testing.T) { }) } } + +func TestGetHTTPTimeout(t *testing.T) { + type args struct { + httpTimeout int64 + httpTimeoutErr error + } + tests := []struct { + name string + args args + want int64 + wantErr error + }{ + { + name: "Test 1: When getHTTPTimeout function executes successfully", + args: args{ + httpTimeout: 12, + }, + want: 12, + wantErr: nil, + }, + { + name: "Test 2: When httpTimeout is 0", + args: args{ + httpTimeout: 0, + }, + want: 10, + wantErr: nil, + }, + { + name: "Test 3: When there is an error in getting httpTimeout", + args: args{ + httpTimeoutErr: errors.New("httpTimeout error"), + }, + want: 10, + wantErr: errors.New("httpTimeout error"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() + + flagSetMock.On("GetRootInt64HTTPTimeout").Return(tt.args.httpTimeout, tt.args.httpTimeoutErr) + utils := &UtilsStruct{} + got, err := utils.GetHTTPTimeout() + if got != tt.want { + t.Errorf("getHTTPTimeout() got = %v, want %v", got, tt.want) + } + if err == nil || tt.wantErr == nil { + if err != tt.wantErr { + t.Errorf("Error for getHTTPTimeout function, got = %v, want = %v", err, tt.wantErr) + } + } else { + if err.Error() != tt.wantErr.Error() { + t.Errorf("Error for getHTTPTimeout function, got = %v, want = %v", err, tt.wantErr) + } + } + }) + } +} diff --git a/cmd/confirm.go b/cmd/confirm.go index a7014da6..000cc361 100644 --- a/cmd/confirm.go +++ b/cmd/confirm.go @@ -52,8 +52,9 @@ func (*UtilsStruct) ClaimBlockReward(options types.TransactionOptions) (common.H log.Error("Error in claiming block reward: ", err) return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(txn).Hex()) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } log.Debug("Only selected block proposer can claim block reward") diff --git a/cmd/confirm_test.go b/cmd/confirm_test.go index cf08feab..90fae9a8 100644 --- a/cmd/confirm_test.go +++ b/cmd/confirm_test.go @@ -7,7 +7,6 @@ import ( "errors" "github.com/stretchr/testify/mock" "math/big" - "razor/cmd/mocks" "razor/core" "razor/core/types" "razor/pkg/bindings" @@ -139,14 +138,7 @@ func TestClaimBlockReward(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - blockManagerMock := new(mocks.BlockManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - blockManagerUtils = blockManagerMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) utilsMock.On("GetSortedProposedBlockIds", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlockIdsErr) @@ -154,7 +146,7 @@ func TestClaimBlockReward(t *testing.T) { utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.selectedBlock, tt.args.selectedBlockErr) utilsMock.On("GetTxnOpts", options).Return(tt.args.txnOpts) blockManagerMock.On("ClaimBlockReward", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts")).Return(tt.args.ClaimBlockRewardTxn, tt.args.ClaimBlockRewardErr) - transactionUtilsMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) + transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) utils := &UtilsStruct{} got, err := utils.ClaimBlockReward(options) diff --git a/cmd/contractAddresses.go b/cmd/contractAddresses.go index 43c6c730..fd5cfadb 100644 --- a/cmd/contractAddresses.go +++ b/cmd/contractAddresses.go @@ -3,9 +3,11 @@ package cmd import ( "fmt" + "razor/core" + "razor/utils" + "github.com/spf13/cobra" "github.com/spf13/pflag" - "razor/core" ) // contractAddressesCmd represents the contractAddresses command @@ -23,8 +25,10 @@ func initialiseContractAddresses(cmd *cobra.Command, args []string) { //This function sets the flag appropriatley and executes the ContractAddresses function func (*UtilsStruct) ExecuteContractAddresses(flagSet *pflag.FlagSet) { + config, err := cmdUtils.GetConfigData() + utils.CheckError("Error in getting config: ", err) log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) fmt.Println("The contract addresses are: ") cmdUtils.ContractAddresses() @@ -32,11 +36,11 @@ func (*UtilsStruct) ExecuteContractAddresses(flagSet *pflag.FlagSet) { //This function provides the list of all contract addresses func (*UtilsStruct) ContractAddresses() { - fmt.Println("StakeManagerAddress :", core.StakeManagerAddress) - fmt.Println("RAZORAddress :", core.RAZORAddress) - fmt.Println("CollectionManagerAddress :", core.CollectionManagerAddress) - fmt.Println("VoteManagerAddress :", core.VoteManagerAddress) - fmt.Println("BlockManagerAddress :", core.BlockManagerAddress) + log.Info("StakeManagerAddress :", core.StakeManagerAddress) + log.Info("RAZORAddress :", core.RAZORAddress) + log.Info("CollectionManagerAddress :", core.CollectionManagerAddress) + log.Info("VoteManagerAddress :", core.VoteManagerAddress) + log.Info("BlockManagerAddress :", core.BlockManagerAddress) } func init() { diff --git a/cmd/contractAddresses_test.go b/cmd/contractAddresses_test.go index 93b742dc..0deedd25 100644 --- a/cmd/contractAddresses_test.go +++ b/cmd/contractAddresses_test.go @@ -3,7 +3,7 @@ package cmd import ( "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "razor/cmd/mocks" + "razor/core/types" "testing" ) @@ -40,13 +40,10 @@ func TestExecuteContractAddresses(t *testing.T) { log.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) + SetUpMockInterfaces() - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) + cmdUtilsMock.On("GetConfigData").Return(types.Configurations{}, nil) cmdUtilsMock.On("ContractAddresses") utils := &UtilsStruct{} diff --git a/cmd/create.go b/cmd/create.go index 6aab759e..63931867 100644 --- a/cmd/create.go +++ b/cmd/create.go @@ -2,13 +2,13 @@ package cmd import ( + "path/filepath" + "razor/utils" + "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/common" "github.com/spf13/cobra" "github.com/spf13/pflag" - "path" - razorAccounts "razor/accounts" - "razor/utils" ) var createCmd = &cobra.Command{ @@ -28,8 +28,10 @@ func initialiseCreate(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the Create function func (*UtilsStruct) ExecuteCreate(flagSet *pflag.FlagSet) { + config, err := cmdUtils.GetConfigData() + utils.CheckError("Error in getting config: ", err) log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Info("The password should be of minimum 8 characters containing least 1 uppercase, lowercase, digit and special character.") password := razorUtils.AssignPassword(flagSet) log.Debug("ExecuteCreate: Calling Create() with argument as input password") @@ -41,14 +43,14 @@ func (*UtilsStruct) ExecuteCreate(flagSet *pflag.FlagSet) { //This function is used to create the new account func (*UtilsStruct) Create(password string) (accounts.Account, error) { - razorPath, err := razorUtils.GetDefaultPath() + razorPath, err := pathUtils.GetDefaultPath() if err != nil { log.Error("Error in fetching .razor directory") return accounts.Account{Address: common.Address{0x00}}, err } log.Debug("Create: .razor directory path: ", razorPath) - keystorePath := path.Join(razorPath, "keystore_files") - account := razorAccounts.AccountUtilsInterface.CreateAccount(keystorePath, password) + keystorePath := filepath.Join(razorPath, "keystore_files") + account := accountUtils.CreateAccount(keystorePath, password) return account, nil } diff --git a/cmd/createCollection.go b/cmd/createCollection.go index 33d8ed11..be61d650 100644 --- a/cmd/createCollection.go +++ b/cmd/createCollection.go @@ -46,11 +46,14 @@ func (*UtilsStruct) ExecuteCreateCollection(flagSet *pflag.FlagSet) { logger.SetLoggerParameters(client, address) log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + name, err := flagSetUtils.GetStringName(flagSet) utils.CheckError("Error in getting name: ", err) @@ -79,13 +82,13 @@ func (*UtilsStruct) ExecuteCreateCollection(flagSet *pflag.FlagSet) { log.Debugf("Calling CreateCollection() with argument collectionInput: %+v", collectionInput) txn, err := cmdUtils.CreateCollection(client, config, collectionInput) utils.CheckError("CreateCollection error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for createCollection: ", err) } //This function allows the admin to create collction if existing jobs are present func (*UtilsStruct) CreateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) { - jobIds := razorUtils.ConvertUintArrayToUint16Array(collectionInput.JobIds) + jobIds := utils.ConvertUintArrayToUint16Array(collectionInput.JobIds) log.Debug("CreateCollection: Uint16 jobIds: ", jobIds) _, err := cmdUtils.WaitForAppropriateState(client, "create collection", 4) if err != nil { @@ -101,7 +104,7 @@ func (*UtilsStruct) CreateCollection(client *ethclient.Client, config types.Conf ContractAddress: core.CollectionManagerAddress, MethodName: "createCollection", Parameters: []interface{}{collectionInput.Tolerance, collectionInput.Power, collectionInput.Aggregation, jobIds, collectionInput.Name}, - ABI: bindings.CollectionManagerABI, + ABI: bindings.CollectionManagerMetaData.ABI, }) log.Debugf("Executing CreateCollection transaction with tolerance: %d, power = %d , aggregation = %d, jobIds = %v, name = %s", collectionInput.Tolerance, collectionInput.Power, collectionInput.Aggregation, jobIds, collectionInput.Name) txn, err := assetManagerUtils.CreateCollection(client, txnOpts, collectionInput.Tolerance, collectionInput.Power, collectionInput.Aggregation, jobIds, collectionInput.Name) @@ -110,8 +113,9 @@ func (*UtilsStruct) CreateCollection(client *ethclient.Client, config types.Conf return core.NilHash, err } log.Info("Creating collection...") - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/createCollection_test.go b/cmd/createCollection_test.go index 27206fbb..ede02549 100644 --- a/cmd/createCollection_test.go +++ b/cmd/createCollection_test.go @@ -5,17 +5,17 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core" + "razor/core/types" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core" - "razor/core/types" - "testing" ) func TestCreateCollection(t *testing.T) { @@ -80,22 +80,13 @@ func TestCreateCollection(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - assetManagerUtilsMock := new(mocks.AssetManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - assetManagerUtils = assetManagerUtilsMock - transactionUtils = transactionUtilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() utilsMock.On("ConvertUintArrayToUint16Array", mock.Anything).Return(tt.args.jobIdUint8) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) cmdUtilsMock.On("WaitForAppropriateState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.Anything).Return(WaitForDisputeOrConfirmStateStatus, tt.args.waitForAppropriateStateErr) - assetManagerUtilsMock.On("CreateCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.createCollectionTxn, tt.args.createCollectionErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + assetManagerMock.On("CreateCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.createCollectionTxn, tt.args.createCollectionErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} got, err := utils.CreateCollection(client, config, collectionInput) @@ -291,24 +282,18 @@ func TestExecuteCreateCollection(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - flagsetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - flagSetUtils = flagsetUtilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagsetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) - flagsetUtilsMock.On("GetStringName", flagSet).Return(tt.args.name, tt.args.nameErr) - flagsetUtilsMock.On("GetUintSliceJobIds", flagSet).Return(tt.args.jobId, tt.args.jobIdErr) - flagsetUtilsMock.On("GetUint32Aggregation", flagSet).Return(tt.args.aggregation, tt.args.aggregationErr) - flagsetUtilsMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) - flagsetUtilsMock.On("GetUint32Tolerance", flagSet).Return(tt.args.tolerance, tt.args.toleranceErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetStringName", flagSet).Return(tt.args.name, tt.args.nameErr) + flagSetMock.On("GetUintSliceJobIds", flagSet).Return(tt.args.jobId, tt.args.jobIdErr) + flagSetMock.On("GetUint32Aggregation", flagSet).Return(tt.args.aggregation, tt.args.aggregationErr) + flagSetMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) + flagSetMock.On("GetUint32Tolerance", flagSet).Return(tt.args.tolerance, tt.args.toleranceErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("CreateCollection", mock.AnythingOfType("*ethclient.Client"), config, mock.Anything).Return(tt.args.createCollectionHash, tt.args.createCollectionErr) utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) diff --git a/cmd/createJob.go b/cmd/createJob.go index 68bbd1b7..30a399fd 100644 --- a/cmd/createJob.go +++ b/cmd/createJob.go @@ -47,11 +47,14 @@ func (*UtilsStruct) ExecuteCreateJob(flagSet *pflag.FlagSet) { logger.SetLoggerParameters(client, address) log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + name, err := flagSetUtils.GetStringName(flagSet) utils.CheckError("Error in getting name: ", err) @@ -83,7 +86,7 @@ func (*UtilsStruct) ExecuteCreateJob(flagSet *pflag.FlagSet) { log.Debugf("ExecuteCreateJob: Calling CreateJob() with argument jobInput: %+v", jobInput) txn, err := cmdUtils.CreateJob(client, config, jobInput) utils.CheckError("CreateJob error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for createJob: ", err) } @@ -98,7 +101,7 @@ func (*UtilsStruct) CreateJob(client *ethclient.Client, config types.Configurati ContractAddress: core.CollectionManagerAddress, MethodName: "createJob", Parameters: []interface{}{jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Name, jobInput.Selector, jobInput.Url}, - ABI: bindings.CollectionManagerABI, + ABI: bindings.CollectionManagerMetaData.ABI, } txnOpts := razorUtils.GetTxnOpts(txnArgs) @@ -108,8 +111,9 @@ func (*UtilsStruct) CreateJob(client *ethclient.Client, config types.Configurati if err != nil { return core.NilHash, err } - log.Info("Transaction Hash: ", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/createJob_test.go b/cmd/createJob_test.go index 14baa81f..4cf358d3 100644 --- a/cmd/createJob_test.go +++ b/cmd/createJob_test.go @@ -5,17 +5,17 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core" + "razor/core/types" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core" - "razor/core/types" - "testing" ) func TestCreateJob(t *testing.T) { @@ -62,18 +62,11 @@ func TestCreateJob(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - assetManagerUtilsMock := new(mocks.AssetManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - assetManagerUtils = assetManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - assetManagerUtilsMock.On("CreateJob", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.createJobTxn, tt.args.createJobErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + assetManagerMock.On("CreateJob", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.createJobTxn, tt.args.createJobErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} got, err := utils.CreateJob(client, config, jobInput) @@ -309,25 +302,19 @@ func TestExecuteCreateJob(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - flagsetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - flagSetUtils = flagsetUtilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagsetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) - flagsetUtilsMock.On("GetStringName", flagSet).Return(tt.args.name, tt.args.nameErr) - flagsetUtilsMock.On("GetStringUrl", flagSet).Return(tt.args.url, tt.args.urlErr) - flagsetUtilsMock.On("GetStringSelector", flagSet).Return(tt.args.selector, tt.args.selectorErr) - flagsetUtilsMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) - flagsetUtilsMock.On("GetUint8Weight", flagSet).Return(tt.args.weight, tt.args.weightErr) - flagsetUtilsMock.On("GetUint8SelectorType", flagSet).Return(tt.args.selectorType, tt.args.selectorTypeErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetStringName", flagSet).Return(tt.args.name, tt.args.nameErr) + flagSetMock.On("GetStringUrl", flagSet).Return(tt.args.url, tt.args.urlErr) + flagSetMock.On("GetStringSelector", flagSet).Return(tt.args.selector, tt.args.selectorErr) + flagSetMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) + flagSetMock.On("GetUint8Weight", flagSet).Return(tt.args.weight, tt.args.weightErr) + flagSetMock.On("GetUint8SelectorType", flagSet).Return(tt.args.selectorType, tt.args.selectorTypeErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("CreateJob", mock.AnythingOfType("*ethclient.Client"), config, mock.Anything).Return(tt.args.createJobHash, tt.args.createJobErr) utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) diff --git a/cmd/create_test.go b/cmd/create_test.go index 0df1acd2..2ddd5a02 100644 --- a/cmd/create_test.go +++ b/cmd/create_test.go @@ -2,17 +2,13 @@ package cmd import ( "errors" + "razor/core/types" + "testing" + "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/common" "github.com/spf13/pflag" - razorAccounts "razor/accounts" - - //"github.com/spf13/pflag" "github.com/stretchr/testify/mock" - Mocks "razor/accounts/mocks" - //razorAccounts "razor/accounts" - "razor/cmd/mocks" - "testing" ) func TestCreate(t *testing.T) { @@ -60,15 +56,10 @@ func TestCreate(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - accountUtilsMock := new(Mocks.AccountInterface) - - razorUtils = utilsMock - razorAccounts.AccountUtilsInterface = accountUtilsMock - - utilsMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) - accountUtilsMock.On("CreateAccount", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(accounts.Account{ + pathMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) + accountsMock.On("CreateAccount", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(accounts.Account{ Address: tt.args.account.Address, URL: accounts.URL{Scheme: "TestKeyScheme", Path: "test/key/path"}, }) @@ -136,16 +127,13 @@ func TestExecuteCreate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) utilsMock.On("AssignPassword", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.password) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) cmdUtilsMock.On("Create", mock.AnythingOfType("string")).Return(tt.args.account, tt.args.accountErr) + cmdUtilsMock.On("GetConfigData").Return(types.Configurations{}, nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/delegate.go b/cmd/delegate.go index 1e2f376f..9645906f 100644 --- a/cmd/delegate.go +++ b/cmd/delegate.go @@ -44,11 +44,14 @@ func (*UtilsStruct) ExecuteDelegate(flagSet *pflag.FlagSet) { logger.SetLoggerParameters(client, address) log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + stakerId, err := flagSetUtils.GetUint32StakerId(flagSet) utils.CheckError("Error in getting stakerId: ", err) log.Debug("ExecuteDelegate: Staker Id: ", stakerId) @@ -80,33 +83,34 @@ func (*UtilsStruct) ExecuteDelegate(flagSet *pflag.FlagSet) { utils.CheckError("Approve error: ", err) if approveTxnHash != core.NilHash { - err = razorUtils.WaitForBlockCompletion(txnArgs.Client, approveTxnHash.String()) + err = razorUtils.WaitForBlockCompletion(txnArgs.Client, approveTxnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for approve: ", err) } log.Debug("ExecuteDelegate:Calling Delegate() with stakerId: ", stakerId) delegateTxnHash, err := cmdUtils.Delegate(txnArgs, stakerId) utils.CheckError("Delegate error: ", err) - err = razorUtils.WaitForBlockCompletion(client, delegateTxnHash.String()) + err = razorUtils.WaitForBlockCompletion(client, delegateTxnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for delegate: ", err) } //This function allows the delegator to stake coins without setting up a node func (*UtilsStruct) Delegate(txnArgs types.TransactionOptions, stakerId uint32) (common.Hash, error) { - log.Infof("Delegating %g razors to Staker %d", razorUtils.GetAmountInDecimal(txnArgs.Amount), stakerId) + log.Infof("Delegating %g razors to Staker %d", utils.GetAmountInDecimal(txnArgs.Amount), stakerId) txnArgs.ContractAddress = core.StakeManagerAddress txnArgs.MethodName = "delegate" - txnArgs.ABI = bindings.StakeManagerABI + txnArgs.ABI = bindings.StakeManagerMetaData.ABI txnArgs.Parameters = []interface{}{stakerId, txnArgs.Amount} delegationTxnOpts := razorUtils.GetTxnOpts(txnArgs) log.Info("Sending Delegate transaction...") log.Debugf("Executing Delegate transaction with stakerId = %d, amount = %s", stakerId, txnArgs.Amount) txn, err := stakeManagerUtils.Delegate(txnArgs.Client, delegationTxnOpts, stakerId, txnArgs.Amount) if err != nil { - return common.Hash{0x00}, err + return core.NilHash, err } - log.Infof("Transaction hash: %s", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/delegate_test.go b/cmd/delegate_test.go index 8973b06a..17e1ea9f 100644 --- a/cmd/delegate_test.go +++ b/cmd/delegate_test.go @@ -6,7 +6,6 @@ import ( "crypto/rand" "errors" "math/big" - "razor/cmd/mocks" "razor/core" "razor/core/types" "testing" @@ -23,11 +22,10 @@ func TestDelegate(t *testing.T) { privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) txnOpts, _ := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(1)) - var txnArgs types.TransactionOptions var stakerId uint32 = 1 type args struct { - amount *big.Float + amount *big.Int txnOpts *bind.TransactOpts delegateTxn *Types.Transaction delegateErr error @@ -42,7 +40,7 @@ func TestDelegate(t *testing.T) { { name: "Test 1: When delegate function executes successfully", args: args{ - amount: big.NewFloat(1000), + amount: big.NewInt(1000), txnOpts: txnOpts, delegateTxn: &Types.Transaction{}, delegateErr: nil, @@ -54,7 +52,7 @@ func TestDelegate(t *testing.T) { { name: "Test 2: When delegate transaction fails", args: args{ - amount: big.NewFloat(1000), + amount: big.NewInt(1000), txnOpts: txnOpts, delegateTxn: &Types.Transaction{}, delegateErr: errors.New("delegate error"), @@ -66,23 +64,17 @@ func TestDelegate(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - utilsMock.On("GetAmountInDecimal", mock.AnythingOfType("*big.Int")).Return(tt.args.amount) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - stakeManagerUtilsMock.On("Delegate", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.delegateTxn, tt.args.delegateErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock + stakeManagerMock.On("Delegate", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.delegateTxn, tt.args.delegateErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.Delegate(txnArgs, stakerId) + got, err := utils.Delegate(types.TransactionOptions{ + Amount: tt.args.amount, + }, stakerId) if got != tt.want { t.Errorf("Txn hash for delegate function, got = %v, want %v", got, tt.want) } @@ -252,22 +244,14 @@ func TestExecuteDelegate(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - flagSetUtils = flagSetUtilsMock - transactionUtils = transactionUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagSetUtilsMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) - flagSetUtilsMock.On("GetUint32StakerId", flagSet).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetUint32StakerId", flagSet).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) utilsMock.On("FetchBalance", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.balance, tt.args.balanceErr) diff --git a/cmd/dispute.go b/cmd/dispute.go index f11b55f0..539d9e80 100644 --- a/cmd/dispute.go +++ b/cmd/dispute.go @@ -3,12 +3,6 @@ package cmd import ( "errors" - "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - solsha3 "github.com/miguelmota/go-solidity-sha3" "math/big" "os" "razor/core" @@ -17,6 +11,13 @@ import ( "razor/pkg/bindings" "razor/utils" "strings" + + "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + Types "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + solsha3 "github.com/miguelmota/go-solidity-sha3" ) var ( @@ -99,8 +100,9 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu log.Error(err) continue } - log.Info("Txn Hash: ", transactionUtils.Hash(disputeBiggestStakeProposedTxn)) - WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, transactionUtils.Hash(disputeBiggestStakeProposedTxn).String()) + disputeBiggestStakeProposedTxnHash := transactionUtils.Hash(disputeBiggestStakeProposedTxn) + log.Info("Txn Hash: ", disputeBiggestStakeProposedTxnHash.Hex()) + WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, disputeBiggestStakeProposedTxnHash.Hex()) //If dispute happens, then storing the bountyId into disputeData file if WaitForBlockCompletionErr == nil { @@ -124,8 +126,9 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu log.Error("Error in disputing: ", err) } if idDisputeTxn != nil { - log.Debugf("Txn Hash: %s", transactionUtils.Hash(idDisputeTxn).String()) - WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, transactionUtils.Hash(idDisputeTxn).String()) + idDisputeTxnHash := transactionUtils.Hash(idDisputeTxn) + log.Debugf("Txn Hash: %s", idDisputeTxnHash.Hex()) + WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, idDisputeTxnHash.Hex()) //If dispute happens, then storing the bountyId into disputeData file if WaitForBlockCompletionErr == nil { @@ -140,7 +143,7 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu } // Median Value dispute - isEqual, mismatchIndex := utils.IsEqual(proposedBlock.Medians, medians) + isEqual, mismatchIndex := utils.IsBigIntArrayEqual(proposedBlock.Medians, medians) if !isEqual && !utils.Contains(backupNodeActionsToIgnore, "disputeMedians") { log.Warn("BLOCK NOT MATCHING WITH LOCAL CALCULATIONS.") log.Debug("HandleDispute: Block Values: ", proposedBlock.Medians) @@ -159,7 +162,7 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu sortedValues := revealedDataMaps.SortedRevealedValues[collectionIdOfWrongMedian-1] log.Debug("HandleDispute: Sorted values: ", sortedValues) - leafId, err := utils.UtilsInterface.GetLeafIdOfACollection(client, collectionIdOfWrongMedian) + leafId, err := razorUtils.GetLeafIdOfACollection(client, collectionIdOfWrongMedian) if err != nil { log.Error("Error in leaf id: ", err) continue @@ -189,13 +192,13 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu func (*UtilsStruct) GetLocalMediansData(client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) { if (globalProposedDataStruct.MediansData == nil && !rogueData.IsRogue) || epoch != globalProposedDataStruct.Epoch { log.Debug("Global propose data struct is not updated, getting the proposed data from file...") - fileName, err := razorUtils.GetProposeDataFileName(account.Address) + fileName, err := pathUtils.GetProposeDataFileName(account.Address) if err != nil { log.Error("Error in getting file name to read median data: ", err) goto CalculateMedian } log.Debug("GetLocalMediansData: Propose data file path: ", fileName) - proposedData, err := razorUtils.ReadFromProposeJsonFile(fileName) + proposedData, err := fileUtils.ReadFromProposeJsonFile(fileName) if err != nil { log.Errorf("Error in getting propose data from file %s: %v", fileName, err) goto CalculateMedian @@ -256,7 +259,7 @@ func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts hashRevealedCollectionIds := solsha3.SoliditySHA3([]string{"uint16[]"}, []interface{}{revealedCollectionIds}) log.Debug("CheckDisputeForIds: Hash of locally calculated reveal collection Ids: ", hashRevealedCollectionIds) - isEqual, _ := utils.IsEqualByte(hashIdsInProposedBlock, hashRevealedCollectionIds) + isEqual, _ := utils.IsByteArrayEqual(hashIdsInProposedBlock, hashRevealedCollectionIds) if isEqual { log.Debug("Revealed collection Ids are correct, no need to dispute for ids") @@ -266,7 +269,7 @@ func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts // Check if the error is in sorted ids isSorted, index0, index1 := utils.IsSorted(idsInProposedBlock) if !isSorted { - transactionOpts.ABI = bindings.BlockManagerABI + transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeOnOrderOfIds" transactionOpts.Parameters = []interface{}{epoch, blockIndex, index0, index1} txnOpts := razorUtils.GetTxnOpts(transactionOpts) @@ -276,14 +279,14 @@ func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts } // Check if the error is collectionIdShouldBePresent - isMissing, _, missingCollectionId := utils.IsMissing(revealedCollectionIds, idsInProposedBlock) - if isMissing { - transactionOpts.ABI = bindings.BlockManagerABI + isValueMissing, _, missingCollectionId := utils.CheckValueMissingInArray(revealedCollectionIds, idsInProposedBlock) + if isValueMissing { + transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeCollectionIdShouldBePresent" transactionOpts.Parameters = []interface{}{epoch, blockIndex, missingCollectionId} txnOpts := razorUtils.GetTxnOpts(transactionOpts) gasLimit := txnOpts.GasLimit - incrementedGasLimit, err := utilsInterface.IncreaseGasLimitValue(client, gasLimit, 5.5) + incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(client, gasLimit, core.DisputeGasMultiplier) if err != nil { return nil, err } @@ -294,14 +297,14 @@ func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts } // Check if the error is collectionIdShouldBeAbsent - isPresent, positionOfPresentValue, presentCollectionId := utils.IsMissing(idsInProposedBlock, revealedCollectionIds) - if isPresent { - transactionOpts.ABI = bindings.BlockManagerABI + isValuePresent, positionOfPresentValue, presentCollectionId := utils.CheckValueMissingInArray(idsInProposedBlock, revealedCollectionIds) + if isValuePresent { + transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeCollectionIdShouldBeAbsent" transactionOpts.Parameters = []interface{}{epoch, blockIndex, presentCollectionId, big.NewInt(int64(positionOfPresentValue))} txnOpts := razorUtils.GetTxnOpts(transactionOpts) gasLimit := txnOpts.GasLimit - incrementedGasLimit, err := utilsInterface.IncreaseGasLimitValue(client, gasLimit, 5.5) + incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(client, gasLimit, core.DisputeGasMultiplier) if err != nil { return nil, err } @@ -373,7 +376,7 @@ func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configuration finalizeDisputeTxnArgs := txnArgs finalizeDisputeTxnArgs.ContractAddress = core.BlockManagerAddress finalizeDisputeTxnArgs.MethodName = "finalizeDispute" - finalizeDisputeTxnArgs.ABI = bindings.BlockManagerABI + finalizeDisputeTxnArgs.ABI = bindings.BlockManagerMetaData.ABI finalizeDisputeTxnArgs.Parameters = []interface{}{epoch, blockIndex, positionOfCollectionInBlock} finalizeDisputeTxnOpts := razorUtils.GetTxnOpts(finalizeDisputeTxnArgs) @@ -386,8 +389,10 @@ func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configuration var nilTransaction *Types.Transaction if finalizeTxn != nilTransaction { + finalizeTxnHash := transactionUtils.Hash(finalizeTxn) + log.Info("Txn Hash: ", finalizeTxnHash.Hex()) log.Debug("Dispute: Checking mining status of FinalizeDispute transaction...") - WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, transactionUtils.Hash(finalizeTxn).String()) + WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, finalizeTxnHash.Hex()) //If dispute happens, then storing the bountyId into disputeData file if WaitForBlockCompletionErr == nil { log.Debug("Storing bounty Id in dispute data file...") @@ -406,7 +411,7 @@ func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configuration resetDisputeTxnArgs := txnArgs resetDisputeTxnArgs.ContractAddress = core.BlockManagerAddress resetDisputeTxnArgs.MethodName = "resetDispute" - resetDisputeTxnArgs.ABI = bindings.BlockManagerABI + resetDisputeTxnArgs.ABI = bindings.BlockManagerMetaData.ABI resetDisputeTxnArgs.Parameters = []interface{}{epoch} resetDisputeTxnOpts := razorUtils.GetTxnOpts(resetDisputeTxnArgs) @@ -440,16 +445,17 @@ func GiveSorted(client *ethclient.Client, blockManager *bindings.BlockManager, t } log.Debug("GiveSorted: Is give sorted initiated: ", isGiveSortedInitiated) + log.Info("Calling GiveSorted...") log.Debugf("Executing GiveSorted transaction with arguments epoch = %d, leafId = %d , sortedValues = %s", epoch, leafId, sortedValues) txn, err := blockManagerUtils.GiveSorted(blockManager, txnOpts, epoch, leafId, sortedValues) if err != nil { return err } - log.Info("Calling GiveSorted...") - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) giveSortedLeafIds = append(giveSortedLeafIds, int(leafId)) - err = razorUtils.WaitForBlockCompletion(client, transactionUtils.Hash(txn).String()) + err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) if err != nil { log.Error("Error in WaitForBlockCompletion for giveSorted: ", err) return err @@ -460,7 +466,7 @@ func GiveSorted(client *ethclient.Client, blockManager *bindings.BlockManager, t //This function returns the collection Id position in block func (*UtilsStruct) GetCollectionIdPositionInBlock(client *ethclient.Client, leafId uint16, proposedBlock bindings.StructsBlock) *big.Int { ids := proposedBlock.Ids - idToBeDisputed, err := utils.UtilsInterface.GetCollectionIdFromLeafId(client, leafId) + idToBeDisputed, err := razorUtils.GetCollectionIdFromLeafId(client, leafId) if err != nil { log.Error("Error in fetching collection id from leaf id") return nil @@ -477,7 +483,7 @@ func (*UtilsStruct) GetCollectionIdPositionInBlock(client *ethclient.Client, lea //This function saves the bountyId in disputeData file and return the error if there is any func (*UtilsStruct) StoreBountyId(client *ethclient.Client, account types.Account) error { - disputeFilePath, err := razorUtils.GetDisputeDataFileName(account.Address) + disputeFilePath, err := pathUtils.GetDisputeDataFileName(account.Address) if err != nil { return err } @@ -485,7 +491,7 @@ func (*UtilsStruct) StoreBountyId(client *ethclient.Client, account types.Accoun var latestBountyId uint32 - latestHeader, err := utils.UtilsInterface.GetLatestBlockWithRetry(client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(client) if err != nil { log.Error("Error in fetching block: ", err) return err @@ -500,7 +506,7 @@ func (*UtilsStruct) StoreBountyId(client *ethclient.Client, account types.Accoun if _, err := path.OSUtilsInterface.Stat(disputeFilePath); !errors.Is(err, os.ErrNotExist) { log.Debug("Fetching dispute data from dispute data file...") - disputeData, err = razorUtils.ReadFromDisputeJsonFile(disputeFilePath) + disputeData, err = fileUtils.ReadFromDisputeJsonFile(disputeFilePath) if err != nil { return err } @@ -514,7 +520,7 @@ func (*UtilsStruct) StoreBountyId(client *ethclient.Client, account types.Accoun //saving the updated bountyIds to disputeData file log.Debug("Saving the updated bountyIds to dispute data file...") - err = razorUtils.SaveDataToDisputeJsonFile(disputeFilePath, disputeData.BountyIdQueue) + err = fileUtils.SaveDataToDisputeJsonFile(disputeFilePath, disputeData.BountyIdQueue) if err != nil { return err } @@ -529,8 +535,9 @@ func (*UtilsStruct) ResetDispute(client *ethclient.Client, blockManager *binding log.Error("error in resetting dispute", err) return } - log.Info("Transaction hash: ", transactionUtils.Hash(txn)) - err = razorUtils.WaitForBlockCompletion(client, transactionUtils.Hash(txn).String()) + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) if err != nil { log.Error("Error in WaitForBlockCompletion for resetDispute: ", err) return @@ -540,7 +547,7 @@ func (*UtilsStruct) ResetDispute(client *ethclient.Client, blockManager *binding //This function returns the bountyId from events func (*UtilsStruct) GetBountyIdFromEvents(client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error) { - fromBlock, err := utils.UtilsInterface.CalculateBlockNumberAtEpochBeginning(client, core.EpochLength, blockNumber) + fromBlock, err := razorUtils.EstimateBlockNumberAtEpochBeginning(client, blockNumber) if err != nil { log.Error(err) return 0, err @@ -554,11 +561,11 @@ func (*UtilsStruct) GetBountyIdFromEvents(client *ethclient.Client, blockNumber }, } log.Debugf("GetBountyIdFromEvents: Query to send in filter logs: %+v", query) - logs, err := utils.UtilsInterface.FilterLogsWithRetry(client, query) + logs, err := clientUtils.FilterLogsWithRetry(client, query) if err != nil { return 0, err } - contractAbi, err := utils.ABIInterface.Parse(strings.NewReader(bindings.StakeManagerABI)) + contractAbi, err := utils.ABIInterface.Parse(strings.NewReader(bindings.StakeManagerMetaData.ABI)) if err != nil { return 0, err } diff --git a/cmd/dispute_test.go b/cmd/dispute_test.go index ae54319f..a7f4af35 100644 --- a/cmd/dispute_test.go +++ b/cmd/dispute_test.go @@ -6,23 +6,19 @@ import ( "crypto/rand" "errors" "fmt" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/stretchr/testify/mock" "io/fs" "math/big" - "razor/cmd/mocks" "razor/core/types" - "razor/path" - pathMocks "razor/path/mocks" "razor/pkg/bindings" - "razor/utils" - mocks2 "razor/utils/mocks" "reflect" "testing" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + Types "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/stretchr/testify/mock" ) func TestDispute(t *testing.T) { @@ -97,23 +93,14 @@ func TestDispute(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - blockManagerUtilsMock := new(mocks.BlockManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - blockManagerUtils = blockManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) cmdUtilsMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) cmdUtilsMock.On("GetCollectionIdPositionInBlock", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.positionOfCollectionInBlock) - blockManagerUtilsMock.On("FinalizeDispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.finalizeDisputeTxn, tt.args.finalizeDisputeErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + blockManagerMock.On("FinalizeDispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.finalizeDisputeTxn, tt.args.finalizeDisputeErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything).Return(tt.args.storeBountyIdErr) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) cmdUtilsMock.On("CheckToDoResetDispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return() @@ -514,19 +501,7 @@ func TestHandleDispute(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - blockManagerUtilsMock := new(mocks.BlockManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - utilsPkgMock := new(mocks2.Utils) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - blockManagerUtils = blockManagerUtilsMock - transactionUtils = transactionUtilsMock - - utils.UtilsInterface = utilsPkgMock + SetUpMockInterfaces() utilsMock.On("GetSortedProposedBlockIds", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlockIdsErr) cmdUtilsMock.On("GetBiggestStakeAndId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32")).Return(tt.args.biggestStake, tt.args.biggestStakeId, tt.args.biggestStakeErr) @@ -537,11 +512,11 @@ func TestHandleDispute(t *testing.T) { }, tt.args.mediansErr) utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.proposedBlock, tt.args.proposedBlockErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - blockManagerUtilsMock.On("DisputeBiggestStakeProposed", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputeBiggestStakeTxn, tt.args.disputeBiggestStakeErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.Hash) + blockManagerMock.On("DisputeBiggestStakeProposed", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputeBiggestStakeTxn, tt.args.disputeBiggestStakeErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.Hash) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) cmdUtilsMock.On("CheckDisputeForIds", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.idDisputeTxn, tt.args.idDisputeTxnErr) - utilsPkgMock.On("GetLeafIdOfACollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.leafId, tt.args.leafIdErr) + utilsMock.On("GetLeafIdOfACollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.leafId, tt.args.leafIdErr) cmdUtilsMock.On("Dispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputeErr) utilsMock.On("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything).Return(tt.args.storeBountyIdErr) @@ -659,23 +634,15 @@ func TestGiveSorted(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - blockManagerUtilsMock := new(mocks.BlockManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) + SetUpMockInterfaces() - razorUtils = utilsMock - blockManagerUtils = blockManagerUtilsMock - transactionUtils = transactionUtilsMock - cmdUtils = cmdUtilsMock - - blockManagerUtilsMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.giveSorted, tt.args.giveSortedErr).Once() - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + blockManagerMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.giveSorted, tt.args.giveSortedErr).Once() + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.waitForBlockCompletionErr) utilsMock.On("GetOptions").Return(callOpts) - blockManagerUtilsMock.On("Disputes", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputesMapping, tt.args.disputesMappingErr) + blockManagerMock.On("Disputes", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputesMapping, tt.args.disputesMappingErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - blockManagerUtilsMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.giveSorted, nil) + blockManagerMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.giveSorted, nil) cmdUtilsMock.On("ResetDispute", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything) err := GiveSorted(client, blockManager, txnArgs, epoch, tt.args.leafId, tt.args.sortedValues) @@ -803,14 +770,10 @@ func TestGetLocalMediansData(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() - utilsMock.On("GetProposeDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) - utilsMock.On("ReadFromProposeJsonFile", mock.Anything).Return(tt.args.proposedData, tt.args.proposeDataErr) + pathMock.On("GetProposeDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) + fileUtilsMock.On("ReadFromProposeJsonFile", mock.Anything).Return(tt.args.proposedData, tt.args.proposeDataErr) cmdUtilsMock.On("MakeBlock", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.medians, tt.args.revealedCollectionIds, tt.args.revealedDataMaps, tt.args.mediansErr) utilsMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("GetEpochLastProposed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.lastProposedEpoch, tt.args.lastProposedEpochErr) @@ -879,11 +842,9 @@ func TestGetCollectionIdPositionInBlock(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsPkgMock := new(mocks2.Utils) - - utils.UtilsInterface = utilsPkgMock + SetUpMockInterfaces() - utilsPkgMock.On("GetCollectionIdFromLeafId", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.idToBeDisputed, tt.args.idToBeDisputedErr) + utilsMock.On("GetCollectionIdFromLeafId", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.idToBeDisputed, tt.args.idToBeDisputedErr) ut := &UtilsStruct{} if got := ut.GetCollectionIdPositionInBlock(client, leafId, tt.args.proposedBlock); !reflect.DeepEqual(got, tt.want) { t.Errorf("GetCollectionIdPositionInBlock() = %v, want %v", got, tt.want) @@ -984,21 +945,14 @@ func TestCheckDisputeForIds(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - blockManagerUtilsMock := new(mocks.BlockManagerInterface) - utilsPkgMock := new(mocks2.Utils) - - utils.UtilsInterface = utilsPkgMock - razorUtils = utilsMock - blockManagerUtils = blockManagerUtilsMock - utilsInterface = utilsPkgMock + SetUpMockInterfaces() utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - blockManagerUtilsMock.On("DisputeOnOrderOfIds", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeOnOrderOfIds, tt.args.DisputeOnOrderOfIdsErr) - utilsPkgMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.incrementedGasLimit, tt.args.incrementedGasLimitErr) - blockManagerUtilsMock.On("DisputeCollectionIdShouldBePresent", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeCollectionIdShouldBePresent, tt.args.DisputeCollectionIdShouldBePresentErr) - blockManagerUtilsMock.On("DisputeCollectionIdShouldBeAbsent", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeCollectionIdShouldBeAbsent, tt.args.DisputeCollectionIdShouldBeAbsentErr) - utilsPkgMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything).Return(uint64(2000), nil) + blockManagerMock.On("DisputeOnOrderOfIds", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeOnOrderOfIds, tt.args.DisputeOnOrderOfIdsErr) + gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.incrementedGasLimit, tt.args.incrementedGasLimitErr) + blockManagerMock.On("DisputeCollectionIdShouldBePresent", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeCollectionIdShouldBePresent, tt.args.DisputeCollectionIdShouldBePresentErr) + blockManagerMock.On("DisputeCollectionIdShouldBeAbsent", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeCollectionIdShouldBeAbsent, tt.args.DisputeCollectionIdShouldBeAbsentErr) + gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything).Return(uint64(2000), nil) ut := &UtilsStruct{} got, err := ut.CheckDisputeForIds(client, transactionOpts, epoch, blockIndex, tt.args.idsInProposedBlock, tt.args.revealedCollectionIds) if (err != nil) != tt.wantErr { @@ -1099,19 +1053,11 @@ func TestGetBountyIdFromEvents(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - abiMock := new(mocks.AbiInterface) - utilsPkgMock := new(mocks2.Utils) - abiUtilsMock := new(mocks2.ABIUtils) - utilsPkgMock2 := new(mocks2.Utils) - - utilsInterface = utilsPkgMock2 - abiUtils = abiMock - utils.UtilsInterface = utilsPkgMock - utils.ABIInterface = abiUtilsMock + SetUpMockInterfaces() - utilsPkgMock.On("CalculateBlockNumberAtEpochBeginning", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) + utilsMock.On("EstimateBlockNumberAtEpochBeginning", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) abiUtilsMock.On("Parse", mock.Anything).Return(tt.args.contractABI, tt.args.contractABIErr) - utilsPkgMock.On("FilterLogsWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.FilterQuery")).Return(tt.args.logs, tt.args.logsErr) + clientUtilsMock.On("FilterLogsWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.FilterQuery")).Return(tt.args.logs, tt.args.logsErr) abiMock.On("Unpack", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.data, tt.args.unpackErr) ut := &UtilsStruct{} got, err := ut.GetBountyIdFromEvents(client, blockNumber, bountyHunter) @@ -1158,16 +1104,10 @@ func TestResetDispute(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - blockManagerMock := new(mocks.BlockManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - blockManagerUtils = blockManagerMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() blockManagerMock.On("ResetDispute", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ResetDisputeTxn, tt.args.ResetDisputeTxnErr) - transactionUtilsMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) + transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) ut := &UtilsStruct{} @@ -1191,11 +1131,9 @@ func BenchmarkGetCollectionIdPositionInBlock(b *testing.B) { for _, v := range table { b.Run(fmt.Sprintf("Number_Of_Ids_In_ProposedBlock_%d", v.numOfIds), func(b *testing.B) { for i := 0; i < b.N; i++ { - utilsPkgMock := new(mocks2.Utils) - - utils.UtilsInterface = utilsPkgMock + SetUpMockInterfaces() - utilsPkgMock.On("GetCollectionIdFromLeafId", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(v.idToBeDisputed, nil) + utilsMock.On("GetCollectionIdFromLeafId", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(v.idToBeDisputed, nil) ut := &UtilsStruct{} ut.GetCollectionIdPositionInBlock(client, leafId, bindings.StructsBlock{Ids: getDummyIds(v.numOfIds)}) } @@ -1227,18 +1165,7 @@ func BenchmarkHandleDispute(b *testing.B) { for _, v := range table { b.Run(fmt.Sprintf("Number_Of_Sorted_Blocks_Proposed%d", v.numOfSortedBlocks), func(b *testing.B) { for i := 0; i < b.N; i++ { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - blockManagerUtilsMock := new(mocks.BlockManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - utilsPkgMock := new(mocks2.Utils) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - blockManagerUtils = blockManagerUtilsMock - transactionUtils = transactionUtilsMock - - utils.UtilsInterface = utilsPkgMock + SetUpMockInterfaces() medians := []*big.Int{big.NewInt(6901548), big.NewInt(498307)} revealedCollectionIds := []uint16{1} @@ -1261,12 +1188,11 @@ func BenchmarkHandleDispute(b *testing.B) { cmdUtilsMock.On("GetLocalMediansData", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(proposedData, nil) utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(proposedBlock, nil) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - blockManagerUtilsMock.On("DisputeBiggestStakeProposed", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&Types.Transaction{}, nil) - transactionUtilsMock.On("Hash", mock.Anything).Return(common.BigToHash(big.NewInt(1))) + blockManagerMock.On("DisputeBiggestStakeProposed", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&Types.Transaction{}, nil) + transactionMock.On("Hash", mock.Anything).Return(common.BigToHash(big.NewInt(1))) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) cmdUtilsMock.On("CheckDisputeForIds", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&Types.Transaction{}, nil) - utilsPkgMock.On("IsEqualUint32", mock.Anything, mock.Anything).Return(true, 0) - utilsPkgMock.On("GetLeafIdOfACollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(0, nil) + utilsMock.On("GetLeafIdOfACollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(0, nil) cmdUtilsMock.On("Dispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) utilsMock.On("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything).Return(nil) @@ -1386,23 +1312,14 @@ func TestStoreBountyId(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(mocks2.Utils) - osUtilsMock := new(pathMocks.OSInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - utils.UtilsInterface = utilsPkgMock - utilsInterface = utilsPkgMock - path.OSUtilsInterface = osUtilsMock + SetUpMockInterfaces() - utilsMock.On("GetDisputeDataFileName", mock.AnythingOfType("string")).Return(tt.args.disputeFilePath, tt.args.disputeFilePathErr) - utilsPkgMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + pathMock.On("GetDisputeDataFileName", mock.AnythingOfType("string")).Return(tt.args.disputeFilePath, tt.args.disputeFilePathErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) cmdUtilsMock.On("GetBountyIdFromEvents", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.latestBountyId, tt.args.latestBountyIdErr) - osUtilsMock.On("Stat", mock.Anything).Return(fileInfo, tt.args.statErr) - utilsMock.On("ReadFromDisputeJsonFile", mock.Anything).Return(tt.args.disputeData, tt.args.disputeDataErr) - utilsMock.On("SaveDataToDisputeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) + osPathMock.On("Stat", mock.Anything).Return(fileInfo, tt.args.statErr) + fileUtilsMock.On("ReadFromDisputeJsonFile", mock.Anything).Return(tt.args.disputeData, tt.args.disputeDataErr) + fileUtilsMock.On("SaveDataToDisputeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) ut := &UtilsStruct{} if err := ut.StoreBountyId(client, account); (err != nil) != tt.wantErr { diff --git a/cmd/import.go b/cmd/import.go index 12eaa9e9..21865520 100644 --- a/cmd/import.go +++ b/cmd/import.go @@ -2,14 +2,15 @@ package cmd import ( + "path/filepath" + "razor/path" + "razor/utils" + "strings" + "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/common" "github.com/spf13/cobra" "github.com/spf13/pflag" - pathPkg "path" - "razor/path" - "razor/utils" - "strings" ) var importCmd = &cobra.Command{ @@ -28,8 +29,10 @@ func initialiseImport(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the ImportAccount function func (*UtilsStruct) ExecuteImport(flagSet *pflag.FlagSet) { + config, err := cmdUtils.GetConfigData() + utils.CheckError("Error in getting config: ", err) log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Calling ImportAccount()...") account, err := cmdUtils.ImportAccount() utils.CheckError("Import error: ", err) @@ -46,7 +49,7 @@ func (*UtilsStruct) ImportAccount() (accounts.Account, error) { log.Info("Enter password to protect keystore file") log.Info("The password should be of minimum 8 characters containing least 1 uppercase, lowercase, digit and special character.") password := razorUtils.PasswordPrompt() - razorPath, err := razorUtils.GetDefaultPath() + razorPath, err := pathUtils.GetDefaultPath() if err != nil { log.Error("Error in fetching .razor directory") return accounts.Account{Address: common.Address{0x00}}, err @@ -57,7 +60,7 @@ func (*UtilsStruct) ImportAccount() (accounts.Account, error) { log.Error("Error in parsing private key") return accounts.Account{Address: common.Address{0x00}}, err } - keystoreDir := pathPkg.Join(razorPath, "keystore_files") + keystoreDir := filepath.Join(razorPath, "keystore_files") if _, err := path.OSUtilsInterface.Stat(keystoreDir); path.OSUtilsInterface.IsNotExist(err) { mkdirErr := path.OSUtilsInterface.Mkdir(keystoreDir, 0700) if mkdirErr != nil { diff --git a/cmd/import_test.go b/cmd/import_test.go index 100ba818..ee2631cb 100644 --- a/cmd/import_test.go +++ b/cmd/import_test.go @@ -10,9 +10,7 @@ import ( "github.com/spf13/pflag" "github.com/stretchr/testify/mock" "io/fs" - "razor/cmd/mocks" - "razor/path" - mocks1 "razor/path/mocks" + "razor/core/types" "testing" ) @@ -149,25 +147,16 @@ func TestImportAccount(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - keystoreUtilsMock := new(mocks.KeystoreInterface) - cryptoUtilsMock := new(mocks.CryptoInterface) - osMock := new(mocks1.OSInterface) - - path.OSUtilsInterface = osMock - razorUtils = utilsMock - keystoreUtils = keystoreUtilsMock - cryptoUtils = cryptoUtilsMock + SetUpMockInterfaces() utilsMock.On("PrivateKeyPrompt").Return(tt.args.privateKey) utilsMock.On("PasswordPrompt").Return(tt.args.password) - utilsMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) - cryptoUtilsMock.On("HexToECDSA", mock.AnythingOfType("string")).Return(tt.args.ecdsaPrivateKey, tt.args.ecdsaPrivateKeyErr) - keystoreUtilsMock.On("ImportECDSA", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.importAccount, tt.args.importAccountErr) - osMock.On("Stat", mock.AnythingOfType("string")).Return(fileInfo, tt.args.statErr) - osMock.On("IsNotExist", mock.Anything).Return(tt.args.isNotExist) - osMock.On("Mkdir", mock.Anything, mock.Anything).Return(tt.args.mkdirErr) + pathMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) + cryptoMock.On("HexToECDSA", mock.AnythingOfType("string")).Return(tt.args.ecdsaPrivateKey, tt.args.ecdsaPrivateKeyErr) + keystoreMock.On("ImportECDSA", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.importAccount, tt.args.importAccountErr) + osPathMock.On("Stat", mock.AnythingOfType("string")).Return(fileInfo, tt.args.statErr) + osPathMock.On("IsNotExist", mock.Anything).Return(tt.args.isNotExist) + osPathMock.On("Mkdir", mock.Anything, mock.Anything).Return(tt.args.mkdirErr) utils := &UtilsStruct{} @@ -225,14 +214,11 @@ func TestExecuteImport(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - cmdUtils = cmdUtilsMock - razorUtils = utilsMock + SetUpMockInterfaces() - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("ImportAccount").Return(tt.args.account, tt.args.accountErr) + cmdUtilsMock.On("GetConfigData").Return(types.Configurations{}, nil) utils := &UtilsStruct{} utils.ExecuteImport(flagSet) diff --git a/cmd/initiateWithdraw.go b/cmd/initiateWithdraw.go index 1d2226ec..8568baed 100644 --- a/cmd/initiateWithdraw.go +++ b/cmd/initiateWithdraw.go @@ -43,13 +43,15 @@ func (*UtilsStruct) ExecuteInitiateWithdraw(flagSet *pflag.FlagSet) { log.Debug("ExecuteInitiateWithdraw: Address: ", address) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) - razorUtils.CheckEthBalanceIsZero(client, address) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) stakerId, err := razorUtils.AssignStakerId(flagSet, client, address) utils.CheckError("Error in fetching stakerId: ", err) @@ -63,19 +65,13 @@ func (*UtilsStruct) ExecuteInitiateWithdraw(flagSet *pflag.FlagSet) { utils.CheckError("InitiateWithdraw error: ", err) if txn != core.NilHash { - err := razorUtils.WaitForBlockCompletion(client, txn.String()) + err := razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for initiateWithdraw: ", err) } } //This function handles the unstake lock func (*UtilsStruct) HandleUnstakeLock(client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - _, err := cmdUtils.WaitForAppropriateState(client, "initiateWithdraw", 0, 1, 4) - if err != nil { - log.Error("Error in fetching epoch: ", err) - return core.NilHash, err - } - unstakeLock, err := razorUtils.GetLock(client, account.Address, stakerId, 0) if err != nil { log.Error("Error in fetching unstakeLock") @@ -111,15 +107,18 @@ func (*UtilsStruct) HandleUnstakeLock(client *ethclient.Client, account types.Ac waitFor := big.NewInt(0).Sub(unstakeLock.UnlockAfter, big.NewInt(int64(epoch))) if waitFor.Cmp(big.NewInt(0)) > 0 { - timeRemaining := int64(uint32(waitFor.Int64())) * core.EpochLength - if waitFor.Cmp(big.NewInt(1)) == 0 { - log.Infof("Withdrawal period not reached. Cannot withdraw now, please wait for %d epoch! (approximately %s)", waitFor, razorUtils.SecondsToReadableTime(int(timeRemaining))) - } else { - log.Infof("Withdrawal period not reached. Cannot withdraw now, please wait for %d epochs! (approximately %s)", waitFor, razorUtils.SecondsToReadableTime(int(timeRemaining))) - } + timeRemaining := uint64(waitFor.Int64()) * core.EpochLength + log.Infof("Withdrawal Initiation period not reached. Cannot initiate withdraw now, please wait for %d epoch(s)! (approximately %s)", waitFor, razorUtils.SecondsToReadableTime(int(timeRemaining))) return core.NilHash, nil } + log.Debug("Waiting for appropriate state to initiate withdraw...") + _, err = cmdUtils.WaitForAppropriateState(client, "initiateWithdraw", 0, 1, 4) + if err != nil { + log.Error("Error in fetching state: ", err) + return core.NilHash, err + } + txnArgs := types.TransactionOptions{ Client: client, Password: account.Password, @@ -128,7 +127,7 @@ func (*UtilsStruct) HandleUnstakeLock(client *ethclient.Client, account types.Ac Config: configurations, ContractAddress: core.StakeManagerAddress, MethodName: "initiateWithdraw", - ABI: bindings.StakeManagerABI, + ABI: bindings.StakeManagerMetaData.ABI, Parameters: []interface{}{stakerId}, } txnOpts := razorUtils.GetTxnOpts(txnArgs) @@ -150,9 +149,9 @@ func (*UtilsStruct) InitiateWithdraw(client *ethclient.Client, txnOpts *bind.Tra return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) - - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/initiateWithdraw_test.go b/cmd/initiateWithdraw_test.go index fe2472f8..67e9165e 100644 --- a/cmd/initiateWithdraw_test.go +++ b/cmd/initiateWithdraw_test.go @@ -6,7 +6,6 @@ import ( "crypto/rand" "errors" "math/big" - "razor/cmd/mocks" "razor/core" "razor/core/types" "testing" @@ -54,37 +53,36 @@ func TestHandleUnstakeLock(t *testing.T) { lock: types.Locks{ UnlockAfter: big.NewInt(4), }, - lockErr: nil, - withdrawReleasePeriod: 4, - withdrawReleasePeriodErr: nil, - txnOpts: txnOpts, - epoch: 5, - epochErr: nil, - withdrawHash: common.BigToHash(big.NewInt(1)), - withdrawErr: nil, + withdrawReleasePeriod: 4, + txnOpts: txnOpts, + epoch: 5, + withdrawHash: common.BigToHash(big.NewInt(1)), }, want: common.BigToHash(big.NewInt(1)), wantErr: nil, }, { - name: "Test 2: When withdrawFunds function executes successfully", + name: "Test 2: When there is an error in getting appropriate state", args: args{ - stateErr: errors.New("error in getting epoch"), + lock: types.Locks{ + UnlockAfter: big.NewInt(4), + }, + withdrawReleasePeriod: 4, + txnOpts: txnOpts, + epoch: 5, + stateErr: errors.New("error in getting state"), }, want: core.NilHash, - wantErr: errors.New("error in getting epoch"), + wantErr: errors.New("error in getting state"), }, { - name: "Test 3: When there is an error in getting epoch", + name: "Test 3: When there is an error in getting lock", args: args{ - lockErr: errors.New("lock error"), - withdrawReleasePeriod: 4, - withdrawReleasePeriodErr: nil, - txnOpts: txnOpts, - epoch: 5, - epochErr: nil, - withdrawHash: common.BigToHash(big.NewInt(1)), - withdrawErr: nil, + lockErr: errors.New("lock error"), + withdrawReleasePeriod: 4, + txnOpts: txnOpts, + epoch: 5, + withdrawHash: common.BigToHash(big.NewInt(1)), }, want: core.NilHash, wantErr: errors.New("lock error"), @@ -95,14 +93,10 @@ func TestHandleUnstakeLock(t *testing.T) { lock: types.Locks{ UnlockAfter: big.NewInt(0), }, - lockErr: nil, - withdrawReleasePeriod: 4, - withdrawReleasePeriodErr: nil, - txnOpts: txnOpts, - epoch: 5, - epochErr: nil, - withdrawHash: common.BigToHash(big.NewInt(1)), - withdrawErr: nil, + withdrawReleasePeriod: 4, + txnOpts: txnOpts, + epoch: 5, + withdrawHash: common.BigToHash(big.NewInt(1)), }, want: core.NilHash, wantErr: errors.New("unstake Razors before withdrawing"), @@ -113,13 +107,10 @@ func TestHandleUnstakeLock(t *testing.T) { lock: types.Locks{ UnlockAfter: big.NewInt(4), }, - lockErr: nil, withdrawReleasePeriodErr: errors.New("withdrawReleasePeriod error"), txnOpts: txnOpts, epoch: 5, - epochErr: nil, withdrawHash: common.BigToHash(big.NewInt(1)), - withdrawErr: nil, }, want: core.NilHash, wantErr: errors.New("withdrawReleasePeriod error"), @@ -130,13 +121,10 @@ func TestHandleUnstakeLock(t *testing.T) { lock: types.Locks{ UnlockAfter: big.NewInt(4), }, - lockErr: nil, - withdrawReleasePeriod: 4, - withdrawReleasePeriodErr: nil, - txnOpts: txnOpts, - epochErr: errors.New("epoch error"), - withdrawHash: common.BigToHash(big.NewInt(1)), - withdrawErr: nil, + withdrawReleasePeriod: 4, + txnOpts: txnOpts, + epochErr: errors.New("epoch error"), + withdrawHash: common.BigToHash(big.NewInt(1)), }, want: core.NilHash, wantErr: errors.New("epoch error"), @@ -147,14 +135,10 @@ func TestHandleUnstakeLock(t *testing.T) { lock: types.Locks{ UnlockAfter: big.NewInt(4), }, - lockErr: nil, - withdrawReleasePeriod: 4, - withdrawReleasePeriodErr: nil, - txnOpts: txnOpts, - epoch: 9, - epochErr: nil, - withdrawHash: common.BigToHash(big.NewInt(1)), - withdrawErr: nil, + withdrawReleasePeriod: 4, + txnOpts: txnOpts, + epoch: 9, + withdrawHash: common.BigToHash(big.NewInt(1)), }, want: core.NilHash, wantErr: nil, @@ -165,15 +149,11 @@ func TestHandleUnstakeLock(t *testing.T) { lock: types.Locks{ UnlockAfter: big.NewInt(4), }, - lockErr: nil, - withdrawReleasePeriod: 4, - withdrawReleasePeriodErr: nil, - txnOpts: txnOpts, - epoch: 3, - epochErr: nil, - time: "10 minutes 0 seconds ", - withdrawHash: common.BigToHash(big.NewInt(1)), - withdrawErr: nil, + withdrawReleasePeriod: 4, + txnOpts: txnOpts, + epoch: 3, + time: "10 minutes 0 seconds ", + withdrawHash: common.BigToHash(big.NewInt(1)), }, want: core.NilHash, wantErr: nil, @@ -184,13 +164,10 @@ func TestHandleUnstakeLock(t *testing.T) { lock: types.Locks{ UnlockAfter: big.NewInt(4), }, - lockErr: nil, - withdrawReleasePeriod: 1, - withdrawReleasePeriodErr: nil, - txnOpts: txnOpts, - epoch: 5, - epochErr: nil, - withdrawErr: errors.New("withdraw error"), + withdrawReleasePeriod: 1, + txnOpts: txnOpts, + epoch: 5, + withdrawErr: errors.New("withdraw error"), }, want: core.NilHash, wantErr: errors.New("withdraw error"), @@ -201,15 +178,11 @@ func TestHandleUnstakeLock(t *testing.T) { lock: types.Locks{ UnlockAfter: big.NewInt(4), }, - lockErr: nil, - withdrawReleasePeriod: 4, - withdrawReleasePeriodErr: nil, - txnOpts: txnOpts, - epoch: 2, - epochErr: nil, - time: "20 minutes 0 seconds ", - withdrawHash: common.BigToHash(big.NewInt(1)), - withdrawErr: nil, + withdrawReleasePeriod: 4, + txnOpts: txnOpts, + epoch: 2, + time: "20 minutes 0 seconds ", + withdrawHash: common.BigToHash(big.NewInt(1)), }, want: core.NilHash, wantErr: nil, @@ -217,15 +190,7 @@ func TestHandleUnstakeLock(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - cmdUtils = cmdUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() cmdUtilsMock.On("WaitForAppropriateState", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) utilsMock.On("GetLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.lock, tt.args.lockErr) @@ -295,15 +260,10 @@ func TestWithdraw(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock - - stakeManagerUtilsMock.On("InitiateWithdraw", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.withdrawTxn, tt.args.withdrawErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + stakeManagerMock.On("InitiateWithdraw", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.withdrawTxn, tt.args.withdrawErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} got, err := utils.InitiateWithdraw(client, txnOpts, stakerId) @@ -412,20 +372,13 @@ func TestExecuteWithdraw(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - flagSetUtils = flagSetUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagSetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) - utilsMock.On("CheckEthBalanceIsZero", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return() + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) utilsMock.On("AssignStakerId", flagSet, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("HandleUnstakeLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.withdrawHash, tt.args.withdrawErr) diff --git a/cmd/interface.go b/cmd/interface.go index 7278a08a..3934c810 100644 --- a/cmd/interface.go +++ b/cmd/interface.go @@ -20,7 +20,6 @@ import ( "github.com/spf13/pflag" ) -//go:generate mockery --name UtilsInterface --output ./mocks/ --case=underscore //go:generate mockery --name FlagSetInterface --output ./mocks/ --case=underscore //go:generate mockery --name UtilsCmdInterface --output ./mocks/ --case=underscore //go:generate mockery --name StakeManagerInterface --output ./mocks/ --case=underscore @@ -37,7 +36,6 @@ import ( //go:generate mockery --name AbiInterface --output ./mocks/ --case=underscore //go:generate mockery --name OSInterface --output ./mocks/ --case=underscore -var razorUtils UtilsInterface var flagSetUtils FlagSetInterface var cmdUtils UtilsCmdInterface var stakeManagerUtils StakeManagerInterface @@ -54,82 +52,6 @@ var stringUtils StringInterface var abiUtils AbiInterface var osUtils OSInterface -type UtilsInterface interface { - GetConfigFilePath() (string, error) - GetEpoch(client *ethclient.Client) (uint32, error) - GetOptions() bind.CallOpts - CalculateBlockTime(client *ethclient.Client) int64 - GetTxnOpts(transactionData types.TransactionOptions) *bind.TransactOpts - AssignPassword(flagSet *pflag.FlagSet) string - GetStringAddress(flagSet *pflag.FlagSet) (string, error) - GetUint32BountyId(flagSet *pflag.FlagSet) (uint32, error) - ConnectToClient(provider string) *ethclient.Client - WaitForBlockCompletion(client *ethclient.Client, hashToRead string) error - GetNumActiveCollections(client *ethclient.Client) (uint16, error) - GetRogueRandomValue(value int) *big.Int - GetRogueRandomMedianValue() uint32 - GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32) (*big.Int, error) - GetDelayedState(client *ethclient.Client, buffer int32) (int64, error) - GetDefaultPath() (string, error) - GetJobFilePath() (string, error) - FetchBalance(client *ethclient.Client, accountAddress string) (*big.Int, error) - IsFlagPassed(name string) bool - GetAmountInWei(amount *big.Int) *big.Int - CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) *big.Int - GetAmountInDecimal(amountInWei *big.Int) *big.Float - GetEpochLastCommitted(client *ethclient.Client, stakerId uint32) (uint32, error) - GetCommitments(client *ethclient.Client, address string) ([32]byte, error) - AllZero(bytesValue [32]byte) bool - ConvertUintArrayToUint16Array(uintArr []uint) []uint16 - ConvertUint32ArrayToBigIntArray(uint32Array []uint32) []*big.Int - GetJobs(client *ethclient.Client) ([]bindings.StructsJob, error) - CheckEthBalanceIsZero(client *ethclient.Client, address string) - AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) - GetLock(client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) - GetStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) - GetUpdatedStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) - GetStakedToken(client *ethclient.Client, address common.Address) *bindings.StakedToken - ConvertSRZRToRZR(sAmount *big.Int, currentStake *big.Int, totalSupply *big.Int) *big.Int - ConvertRZRToSRZR(sAmount *big.Int, currentStake *big.Int, totalSupply *big.Int) (*big.Int, error) - GetWithdrawInitiationPeriod(client *ethclient.Client) (uint16, error) - GetCollections(client *ethclient.Client) ([]bindings.StructsCollection, error) - GetInfluenceSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) - GetStakerId(client *ethclient.Client, address string) (uint32, error) - GetNumberOfStakers(client *ethclient.Client) (uint32, error) - GetNumberOfProposedBlocks(client *ethclient.Client, epoch uint32) (uint8, error) - GetMaxAltBlocks(client *ethclient.Client) (uint8, error) - GetProposedBlock(client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) - GetEpochLastRevealed(client *ethclient.Client, stakerId uint32) (uint32, error) - GetVoteValue(client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) - GetTotalInfluenceRevealed(client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) - GetActiveCollections(client *ethclient.Client) ([]uint16, error) - GetBlockManager(client *ethclient.Client) *bindings.BlockManager - GetSortedProposedBlockIds(client *ethclient.Client, epoch uint32) ([]uint32, error) - PrivateKeyPrompt() string - PasswordPrompt() string - GetMaxCommission(client *ethclient.Client) (uint8, error) - GetEpochLimitForUpdateCommission(client *ethclient.Client) (uint16, error) - GetStakeSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) - GetStake(client *ethclient.Client, stakerId uint32) (*big.Int, error) - ConvertWeiToEth(data *big.Int) (*big.Float, error) - WaitTillNextNSecs(seconds int32) - DeleteJobFromJSON(s string, jobId string) error - AddJobToJSON(s string, job *types.StructsJob) error - GetStakerSRZRBalance(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) - SecondsToReadableTime(time int) string - SaveDataToCommitJsonFile(flePath string, epoch uint32, commitFileData types.CommitData) error - ReadFromCommitJsonFile(filePath string) (types.CommitFileData, error) - SaveDataToProposeJsonFile(flePath string, proposeFileData types.ProposeFileData) error - ReadFromProposeJsonFile(filePath string) (types.ProposeFileData, error) - SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []uint32) error - ReadFromDisputeJsonFile(filePath string) (types.DisputeFileData, error) - AssignLogFile(flagSet *pflag.FlagSet) - GetCommitDataFileName(address string) (string, error) - GetProposeDataFileName(address string) (string, error) - GetDisputeDataFileName(address string) (string, error) - GetEpochLastProposed(client *ethclient.Client, stakerId uint32) (uint32, error) -} - type StakeManagerInterface interface { Stake(client *ethclient.Client, txnOpts *bind.TransactOpts, epoch uint32, amount *big.Int) (*Types.Transaction, error) ResetUnstakeLock(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32) (*Types.Transaction, error) @@ -140,8 +62,8 @@ type StakeManagerInterface interface { Unstake(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32, sAmount *big.Int) (*Types.Transaction, error) RedeemBounty(client *ethclient.Client, opts *bind.TransactOpts, bountyId uint32) (*Types.Transaction, error) UpdateCommission(client *ethclient.Client, opts *bind.TransactOpts, commission uint8) (*Types.Transaction, error) - ApproveUnstake(client *ethclient.Client, opts *bind.TransactOpts, staker bindings.StructsStaker, amount *big.Int) (*Types.Transaction, error) - ClaimStakeReward(client *ethclient.Client, opts *bind.TransactOpts) (*Types.Transaction, error) + ApproveUnstake(client *ethclient.Client, opts *bind.TransactOpts, stakerTokenAddress common.Address, amount *big.Int) (*Types.Transaction, error) + ClaimStakerReward(client *ethclient.Client, opts *bind.TransactOpts) (*Types.Transaction, error) //Getter methods StakerInfo(client *ethclient.Client, opts *bind.CallOpts, stakerId uint32) (types.Staker, error) @@ -189,6 +111,7 @@ type AssetManagerInterface interface { type FlagSetInterface interface { GetStringProvider(flagSet *pflag.FlagSet) (string, error) + GetStringAlternateProvider(flagSet *pflag.FlagSet) (string, error) GetFloat32GasMultiplier(flagSet *pflag.FlagSet) (float32, error) GetInt32Buffer(flagSet *pflag.FlagSet) (int32, error) GetInt32Wait(flagSet *pflag.FlagSet) (int32, error) @@ -197,8 +120,10 @@ type FlagSetInterface interface { GetUint64GasLimitOverride(flagSet *pflag.FlagSet) (uint64, error) GetStringLogLevel(flagSet *pflag.FlagSet) (string, error) GetInt64RPCTimeout(flagSet *pflag.FlagSet) (int64, error) + GetInt64HTTPTimeout(flagSet *pflag.FlagSet) (int64, error) GetUint32BountyId(flagSet *pflag.FlagSet) (uint32, error) GetRootStringProvider() (string, error) + GetRootStringAlternateProvider() (string, error) GetRootFloat32GasMultiplier() (float32, error) GetRootInt32Buffer() (int32, error) GetRootInt32Wait() (int32, error) @@ -207,6 +132,10 @@ type FlagSetInterface interface { GetRootFloat32GasLimit() (float32, error) GetRootUint64GasLimitOverride() (uint64, error) GetRootInt64RPCTimeout() (int64, error) + GetRootInt64HTTPTimeout() (int64, error) + GetRootIntLogFileMaxSize() (int, error) + GetRootIntLogFileMaxBackups() (int, error) + GetRootIntLogFileMaxAge() (int, error) GetStringFrom(flagSet *pflag.FlagSet) (string, error) GetStringTo(flagSet *pflag.FlagSet) (string, error) GetStringAddress(flagSet *pflag.FlagSet) (string, error) @@ -216,7 +145,6 @@ type FlagSetInterface interface { GetStringSelector(flagSet *pflag.FlagSet) (string, error) GetInt8Power(flagSet *pflag.FlagSet) (int8, error) GetUint8Weight(flagSet *pflag.FlagSet) (uint8, error) - GetUint16AssetId(flagSet *pflag.FlagSet) (uint16, error) GetUint8SelectorType(flagSet *pflag.FlagSet) (uint8, error) GetStringStatus(flagSet *pflag.FlagSet) (string, error) GetUint8Commission(flagSet *pflag.FlagSet) (uint8, error) @@ -233,11 +161,15 @@ type FlagSetInterface interface { GetStringExposeMetrics(flagSet *pflag.FlagSet) (string, error) GetStringCertFile(flagSet *pflag.FlagSet) (string, error) GetStringCertKey(flagSet *pflag.FlagSet) (string, error) + GetIntLogFileMaxSize(flagSet *pflag.FlagSet) (int, error) + GetIntLogFileMaxBackups(flagSet *pflag.FlagSet) (int, error) + GetIntLogFileMaxAge(flagSet *pflag.FlagSet) (int, error) } type UtilsCmdInterface interface { SetConfig(flagSet *pflag.FlagSet) error GetProvider() (string, error) + GetAlternateProvider() (string, error) GetMultiplier() (float32, error) GetWaitTime() (int32, error) GetGasPrice() (int32, error) @@ -246,6 +178,10 @@ type UtilsCmdInterface interface { GetGasLimitOverride() (uint64, error) GetBufferPercent() (int32, error) GetRPCTimeout() (int64, error) + GetHTTPTimeout() (int64, error) + GetLogFileMaxSize() (int, error) + GetLogFileMaxBackups() (int, error) + GetLogFileMaxAge() (int, error) GetConfigData() (types.Configurations, error) ExecuteClaimBounty(flagSet *pflag.FlagSet) ClaimBounty(config types.Configurations, client *ethclient.Client, redeemBountyInput types.RedeemBountyInput) (common.Hash, error) @@ -257,7 +193,7 @@ type UtilsCmdInterface interface { AssignAmountInWei(flagSet *pflag.FlagSet) (*big.Int, error) ExecuteTransfer(flagSet *pflag.FlagSet) Transfer(client *ethclient.Client, config types.Configurations, transferInput types.TransferInput) (common.Hash, error) - HandleRevealState(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error + CheckForLastCommitted(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error Reveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, commitData types.CommitData, signature []byte) (common.Hash, error) GenerateTreeRevealData(merkleTree [][][]byte, commitData types.CommitData) bindings.StructsMerkleTree IndexRevealEventsOfCurrentEpoch(client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) @@ -271,7 +207,7 @@ type UtilsCmdInterface interface { GetJobList(client *ethclient.Client) error ExecuteUnstake(flagSet *pflag.FlagSet) Unstake(config types.Configurations, client *ethclient.Client, input types.UnstakeInput) (common.Hash, error) - ApproveUnstake(client *ethclient.Client, staker bindings.StructsStaker, txnArgs types.TransactionOptions) (common.Hash, error) + ApproveUnstake(client *ethclient.Client, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) ExecuteInitiateWithdraw(flagSet *pflag.FlagSet) ExecuteUnlockWithdraw(flagSet *pflag.FlagSet) InitiateWithdraw(client *ethclient.Client, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) @@ -289,7 +225,6 @@ type UtilsCmdInterface interface { GetStakerInfo(client *ethclient.Client, stakerId uint32) error ExecuteUpdateCollection(flagSet *pflag.FlagSet) UpdateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) - InfluencedMedian(sortedVotes []*big.Int, totalInfluenceRevealed *big.Int) *big.Int MakeBlock(client *ethclient.Client, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) IsElectedProposer(proposer types.ElectedProposer, currentStakerStake *big.Int) bool GetSortedRevealedValues(client *ethclient.Client, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) @@ -384,7 +319,6 @@ type AbiUtils struct{} type OSUtils struct{} func InitializeInterfaces() { - razorUtils = Utils{} flagSetUtils = FLagSetUtils{} cmdUtils = &UtilsStruct{} stakeManagerUtils = StakeManagerUtils{} diff --git a/cmd/jobList_test.go b/cmd/jobList_test.go index dbe9f165..ba5d1955 100644 --- a/cmd/jobList_test.go +++ b/cmd/jobList_test.go @@ -5,7 +5,6 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "razor/cmd/mocks" "razor/core/types" "razor/pkg/bindings" "testing" @@ -65,9 +64,7 @@ func TestGetJobList(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - razorUtils = utilsMock + SetUpMockInterfaces() utilsMock.On("GetJobs", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.jobList, tt.args.jobListErr) utils := &UtilsStruct{} @@ -136,14 +133,9 @@ func TestExecuteJobList(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("GetJobList", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.jobListErr) diff --git a/cmd/listAccounts.go b/cmd/listAccounts.go index ebf9469f..c0505fde 100644 --- a/cmd/listAccounts.go +++ b/cmd/listAccounts.go @@ -2,11 +2,12 @@ package cmd import ( + "path/filepath" + "razor/utils" + "github.com/ethereum/go-ethereum/accounts" "github.com/spf13/cobra" "github.com/spf13/pflag" - pathPkg "path" - "razor/utils" ) var listAccountsCmd = &cobra.Command{ @@ -25,8 +26,12 @@ func initialiseListAccounts(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the ListAccounts function func (*UtilsStruct) ExecuteListAccounts(flagSet *pflag.FlagSet) { + config, err := cmdUtils.GetConfigData() + utils.CheckError("Error in getting config: ", err) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) + log.Debug("ExecuteListAccounts: Calling ListAccounts()...") allAccounts, err := cmdUtils.ListAccounts() utils.CheckError("ListAccounts error: ", err) @@ -38,14 +43,14 @@ func (*UtilsStruct) ExecuteListAccounts(flagSet *pflag.FlagSet) { //This function is used to list all accessible accounts func (*UtilsStruct) ListAccounts() ([]accounts.Account, error) { - path, err := razorUtils.GetDefaultPath() + path, err := pathUtils.GetDefaultPath() if err != nil { log.Error("Error in fetching .razor directory") return nil, err } log.Debug("ListAccounts: .razor directory path: ", path) - keystorePath := pathPkg.Join(path, "keystore_files") + keystorePath := filepath.Join(path, "keystore_files") log.Debug("ListAccounts: Keystore path: ", keystorePath) return keystoreUtils.Accounts(keystorePath), nil } diff --git a/cmd/listAccounts_test.go b/cmd/listAccounts_test.go index 9ac14dfc..9f0d74f9 100644 --- a/cmd/listAccounts_test.go +++ b/cmd/listAccounts_test.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "razor/cmd/mocks" + "razor/core/types" "reflect" "testing" ) @@ -57,15 +57,10 @@ func TestListAccounts(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - keystoreUtilsMock := new(mocks.KeystoreInterface) - - razorUtils = utilsMock - keystoreUtils = keystoreUtilsMock - - utilsMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) - keystoreUtilsMock.On("Accounts", mock.AnythingOfType("string")).Return(tt.args.accounts) + pathMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) + keystoreMock.On("Accounts", mock.AnythingOfType("string")).Return(tt.args.accounts) utils := &UtilsStruct{} got, err := utils.ListAccounts() @@ -129,14 +124,11 @@ func TestExecuteListAccounts(t *testing.T) { log.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("ListAccounts").Return(tt.args.allAccounts, tt.args.allAccountsErr) + cmdUtilsMock.On("GetConfigData").Return(types.Configurations{}, nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/mocks/flag_set_interface.go b/cmd/mocks/flag_set_interface.go index 9788347a..13b98125 100644 --- a/cmd/mocks/flag_set_interface.go +++ b/cmd/mocks/flag_set_interface.go @@ -159,6 +159,27 @@ func (_m *FlagSetInterface) GetInt32Wait(flagSet *pflag.FlagSet) (int32, error) return r0, r1 } +// GetInt64HTTPTimeout provides a mock function with given fields: flagSet +func (_m *FlagSetInterface) GetInt64HTTPTimeout(flagSet *pflag.FlagSet) (int64, error) { + ret := _m.Called(flagSet) + + var r0 int64 + if rf, ok := ret.Get(0).(func(*pflag.FlagSet) int64); ok { + r0 = rf(flagSet) + } else { + r0 = ret.Get(0).(int64) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*pflag.FlagSet) error); ok { + r1 = rf(flagSet) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetInt64RPCTimeout provides a mock function with given fields: flagSet func (_m *FlagSetInterface) GetInt64RPCTimeout(flagSet *pflag.FlagSet) (int64, error) { ret := _m.Called(flagSet) @@ -201,6 +222,69 @@ func (_m *FlagSetInterface) GetInt8Power(flagSet *pflag.FlagSet) (int8, error) { return r0, r1 } +// GetIntLogFileMaxAge provides a mock function with given fields: flagSet +func (_m *FlagSetInterface) GetIntLogFileMaxAge(flagSet *pflag.FlagSet) (int, error) { + ret := _m.Called(flagSet) + + var r0 int + if rf, ok := ret.Get(0).(func(*pflag.FlagSet) int); ok { + r0 = rf(flagSet) + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*pflag.FlagSet) error); ok { + r1 = rf(flagSet) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetIntLogFileMaxBackups provides a mock function with given fields: flagSet +func (_m *FlagSetInterface) GetIntLogFileMaxBackups(flagSet *pflag.FlagSet) (int, error) { + ret := _m.Called(flagSet) + + var r0 int + if rf, ok := ret.Get(0).(func(*pflag.FlagSet) int); ok { + r0 = rf(flagSet) + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*pflag.FlagSet) error); ok { + r1 = rf(flagSet) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetIntLogFileMaxSize provides a mock function with given fields: flagSet +func (_m *FlagSetInterface) GetIntLogFileMaxSize(flagSet *pflag.FlagSet) (int, error) { + ret := _m.Called(flagSet) + + var r0 int + if rf, ok := ret.Get(0).(func(*pflag.FlagSet) int); ok { + r0 = rf(flagSet) + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*pflag.FlagSet) error); ok { + r1 = rf(flagSet) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetRootFloat32GasLimit provides a mock function with given fields: func (_m *FlagSetInterface) GetRootFloat32GasLimit() (float32, error) { ret := _m.Called() @@ -306,6 +390,27 @@ func (_m *FlagSetInterface) GetRootInt32Wait() (int32, error) { return r0, r1 } +// GetRootInt64HTTPTimeout provides a mock function with given fields: +func (_m *FlagSetInterface) GetRootInt64HTTPTimeout() (int64, error) { + ret := _m.Called() + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetRootInt64RPCTimeout provides a mock function with given fields: func (_m *FlagSetInterface) GetRootInt64RPCTimeout() (int64, error) { ret := _m.Called() @@ -327,6 +432,90 @@ func (_m *FlagSetInterface) GetRootInt64RPCTimeout() (int64, error) { return r0, r1 } +// GetRootIntLogFileMaxAge provides a mock function with given fields: +func (_m *FlagSetInterface) GetRootIntLogFileMaxAge() (int, error) { + ret := _m.Called() + + var r0 int + if rf, ok := ret.Get(0).(func() int); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetRootIntLogFileMaxBackups provides a mock function with given fields: +func (_m *FlagSetInterface) GetRootIntLogFileMaxBackups() (int, error) { + ret := _m.Called() + + var r0 int + if rf, ok := ret.Get(0).(func() int); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetRootIntLogFileMaxSize provides a mock function with given fields: +func (_m *FlagSetInterface) GetRootIntLogFileMaxSize() (int, error) { + ret := _m.Called() + + var r0 int + if rf, ok := ret.Get(0).(func() int); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetRootStringAlternateProvider provides a mock function with given fields: +func (_m *FlagSetInterface) GetRootStringAlternateProvider() (string, error) { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetRootStringLogLevel provides a mock function with given fields: func (_m *FlagSetInterface) GetRootStringLogLevel() (string, error) { ret := _m.Called() @@ -411,6 +600,27 @@ func (_m *FlagSetInterface) GetStringAddress(flagSet *pflag.FlagSet) (string, er return r0, r1 } +// GetStringAlternateProvider provides a mock function with given fields: flagSet +func (_m *FlagSetInterface) GetStringAlternateProvider(flagSet *pflag.FlagSet) (string, error) { + ret := _m.Called(flagSet) + + var r0 string + if rf, ok := ret.Get(0).(func(*pflag.FlagSet) string); ok { + r0 = rf(flagSet) + } else { + r0 = ret.Get(0).(string) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*pflag.FlagSet) error); ok { + r1 = rf(flagSet) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetStringCertFile provides a mock function with given fields: flagSet func (_m *FlagSetInterface) GetStringCertFile(flagSet *pflag.FlagSet) (string, error) { ret := _m.Called(flagSet) @@ -709,27 +919,6 @@ func (_m *FlagSetInterface) GetStringValue(flagSet *pflag.FlagSet) (string, erro return r0, r1 } -// GetUint16AssetId provides a mock function with given fields: flagSet -func (_m *FlagSetInterface) GetUint16AssetId(flagSet *pflag.FlagSet) (uint16, error) { - ret := _m.Called(flagSet) - - var r0 uint16 - if rf, ok := ret.Get(0).(func(*pflag.FlagSet) uint16); ok { - r0 = rf(flagSet) - } else { - r0 = ret.Get(0).(uint16) - } - - var r1 error - if rf, ok := ret.Get(1).(func(*pflag.FlagSet) error); ok { - r1 = rf(flagSet) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // GetUint16CollectionId provides a mock function with given fields: flagSet func (_m *FlagSetInterface) GetUint16CollectionId(flagSet *pflag.FlagSet) (uint16, error) { ret := _m.Called(flagSet) diff --git a/cmd/mocks/stake_manager_interface.go b/cmd/mocks/stake_manager_interface.go index 51958b1f..f0661906 100644 --- a/cmd/mocks/stake_manager_interface.go +++ b/cmd/mocks/stake_manager_interface.go @@ -4,10 +4,11 @@ package mocks import ( big "math/big" - bindings "razor/pkg/bindings" bind "github.com/ethereum/go-ethereum/accounts/abi/bind" + common "github.com/ethereum/go-ethereum/common" + coretypes "razor/core/types" ethclient "github.com/ethereum/go-ethereum/ethclient" @@ -22,13 +23,13 @@ type StakeManagerInterface struct { mock.Mock } -// ApproveUnstake provides a mock function with given fields: client, opts, staker, amount -func (_m *StakeManagerInterface) ApproveUnstake(client *ethclient.Client, opts *bind.TransactOpts, staker bindings.StructsStaker, amount *big.Int) (*types.Transaction, error) { - ret := _m.Called(client, opts, staker, amount) +// ApproveUnstake provides a mock function with given fields: client, opts, stakerTokenAddress, amount +func (_m *StakeManagerInterface) ApproveUnstake(client *ethclient.Client, opts *bind.TransactOpts, stakerTokenAddress common.Address, amount *big.Int) (*types.Transaction, error) { + ret := _m.Called(client, opts, stakerTokenAddress, amount) var r0 *types.Transaction - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, bindings.StructsStaker, *big.Int) *types.Transaction); ok { - r0 = rf(client, opts, staker, amount) + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) *types.Transaction); ok { + r0 = rf(client, opts, stakerTokenAddress, amount) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*types.Transaction) @@ -36,8 +37,8 @@ func (_m *StakeManagerInterface) ApproveUnstake(client *ethclient.Client, opts * } var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, bindings.StructsStaker, *big.Int) error); ok { - r1 = rf(client, opts, staker, amount) + if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) error); ok { + r1 = rf(client, opts, stakerTokenAddress, amount) } else { r1 = ret.Error(1) } @@ -45,8 +46,8 @@ func (_m *StakeManagerInterface) ApproveUnstake(client *ethclient.Client, opts * return r0, r1 } -// ClaimStakeReward provides a mock function with given fields: client, opts -func (_m *StakeManagerInterface) ClaimStakeReward(client *ethclient.Client, opts *bind.TransactOpts) (*types.Transaction, error) { +// ClaimStakerReward provides a mock function with given fields: client, opts +func (_m *StakeManagerInterface) ClaimStakerReward(client *ethclient.Client, opts *bind.TransactOpts) (*types.Transaction, error) { ret := _m.Called(client, opts) var r0 *types.Transaction diff --git a/cmd/mocks/utils_cmd_interface.go b/cmd/mocks/utils_cmd_interface.go index 960bbbd9..2a96d3ac 100644 --- a/cmd/mocks/utils_cmd_interface.go +++ b/cmd/mocks/utils_cmd_interface.go @@ -54,13 +54,13 @@ func (_m *UtilsCmdInterface) Approve(txnArgs types.TransactionOptions) (common.H return r0, r1 } -// ApproveUnstake provides a mock function with given fields: client, staker, txnArgs -func (_m *UtilsCmdInterface) ApproveUnstake(client *ethclient.Client, staker bindings.StructsStaker, txnArgs types.TransactionOptions) (common.Hash, error) { - ret := _m.Called(client, staker, txnArgs) +// ApproveUnstake provides a mock function with given fields: client, stakerTokenAddress, txnArgs +func (_m *UtilsCmdInterface) ApproveUnstake(client *ethclient.Client, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) { + ret := _m.Called(client, stakerTokenAddress, txnArgs) var r0 common.Hash - if rf, ok := ret.Get(0).(func(*ethclient.Client, bindings.StructsStaker, types.TransactionOptions) common.Hash); ok { - r0 = rf(client, staker, txnArgs) + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, types.TransactionOptions) common.Hash); ok { + r0 = rf(client, stakerTokenAddress, txnArgs) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) @@ -68,8 +68,8 @@ func (_m *UtilsCmdInterface) ApproveUnstake(client *ethclient.Client, staker bin } var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, bindings.StructsStaker, types.TransactionOptions) error); ok { - r1 = rf(client, staker, txnArgs) + if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address, types.TransactionOptions) error); ok { + r1 = rf(client, stakerTokenAddress, txnArgs) } else { r1 = ret.Error(1) } @@ -176,6 +176,20 @@ func (_m *UtilsCmdInterface) CheckDisputeForIds(client *ethclient.Client, transa return r0, r1 } +// CheckForLastCommitted provides a mock function with given fields: client, staker, epoch +func (_m *UtilsCmdInterface) CheckForLastCommitted(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { + ret := _m.Called(client, staker, epoch) + + var r0 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, bindings.StructsStaker, uint32) error); ok { + r0 = rf(client, staker, epoch) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // CheckToDoResetDispute provides a mock function with given fields: client, blockManager, txnOpts, epoch, sortedValues func (_m *UtilsCmdInterface) CheckToDoResetDispute(client *ethclient.Client, blockManager *bindings.BlockManager, txnOpts *bind.TransactOpts, epoch uint32, sortedValues []*big.Int) { _m.Called(client, blockManager, txnOpts, epoch, sortedValues) @@ -493,6 +507,27 @@ func (_m *UtilsCmdInterface) GenerateTreeRevealData(merkleTree [][][]byte, commi return r0 } +// GetAlternateProvider provides a mock function with given fields: +func (_m *UtilsCmdInterface) GetAlternateProvider() (string, error) { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetBiggestStakeAndId provides a mock function with given fields: client, address, epoch func (_m *UtilsCmdInterface) GetBiggestStakeAndId(client *ethclient.Client, address string, epoch uint32) (*big.Int, uint32, error) { ret := _m.Called(client, address, epoch) @@ -707,6 +742,27 @@ func (_m *UtilsCmdInterface) GetGasPrice() (int32, error) { return r0, r1 } +// GetHTTPTimeout provides a mock function with given fields: +func (_m *UtilsCmdInterface) GetHTTPTimeout() (int64, error) { + ret := _m.Called() + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetIteration provides a mock function with given fields: client, proposer, bufferPercent func (_m *UtilsCmdInterface) GetIteration(client *ethclient.Client, proposer types.ElectedProposer, bufferPercent int32) int { ret := _m.Called(client, proposer, bufferPercent) @@ -756,6 +812,69 @@ func (_m *UtilsCmdInterface) GetLocalMediansData(client *ethclient.Client, accou return r0, r1 } +// GetLogFileMaxAge provides a mock function with given fields: +func (_m *UtilsCmdInterface) GetLogFileMaxAge() (int, error) { + ret := _m.Called() + + var r0 int + if rf, ok := ret.Get(0).(func() int); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetLogFileMaxBackups provides a mock function with given fields: +func (_m *UtilsCmdInterface) GetLogFileMaxBackups() (int, error) { + ret := _m.Called() + + var r0 int + if rf, ok := ret.Get(0).(func() int); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetLogFileMaxSize provides a mock function with given fields: +func (_m *UtilsCmdInterface) GetLogFileMaxSize() (int, error) { + ret := _m.Called() + + var r0 int + if rf, ok := ret.Get(0).(func() int); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetLogLevel provides a mock function with given fields: func (_m *UtilsCmdInterface) GetLogLevel() (string, error) { ret := _m.Called() @@ -1024,20 +1143,6 @@ func (_m *UtilsCmdInterface) HandleExit() { _m.Called() } -// HandleRevealState provides a mock function with given fields: client, staker, epoch -func (_m *UtilsCmdInterface) HandleRevealState(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { - ret := _m.Called(client, staker, epoch) - - var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, bindings.StructsStaker, uint32) error); ok { - r0 = rf(client, staker, epoch) - } else { - r0 = ret.Error(0) - } - - return r0 -} - // HandleUnstakeLock provides a mock function with given fields: client, account, configurations, stakerId func (_m *UtilsCmdInterface) HandleUnstakeLock(client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { ret := _m.Called(client, account, configurations, stakerId) @@ -1128,22 +1233,6 @@ func (_m *UtilsCmdInterface) IndexRevealEventsOfCurrentEpoch(client *ethclient.C return r0, r1 } -// InfluencedMedian provides a mock function with given fields: sortedVotes, totalInfluenceRevealed -func (_m *UtilsCmdInterface) InfluencedMedian(sortedVotes []*big.Int, totalInfluenceRevealed *big.Int) *big.Int { - ret := _m.Called(sortedVotes, totalInfluenceRevealed) - - var r0 *big.Int - if rf, ok := ret.Get(0).(func([]*big.Int, *big.Int) *big.Int); ok { - r0 = rf(sortedVotes, totalInfluenceRevealed) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - return r0 -} - // InitiateCommit provides a mock function with given fields: client, config, account, epoch, stakerId, rogueData func (_m *UtilsCmdInterface) InitiateCommit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, rogueData types.Rogue) error { ret := _m.Called(client, config, account, epoch, stakerId, rogueData) diff --git a/cmd/modifyCollectionStatus.go b/cmd/modifyCollectionStatus.go index 3eb0b3f1..6e968d2c 100644 --- a/cmd/modifyCollectionStatus.go +++ b/cmd/modifyCollectionStatus.go @@ -41,11 +41,16 @@ func (*UtilsStruct) ExecuteModifyCollectionStatus(flagSet *pflag.FlagSet) { log.Debug("ExecuteModifyCollectionStatus: Address: ", address) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + collectionId, err := flagSetUtils.GetUint16CollectionId(flagSet) utils.CheckError("Error in getting collectionId: ", err) @@ -66,7 +71,7 @@ func (*UtilsStruct) ExecuteModifyCollectionStatus(flagSet *pflag.FlagSet) { txn, err := cmdUtils.ModifyCollectionStatus(client, config, modifyCollectionInput) utils.CheckError("Error in changing collection active status: ", err) if txn != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for modifyCollectionStatus: ", err) } } @@ -103,7 +108,7 @@ func (*UtilsStruct) ModifyCollectionStatus(client *ethclient.Client, config type ContractAddress: core.CollectionManagerAddress, MethodName: "setCollectionStatus", Parameters: []interface{}{modifyCollectionInput.Status, modifyCollectionInput.CollectionId}, - ABI: bindings.CollectionManagerABI, + ABI: bindings.CollectionManagerMetaData.ABI, } txnOpts := razorUtils.GetTxnOpts(txnArgs) @@ -113,8 +118,9 @@ func (*UtilsStruct) ModifyCollectionStatus(client *ethclient.Client, config type if err != nil { return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(txn).String()) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/modifyCollectionStatus_test.go b/cmd/modifyCollectionStatus_test.go index bf473e9f..3a157f41 100644 --- a/cmd/modifyCollectionStatus_test.go +++ b/cmd/modifyCollectionStatus_test.go @@ -5,17 +5,17 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core" + "razor/core/types" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core" - "razor/core/types" - "testing" ) func TestCheckCurrentStatus(t *testing.T) { @@ -56,15 +56,10 @@ func TestCheckCurrentStatus(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - assetManageUtilsMock := new(mocks.AssetManagerInterface) - - razorUtils = utilsMock - assetManagerUtils = assetManageUtilsMock + SetUpMockInterfaces() utilsMock.On("GetOptions").Return(tt.args.callOpts) - assetManageUtilsMock.On("GetActiveStatus", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.AnythingOfType("uint16")).Return(tt.args.activeStatus, tt.args.activeStatusErr) + assetManagerMock.On("GetActiveStatus", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.AnythingOfType("uint16")).Return(tt.args.activeStatus, tt.args.activeStatusErr) utils := &UtilsStruct{} got, err := utils.CheckCurrentStatus(client, assetId) @@ -175,22 +170,13 @@ func TestModifyAssetStatus(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsMock := new(mocks.UtilsInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - assetManagerUtilsMock := new(mocks.AssetManagerInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - transactionUtils = transactionUtilsMock - assetManagerUtils = assetManagerUtilsMock + SetUpMockInterfaces() cmdUtilsMock.On("CheckCurrentStatus", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint16")).Return(tt.args.currentStatus, tt.args.currentStatusErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) cmdUtilsMock.On("WaitForAppropriateState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.Anything).Return(tt.args.epoch, tt.args.epochErr) - assetManagerUtilsMock.On("SetCollectionStatus", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.SetCollectionStatus, tt.args.SetAssetStatusErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + assetManagerMock.On("SetCollectionStatus", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.SetCollectionStatus, tt.args.SetAssetStatusErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} @@ -341,23 +327,14 @@ func TestExecuteModifyAssetStatus(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - flagsetUtilsMock := new(mocks.FlagSetInterface) - stringMock := new(mocks.StringInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - flagSetUtils = flagsetUtilsMock - stringUtils = stringMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + SetUpMockInterfaces() + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) - flagsetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) - flagsetUtilsMock.On("GetUint16CollectionId", flagSet).Return(tt.args.collectionId, tt.args.collectionIdErr) - flagsetUtilsMock.On("GetStringStatus", flagSet).Return(tt.args.status, tt.args.statusErr) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetUint16CollectionId", flagSet).Return(tt.args.collectionId, tt.args.collectionIdErr) + flagSetMock.On("GetStringStatus", flagSet).Return(tt.args.status, tt.args.statusErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) stringMock.On("ParseBool", mock.AnythingOfType("string")).Return(tt.args.parseStatus, tt.args.parseStatusErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("ModifyCollectionStatus", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ModifyCollectionStatusHash, tt.args.ModifyCollectionStatusErr) diff --git a/cmd/propose.go b/cmd/propose.go index 311098c0..3a66e4f0 100644 --- a/cmd/propose.go +++ b/cmd/propose.go @@ -4,8 +4,6 @@ package cmd import ( "encoding/hex" "errors" - "github.com/ethereum/go-ethereum/ethclient" - solsha3 "github.com/miguelmota/go-solidity-sha3" "math" "math/big" "razor/core" @@ -14,6 +12,9 @@ import ( "razor/utils" "sort" "time" + + "github.com/ethereum/go-ethereum/ethclient" + solsha3 "github.com/miguelmota/go-solidity-sha3" ) var globalProposedDataStruct types.ProposeFileData @@ -28,7 +29,7 @@ var globalProposedDataStruct types.ProposeFileData //This functions handles the propose state func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) error { - if state, err := razorUtils.GetDelayedState(client, config.BufferPercent); err != nil || state != 2 { + if state, err := razorUtils.GetBufferedState(client, config.BufferPercent); err != nil || state != 2 { log.Error("Not propose state") return err } @@ -148,7 +149,7 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration ChainId: core.ChainId, Config: config, ContractAddress: core.BlockManagerAddress, - ABI: bindings.BlockManagerABI, + ABI: bindings.BlockManagerMetaData.ABI, MethodName: "propose", Parameters: []interface{}{epoch, ids, medians, big.NewInt(int64(iteration)), biggestStakerId}, }) @@ -160,9 +161,9 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration return err } proposeTxn := transactionUtils.Hash(txn) - log.Info("Txn Hash: ", proposeTxn) + log.Info("Txn Hash: ", proposeTxn.Hex()) if proposeTxn != core.NilHash { - waitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, proposeTxn.String()) + waitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, proposeTxn.Hex()) if waitForBlockCompletionErr != nil { log.Error("Error in WaitForBlockCompletionErr for propose: ", waitForBlockCompletionErr) return waitForBlockCompletionErr @@ -178,13 +179,13 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration log.Debugf("Propose: Global propose data struct: %+v", globalProposedDataStruct) log.Debug("Saving proposed data for recovery...") - fileName, err := razorUtils.GetProposeDataFileName(account.Address) + fileName, err := pathUtils.GetProposeDataFileName(account.Address) if err != nil { log.Error("Error in getting file name to save median data: ", err) return err } log.Debug("Propose: Propose data file path: ", fileName) - err = razorUtils.SaveDataToProposeJsonFile(fileName, globalProposedDataStruct) + err = fileUtils.SaveDataToProposeJsonFile(fileName, globalProposedDataStruct) if err != nil { log.Errorf("Error in saving data to file %s: %v", fileName, err) return err @@ -215,7 +216,7 @@ func (*UtilsStruct) GetBiggestStakeAndId(client *ethclient.Client, address strin } log.Debug("GetBiggestStakeAndId: Buffer Percent: ", bufferPercent) - stateRemainingTime, err := utilsInterface.GetRemainingTimeOfCurrentState(client, bufferPercent) + stateRemainingTime, err := razorUtils.GetRemainingTimeOfCurrentState(client, bufferPercent) if err != nil { return nil, 0, err } @@ -260,7 +261,7 @@ func (*UtilsStruct) GetIteration(client *ethclient.Client, proposer types.Electe } log.Debug("GetIteration: Stake: ", stake) currentStakerStake := big.NewInt(1).Mul(stake, big.NewInt(int64(math.Exp2(32)))) - stateRemainingTime, err := utilsInterface.GetRemainingTimeOfCurrentState(client, bufferPercent) + stateRemainingTime, err := razorUtils.GetRemainingTimeOfCurrentState(client, bufferPercent) if err != nil { return -1 } @@ -373,7 +374,7 @@ func (*UtilsStruct) MakeBlock(client *ethclient.Client, blockNumber *big.Int, ep } log.Debugf("MakeBlock: Revealed data map: %+v", revealedDataMaps) - activeCollections, err := razorUtils.GetActiveCollections(client) + activeCollections, err := razorUtils.GetActiveCollectionIds(client) if err != nil { return nil, nil, nil, err } @@ -425,19 +426,6 @@ func (*UtilsStruct) MakeBlock(client *ethclient.Client, blockNumber *big.Int, ep return medians, idsRevealedInThisEpoch, revealedDataMaps, nil } -//This function returns the influenced median -func (*UtilsStruct) InfluencedMedian(sortedVotes []*big.Int, totalInfluenceRevealed *big.Int) *big.Int { - accProd := big.NewInt(0) - - for _, vote := range sortedVotes { - accProd = accProd.Add(accProd, vote) - } - if totalInfluenceRevealed.Cmp(big.NewInt(0)) == 0 { - return accProd - } - return accProd.Div(accProd, totalInfluenceRevealed) -} - func (*UtilsStruct) GetSmallestStakeAndId(client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { numberOfStakers, err := razorUtils.GetNumberOfStakers(client) if err != nil { diff --git a/cmd/propose_test.go b/cmd/propose_test.go index 2d9e44ab..b70a6c1b 100644 --- a/cmd/propose_test.go +++ b/cmd/propose_test.go @@ -6,16 +6,14 @@ import ( "crypto/rand" "errors" "fmt" - "github.com/stretchr/testify/mock" "math/big" - "razor/cmd/mocks" "razor/core/types" "razor/pkg/bindings" - "razor/utils" - Mocks "razor/utils/mocks" "reflect" "testing" + "github.com/stretchr/testify/mock" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" @@ -540,18 +538,9 @@ func TestPropose(t *testing.T) { }, } for _, tt := range tests { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - blockManagerUtilsMock := new(mocks.BlockManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - blockManagerUtils = blockManagerUtilsMock - transactionUtils = transactionUtilsMock - - utilsMock.On("GetDelayedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) + utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) utilsMock.On("GetNumberOfStakers", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.numStakers, tt.args.numStakerErr) cmdUtilsMock.On("GetBiggestStakeAndId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32")).Return(tt.args.biggestStake, tt.args.biggestStakerId, tt.args.biggestStakerIdErr) cmdUtilsMock.On("GetSmallestStakeAndId", mock.Anything, mock.Anything).Return(tt.args.smallestStake, tt.args.smallestStakerId, tt.args.smallestStakerIdErr) @@ -566,11 +555,11 @@ func TestPropose(t *testing.T) { utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.lastProposedBlockStruct, tt.args.lastProposedBlockStructErr) cmdUtilsMock.On("MakeBlock", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.medians, tt.args.ids, tt.args.revealDataMaps, tt.args.mediansErr) utilsMock.On("ConvertUint32ArrayToBigIntArray", mock.Anything).Return(tt.args.mediansBigInt) - utilsMock.On("GetProposeDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) - utilsMock.On("SaveDataToProposeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) + pathMock.On("GetProposeDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) + fileUtilsMock.On("SaveDataToProposeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - blockManagerUtilsMock.On("Propose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.proposeTxn, tt.args.proposeErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + blockManagerMock.On("Propose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.proposeTxn, tt.args.proposeErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) cmdUtilsMock.On("GetBufferPercent").Return(tt.args.bufferPercent, tt.args.bufferPercentErr) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.waitForBlockCompletionErr) @@ -689,18 +678,11 @@ func TestGetBiggestStakeAndId(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(Mocks.Utils) - - razorUtils = utilsMock - utilsInterface = utilsPkgMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() utilsMock.On("GetNumberOfStakers", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.numOfStakers, tt.args.numOfStakersErr) utilsMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.stake, tt.args.stakeErr) - utilsPkgMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(tt.args.remainingTime, tt.args.remainingTimeErr) + utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(tt.args.remainingTime, tt.args.remainingTimeErr) cmdUtilsMock.On("GetBufferPercent").Return(tt.args.bufferPercent, tt.args.bufferPercentErr) utils := &UtilsStruct{} @@ -785,16 +767,11 @@ func TestGetIteration(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsMock := new(mocks.UtilsInterface) - utilsPkgMock := new(Mocks.Utils) - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - utilsInterface = utilsPkgMock + SetUpMockInterfaces() utilsMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.stakeSnapshot, tt.args.stakeSnapshotErr) cmdUtilsMock.On("IsElectedProposer", mock.Anything, mock.Anything).Return(tt.args.isElectedProposer) - utilsPkgMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(tt.args.remainingTime, tt.args.remainingTimeErr) + utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(tt.args.remainingTime, tt.args.remainingTimeErr) utils := &UtilsStruct{} @@ -805,51 +782,6 @@ func TestGetIteration(t *testing.T) { } } -func TestInfluencedMedian(t *testing.T) { - type args struct { - sortedVotes []*big.Int - totalInfluenceRevealed *big.Int - } - tests := []struct { - name string - args args - want *big.Int - }{ - { - name: "Test if sortedVotes is empty", - args: args{ - sortedVotes: []*big.Int{}, - totalInfluenceRevealed: big.NewInt(1).Mul(big.NewInt(4200), big.NewInt(1e18)), - }, - want: big.NewInt(0), - }, - { - name: "Test if totalInfluenceRevealed is 0", - args: args{ - sortedVotes: []*big.Int{big.NewInt(1).Mul(big.NewInt(697690000), big.NewInt(1e18)), big.NewInt(1).Mul(big.NewInt(697629800), big.NewInt(1e18)), big.NewInt(1).Mul(big.NewInt(697718000), big.NewInt(1e18))}, - totalInfluenceRevealed: big.NewInt(0), - }, - want: big.NewInt(1).Mul(big.NewInt(2093037800), big.NewInt(1e18)), - }, - { - name: "Test if all the values are present", - args: args{ - sortedVotes: []*big.Int{big.NewInt(1).Mul(big.NewInt(697690000), big.NewInt(1e18)), big.NewInt(1).Mul(big.NewInt(697629800), big.NewInt(1e18)), big.NewInt(1).Mul(big.NewInt(697718000), big.NewInt(1e18))}, - totalInfluenceRevealed: big.NewInt(1).Mul(big.NewInt(4200), big.NewInt(1e18)), - }, - want: big.NewInt(498342), - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - utils := &UtilsStruct{} - if got := utils.InfluencedMedian(tt.args.sortedVotes, tt.args.totalInfluenceRevealed); !reflect.DeepEqual(got, tt.want) { - t.Errorf("influencedMedian() = %v, want %v", got, tt.want) - } - }) - } -} - func TestIsElectedProposer(t *testing.T) { randaoHash := []byte{142, 170, 157, 83, 109, 43, 34, 152, 21, 154, 159, 12, 195, 119, 50, 186, 218, 57, 39, 173, 228, 135, 20, 100, 149, 27, 169, 158, 34, 113, 66, 64} @@ -1012,7 +944,7 @@ func TestMakeBlock(t *testing.T) { epoch uint32 ) - randomValue := utils.GetRogueRandomValue(10000000) + randomValue := big.NewInt(1111) type args struct { revealedDataMaps *types.RevealedDataMaps @@ -1141,14 +1073,10 @@ func TestMakeBlock(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() cmdUtilsMock.On("GetSortedRevealedValues", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.revealedDataMaps, tt.args.revealedDataMapsErr) - utilsMock.On("GetActiveCollections", mock.Anything).Return(tt.args.activeCollections, tt.args.activeCollectionsErr) + utilsMock.On("GetActiveCollectionIds", mock.Anything).Return(tt.args.activeCollections, tt.args.activeCollectionsErr) utilsMock.On("GetRogueRandomValue", mock.Anything).Return(randomValue) ut := &UtilsStruct{} got, got1, got2, err := ut.MakeBlock(client, blockNumber, epoch, tt.args.rogueData) @@ -1209,9 +1137,7 @@ func TestGetSortedRevealedValues(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() cmdUtilsMock.On("IndexRevealEventsOfCurrentEpoch", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.assignedAssets, tt.args.assignedAssetsErr) ut := &UtilsStruct{} @@ -1286,14 +1212,7 @@ func TestGetSmallestStakeAndId(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(Mocks.Utils) - - razorUtils = utilsMock - utilsInterface = utilsPkgMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() utilsMock.On("GetNumberOfStakers", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.numOfStakers, tt.args.numOfStakersErr) utilsMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.stake, tt.args.stakeErr) @@ -1349,15 +1268,12 @@ func BenchmarkGetIteration(b *testing.B) { for _, v := range table { b.Run(fmt.Sprintf("Stakers_Stake_%d", v.stakeSnapshot), func(b *testing.B) { for i := 0; i < b.N; i++ { - utilsMock := new(mocks.UtilsInterface) - utilsPkgMock := new(Mocks.Utils) + SetUpMockInterfaces() - razorUtils = utilsMock cmdUtils = &UtilsStruct{} - utilsInterface = utilsPkgMock utilsMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(big.NewInt(1).Mul(v.stakeSnapshot, big.NewInt(1e18)), nil) - utilsPkgMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(int64(100), nil) + utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(int64(100), nil) cmdUtils.GetIteration(client, proposer, bufferPercent) } @@ -1382,17 +1298,11 @@ func BenchmarkGetBiggestStakeAndId(b *testing.B) { for _, v := range table { b.Run(fmt.Sprintf("Stakers_Stake_%d", v.numOfStakers), func(b *testing.B) { for i := 0; i < b.N; i++ { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(Mocks.Utils) - - razorUtils = utilsMock - utilsInterface = utilsPkgMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() utilsMock.On("GetNumberOfStakers", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(v.numOfStakers, nil) utilsMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(big.NewInt(10000), nil) - utilsPkgMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(int64(150), nil) + utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(int64(150), nil) cmdUtilsMock.On("GetBufferPercent").Return(int32(60), nil) ut := &UtilsStruct{} @@ -1405,27 +1315,6 @@ func BenchmarkGetBiggestStakeAndId(b *testing.B) { } } -func BenchmarkInfluencedMedian(b *testing.B) { - var table = []struct { - numOfSortedVotes int - totalInfluenceRevealed *big.Int - }{ - {numOfSortedVotes: 10, totalInfluenceRevealed: big.NewInt(1).Mul(big.NewInt(4200), big.NewInt(1e18))}, - {numOfSortedVotes: 100, totalInfluenceRevealed: big.NewInt(1).Mul(big.NewInt(42000), big.NewInt(1e18))}, - {numOfSortedVotes: 500, totalInfluenceRevealed: big.NewInt(1).Mul(big.NewInt(42000), big.NewInt(1e18))}, - {numOfSortedVotes: 1000, totalInfluenceRevealed: big.NewInt(1).Mul(big.NewInt(420000), big.NewInt(1e18))}, - } - for _, v := range table { - b.Run(fmt.Sprintf("Number_Of_Sorted_Votes_%d", v.numOfSortedVotes), func(b *testing.B) { - for i := 0; i < b.N; i++ { - utils := &UtilsStruct{} - sortedVotes := GetDummyVotes(v.numOfSortedVotes) - utils.InfluencedMedian(sortedVotes, v.totalInfluenceRevealed) - } - }) - } -} - func BenchmarkGetSortedRevealedValues(b *testing.B) { var ( client *ethclient.Client @@ -1444,9 +1333,8 @@ func BenchmarkGetSortedRevealedValues(b *testing.B) { for _, v := range table { b.Run(fmt.Sprintf("Number_Of_Assigned_Assets_%d, Number_Of_Revealed_Votes_%d", v.numOfAssignedAssets, v.numOfRevealedValues), func(b *testing.B) { for i := 0; i < b.N; i++ { - cmdUtilsMock := new(mocks.UtilsCmdInterface) + SetUpMockInterfaces() - cmdUtils = cmdUtilsMock asset := GetDummyRevealedValues(v.numOfRevealedValues) cmdUtilsMock.On("IndexRevealEventsOfCurrentEpoch", mock.Anything, mock.Anything, mock.Anything).Return(GetDummyAssignedAssets(asset, v.numOfAssignedAssets), nil) @@ -1479,11 +1367,7 @@ func BenchmarkMakeBlock(b *testing.B) { for _, v := range table { b.Run(fmt.Sprintf("Number_Of_Votes_%d", v.numOfVotes), func(b *testing.B) { for i := 0; i < b.N; i++ { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() votes := GetDummyVotes(v.numOfVotes) @@ -1492,7 +1376,7 @@ func BenchmarkMakeBlock(b *testing.B) { VoteWeights: map[string]*big.Int{(big.NewInt(1).Mul(big.NewInt(697718000), big.NewInt(1e18))).String(): big.NewInt(100)}, InfluenceSum: map[uint16]*big.Int{0: big.NewInt(100)}, }, nil) - utilsMock.On("GetActiveCollections", mock.Anything).Return([]uint16{1}, nil) + utilsMock.On("GetActiveCollectionIds", mock.Anything).Return([]uint16{1}, nil) ut := &UtilsStruct{} _, _, _, err := ut.MakeBlock(client, blockNumber, epoch, types.Rogue{IsRogue: false}) if err != nil { diff --git a/cmd/resetUnstakeLock.go b/cmd/resetUnstakeLock.go index 5da926b8..477e86d7 100644 --- a/cmd/resetUnstakeLock.go +++ b/cmd/resetUnstakeLock.go @@ -43,12 +43,16 @@ func (*UtilsStruct) ExecuteExtendLock(flagSet *pflag.FlagSet) { utils.CheckError("Error in getting address: ", err) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + stakerId, err := razorUtils.AssignStakerId(flagSet, client, address) utils.CheckError("Error in getting stakerId: ", err) @@ -60,7 +64,7 @@ func (*UtilsStruct) ExecuteExtendLock(flagSet *pflag.FlagSet) { log.Debugf("ExecuteExtendLock: Calling ResetUnstakeLock with arguments extendLockInput = %+v", extendLockInput) txn, err := cmdUtils.ResetUnstakeLock(client, config, extendLockInput) utils.CheckError("Error in extending lock: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for resetUnstakeLock: ", err) } @@ -75,7 +79,7 @@ func (*UtilsStruct) ResetUnstakeLock(client *ethclient.Client, config types.Conf ContractAddress: core.StakeManagerAddress, MethodName: "resetUnstakeLock", Parameters: []interface{}{extendLockInput.StakerId}, - ABI: bindings.StakeManagerABI, + ABI: bindings.StakeManagerMetaData.ABI, }) log.Info("Extending lock...") @@ -84,8 +88,9 @@ func (*UtilsStruct) ResetUnstakeLock(client *ethclient.Client, config types.Conf if err != nil { return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/resetUnstakeLock_test.go b/cmd/resetUnstakeLock_test.go index 55b1f4fa..5c1d985f 100644 --- a/cmd/resetUnstakeLock_test.go +++ b/cmd/resetUnstakeLock_test.go @@ -5,17 +5,17 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core" + "razor/core/types" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core" - "razor/core/types" - "testing" ) func TestExtendLock(t *testing.T) { @@ -64,18 +64,11 @@ func TestExtendLock(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - stakeManagerUtilsMock.On("ResetUnstakeLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32")).Return(tt.args.resetLockTxn, tt.args.resetLockErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + stakeManagerMock.On("ResetUnstakeLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32")).Return(tt.args.resetLockTxn, tt.args.resetLockErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} @@ -185,19 +178,13 @@ func TestExecuteExtendLock(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - flagSetUtils = flagSetUtilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagSetUtilsMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) utilsMock.On("AssignStakerId", flagSet, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) diff --git a/cmd/reveal.go b/cmd/reveal.go index af8e1a97..c0d1be8a 100644 --- a/cmd/reveal.go +++ b/cmd/reveal.go @@ -15,13 +15,13 @@ import ( "github.com/ethereum/go-ethereum/ethclient" ) -//This function handles the reveal state -func (*UtilsStruct) HandleRevealState(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { +//This function checks for epoch last committed +func (*UtilsStruct) CheckForLastCommitted(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { epochLastCommitted, err := razorUtils.GetEpochLastCommitted(client, staker.Id) if err != nil { return err } - log.Debug("HandleRevealState: Staker last epoch committed: ", epochLastCommitted) + log.Debug("CheckForLastCommitted: Staker last epoch committed: ", epochLastCommitted) if epochLastCommitted != epoch { return errors.New("commitment for this epoch not found on network.... aborting reveal") } @@ -30,13 +30,18 @@ func (*UtilsStruct) HandleRevealState(client *ethclient.Client, staker bindings. //This function checks if the state is reveal or not and then reveals the votes func (*UtilsStruct) Reveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, commitData types.CommitData, signature []byte) (common.Hash, error) { - if state, err := razorUtils.GetDelayedState(client, config.BufferPercent); err != nil || state != 1 { + if state, err := razorUtils.GetBufferedState(client, config.BufferPercent); err != nil || state != 1 { log.Error("Not reveal state") return core.NilHash, err } log.Debug("Creating merkle tree...") - merkleTree := utils.MerkleInterface.CreateMerkle(commitData.Leaves) + merkleTree, err := merkleUtils.CreateMerkle(commitData.Leaves) + + if err != nil { + log.Error("Error in getting merkle tree: ", err) + return core.NilHash, err + } log.Debug("Generating tree reveal data...") treeRevealData := cmdUtils.GenerateTreeRevealData(merkleTree, commitData) @@ -56,19 +61,19 @@ func (*UtilsStruct) Reveal(client *ethclient.Client, config types.Configurations ChainId: core.ChainId, Config: config, ContractAddress: core.VoteManagerAddress, - ABI: bindings.VoteManagerABI, + ABI: bindings.VoteManagerMetaData.ABI, MethodName: "reveal", Parameters: []interface{}{epoch, treeRevealData, signature}, }) log.Debugf("Executing Reveal transaction wih epoch = %d, treeRevealData = %v, signature = %v", epoch, treeRevealData, signature) - txnOpts.GasLimit = 50000000 txn, err := voteManagerUtils.Reveal(client, txnOpts, epoch, treeRevealData, signature) if err != nil { log.Error(err) return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } //This function generates the tree reveal data @@ -87,11 +92,16 @@ func (*UtilsStruct) GenerateTreeRevealData(merkleTree [][][]byte, commitData typ LeafId: uint16(commitData.SeqAllottedCollections[i].Uint64()), Value: big.NewInt(commitData.Leaves[commitData.SeqAllottedCollections[i].Uint64()].Int64()), } - proof := utils.MerkleInterface.GetProofPath(merkleTree, value.LeafId) + proof := merkleUtils.GetProofPath(merkleTree, value.LeafId) values = append(values, value) proofs = append(proofs, proof) } - root := utils.MerkleInterface.GetMerkleRoot(merkleTree) + + root, err := merkleUtils.GetMerkleRoot(merkleTree) + if err != nil { + log.Error("Error in getting root: ", err) + return bindings.StructsMerkleTree{} + } log.Debugf("GenerateTreeRevealData: values = %+v, proofs = %+v, root = %v", values, proofs, root) return bindings.StructsMerkleTree{ @@ -104,7 +114,7 @@ func (*UtilsStruct) GenerateTreeRevealData(merkleTree [][][]byte, commitData typ //This function indexes the reveal events of current epoch func (*UtilsStruct) IndexRevealEventsOfCurrentEpoch(client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) { log.Debug("Fetching reveal events of current epoch...") - fromBlock, err := utils.UtilsInterface.CalculateBlockNumberAtEpochBeginning(client, core.EpochLength, blockNumber) + fromBlock, err := razorUtils.EstimateBlockNumberAtEpochBeginning(client, blockNumber) if err != nil { return nil, errors.New("Not able to Fetch Block: " + err.Error()) } @@ -117,11 +127,11 @@ func (*UtilsStruct) IndexRevealEventsOfCurrentEpoch(client *ethclient.Client, bl }, } log.Debugf("IndexRevealEventsOfCurrentEpoch: Query to send in filter logs: %+v", query) - logs, err := utils.UtilsInterface.FilterLogsWithRetry(client, query) + logs, err := clientUtils.FilterLogsWithRetry(client, query) if err != nil { return nil, err } - contractAbi, err := utils.ABIInterface.Parse(strings.NewReader(bindings.VoteManagerABI)) + contractAbi, err := utils.ABIInterface.Parse(strings.NewReader(bindings.VoteManagerMetaData.ABI)) if err != nil { return nil, err } diff --git a/cmd/reveal_test.go b/cmd/reveal_test.go index 6c77b922..d551b532 100644 --- a/cmd/reveal_test.go +++ b/cmd/reveal_test.go @@ -6,24 +6,22 @@ import ( "crypto/rand" "errors" "fmt" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/stretchr/testify/mock" "math/big" - "razor/cmd/mocks" "razor/core" "razor/core/types" "razor/pkg/bindings" - utils2 "razor/utils" - mocks2 "razor/utils/mocks" "reflect" "testing" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + Types "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/stretchr/testify/mock" ) -func TestHandleRevealState(t *testing.T) { +func TestCheckForLastCommitted(t *testing.T) { var client *ethclient.Client staker := bindings.StructsStaker{ Id: 1, @@ -40,7 +38,7 @@ func TestHandleRevealState(t *testing.T) { want error }{ { - name: "Test 1: When HandleRevealState returns no error", + name: "Test 1: When CheckForLastCommitted returns no error", args: args{ epoch: 1, epochLastCommitted: 1, @@ -58,7 +56,7 @@ func TestHandleRevealState(t *testing.T) { want: errors.New("epochLastCommitted"), }, { - name: "Test 3: When HandleRevealState returns an error when epoch != epochLastCommitted", + name: "Test 3: When CheckForLastCommitted returns an error when epoch != epochLastCommitted", args: args{ epoch: 3, epochLastCommitted: 2, @@ -69,22 +67,20 @@ func TestHandleRevealState(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - razorUtils = utilsMock + SetUpMockInterfaces() utilsMock.On("GetEpochLastCommitted", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.epochLastCommitted, tt.args.epochLastCommittedErr) utils := &UtilsStruct{} - err := utils.HandleRevealState(client, staker, tt.args.epoch) + err := utils.CheckForLastCommitted(client, staker, tt.args.epoch) if err == nil || tt.want == nil { if err != tt.want { - t.Errorf("Error for HandleRevealState function, got = %v, want %v", err, tt.want) + t.Errorf("Error for CheckForLastCommitted function, got = %v, want %v", err, tt.want) } } else { if err.Error() != tt.want.Error() { - t.Errorf("Error for HandleRevealState function, got = %v, want %v", err, tt.want) + t.Errorf("Error for CheckForLastCommitted function, got = %v, want %v", err, tt.want) } } @@ -107,6 +103,7 @@ func TestReveal(t *testing.T) { state int64 stateErr error merkleTree [][][]byte + merkleTreeErr error treeRevealData bindings.StructsMerkleTree txnOpts *bind.TransactOpts revealTxn *Types.Transaction @@ -157,28 +154,26 @@ func TestReveal(t *testing.T) { want: core.NilHash, wantErr: errors.New("reveal error"), }, + { + name: "Test 7: When there is an error in getting merkle tree", + args: args{ + state: 1, + merkleTreeErr: errors.New("merkle tree error"), + }, + want: core.NilHash, + wantErr: errors.New("merkle tree error"), + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - voteManagerUtilsMock := new(mocks.VoteManagerInterface) - merkleInterface := new(mocks2.MerkleTreeInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - transactionUtils = transactionUtilsMock - voteManagerUtils = voteManagerUtilsMock - cmdUtils = cmdUtilsMock - utils2.MerkleInterface = merkleInterface - - utilsMock.On("GetDelayedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) - merkleInterface.On("CreateMerkle", mock.Anything).Return(tt.args.merkleTree) + utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) + merkleUtilsMock.On("CreateMerkle", mock.Anything).Return(tt.args.merkleTree, tt.args.merkleTreeErr) cmdUtilsMock.On("GenerateTreeRevealData", mock.Anything, mock.Anything).Return(tt.args.treeRevealData) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(tt.args.txnOpts) - voteManagerUtilsMock.On("Reveal", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32"), mock.Anything, mock.Anything).Return(tt.args.revealTxn, tt.args.revealErr) - transactionUtilsMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) + voteManagerMock.On("Reveal", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32"), mock.Anything, mock.Anything).Return(tt.args.revealTxn, tt.args.revealErr) + transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) utils := &UtilsStruct{} @@ -205,6 +200,7 @@ func TestGenerateTreeRevealData(t *testing.T) { commitData types.CommitData proof [][32]byte root [32]byte + rootErr error } tests := []struct { name string @@ -237,15 +233,26 @@ func TestGenerateTreeRevealData(t *testing.T) { Root: [32]byte{}, }, }, + { + name: "Test 3: When there is an error in getting root", + args: args{ + merkleTree: [][][]byte{}, + commitData: types.CommitData{ + AssignedCollections: map[int]bool{1: true}, + SeqAllottedCollections: []*big.Int{big.NewInt(1)}, + Leaves: []*big.Int{big.NewInt(1), big.NewInt(2)}, + }, + rootErr: errors.New("root error"), + }, + want: bindings.StructsMerkleTree{}, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - merkleInterface := new(mocks2.MerkleTreeInterface) + SetUpMockInterfaces() - utils2.MerkleInterface = merkleInterface - - merkleInterface.On("GetProofPath", mock.Anything, mock.Anything).Return(tt.args.proof) - merkleInterface.On("GetMerkleRoot", mock.Anything).Return(tt.args.root) + merkleUtilsMock.On("GetProofPath", mock.Anything, mock.Anything).Return(tt.args.proof) + merkleUtilsMock.On("GetMerkleRoot", mock.Anything).Return(tt.args.root, tt.args.rootErr) ut := &UtilsStruct{} if got := ut.GenerateTreeRevealData(tt.args.merkleTree, tt.args.commitData); !reflect.DeepEqual(got, tt.want) { t.Errorf("GenerateTreeRevealData() = %v, want %v", got, tt.want) @@ -318,14 +325,10 @@ func TestIndexRevealEventsOfCurrentEpoch(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsPkgMock := new(mocks2.Utils) - abiUtilsMock := new(mocks2.ABIUtils) - - utils2.UtilsInterface = utilsPkgMock - utils2.ABIInterface = abiUtilsMock + SetUpMockInterfaces() - utilsPkgMock.On("CalculateBlockNumberAtEpochBeginning", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) - utilsPkgMock.On("FilterLogsWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.FilterQuery")).Return(tt.args.logs, tt.args.logsErr) + utilsMock.On("EstimateBlockNumberAtEpochBeginning", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) + clientUtilsMock.On("FilterLogsWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.FilterQuery")).Return(tt.args.logs, tt.args.logsErr) abiUtilsMock.On("Parse", mock.Anything).Return(tt.args.contractAbi, tt.args.contractAbiErr) abiUtilsMock.On("Unpack", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.data, tt.args.unpackErr) ut := &UtilsStruct{} @@ -354,11 +357,10 @@ func BenchmarkGenerateTreeRevealData(b *testing.B) { for _, v := range table { b.Run(fmt.Sprintf("Number_Of_Allotted_Collections%d", v.numOfAllottedCollections), func(b *testing.B) { merkleTree := [][][]byte{{{byte(1)}, {byte(2)}}, {{byte(3)}, {byte(4)}}, {{byte(5)}, {byte(6)}}} - merkleInterface := new(mocks2.MerkleTreeInterface) - utils2.MerkleInterface = merkleInterface + SetUpMockInterfaces() - merkleInterface.On("GetProofPath", mock.Anything, mock.Anything).Return([][32]byte{[32]byte{1, 2, 3}, {4, 5, 6}}) - merkleInterface.On("GetMerkleRoot", mock.Anything).Return([32]byte{100}) + merkleUtilsMock.On("GetProofPath", mock.Anything, mock.Anything).Return([][32]byte{[32]byte{1, 2, 3}, {4, 5, 6}}) + merkleUtilsMock.On("GetMerkleRoot", mock.Anything).Return([32]byte{100}, nil) ut := &UtilsStruct{} seqAllottedCollections := getDummySeqAllottedCollection(v.numOfAllottedCollections) diff --git a/cmd/root.go b/cmd/root.go index 494dd28f..56eca6b7 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -3,17 +3,18 @@ package cmd import ( "fmt" - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "github.com/spf13/viper" "os" "razor/core" "razor/logger" "razor/path" + + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var ( Provider string + AlternateProvider string GasMultiplier float32 BufferPercent int32 WaitTime int32 @@ -23,6 +24,10 @@ var ( GasLimitOverride uint64 LogFile string RPCTimeout int64 + HTTPTimeout int64 + LogFileMaxSize int + LogFileMaxBackups int + LogFileMaxAge int ) var log = logger.NewLogger() @@ -56,6 +61,7 @@ func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVarP(&Provider, "provider", "p", "", "provider name") + rootCmd.PersistentFlags().StringVarP(&AlternateProvider, "alternateProvider", "", "", "alternate provider name") rootCmd.PersistentFlags().Float32VarP(&GasMultiplier, "gasmultiplier", "g", -1, "gas multiplier value") rootCmd.PersistentFlags().Int32VarP(&BufferPercent, "buffer", "b", 0, "buffer percent") rootCmd.PersistentFlags().Int32VarP(&WaitTime, "wait", "w", -1, "wait time") @@ -65,6 +71,10 @@ func init() { rootCmd.PersistentFlags().Uint64VarP(&GasLimitOverride, "gasLimitOverride", "", 0, "gas limit to be over ridden for a transaction") rootCmd.PersistentFlags().StringVarP(&LogFile, "logFile", "", "", "name of log file") rootCmd.PersistentFlags().Int64VarP(&RPCTimeout, "rpcTimeout", "", 0, "RPC timeout if its not responding") + rootCmd.PersistentFlags().Int64VarP(&HTTPTimeout, "httpTimeout", "", 0, "HTTP request timeout if its not responding") + rootCmd.PersistentFlags().IntVarP(&LogFileMaxSize, "logFileMaxSize", "", 0, "max size of log file MB") + rootCmd.PersistentFlags().IntVarP(&LogFileMaxBackups, "logFileMaxBackups", "", 0, "max number of old log files to retain") + rootCmd.PersistentFlags().IntVarP(&LogFileMaxAge, "logFileMaxAge", "", 0, "max number of days to retain old log files") rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } @@ -89,29 +99,4 @@ func initConfig() { log.Warn("error in reading config") } } - - setLogLevel() -} - -//This function sets the log level -func setLogLevel() { - config, err := cmdUtils.GetConfigData() - if err != nil { - log.Fatal(err) - } - - if config.LogLevel == "debug" { - log.SetLevel(logrus.DebugLevel) - } - - log.Debug("Config details: ") - log.Debugf("Provider: %s", config.Provider) - log.Debugf("Gas Multiplier: %.2f", config.GasMultiplier) - log.Debugf("Buffer Percent: %d", config.BufferPercent) - log.Debugf("Wait Time: %d", config.WaitTime) - log.Debugf("Gas Price: %d", config.GasPrice) - log.Debugf("Log Level: %s", config.LogLevel) - log.Debugf("Gas Limit: %.2f", config.GasLimitMultiplier) - log.Debugf("Gas Limit Override: %d", config.GasLimitOverride) - log.Debugf("RPC Timeout: %d", config.RPCTimeout) } diff --git a/cmd/setConfig.go b/cmd/setConfig.go index bd7ed9ad..302a787e 100644 --- a/cmd/setConfig.go +++ b/cmd/setConfig.go @@ -3,6 +3,7 @@ package cmd import ( "razor/core" + "razor/core/types" "razor/metrics" "razor/utils" @@ -29,11 +30,15 @@ Example: //This function returns the error if there is any and sets the config func (*UtilsStruct) SetConfig(flagSet *pflag.FlagSet) error { log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, types.Configurations{}) provider, err := flagSetUtils.GetStringProvider(flagSet) if err != nil { return err } + alternateProvider, err := flagSetUtils.GetStringAlternateProvider(flagSet) + if err != nil { + return err + } gasMultiplier, err := flagSetUtils.GetFloat32GasMultiplier(flagSet) if err != nil { return err @@ -66,8 +71,24 @@ func (*UtilsStruct) SetConfig(flagSet *pflag.FlagSet) error { if rpcTimeoutErr != nil { return rpcTimeoutErr } + httpTimeout, httpTimeoutErr := flagSetUtils.GetInt64HTTPTimeout(flagSet) + if httpTimeoutErr != nil { + return httpTimeoutErr + } + logFileMaxSize, err := flagSetUtils.GetIntLogFileMaxSize(flagSet) + if err != nil { + return err + } + logFileMaxBackups, err := flagSetUtils.GetIntLogFileMaxBackups(flagSet) + if err != nil { + return err + } + logFileMaxAge, err := flagSetUtils.GetIntLogFileMaxAge(flagSet) + if err != nil { + return err + } - path, pathErr := razorUtils.GetConfigFilePath() + path, pathErr := pathUtils.GetConfigFilePath() if pathErr != nil { log.Error("Error in fetching config file path") return pathErr @@ -103,6 +124,9 @@ func (*UtilsStruct) SetConfig(flagSet *pflag.FlagSet) error { if provider != "" { viper.Set("provider", provider) } + if alternateProvider != "" { + viper.Set("alternateProvider", alternateProvider) + } if gasMultiplier != -1 { viper.Set("gasmultiplier", gasMultiplier) } @@ -127,8 +151,21 @@ func (*UtilsStruct) SetConfig(flagSet *pflag.FlagSet) error { if rpcTimeout != 0 { viper.Set("rpcTimeout", rpcTimeout) } - if provider == "" && gasMultiplier == -1 && bufferPercent == 0 && waitTime == -1 && gasPrice == -1 && logLevel == "" && gasLimit == -1 && gasLimitOverride == 0 && rpcTimeout == 0 { - viper.Set("provider", core.DefaultProvider) + if httpTimeout != 0 { + viper.Set("httpTimeout", httpTimeout) + } + if logFileMaxSize != 0 { + viper.Set("logFileMaxSize", logFileMaxSize) + } + if logFileMaxBackups != 0 { + viper.Set("logFileMaxBackups", logFileMaxBackups) + } + if logFileMaxAge != 0 { + viper.Set("logFileMaxAge", logFileMaxAge) + } + if provider == "" && alternateProvider == "" && gasMultiplier == -1 && bufferPercent == 0 && waitTime == -1 && gasPrice == -1 && logLevel == "" && gasLimit == -1 && gasLimitOverride == 0 && rpcTimeout == 0 && httpTimeout == 0 && logFileMaxSize == 0 && logFileMaxBackups == 0 && logFileMaxAge == 0 { + viper.Set("provider", "") + viper.Set("alternateProvider", "") viper.Set("gasmultiplier", core.DefaultGasMultiplier) viper.Set("buffer", core.DefaultBufferPercent) viper.Set("wait", core.DefaultWaitTime) @@ -137,7 +174,10 @@ func (*UtilsStruct) SetConfig(flagSet *pflag.FlagSet) error { viper.Set("gasLimit", core.DefaultGasLimit) viper.Set("gasLimitOverride", core.DefaultGasLimitOverride) viper.Set("rpcTimeout", core.DefaultRPCTimeout) - //viper.Set("exposeMetricsPort", "") + viper.Set("httpTimeout", core.DefaultHTTPTimeout) + viper.Set("logFileMaxSize", core.DefaultLogFileMaxSize) + viper.Set("logFileMaxBackups", core.DefaultLogFileMaxBackups) + viper.Set("logFileMaxAge", core.DefaultLogFileMaxAge) log.Info("Config values set to default. Use setConfig to modify the values.") } @@ -154,6 +194,7 @@ func init() { var ( Provider string + AlternateProvider string GasMultiplier float32 BufferPercent int32 WaitTime int32 @@ -162,11 +203,16 @@ func init() { GasLimitMultiplier float32 GasLimitOverride uint64 RPCTimeout int64 + HTTPTimeout int64 ExposeMetrics string CertFile string CertKey string + LogFileMaxSize int + LogFileMaxBackups int + LogFileMaxAge int ) setConfig.Flags().StringVarP(&Provider, "provider", "p", "", "provider name") + setConfig.Flags().StringVarP(&AlternateProvider, "alternateProvider", "", "", "alternate provider name") setConfig.Flags().Float32VarP(&GasMultiplier, "gasmultiplier", "g", -1, "gas multiplier value") setConfig.Flags().Int32VarP(&BufferPercent, "buffer", "b", 0, "buffer percent") setConfig.Flags().Int32VarP(&WaitTime, "wait", "w", -1, "wait time (in secs)") @@ -175,8 +221,12 @@ func init() { setConfig.Flags().Float32VarP(&GasLimitMultiplier, "gasLimit", "", -1, "gas limit percentage increase") setConfig.Flags().Uint64VarP(&GasLimitOverride, "gasLimitOverride", "", 0, "gas limit to be over ridden for a transaction") setConfig.Flags().Int64VarP(&RPCTimeout, "rpcTimeout", "", 0, "RPC timeout if its not responding") + setConfig.Flags().Int64VarP(&HTTPTimeout, "httpTimeout", "", 0, "http request timeout if its not responding") setConfig.Flags().StringVarP(&ExposeMetrics, "exposeMetrics", "", "", "port number") setConfig.Flags().StringVarP(&CertFile, "certFile", "", "", "ssl certificate path") setConfig.Flags().StringVarP(&CertKey, "certKey", "", "", "ssl certificate key path") + setConfig.Flags().IntVarP(&LogFileMaxSize, "logFileMaxSize", "", 0, "max size of log file in MB") + setConfig.Flags().IntVarP(&LogFileMaxBackups, "logFileMaxBackups", "", 0, "max number of old log files to retain") + setConfig.Flags().IntVarP(&LogFileMaxAge, "logFileMaxAge", "", 0, "max number of days to retain old log files") } diff --git a/cmd/setConfig_test.go b/cmd/setConfig_test.go index d08a08d3..a16a06db 100644 --- a/cmd/setConfig_test.go +++ b/cmd/setConfig_test.go @@ -2,7 +2,6 @@ package cmd import ( "errors" - "razor/cmd/mocks" "testing" "github.com/spf13/pflag" @@ -10,12 +9,13 @@ import ( ) func TestSetConfig(t *testing.T) { - var flagSet *pflag.FlagSet type args struct { provider string providerErr error + alternateProvider string + alternateProviderErr error gasmultiplier float32 gasmultiplierErr error buffer int32 @@ -35,6 +35,8 @@ func TestSetConfig(t *testing.T) { gasLimitOverrideErr error rpcTimeout int64 rpcTimeoutErr error + httpTimeout int64 + httpTimeoutErr error isFlagPassed bool port string portErr error @@ -42,6 +44,12 @@ func TestSetConfig(t *testing.T) { certFileErr error certKey string certKeyErr error + logFileMaxSize int + logFileMaxSizeErr error + logFileMaxBackups int + logFileMaxBackupsErr error + logFileMaxAge int + logFileMaxAgeErr error } tests := []struct { name string @@ -51,162 +59,120 @@ func TestSetConfig(t *testing.T) { { name: "Test 1: When values are passed to all flags and setConfig returns no error", args: args{ - provider: "http://127.0.0.1", - gasmultiplier: 2, - buffer: 20, - waitTime: 2, - gasPrice: 1, - logLevel: "debug", - path: "/home/config", - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, - rpcTimeout: 10, + provider: "http://127.0.0.1", + alternateProvider: "http://127.0.0.1:8545", + gasmultiplier: 2, + buffer: 20, + waitTime: 2, + gasPrice: 1, + logLevel: "debug", + path: "/home/config", + gasLimitMultiplier: 10, + rpcTimeout: 10, + httpTimeout: 20, + logFileMaxSize: 6, + logFileMaxBackups: 11, + logFileMaxAge: 31, }, wantErr: nil, }, { name: "Test 2: When parameters are set to default values and setConfig returns no error", args: args{ - provider: "", - gasmultiplier: -1, - buffer: 0, - waitTime: -1, - gasPrice: -1, - logLevel: "", - path: "/home/config", - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, - rpcTimeout: 0, + provider: "", + gasmultiplier: -1, + buffer: 0, + waitTime: -1, + gasPrice: -1, + logLevel: "", + path: "/home/config", + gasLimitMultiplier: 10, + rpcTimeout: 0, + httpTimeout: 0, }, wantErr: nil, }, { name: "Test 3: When there is an error in getting provider", args: args{ - providerErr: errors.New("provider error"), - gasmultiplier: 2, - buffer: 20, - waitTime: 2, - gasPrice: 1, - logLevel: "debug", - path: "/home/config", - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, + providerErr: errors.New("provider error"), }, wantErr: errors.New("provider error"), }, { name: "Test 4: When there is an error in getting gasmultiplier", args: args{ - provider: "http://127.0.0.1", - gasmultiplierErr: errors.New("gasmultiplier error"), - buffer: 20, - waitTime: 2, - gasPrice: 1, - logLevel: "debug", - path: "/home/config", - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, + provider: "http://127.0.0.1", + gasmultiplierErr: errors.New("gasmultiplier error"), }, wantErr: errors.New("gasmultiplier error"), }, { name: "Test 5: When there is an error in getting buffer", args: args{ - provider: "http://127.0.0.1", - gasmultiplier: 2, - bufferErr: errors.New("buffer error"), - waitTime: 2, - gasPrice: 1, - logLevel: "debug", - path: "/home/config", - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, + provider: "http://127.0.0.1", + gasmultiplier: 2, + bufferErr: errors.New("buffer error"), }, wantErr: errors.New("buffer error"), }, { name: "Test 6: When there is an error in getting waitTime", args: args{ - provider: "http://127.0.0.1", - gasmultiplier: 2, - buffer: 20, - waitTimeErr: errors.New("waitTime error"), - gasPrice: 1, - logLevel: "debug", - path: "/home/config", - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, + provider: "http://127.0.0.1", + gasmultiplier: 2, + buffer: 20, + waitTimeErr: errors.New("waitTime error"), }, wantErr: errors.New("waitTime error"), }, { name: "Test 7: When there is an error in getting gasprice", args: args{ - provider: "http://127.0.0.1", - gasmultiplier: 2, - buffer: 20, - waitTime: 2, - gasPriceErr: errors.New("gasprice error"), - logLevel: "debug", - path: "/home/config", - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, + provider: "http://127.0.0.1", + gasmultiplier: 2, + buffer: 20, + waitTime: 2, + gasPriceErr: errors.New("gasprice error"), }, wantErr: errors.New("gasprice error"), }, { name: "Test 8: When there is an error in getting logLevel", args: args{ - provider: "http://127.0.0.1", - gasmultiplier: 2, - buffer: 20, - waitTime: 2, - gasPrice: 1, - logLevelErr: errors.New("logLevel error"), - path: "/home/config", - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, + provider: "http://127.0.0.1", + gasmultiplier: 2, + buffer: 20, + waitTime: 2, + gasPrice: 1, + logLevelErr: errors.New("logLevel error"), }, wantErr: errors.New("logLevel error"), }, { name: "Test 9: When there is an error in getting path", args: args{ - provider: "http://127.0.0.1", - gasmultiplier: 2, - buffer: 20, - waitTime: 2, - gasPrice: 1, - logLevel: "debug", - pathErr: errors.New("path error"), - configErr: nil, - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, + provider: "http://127.0.0.1", + gasmultiplier: 2, + buffer: 20, + waitTime: 2, + gasPrice: 1, + logLevel: "debug", + pathErr: errors.New("path error"), }, wantErr: errors.New("path error"), }, { name: "Test 10: When there is an error in writing config", args: args{ - provider: "http://127.0.0.1", - gasmultiplier: 2, - buffer: 20, - waitTime: 2, - gasPrice: 1, - logLevel: "debug", - path: "/home/config", - configErr: errors.New("writing config error"), - gasLimitMultiplier: 10, - gasLimitMultiplierErr: nil, + provider: "http://127.0.0.1", + gasmultiplier: 2, + buffer: 20, + waitTime: 2, + gasPrice: 1, + logLevel: "debug", + path: "/home/config", + configErr: errors.New("writing config error"), }, wantErr: errors.New("writing config error"), }, @@ -229,7 +195,6 @@ func TestSetConfig(t *testing.T) { gasPrice: 1, logLevel: "debug", path: "/home/config", - configErr: nil, gasLimitMultiplier: -1, gasLimitMultiplierErr: errors.New("gasLimitMultiplier error"), }, @@ -238,16 +203,16 @@ func TestSetConfig(t *testing.T) { { name: "Test 13: When default nil values are passed", args: args{ - provider: "", - gasmultiplier: -1, - buffer: 0, - waitTime: -1, - gasPrice: -1, - logLevel: "", - path: "/home/config", - configErr: nil, - gasLimitMultiplier: -1, - gasLimitMultiplierErr: nil, + provider: "", + gasmultiplier: -1, + buffer: 0, + waitTime: -1, + gasPrice: -1, + logLevel: "", + rpcTimeout: 0, + httpTimeout: 0, + path: "/home/config", + gasLimitMultiplier: -1, }, wantErr: nil, }, @@ -278,7 +243,6 @@ func TestSetConfig(t *testing.T) { gasPrice: 1, logLevel: "debug", path: "/home/config", - configErr: nil, gasLimitMultiplier: -1, rpcTimeoutErr: errors.New("rpcTimeout error"), }, @@ -299,35 +263,55 @@ func TestSetConfig(t *testing.T) { }, wantErr: errors.New("gasLimitOverride error"), }, + { + name: "Test 18: When there is an error in getting HTTP timeout", + args: args{ + provider: "http://127.0.0.1", + gasmultiplier: 2, + buffer: 20, + waitTime: 2, + gasPrice: 1, + logLevel: "debug", + path: "/home/config", + gasLimitMultiplier: -1, + rpcTimeout: 10, + httpTimeoutErr: errors.New("httpTimeout error"), + }, + wantErr: errors.New("httpTimeout error"), + }, + { + name: "Test 18: When there is an error in getting alternate provider", + args: args{ + provider: "http://127.0.0.1", + alternateProviderErr: errors.New("alternate provider error"), + }, + wantErr: errors.New("alternate provider error"), + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - viperMock := new(mocks.ViperInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - flagSetUtils = flagSetUtilsMock - viperUtils = viperMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) - flagSetUtilsMock.On("GetStringProvider", flagSet).Return(tt.args.provider, tt.args.providerErr) - flagSetUtilsMock.On("GetFloat32GasMultiplier", flagSet).Return(tt.args.gasmultiplier, tt.args.gasmultiplierErr) - flagSetUtilsMock.On("GetInt32Buffer", flagSet).Return(tt.args.buffer, tt.args.bufferErr) - flagSetUtilsMock.On("GetInt32Wait", flagSet).Return(tt.args.waitTime, tt.args.waitTimeErr) - flagSetUtilsMock.On("GetInt32GasPrice", flagSet).Return(tt.args.gasPrice, tt.args.gasPriceErr) - flagSetUtilsMock.On("GetStringLogLevel", flagSet).Return(tt.args.logLevel, tt.args.logLevelErr) - flagSetUtilsMock.On("GetFloat32GasLimit", flagSet).Return(tt.args.gasLimitMultiplier, tt.args.gasLimitMultiplierErr) - flagSetUtilsMock.On("GetUint64GasLimitOverride", flagSet).Return(tt.args.gasLimitOverride, tt.args.gasLimitOverrideErr) - flagSetUtilsMock.On("GetInt64RPCTimeout", flagSet).Return(tt.args.rpcTimeout, tt.args.rpcTimeoutErr) - flagSetUtilsMock.On("GetStringExposeMetrics", flagSet).Return(tt.args.port, tt.args.portErr) - flagSetUtilsMock.On("GetStringCertFile", flagSet).Return(tt.args.certFile, tt.args.certFileErr) - flagSetUtilsMock.On("GetStringCertKey", flagSet).Return(tt.args.certKey, tt.args.certKeyErr) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) + flagSetMock.On("GetStringProvider", flagSet).Return(tt.args.provider, tt.args.providerErr) + flagSetMock.On("GetStringAlternateProvider", flagSet).Return(tt.args.alternateProvider, tt.args.alternateProviderErr) + flagSetMock.On("GetFloat32GasMultiplier", flagSet).Return(tt.args.gasmultiplier, tt.args.gasmultiplierErr) + flagSetMock.On("GetInt32Buffer", flagSet).Return(tt.args.buffer, tt.args.bufferErr) + flagSetMock.On("GetInt32Wait", flagSet).Return(tt.args.waitTime, tt.args.waitTimeErr) + flagSetMock.On("GetInt32GasPrice", flagSet).Return(tt.args.gasPrice, tt.args.gasPriceErr) + flagSetMock.On("GetStringLogLevel", flagSet).Return(tt.args.logLevel, tt.args.logLevelErr) + flagSetMock.On("GetFloat32GasLimit", flagSet).Return(tt.args.gasLimitMultiplier, tt.args.gasLimitMultiplierErr) + flagSetMock.On("GetUint64GasLimitOverride", flagSet).Return(tt.args.gasLimitOverride, tt.args.gasLimitOverrideErr) + flagSetMock.On("GetInt64RPCTimeout", flagSet).Return(tt.args.rpcTimeout, tt.args.rpcTimeoutErr) + flagSetMock.On("GetInt64HTTPTimeout", flagSet).Return(tt.args.httpTimeout, tt.args.httpTimeoutErr) + flagSetMock.On("GetStringExposeMetrics", flagSet).Return(tt.args.port, tt.args.portErr) + flagSetMock.On("GetStringCertFile", flagSet).Return(tt.args.certFile, tt.args.certFileErr) + flagSetMock.On("GetStringCertKey", flagSet).Return(tt.args.certKey, tt.args.certKeyErr) + flagSetMock.On("GetIntLogFileMaxSize", mock.Anything).Return(tt.args.logFileMaxSize, tt.args.logFileMaxSizeErr) + flagSetMock.On("GetIntLogFileMaxBackups", mock.Anything).Return(tt.args.logFileMaxBackups, tt.args.logFileMaxBackupsErr) + flagSetMock.On("GetIntLogFileMaxAge", mock.Anything).Return(tt.args.logFileMaxAge, tt.args.logFileMaxAgeErr) utilsMock.On("IsFlagPassed", mock.Anything).Return(tt.args.isFlagPassed) - utilsMock.On("GetConfigFilePath").Return(tt.args.path, tt.args.pathErr) + pathMock.On("GetConfigFilePath").Return(tt.args.path, tt.args.pathErr) viperMock.On("ViperWriteConfigAs", mock.AnythingOfType("string")).Return(tt.args.configErr) utils := &UtilsStruct{} diff --git a/cmd/setDelegation.go b/cmd/setDelegation.go index bfa90dee..30b41fe4 100644 --- a/cmd/setDelegation.go +++ b/cmd/setDelegation.go @@ -43,11 +43,16 @@ func (*UtilsStruct) ExecuteSetDelegation(flagSet *pflag.FlagSet) { utils.CheckError("Error in getting address: ", err) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + statusString, err := flagSetUtils.GetStringStatus(flagSet) utils.CheckError("Error in getting status: ", err) @@ -73,7 +78,7 @@ func (*UtilsStruct) ExecuteSetDelegation(flagSet *pflag.FlagSet) { txn, err := cmdUtils.SetDelegation(client, config, delegationInput) utils.CheckError("SetDelegation error: ", err) if txn != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for setDelegation: ", err) } } @@ -106,7 +111,7 @@ func (*UtilsStruct) SetDelegation(client *ethclient.Client, config types.Configu ChainId: core.ChainId, Config: config, ContractAddress: core.StakeManagerAddress, - ABI: bindings.StakeManagerABI, + ABI: bindings.StakeManagerMetaData.ABI, MethodName: "setDelegationAcceptance", Parameters: []interface{}{delegationInput.Status}, } @@ -123,8 +128,9 @@ func (*UtilsStruct) SetDelegation(client *ethclient.Client, config types.Configu log.Error("Error in setting delegation acceptance") return core.NilHash, err } - log.Infof("Transaction hash: %s", transactionUtils.Hash(delegationAcceptanceTxn)) - return transactionUtils.Hash(delegationAcceptanceTxn), nil + delegationAcceptanceTxnHash := transactionUtils.Hash(delegationAcceptanceTxn) + log.Info("Txn Hash: ", delegationAcceptanceTxnHash.Hex()) + return delegationAcceptanceTxnHash, nil } func init() { diff --git a/cmd/setDelegation_test.go b/cmd/setDelegation_test.go index 9e7bf53c..649ce637 100644 --- a/cmd/setDelegation_test.go +++ b/cmd/setDelegation_test.go @@ -10,6 +10,7 @@ import ( "razor/core" "razor/core/types" "razor/pkg/bindings" + utilsPkgMocks "razor/utils/mocks" "testing" "github.com/ethereum/go-ethereum/accounts/abi/bind" @@ -146,7 +147,7 @@ func TestSetDelegation(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) + utilsMock := new(utilsPkgMocks.Utils) stakeManagerUtilsMock := new(mocks.StakeManagerInterface) transactionUtilsMock := new(mocks.TransactionInterface) cmdUtilsMock := new(mocks.UtilsCmdInterface) @@ -400,21 +401,24 @@ func TestExecuteSetDelegation(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) + utilsMock := new(utilsPkgMocks.Utils) cmdUtilsMock := new(mocks.UtilsCmdInterface) flagSetUtilsMock := new(mocks.FlagSetInterface) stakeManagerUtilsMock := new(mocks.StakeManagerInterface) stringMock := new(mocks.StringInterface) + fileUtilsMock := new(utilsPkgMocks.FileUtils) razorUtils = utilsMock cmdUtils = cmdUtilsMock flagSetUtils = flagSetUtilsMock stakeManagerUtils = stakeManagerUtilsMock stringUtils = stringMock + fileUtils = fileUtilsMock - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) flagSetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) flagSetUtilsMock.On("GetStringStatus", flagSet).Return(tt.args.status, tt.args.statusErr) flagSetUtilsMock.On("GetUint8Commission", flagSet).Return(tt.args.commission, tt.args.commissionErr) diff --git a/cmd/stakerInfo_test.go b/cmd/stakerInfo_test.go index 365ee2b3..c7367672 100644 --- a/cmd/stakerInfo_test.go +++ b/cmd/stakerInfo_test.go @@ -11,6 +11,7 @@ import ( "math/big" "razor/cmd/mocks" "razor/core/types" + utilsPkgMocks "razor/utils/mocks" "testing" ) @@ -212,7 +213,7 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) + utilsMock := new(utilsPkgMocks.Utils) stakeManagerMock := new(mocks.StakeManagerInterface) razorUtils = utilsMock @@ -306,15 +307,17 @@ func TestUtilsStruct_ExecuteStakerinfo(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) + utilsMock := new(utilsPkgMocks.Utils) cmdUtilsMock := new(mocks.UtilsCmdInterface) flagSetUtilsMock := new(mocks.FlagSetInterface) + fileUtilsMock := new(utilsPkgMocks.FileUtils) razorUtils = utilsMock cmdUtils = cmdUtilsMock flagSetUtils = flagSetUtilsMock + fileUtils = fileUtilsMock - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) flagSetUtilsMock.On("GetUint32StakerId", flagSet).Return(tt.args.stakerId, tt.args.stakerIdErr) diff --git a/cmd/struct-utils.go b/cmd/struct-utils.go index f1b300ed..b5e76e45 100644 --- a/cmd/struct-utils.go +++ b/cmd/struct-utils.go @@ -5,6 +5,7 @@ import ( "crypto/ecdsa" "math/big" "os" + "razor/accounts" "razor/core" "razor/core/types" "razor/path" @@ -26,17 +27,24 @@ import ( "github.com/spf13/viper" ) -var utilsInterface = utils.UtilsInterface +var ( + razorUtils = utils.UtilsInterface + pathUtils = path.PathUtilsInterface + clientUtils = utils.ClientInterface + fileUtils = utils.FileInterface + gasUtils = utils.GasInterface + merkleUtils = utils.MerkleInterface + accountUtils = accounts.AccountUtilsInterface +) //This function initializes the utils func InitializeUtils() { - utilsInterface = &utils.UtilsStruct{} + razorUtils = &utils.UtilsStruct{} utils.UtilsInterface = &utils.UtilsStruct{} utils.EthClient = &utils.EthClientStruct{} utils.ClientInterface = &utils.ClientStruct{} utils.Time = &utils.TimeStruct{} utils.OS = &utils.OSStruct{} - utils.Bufio = &utils.BufioStruct{} utils.CoinInterface = &utils.CoinStruct{} utils.MerkleInterface = &utils.MerkleTreeStruct{} utils.IOInterface = &utils.IOStruct{} @@ -54,6 +62,16 @@ func InitializeUtils() { utils.RetryInterface = &utils.RetryStruct{} utils.MerkleInterface = &utils.MerkleTreeStruct{} utils.FlagSetInterface = &utils.FlagSetStruct{} + clientUtils = &utils.ClientStruct{} + utils.ClientInterface = &utils.ClientStruct{} + fileUtils = &utils.FileStruct{} + utils.FileInterface = &utils.FileStruct{} + gasUtils = &utils.GasStruct{} + utils.GasInterface = &utils.GasStruct{} + merkleUtils = &utils.MerkleTreeStruct{} + utils.MerkleInterface = &utils.MerkleTreeStruct{} + accountUtils = &accounts.AccountUtils{} + accounts.AccountUtilsInterface = &accounts.AccountUtils{} } func ExecuteTransaction(interfaceName interface{}, methodName string, args ...interface{}) (*Types.Transaction, error) { @@ -65,381 +83,6 @@ func ExecuteTransaction(interfaceName interface{}, methodName string, args ...in return returnedValues[0].Interface().(*Types.Transaction), nil } -//This function returns the config file path -func (u Utils) GetConfigFilePath() (string, error) { - return path.PathUtilsInterface.GetConfigFilePath() -} - -//This function returns the epoch -func (u Utils) GetEpoch(client *ethclient.Client) (uint32, error) { - return utilsInterface.GetEpoch(client) -} - -//This function returns the options -func (u Utils) GetOptions() bind.CallOpts { - return utilsInterface.GetOptions() -} - -//This function returns the block time -func (u Utils) CalculateBlockTime(client *ethclient.Client) int64 { - return utilsInterface.CalculateBlockTime(client) -} - -//This function returns the transaction opts -func (u Utils) GetTxnOpts(transactionData types.TransactionOptions) *bind.TransactOpts { - return utilsInterface.GetTxnOpts(transactionData) -} - -//This function returns the config data -func (u Utils) GetConfigData() (types.Configurations, error) { - return cmdUtils.GetConfigData() -} - -//This function assigns the password -func (u Utils) AssignPassword(flagSet *pflag.FlagSet) string { - return utils.AssignPassword(flagSet) -} - -//This function returns the string address -func (u Utils) GetStringAddress(flagSet *pflag.FlagSet) (string, error) { - return flagSet.GetString("address") -} - -//This function returns the Uint32 bountyId -func (u Utils) GetUint32BountyId(flagSet *pflag.FlagSet) (uint32, error) { - return flagSet.GetUint32("bountyId") -} - -//This function connects to the client -func (u Utils) ConnectToClient(provider string) *ethclient.Client { - returnedValues := utils.InvokeFunctionWithTimeout(utilsInterface, "ConnectToClient", provider) - returnedError := utils.CheckIfAnyError(returnedValues) - if returnedError != nil { - return nil - } - return returnedValues[0].Interface().(*ethclient.Client) -} - -//This function waits for the block completion -func (u Utils) WaitForBlockCompletion(client *ethclient.Client, hashToRead string) error { - return utilsInterface.WaitForBlockCompletion(client, hashToRead) -} - -//This function returns the number of active collections -func (u Utils) GetNumActiveCollections(client *ethclient.Client) (uint16, error) { - return utilsInterface.GetNumActiveCollections(client) -} - -//This function returns rogue random value -func (u Utils) GetRogueRandomValue(value int) *big.Int { - return utils.GetRogueRandomValue(value) -} - -//This function returns the rogue median value -func (u Utils) GetRogueRandomMedianValue() uint32 { - return utils.GetRogueRandomMedianValue() -} - -//This function returns the aggregated data of collection -func (u Utils) GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32) (*big.Int, error) { - return utilsInterface.GetAggregatedDataOfCollection(client, collectionId, epoch) -} - -//This function returns the delayed state -func (u Utils) GetDelayedState(client *ethclient.Client, buffer int32) (int64, error) { - return utilsInterface.GetDelayedState(client, buffer) -} - -//This function returns the default path -func (u Utils) GetDefaultPath() (string, error) { - return path.PathUtilsInterface.GetDefaultPath() -} - -//This function returns the job file path -func (u Utils) GetJobFilePath() (string, error) { - return path.PathUtilsInterface.GetJobFilePath() -} - -//This function fetches the balance -func (u Utils) FetchBalance(client *ethclient.Client, accountAddress string) (*big.Int, error) { - return utilsInterface.FetchBalance(client, accountAddress) -} - -//This function checks if the flag is passed -func (u Utils) IsFlagPassed(name string) bool { - return utilsInterface.IsFlagPassed(name) -} - -//This function returns the amount in wei -func (u Utils) GetAmountInWei(amount *big.Int) *big.Int { - return utils.GetAmountInWei(amount) -} - -//This function checks the amount and balance -func (u Utils) CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) *big.Int { - return utils.CheckAmountAndBalance(amountInWei, balance) -} - -//This function returns the amount in decimal -func (u Utils) GetAmountInDecimal(amountInWei *big.Int) *big.Float { - return utils.GetAmountInDecimal(amountInWei) -} - -//This function returns the epoch which is last committed -func (u Utils) GetEpochLastCommitted(client *ethclient.Client, stakerId uint32) (uint32, error) { - return utilsInterface.GetEpochLastCommitted(client, stakerId) -} - -//This function returns the commitments -func (u Utils) GetCommitments(client *ethclient.Client, address string) ([32]byte, error) { - return utilsInterface.GetCommitments(client, address) -} - -//This function returns if all the values in bytesValue is zero -func (u Utils) AllZero(bytesValue [32]byte) bool { - return utils.AllZero(bytesValue) -} - -//This function converts the Uint array to Uint16 array -func (u Utils) ConvertUintArrayToUint16Array(uintArr []uint) []uint16 { - return utils.ConvertUintArrayToUint16Array(uintArr) -} - -//This function returns the jobs array -func (u Utils) GetJobs(client *ethclient.Client) ([]bindings.StructsJob, error) { - return utilsInterface.GetJobs(client) -} - -//This function if the eth balance is zero or not -func (u Utils) CheckEthBalanceIsZero(client *ethclient.Client, address string) { - utilsInterface.CheckEthBalanceIsZero(client, address) -} - -//This function assigns the stakerId -func (u Utils) AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) { - return utilsInterface.AssignStakerId(flagSet, client, address) -} - -//This function returns the lock -func (u Utils) GetLock(client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) { - return utilsInterface.GetLock(client, address, stakerId, lockType) -} - -//This function returns the staker -func (u Utils) GetStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { - return utilsInterface.GetStaker(client, stakerId) -} - -//This function returns the updated staker -func (u Utils) GetUpdatedStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { - return utilsInterface.GetStaker(client, stakerId) -} - -//This function returns the staked token -func (u Utils) GetStakedToken(client *ethclient.Client, address common.Address) *bindings.StakedToken { - return utilsInterface.GetStakedToken(client, address) -} - -//This function converts the SRazor to Razor -func (u Utils) ConvertSRZRToRZR(sAmount *big.Int, currentStake *big.Int, totalSupply *big.Int) *big.Int { - return utils.ConvertSRZRToRZR(sAmount, currentStake, totalSupply) -} - -//This function converts the Razor to SRazors -func (u Utils) ConvertRZRToSRZR(sAmount *big.Int, currentStake *big.Int, totalSupply *big.Int) (*big.Int, error) { - return utils.ConvertRZRToSRZR(sAmount, currentStake, totalSupply) -} - -//This function returns the withdraw initiation period -func (u Utils) GetWithdrawInitiationPeriod(client *ethclient.Client) (uint16, error) { - return utilsInterface.GetWithdrawInitiationPeriod(client) -} - -//This function returns the influence snapshot -func (u Utils) GetInfluenceSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - return utilsInterface.GetInfluenceSnapshot(client, stakerId, epoch) -} - -//This function returns the collections -func (u Utils) GetCollections(client *ethclient.Client) ([]bindings.StructsCollection, error) { - return utilsInterface.GetAllCollections(client) -} - -//This function returns the number of stakers -func (u Utils) GetNumberOfStakers(client *ethclient.Client) (uint32, error) { - return utilsInterface.GetNumberOfStakers(client) -} - -//This function returns the number of proposed blocks -func (u Utils) GetNumberOfProposedBlocks(client *ethclient.Client, epoch uint32) (uint8, error) { - return utilsInterface.GetNumberOfProposedBlocks(client, epoch) -} - -//This function returns the maximum alt blocks -func (u Utils) GetMaxAltBlocks(client *ethclient.Client) (uint8, error) { - return utilsInterface.GetMaxAltBlocks(client) -} - -//This function returns the proposed block -func (u Utils) GetProposedBlock(client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) { - return utilsInterface.GetProposedBlock(client, epoch, proposedBlockId) -} - -//This function returns the epoch which is last revealed -func (u Utils) GetEpochLastRevealed(client *ethclient.Client, stakerId uint32) (uint32, error) { - return utilsInterface.GetEpochLastRevealed(client, stakerId) -} - -//This function returns the epoch which is last proposed -func (u Utils) GetEpochLastProposed(client *ethclient.Client, stakerId uint32) (uint32, error) { - return utilsInterface.GetEpochLastProposed(client, stakerId) -} - -//This function returns the vote value -func (u Utils) GetVoteValue(client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) { - return utilsInterface.GetVoteValue(client, epoch, stakerId, medianIndex) -} - -//This function returns the total influence revealed -func (u Utils) GetTotalInfluenceRevealed(client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) { - return utilsInterface.GetTotalInfluenceRevealed(client, epoch, medianIndex) -} - -//This function returns the Uint32 Array to BigInt array -func (u Utils) ConvertUint32ArrayToBigIntArray(uint32Array []uint32) []*big.Int { - return utils.ConvertUint32ArrayToBigIntArray(uint32Array) -} - -//This function returns the active collections -func (u Utils) GetActiveCollections(client *ethclient.Client) ([]uint16, error) { - return utilsInterface.GetActiveCollectionIds(client) -} - -//This function retrns the block manager -func (u Utils) GetBlockManager(client *ethclient.Client) *bindings.BlockManager { - return utilsInterface.GetBlockManager(client) -} - -//This function returns the sorted proposed block Ids -func (u Utils) GetSortedProposedBlockIds(client *ethclient.Client, epoch uint32) ([]uint32, error) { - return utilsInterface.GetSortedProposedBlockIds(client, epoch) -} - -//This function returns the stakerId -func (u Utils) GetStakerId(client *ethclient.Client, address string) (uint32, error) { - return utilsInterface.GetStakerId(client, address) -} - -//This function returns the stake -func (u Utils) GetStake(client *ethclient.Client, stakerId uint32) (*big.Int, error) { - return utilsInterface.GetStake(client, stakerId) -} - -//This function prompts the private key -func (u Utils) PrivateKeyPrompt() string { - return utils.PrivateKeyPrompt() -} - -//This function prompts the password -func (u Utils) PasswordPrompt() string { - return utils.PasswordPrompt() -} - -//This function returns the max commission -func (u Utils) GetMaxCommission(client *ethclient.Client) (uint8, error) { - return utilsInterface.GetMaxCommission(client) -} - -//This function returns the epoch limit for updated commission -func (u Utils) GetEpochLimitForUpdateCommission(client *ethclient.Client) (uint16, error) { - return utilsInterface.GetEpochLimitForUpdateCommission(client) -} - -//This function returns the stake snapshot -func (u Utils) GetStakeSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - return utilsInterface.GetStakeSnapshot(client, stakerId, epoch) -} - -//This function converts the wei to eth -func (u Utils) ConvertWeiToEth(data *big.Int) (*big.Float, error) { - return utils.ConvertWeiToEth(data) -} - -//This function wait till next N seconds -func (u Utils) WaitTillNextNSecs(seconds int32) { - utilsInterface.WaitTillNextNSecs(seconds) -} - -//This function deletes the job from JSON -func (u Utils) DeleteJobFromJSON(s string, jobId string) error { - return utilsInterface.DeleteJobFromJSON(s, jobId) -} - -//This function adds the job to JSON -func (u Utils) AddJobToJSON(s string, job *types.StructsJob) error { - return utilsInterface.AddJobToJSON(s, job) -} - -//This function converts seconds into readable time -func (u Utils) SecondsToReadableTime(time int) string { - return utilsInterface.SecondsToReadableTime(time) -} - -//This function returns the staker SRZR balance -func (u Utils) GetStakerSRZRBalance(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) { - return utilsInterface.GetStakerSRZRBalance(client, staker) -} - -//This function saves the data to commit JSON File -func (u Utils) SaveDataToCommitJsonFile(flePath string, epoch uint32, commitFileData types.CommitData) error { - return utilsInterface.SaveDataToCommitJsonFile(flePath, epoch, commitFileData) -} - -//This function reads from the commit JSON file -func (u Utils) ReadFromCommitJsonFile(filePath string) (types.CommitFileData, error) { - return utilsInterface.ReadFromCommitJsonFile(filePath) -} - -//This function assigns the log file -func (u Utils) AssignLogFile(flagSet *pflag.FlagSet) { - utilsInterface.AssignLogFile(flagSet) -} - -//This function reads from propose JSON file -func (u Utils) ReadFromProposeJsonFile(filePath string) (types.ProposeFileData, error) { - return utilsInterface.ReadFromProposeJsonFile(filePath) -} - -//This function saves the data to propose JSON file -func (u Utils) SaveDataToProposeJsonFile(flePath string, proposeFileData types.ProposeFileData) error { - return utilsInterface.SaveDataToProposeJsonFile(flePath, proposeFileData) -} - -//This function saves data to Dispute JSON file -func (u Utils) SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []uint32) error { - return utilsInterface.SaveDataToDisputeJsonFile(filePath, bountyIdQueue) -} - -//This function reads from Dispute JSON file -func (u Utils) ReadFromDisputeJsonFile(filePath string) (types.DisputeFileData, error) { - return utilsInterface.ReadFromDisputeJsonFile(filePath) -} - -//This function returns the proposed data JSON file -func (u Utils) GetProposeDataFileName(address string) (string, error) { - return path.PathUtilsInterface.GetProposeDataFileName(address) -} - -//This function returns the commit data file name -func (u Utils) GetCommitDataFileName(address string) (string, error) { - return path.PathUtilsInterface.GetCommitDataFileName(address) -} - -//This function returns the dispute data file name -func (u Utils) GetDisputeDataFileName(address string) (string, error) { - return path.PathUtilsInterface.GetDisputeDataFileName(address) -} - //This function returns the hash func (transactionUtils TransactionUtils) Hash(txn *Types.Transaction) common.Hash { return txn.Hash() @@ -447,68 +90,68 @@ func (transactionUtils TransactionUtils) Hash(txn *Types.Transaction) common.Has //This function is of staking the razors func (stakeManagerUtils StakeManagerUtils) Stake(client *ethclient.Client, txnOpts *bind.TransactOpts, epoch uint32, amount *big.Int) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "Stake", txnOpts, epoch, amount) } //This function resets the unstake lock func (stakeManagerUtils StakeManagerUtils) ResetUnstakeLock(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "ResetUnstakeLock", opts, stakerId) } //This function is for delegation func (stakeManagerUtils StakeManagerUtils) Delegate(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32, amount *big.Int) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "Delegate", opts, stakerId, amount) } //This function initiates the withdraw func (stakeManagerUtils StakeManagerUtils) InitiateWithdraw(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "InitiateWithdraw", opts, stakerId) } //This function unlocks the withdraw amount func (stakeManagerUtils StakeManagerUtils) UnlockWithdraw(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "UnlockWithdraw", opts, stakerId) } //This function sets the delegation acceptance or rejection func (stakeManagerUtils StakeManagerUtils) SetDelegationAcceptance(client *ethclient.Client, opts *bind.TransactOpts, status bool) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "SetDelegationAcceptance", opts, status) } //This function updates the commission func (stakeManagerUtils StakeManagerUtils) UpdateCommission(client *ethclient.Client, opts *bind.TransactOpts, commission uint8) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "UpdateCommission", opts, commission) } //This function allows to unstake the razors func (stakeManagerUtils StakeManagerUtils) Unstake(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32, sAmount *big.Int) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "Unstake", opts, stakerId, sAmount) } //This function approves the unstake your razor -func (stakeManagerUtils StakeManagerUtils) ApproveUnstake(client *ethclient.Client, opts *bind.TransactOpts, staker bindings.StructsStaker, amount *big.Int) (*Types.Transaction, error) { - stakedToken := razorUtils.GetStakedToken(client, staker.TokenAddress) - log.Debugf("ApproveUnstake: Executing Approve transaction for stakedToken address: %s with arguments amount : %s", staker.TokenAddress, amount) +func (stakeManagerUtils StakeManagerUtils) ApproveUnstake(client *ethclient.Client, opts *bind.TransactOpts, stakerTokenAddress common.Address, amount *big.Int) (*Types.Transaction, error) { + stakedToken := razorUtils.GetStakedToken(client, stakerTokenAddress) + log.Debugf("ApproveUnstake: Executing Approve transaction for stakedToken address: %s with arguments amount : %s", stakerTokenAddress, amount) return ExecuteTransaction(stakedToken, "Approve", opts, common.HexToAddress(core.StakeManagerAddress), amount) } //This function is used to redeem the bounty func (stakeManagerUtils StakeManagerUtils) RedeemBounty(client *ethclient.Client, opts *bind.TransactOpts, bountyId uint32) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "RedeemBounty", opts, bountyId) } //This function returns the staker Info func (stakeManagerUtils StakeManagerUtils) StakerInfo(client *ethclient.Client, opts *bind.CallOpts, stakerId uint32) (types.Staker, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) returnedValues := utils.InvokeFunctionWithTimeout(stakeManager, "Stakers", opts, stakerId) returnedError := utils.CheckIfAnyError(returnedValues) if returnedError != nil { @@ -532,7 +175,7 @@ func (stakeManagerUtils StakeManagerUtils) StakerInfo(client *ethclient.Client, //This function returns the maturity func (stakeManagerUtils StakeManagerUtils) GetMaturity(client *ethclient.Client, opts *bind.CallOpts, age uint32) (uint16, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) index := age / 10000 returnedValues := utils.InvokeFunctionWithTimeout(stakeManager, "Maturities", opts, big.NewInt(int64(index))) returnedError := utils.CheckIfAnyError(returnedValues) @@ -544,7 +187,7 @@ func (stakeManagerUtils StakeManagerUtils) GetMaturity(client *ethclient.Client, //This function returns the bounty lock func (stakeManagerUtils StakeManagerUtils) GetBountyLock(client *ethclient.Client, opts *bind.CallOpts, bountyId uint32) (types.BountyLock, error) { - stakeManager := utilsInterface.GetStakeManager(client) + stakeManager := razorUtils.GetStakeManager(client) returnedValues := utils.InvokeFunctionWithTimeout(stakeManager, "BountyLocks", opts, bountyId) returnedError := utils.CheckIfAnyError(returnedValues) if returnedError != nil { @@ -559,20 +202,20 @@ func (stakeManagerUtils StakeManagerUtils) GetBountyLock(client *ethclient.Clien } //This function is used to claim the staker reward -func (stakeManagerUtils StakeManagerUtils) ClaimStakeReward(client *ethclient.Client, opts *bind.TransactOpts) (*Types.Transaction, error) { - stakeManager := utilsInterface.GetStakeManager(client) +func (stakeManagerUtils StakeManagerUtils) ClaimStakerReward(client *ethclient.Client, opts *bind.TransactOpts) (*Types.Transaction, error) { + stakeManager := razorUtils.GetStakeManager(client) return ExecuteTransaction(stakeManager, "ClaimStakerReward", opts) } //This function is used to claim the block reward func (blockManagerUtils BlockManagerUtils) ClaimBlockReward(client *ethclient.Client, opts *bind.TransactOpts) (*Types.Transaction, error) { - blockManager := utilsInterface.GetBlockManager(client) + blockManager := razorUtils.GetBlockManager(client) return ExecuteTransaction(blockManager, "ClaimBlockReward", opts) } //Thid function is used to finalize the dispute func (blockManagerUtils BlockManagerUtils) FinalizeDispute(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, positionOfCollectionInBlock *big.Int) (*Types.Transaction, error) { - blockManager := utilsInterface.GetBlockManager(client) + blockManager := razorUtils.GetBlockManager(client) var ( txn *Types.Transaction err error @@ -593,7 +236,7 @@ func (blockManagerUtils BlockManagerUtils) FinalizeDispute(client *ethclient.Cli //This function is used to dispute the biggest staker which is proposed func (blockManagerUtils BlockManagerUtils) DisputeBiggestStakeProposed(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, correctBiggestStakerId uint32) (*Types.Transaction, error) { - blockManager := utilsInterface.GetBlockManager(client) + blockManager := razorUtils.GetBlockManager(client) var ( txn *Types.Transaction err error @@ -614,7 +257,7 @@ func (blockManagerUtils BlockManagerUtils) DisputeBiggestStakeProposed(client *e //This function is used to check if dispute collection Id is absent or not func (blockManagerUtils BlockManagerUtils) DisputeCollectionIdShouldBeAbsent(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, id uint16, positionOfCollectionInBlock *big.Int) (*Types.Transaction, error) { - blockManager := utilsInterface.GetBlockManager(client) + blockManager := razorUtils.GetBlockManager(client) var ( txn *Types.Transaction err error @@ -636,7 +279,7 @@ func (blockManagerUtils BlockManagerUtils) DisputeCollectionIdShouldBeAbsent(cli //This function is used to check if dispute collection Id is present or not func (blockManagerUtils BlockManagerUtils) DisputeCollectionIdShouldBePresent(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, id uint16) (*Types.Transaction, error) { - blockManager := utilsInterface.GetBlockManager(client) + blockManager := razorUtils.GetBlockManager(client) var ( txn *Types.Transaction err error @@ -657,7 +300,7 @@ func (blockManagerUtils BlockManagerUtils) DisputeCollectionIdShouldBePresent(cl //This function is used to do dispute on order of Ids func (blockManagerUtils BlockManagerUtils) DisputeOnOrderOfIds(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, index0 *big.Int, index1 *big.Int) (*Types.Transaction, error) { - blockManager := utilsInterface.GetBlockManager(client) + blockManager := razorUtils.GetBlockManager(client) var ( txn *Types.Transaction err error @@ -678,7 +321,7 @@ func (blockManagerUtils BlockManagerUtils) DisputeOnOrderOfIds(client *ethclient //This function is used for proposing the block func (blockManagerUtils BlockManagerUtils) Propose(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, ids []uint16, medians []*big.Int, iteration *big.Int, biggestInfluencerId uint32) (*Types.Transaction, error) { - blockManager := utilsInterface.GetBlockManager(client) + blockManager := razorUtils.GetBlockManager(client) var ( txn *Types.Transaction err error @@ -709,7 +352,7 @@ func (blockManagerUtils BlockManagerUtils) ResetDispute(blockManager *bindings.B //This functiom gets Disputes mapping func (blockManagerUtils BlockManagerUtils) Disputes(client *ethclient.Client, opts *bind.CallOpts, epoch uint32, address common.Address) (types.DisputesStruct, error) { - blockManager := utilsInterface.GetBlockManager(client) + blockManager := razorUtils.GetBlockManager(client) returnedValues := utils.InvokeFunctionWithTimeout(blockManager, "Disputes", opts, epoch, address) returnedError := utils.CheckIfAnyError(returnedValues) if returnedError != nil { @@ -726,7 +369,7 @@ func (blockManagerUtils BlockManagerUtils) Disputes(client *ethclient.Client, op //This function is used to reveal the values func (voteManagerUtils VoteManagerUtils) Reveal(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, tree bindings.StructsMerkleTree, signature []byte) (*Types.Transaction, error) { - voteManager := utilsInterface.GetVoteManager(client) + voteManager := razorUtils.GetVoteManager(client) var ( txn *Types.Transaction err error @@ -747,7 +390,7 @@ func (voteManagerUtils VoteManagerUtils) Reveal(client *ethclient.Client, opts * //This function is used to commit the values func (voteManagerUtils VoteManagerUtils) Commit(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, commitment [32]byte) (*Types.Transaction, error) { - voteManager := utilsInterface.GetVoteManager(client) + voteManager := razorUtils.GetVoteManager(client) var ( txn *Types.Transaction err error @@ -768,7 +411,7 @@ func (voteManagerUtils VoteManagerUtils) Commit(client *ethclient.Client, opts * //This function is used to check the allowance of staker func (tokenManagerUtils TokenManagerUtils) Allowance(client *ethclient.Client, opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - tokenManager := utilsInterface.GetTokenManager(client) + tokenManager := razorUtils.GetTokenManager(client) returnedValues := utils.InvokeFunctionWithTimeout(tokenManager, "Allowance", opts, owner, spender) returnedError := utils.CheckIfAnyError(returnedValues) if returnedError != nil { @@ -779,31 +422,31 @@ func (tokenManagerUtils TokenManagerUtils) Allowance(client *ethclient.Client, o //This function is used to approve the transaction func (tokenManagerUtils TokenManagerUtils) Approve(client *ethclient.Client, opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*Types.Transaction, error) { - tokenManager := utilsInterface.GetTokenManager(client) + tokenManager := razorUtils.GetTokenManager(client) return ExecuteTransaction(tokenManager, "Approve", opts, spender, amount) } //This function is used to transfer the tokens func (tokenManagerUtils TokenManagerUtils) Transfer(client *ethclient.Client, opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*Types.Transaction, error) { - tokenManager := utilsInterface.GetTokenManager(client) + tokenManager := razorUtils.GetTokenManager(client) return ExecuteTransaction(tokenManager, "Transfer", opts, recipient, amount) } //This function is used to create the job func (assetManagerUtils AssetManagerUtils) CreateJob(client *ethclient.Client, opts *bind.TransactOpts, weight uint8, power int8, selectorType uint8, name string, selector string, url string) (*Types.Transaction, error) { - assetManager := utilsInterface.GetCollectionManager(client) + assetManager := razorUtils.GetCollectionManager(client) return ExecuteTransaction(assetManager, "CreateJob", opts, weight, power, selectorType, name, selector, url) } //This function is used to set the collection status func (assetManagerUtils AssetManagerUtils) SetCollectionStatus(client *ethclient.Client, opts *bind.TransactOpts, assetStatus bool, id uint16) (*Types.Transaction, error) { - assetManager := utilsInterface.GetCollectionManager(client) + assetManager := razorUtils.GetCollectionManager(client) return ExecuteTransaction(assetManager, "SetCollectionStatus", opts, assetStatus, id) } //This function is used to get the active status func (assetManagerUtils AssetManagerUtils) GetActiveStatus(client *ethclient.Client, opts *bind.CallOpts, id uint16) (bool, error) { - assetMananger := utilsInterface.GetCollectionManager(client) + assetMananger := razorUtils.GetCollectionManager(client) returnedValues := utils.InvokeFunctionWithTimeout(assetMananger, "GetCollectionStatus", opts, id) returnedError := utils.CheckIfAnyError(returnedValues) if returnedError != nil { @@ -814,19 +457,19 @@ func (assetManagerUtils AssetManagerUtils) GetActiveStatus(client *ethclient.Cli //This function is used to update the job func (assetManagerUtils AssetManagerUtils) UpdateJob(client *ethclient.Client, opts *bind.TransactOpts, jobId uint16, weight uint8, power int8, selectorType uint8, selector string, url string) (*Types.Transaction, error) { - assetManager := utilsInterface.GetCollectionManager(client) + assetManager := razorUtils.GetCollectionManager(client) return ExecuteTransaction(assetManager, "UpdateJob", opts, jobId, weight, power, selectorType, selector, url) } //This function is used to create the collection func (assetManagerUtils AssetManagerUtils) CreateCollection(client *ethclient.Client, opts *bind.TransactOpts, tolerance uint32, power int8, aggregationMethod uint32, jobIDs []uint16, name string) (*Types.Transaction, error) { - assetManager := utilsInterface.GetCollectionManager(client) + assetManager := razorUtils.GetCollectionManager(client) return ExecuteTransaction(assetManager, "CreateCollection", opts, tolerance, power, aggregationMethod, jobIDs, name) } //This function is used to update the collection func (assetManagerUtils AssetManagerUtils) UpdateCollection(client *ethclient.Client, opts *bind.TransactOpts, collectionId uint16, tolerance uint32, aggregationMethod uint32, power int8, jobIds []uint16) (*Types.Transaction, error) { - assetManager := utilsInterface.GetCollectionManager(client) + assetManager := razorUtils.GetCollectionManager(client) return ExecuteTransaction(assetManager, "UpdateCollection", opts, collectionId, tolerance, aggregationMethod, power, jobIds) } @@ -835,6 +478,10 @@ func (flagSetUtils FLagSetUtils) GetStringProvider(flagSet *pflag.FlagSet) (stri return flagSet.GetString("provider") } +func (flagSetUtils FLagSetUtils) GetStringAlternateProvider(flagSet *pflag.FlagSet) (string, error) { + return flagSet.GetString("alternateProvider") +} + //This function returns gas multiplier in float 32 func (flagSetUtils FLagSetUtils) GetFloat32GasMultiplier(flagSet *pflag.FlagSet) (float32, error) { return flagSet.GetFloat32("gasmultiplier") @@ -860,7 +507,7 @@ func (flagSetUtils FLagSetUtils) GetStringLogLevel(flagSet *pflag.FlagSet) (stri return flagSet.GetString("logLevel") } -//This function returns RPC timeout in Int64 +//This function returns RPC Timeout in Int64 func (flagSetUtils FLagSetUtils) GetInt64RPCTimeout(flagSet *pflag.FlagSet) (int64, error) { return flagSet.GetInt64("rpcTimeout") } @@ -870,6 +517,11 @@ func (flagSetUtils FLagSetUtils) GetUint64GasLimitOverride(flagSet *pflag.FlagSe return flagSet.GetUint64("gasLimitOverride") } +//This function returns HTTP Timeout in Int64 +func (flagSetUtils FLagSetUtils) GetInt64HTTPTimeout(flagSet *pflag.FlagSet) (int64, error) { + return flagSet.GetInt64("httpTimeout") +} + //This function returns Gas Limit in Float32 func (flagSetUtils FLagSetUtils) GetFloat32GasLimit(flagSet *pflag.FlagSet) (float32, error) { return flagSet.GetFloat32("gasLimit") @@ -885,6 +537,11 @@ func (flagSetUtils FLagSetUtils) GetRootStringProvider() (string, error) { return rootCmd.PersistentFlags().GetString("provider") } +//This function returns the alternate provider of root in string +func (flagSetUtils FLagSetUtils) GetRootStringAlternateProvider() (string, error) { + return rootCmd.PersistentFlags().GetString("alternateProvider") +} + //This function returns the gas multiplier of root in float32 func (flagSetUtils FLagSetUtils) GetRootFloat32GasMultiplier() (float32, error) { return rootCmd.PersistentFlags().GetFloat32("gasmultiplier") @@ -920,24 +577,56 @@ func (flagSetUtils FLagSetUtils) GetRootUint64GasLimitOverride() (uint64, error) return rootCmd.PersistentFlags().GetUint64("gasLimitOverride") } -//This function returns the gas limit of root in Float32 +//This function returns the rpcTimeout of root in Int64 func (flagSetUtils FLagSetUtils) GetRootInt64RPCTimeout() (int64, error) { return rootCmd.PersistentFlags().GetInt64("rpcTimeout") } +//This function returns the HTTPTimeout of root in Int64 +func (flagSetUtils FLagSetUtils) GetRootInt64HTTPTimeout() (int64, error) { + return rootCmd.PersistentFlags().GetInt64("httpTimeout") +} + +//This function returns the max size of log file for root flag in Int +func (flagSetUtils FLagSetUtils) GetRootIntLogFileMaxSize() (int, error) { + return rootCmd.PersistentFlags().GetInt("logFileMaxSize") +} + +//This function returns the max number of backups for logFile for root flag in Int +func (flagSetUtils FLagSetUtils) GetRootIntLogFileMaxBackups() (int, error) { + return rootCmd.PersistentFlags().GetInt("logFileMaxBackups") +} + +//This function returns the max age of logFle for root file in Int +func (flagSetUtils FLagSetUtils) GetRootIntLogFileMaxAge() (int, error) { + return rootCmd.PersistentFlags().GetInt("logFileMaxAge") +} + //This function returns the from in string func (flagSetUtils FLagSetUtils) GetStringFrom(flagSet *pflag.FlagSet) (string, error) { - return flagSet.GetString("from") + from, err := flagSet.GetString("from") + if err != nil { + return "", err + } + return utils.ValidateAddress(from) } //This function returns the to in string func (flagSetUtils FLagSetUtils) GetStringTo(flagSet *pflag.FlagSet) (string, error) { - return flagSet.GetString("to") + to, err := flagSet.GetString("to") + if err != nil { + return "", err + } + return utils.ValidateAddress(to) } //This function returns the address in string func (flagSetUtils FLagSetUtils) GetStringAddress(flagSet *pflag.FlagSet) (string, error) { - return flagSet.GetString("address") + address, err := flagSet.GetString("address") + if err != nil { + return "", err + } + return utils.ValidateAddress(address) } //This function returns the stakerId in Uint32 @@ -970,11 +659,6 @@ func (flagSetUtils FLagSetUtils) GetUint8Weight(flagSet *pflag.FlagSet) (uint8, return flagSet.GetUint8("weight") } -//This function returns the AssetId in Uint16 -func (flagSetUtils FLagSetUtils) GetUint16AssetId(flagSet *pflag.FlagSet) (uint16, error) { - return flagSet.GetUint16("assetId") -} - //This function returns the selectorType in Uint8 func (flagSetUtils FLagSetUtils) GetUint8SelectorType(flagSet *pflag.FlagSet) (uint8, error) { return flagSet.GetUint8("selectorType") @@ -1055,6 +739,21 @@ func (flagSetUtils FLagSetUtils) GetStringCertKey(flagSet *pflag.FlagSet) (strin return flagSet.GetString("certKey") } +//This function returns the max size of log file in Int +func (flagSetUtils FLagSetUtils) GetIntLogFileMaxSize(flagSet *pflag.FlagSet) (int, error) { + return flagSet.GetInt("logFileMaxSize") +} + +//This function returns the max number of backups for logFile in Int +func (flagSetUtils FLagSetUtils) GetIntLogFileMaxBackups(flagSet *pflag.FlagSet) (int, error) { + return flagSet.GetInt("logFileMaxBackups") +} + +//This function returns the max nage for logFle in Int +func (flagSetUtils FLagSetUtils) GetIntLogFileMaxAge(flagSet *pflag.FlagSet) (int, error) { + return flagSet.GetInt("logFileMaxAge") +} + //This function returns the accounts func (keystoreUtils KeystoreUtils) Accounts(path string) []ethAccounts.Account { ks := keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP) diff --git a/cmd/test_utils.go b/cmd/test_utils.go new file mode 100644 index 00000000..afe5f44b --- /dev/null +++ b/cmd/test_utils.go @@ -0,0 +1,170 @@ +package cmd + +import ( + accountsPkgMocks "razor/accounts/mocks" + "razor/cmd/mocks" + "razor/path" + pathPkgMocks "razor/path/mocks" + "razor/utils" + utilsPkgMocks "razor/utils/mocks" +) + +var ( + utilsMock *utilsPkgMocks.Utils + clientUtilsMock *utilsPkgMocks.ClientUtils + timeUtilsMock *utilsPkgMocks.TimeUtils + osUtilsMock *utilsPkgMocks.OSUtils + coinUtilsMock *utilsPkgMocks.CoinUtils + merkleUtilsMock *utilsPkgMocks.MerkleTreeInterface + ioUtilsMock *utilsPkgMocks.IOUtils + abiUtilsMock *utilsPkgMocks.ABIUtils + bindUtilsMock *utilsPkgMocks.BindUtils + accountUtilsMock *utilsPkgMocks.AccountsUtils + blockManagerUtilsMock *utilsPkgMocks.BlockManagerUtils + stakeManagerUtilsMock *utilsPkgMocks.StakeManagerUtils + assetManagerUtilsMock *utilsPkgMocks.AssetManagerUtils + voteManagerUtilsMock *utilsPkgMocks.VoteManagerUtils + bindingUtilsMock *utilsPkgMocks.BindingsUtils + jsonUtilsMock *utilsPkgMocks.JsonUtils + stakedTokenUtilsMock *utilsPkgMocks.StakedTokenUtils + retryUtilsMock *utilsPkgMocks.RetryUtils + fileUtilsMock *utilsPkgMocks.FileUtils + gasUtilsMock *utilsPkgMocks.GasUtils + cmdUtilsMock *mocks.UtilsCmdInterface + flagSetMock *mocks.FlagSetInterface + transactionMock *mocks.TransactionInterface + stakeManagerMock *mocks.StakeManagerInterface + blockManagerMock *mocks.BlockManagerInterface + voteManagerMock *mocks.VoteManagerInterface + keystoreMock *mocks.KeystoreInterface + tokenManagerMock *mocks.TokenManagerInterface + assetManagerMock *mocks.AssetManagerInterface + cryptoMock *mocks.CryptoInterface + viperMock *mocks.ViperInterface + timeMock *mocks.TimeInterface + stringMock *mocks.StringInterface + abiMock *mocks.AbiInterface + osMock *mocks.OSInterface + pathMock *pathPkgMocks.PathInterface + osPathMock *pathPkgMocks.OSInterface + accountsMock *accountsPkgMocks.AccountInterface +) + +func SetUpMockInterfaces() { + utilsMock = new(utilsPkgMocks.Utils) + razorUtils = utilsMock + + clientUtilsMock = new(utilsPkgMocks.ClientUtils) + clientUtils = clientUtilsMock + + cmdUtilsMock = new(mocks.UtilsCmdInterface) + cmdUtils = cmdUtilsMock + + fileUtilsMock = new(utilsPkgMocks.FileUtils) + fileUtils = fileUtilsMock + + timeUtilsMock = new(utilsPkgMocks.TimeUtils) + utils.Time = timeUtilsMock + + osUtilsMock = new(utilsPkgMocks.OSUtils) + utils.OS = osUtilsMock + + coinUtilsMock = new(utilsPkgMocks.CoinUtils) + utils.CoinInterface = coinUtilsMock + + merkleUtilsMock = new(utilsPkgMocks.MerkleTreeInterface) + merkleUtils = merkleUtilsMock + + ioUtilsMock = new(utilsPkgMocks.IOUtils) + utils.IOInterface = ioUtilsMock + + abiUtilsMock = new(utilsPkgMocks.ABIUtils) + utils.ABIInterface = abiUtilsMock + + bindUtilsMock = new(utilsPkgMocks.BindUtils) + utils.BindingsInterface = bindingUtilsMock + + accountUtilsMock = new(utilsPkgMocks.AccountsUtils) + utils.AccountsInterface = accountUtilsMock + + blockManagerUtilsMock = new(utilsPkgMocks.BlockManagerUtils) + utils.BlockManagerInterface = blockManagerUtilsMock + + stakeManagerUtilsMock = new(utilsPkgMocks.StakeManagerUtils) + utils.StakeManagerInterface = stakeManagerUtilsMock + + assetManagerUtilsMock = new(utilsPkgMocks.AssetManagerUtils) + utils.AssetManagerInterface = assetManagerUtilsMock + + voteManagerUtilsMock = new(utilsPkgMocks.VoteManagerUtils) + utils.VoteManagerInterface = voteManagerUtilsMock + + bindingUtilsMock = new(utilsPkgMocks.BindingsUtils) + utils.BindInterface = bindUtilsMock + + jsonUtilsMock = new(utilsPkgMocks.JsonUtils) + utils.JsonInterface = jsonUtilsMock + + stakedTokenUtilsMock = new(utilsPkgMocks.StakedTokenUtils) + utils.StakedTokenInterface = stakedTokenUtilsMock + + retryUtilsMock = new(utilsPkgMocks.RetryUtils) + utils.RetryInterface = retryUtilsMock + + flagSetMock = new(mocks.FlagSetInterface) + flagSetUtils = flagSetMock + + transactionMock = new(mocks.TransactionInterface) + transactionUtils = transactionMock + + fileUtilsMock = new(utilsPkgMocks.FileUtils) + fileUtils = fileUtilsMock + + gasUtilsMock = new(utilsPkgMocks.GasUtils) + gasUtils = gasUtilsMock + + stakeManagerMock = new(mocks.StakeManagerInterface) + stakeManagerUtils = stakeManagerMock + + blockManagerMock = new(mocks.BlockManagerInterface) + blockManagerUtils = blockManagerMock + + voteManagerMock = new(mocks.VoteManagerInterface) + voteManagerUtils = voteManagerMock + + keystoreMock = new(mocks.KeystoreInterface) + keystoreUtils = keystoreMock + + tokenManagerMock = new(mocks.TokenManagerInterface) + tokenManagerUtils = tokenManagerMock + + assetManagerMock = new(mocks.AssetManagerInterface) + assetManagerUtils = assetManagerMock + + cryptoMock = new(mocks.CryptoInterface) + cryptoUtils = cryptoMock + + viperMock = new(mocks.ViperInterface) + viperUtils = viperMock + + timeMock = new(mocks.TimeInterface) + timeUtils = timeMock + + stringMock = new(mocks.StringInterface) + stringUtils = stringMock + + abiMock = new(mocks.AbiInterface) + abiUtils = abiMock + + osMock = new(mocks.OSInterface) + osUtils = osMock + + pathMock = new(pathPkgMocks.PathInterface) + pathUtils = pathMock + + osPathMock = new(pathPkgMocks.OSInterface) + path.OSUtilsInterface = osPathMock + + accountsMock = new(accountsPkgMocks.AccountInterface) + accountUtils = accountsMock +} diff --git a/cmd/transfer.go b/cmd/transfer.go index 9cf56a05..b467ee42 100644 --- a/cmd/transfer.go +++ b/cmd/transfer.go @@ -43,12 +43,16 @@ func (*UtilsStruct) ExecuteTransfer(flagSet *pflag.FlagSet) { utils.CheckError("Error in getting fromAddress: ", err) logger.SetLoggerParameters(client, fromAddress) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(fromAddress, password) + utils.CheckError("Error in fetching private key from given password: ", err) + toAddress, err := flagSetUtils.GetStringTo(flagSet) utils.CheckError("Error in getting toAddress: ", err) @@ -70,8 +74,8 @@ func (*UtilsStruct) ExecuteTransfer(flagSet *pflag.FlagSet) { log.Debugf("Calling Transfer() with arguments transferInput = %+v", transferInput) txn, err := cmdUtils.Transfer(client, config, transferInput) utils.CheckError("Transfer error: ", err) - log.Info("Transaction Hash: ", txn) - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for transfer: ", err) } @@ -89,9 +93,9 @@ func (*UtilsStruct) Transfer(client *ethclient.Client, config types.Configuratio ContractAddress: core.RAZORAddress, MethodName: "transfer", Parameters: []interface{}{common.HexToAddress(transferInput.ToAddress), transferInput.ValueInWei}, - ABI: bindings.RAZORABI, + ABI: bindings.RAZORMetaData.ABI, }) - log.Infof("Transferring %g tokens from %s to %s", razorUtils.GetAmountInDecimal(transferInput.ValueInWei), transferInput.FromAddress, transferInput.ToAddress) + log.Infof("Transferring %g tokens from %s to %s", utils.GetAmountInDecimal(transferInput.ValueInWei), transferInput.FromAddress, transferInput.ToAddress) log.Debugf("Executing Transfer transaction with toAddress: %s, amount: %s", transferInput.ToAddress, transferInput.ValueInWei) txn, err := tokenManagerUtils.Transfer(client, txnOpts, common.HexToAddress(transferInput.ToAddress), transferInput.ValueInWei) @@ -100,7 +104,9 @@ func (*UtilsStruct) Transfer(client *ethclient.Client, config types.Configuratio return core.NilHash, err } - return transactionUtils.Hash(txn), err + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/transfer_test.go b/cmd/transfer_test.go index 968b3896..30410690 100644 --- a/cmd/transfer_test.go +++ b/cmd/transfer_test.go @@ -5,13 +5,13 @@ import ( "crypto/elliptic" "crypto/rand" "errors" - "github.com/stretchr/testify/mock" "math/big" - "razor/cmd/mocks" "razor/core" "razor/core/types" "testing" + "github.com/stretchr/testify/mock" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" @@ -22,7 +22,6 @@ import ( func TestTransfer(t *testing.T) { var client *ethclient.Client var config types.Configurations - var transferInput types.TransferInput privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) txnOpts, _ := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(31000)) @@ -70,24 +69,19 @@ func TestTransfer(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - tokenManangerUtilsMock := new(mocks.TokenManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - tokenManagerUtils = tokenManangerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("CheckAmountAndBalance", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("*big.Int")).Return(tt.args.amount) utilsMock.On("GetTxnOpts", mock.Anything).Return(tt.args.txnOpts) utilsMock.On("GetAmountInDecimal", mock.AnythingOfType("*big.Int")).Return(tt.args.decimalAmount) - tokenManangerUtilsMock.On("Transfer", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("common.Address"), mock.AnythingOfType("*big.Int")).Return(tt.args.transferTxn, tt.args.transferErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.transferHash) + tokenManagerMock.On("Transfer", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("common.Address"), mock.AnythingOfType("*big.Int")).Return(tt.args.transferTxn, tt.args.transferErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.transferHash) utils := &UtilsStruct{} - got, err := utils.Transfer(client, config, transferInput) + got, err := utils.Transfer(client, config, types.TransferInput{ + ValueInWei: big.NewInt(1).Mul(big.NewInt(1), big.NewInt(1e18)), + }) if got != tt.want { t.Errorf("Txn hash for transfer function, got = %v, want = %v", got, tt.want) } @@ -256,22 +250,15 @@ func TestExecuteTransfer(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - flagsetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - flagSetUtils = flagsetUtilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagsetUtilsMock.On("GetStringFrom", flagSet).Return(tt.args.from, tt.args.fromErr) - flagsetUtilsMock.On("GetStringTo", flagSet).Return(tt.args.to, tt.args.toErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringFrom", flagSet).Return(tt.args.from, tt.args.fromErr) + flagSetMock.On("GetStringTo", flagSet).Return(tt.args.to, tt.args.toErr) cmdUtilsMock.On("AssignAmountInWei", flagSet).Return(tt.args.amount, tt.args.amountErr) - utilsMock.On("AssignPassword", flagSet).Return() utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) utilsMock.On("FetchBalance", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.balance, tt.args.balanceErr) cmdUtilsMock.On("Transfer", mock.AnythingOfType("*ethclient.Client"), config, mock.AnythingOfType("types.TransferInput")).Return(tt.args.transferHash, tt.args.transferErr) diff --git a/cmd/unlockWithdraw.go b/cmd/unlockWithdraw.go index d42b9352..7657beb2 100644 --- a/cmd/unlockWithdraw.go +++ b/cmd/unlockWithdraw.go @@ -43,13 +43,15 @@ func (*UtilsStruct) ExecuteUnlockWithdraw(flagSet *pflag.FlagSet) { log.Debug("ExecuteUnlockWithdraw: Address: ", address) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) - razorUtils.CheckEthBalanceIsZero(client, address) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) stakerId, err := razorUtils.AssignStakerId(flagSet, client, address) utils.CheckError("Error in fetching stakerId: ", err) @@ -63,7 +65,7 @@ func (*UtilsStruct) ExecuteUnlockWithdraw(flagSet *pflag.FlagSet) { utils.CheckError("UnlockWithdraw error: ", err) if txn != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for unlockWithdraw: ", err) } } @@ -88,6 +90,13 @@ func (*UtilsStruct) HandleWithdrawLock(client *ethclient.Client, account types.A } log.Debug("HandleWithdrawLock: Epoch: ", epoch) + waitFor := big.NewInt(0).Sub(withdrawLock.UnlockAfter, big.NewInt(int64(epoch))) + if waitFor.Cmp(big.NewInt(0)) > 0 { + timeRemaining := uint64(waitFor.Int64()) * core.EpochLength + log.Infof("Withdrawal period not reached. Cannot withdraw now, please wait for %d epoch(s)! (approximately %s)", waitFor, razorUtils.SecondsToReadableTime(int(timeRemaining))) + return core.NilHash, nil + } + if big.NewInt(int64(epoch)).Cmp(withdrawLock.UnlockAfter) >= 0 { txnArgs := types.TransactionOptions{ Client: client, @@ -97,7 +106,7 @@ func (*UtilsStruct) HandleWithdrawLock(client *ethclient.Client, account types.A Config: configurations, ContractAddress: core.StakeManagerAddress, MethodName: "unlockWithdraw", - ABI: bindings.StakeManagerABI, + ABI: bindings.StakeManagerMetaData.ABI, Parameters: []interface{}{stakerId}, } txnOpts := razorUtils.GetTxnOpts(txnArgs) @@ -118,9 +127,9 @@ func (*UtilsStruct) UnlockWithdraw(client *ethclient.Client, txnOpts *bind.Trans return core.NilHash, err } - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) - - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/unlockWithdraw_test.go b/cmd/unlockWithdraw_test.go index 3d45424f..c8e38ad0 100644 --- a/cmd/unlockWithdraw_test.go +++ b/cmd/unlockWithdraw_test.go @@ -5,18 +5,18 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core" + "razor/core/types" + "reflect" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core" - "razor/core/types" - "reflect" - "testing" ) func TestExecuteUnlockWithdraw(t *testing.T) { @@ -94,24 +94,14 @@ func TestExecuteUnlockWithdraw(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - flagSetUtils = flagSetUtilsMock - cmdUtils = cmdUtilsMock - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) - flagSetUtilsMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) + flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsMock.On("CheckEthBalanceIsZero", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return() utilsMock.On("AssignStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) cmdUtilsMock.On("HandleWithdrawLock", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.txn, tt.args.err) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(nil) @@ -143,6 +133,7 @@ func TestHandleWithdrawLock(t *testing.T) { txnOpts *bind.TransactOpts unlockWithdraw common.Hash unlockWithdrawErr error + time string } tests := []struct { name string @@ -200,25 +191,21 @@ func TestHandleWithdrawLock(t *testing.T) { UnlockAfter: big.NewInt(4), }, epoch: 3, + time: "20 minutes 0 seconds", }, want: core.NilHash, - wantErr: true, + wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() utilsMock.On("GetLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.withdrawLock, tt.args.withdrawLockErr) utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) cmdUtilsMock.On("UnlockWithdraw", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.unlockWithdraw, tt.args.unlockWithdrawErr) - + utilsMock.On("SecondsToReadableTime", mock.AnythingOfType("int")).Return(tt.args.time) ut := &UtilsStruct{} got, err := ut.HandleWithdrawLock(client, account, configurations, stakerId) if (err != nil) != tt.wantErr { @@ -270,14 +257,10 @@ func TestUnlockWithdraw(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() - stakeManagerUtilsMock.On("UnlockWithdraw", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32")).Return(tt.args.txn, tt.args.txnErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + stakeManagerMock.On("UnlockWithdraw", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32")).Return(tt.args.txn, tt.args.txnErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) ut := &UtilsStruct{} got, err := ut.UnlockWithdraw(client, txnOpts, stakerId) if (err != nil) != tt.wantErr { diff --git a/cmd/unstake.go b/cmd/unstake.go index 06d52379..40c6abbe 100644 --- a/cmd/unstake.go +++ b/cmd/unstake.go @@ -46,18 +46,20 @@ func (*UtilsStruct) ExecuteUnstake(flagSet *pflag.FlagSet) { utils.CheckError("Error in getting address: ", err) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + log.Debug("Getting amount in wei...") valueInWei, err := cmdUtils.AssignAmountInWei(flagSet) utils.CheckError("Error in getting amountInWei: ", err) - razorUtils.CheckEthBalanceIsZero(client, address) - stakerId, err := razorUtils.AssignStakerId(flagSet, client, address) utils.CheckError("StakerId error: ", err) @@ -72,7 +74,7 @@ func (*UtilsStruct) ExecuteUnstake(flagSet *pflag.FlagSet) { txnHash, err := cmdUtils.Unstake(config, client, unstakeInput) utils.CheckError("Unstake Error: ", err) if txnHash != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txnHash.String()) + err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for unstake: ", err) } } @@ -93,15 +95,16 @@ func (*UtilsStruct) Unstake(config types.Configurations, client *ethclient.Clien log.Error("Error in getting staker: ", err) return core.NilHash, err } + log.Debugf("Unstake: Staker info: %+v", staker) log.Debug("Unstake: Calling ApproveUnstake()...") - approveHash, err := cmdUtils.ApproveUnstake(client, staker, txnArgs) + approveHash, err := cmdUtils.ApproveUnstake(client, staker.TokenAddress, txnArgs) if err != nil { return core.NilHash, err } if approveHash != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, approveHash.String()) + err = razorUtils.WaitForBlockCompletion(client, approveHash.Hex()) if err != nil { return core.NilHash, err } @@ -111,7 +114,7 @@ func (*UtilsStruct) Unstake(config types.Configurations, client *ethclient.Clien txnArgs.ContractAddress = core.StakeManagerAddress txnArgs.MethodName = "unstake" - txnArgs.ABI = bindings.StakeManagerABI + txnArgs.ABI = bindings.StakeManagerMetaData.ABI unstakeLock, err := razorUtils.GetLock(txnArgs.Client, txnArgs.AccountAddress, stakerId, 0) if err != nil { @@ -135,21 +138,23 @@ func (*UtilsStruct) Unstake(config types.Configurations, client *ethclient.Clien log.Error("Error in un-staking: ", err) return core.NilHash, err } - log.Info("Transaction hash: ", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } //This function approves the unstake -func (*UtilsStruct) ApproveUnstake(client *ethclient.Client, staker bindings.StructsStaker, txnArgs types.TransactionOptions) (common.Hash, error) { +func (*UtilsStruct) ApproveUnstake(client *ethclient.Client, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) { txnOpts := razorUtils.GetTxnOpts(txnArgs) log.Infof("Approving %d amount for unstake...", txnArgs.Amount) - txn, err := stakeManagerUtils.ApproveUnstake(client, txnOpts, staker, txnArgs.Amount) + txn, err := stakeManagerUtils.ApproveUnstake(client, txnOpts, stakerTokenAddress, txnArgs.Amount) if err != nil { log.Error("Error in approving for unstake") return core.NilHash, err } - log.Info("Transaction Hash: ", transactionUtils.Hash(txn).String()) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { diff --git a/cmd/unstake_test.go b/cmd/unstake_test.go index c594cc62..9ccde643 100644 --- a/cmd/unstake_test.go +++ b/cmd/unstake_test.go @@ -5,19 +5,19 @@ import ( "crypto/elliptic" "crypto/rand" "errors" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/spf13/pflag" - "github.com/stretchr/testify/mock" "math/big" - "razor/cmd/mocks" "razor/core" "razor/core/types" "razor/pkg/bindings" "reflect" "testing" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + Types "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/spf13/pflag" + "github.com/stretchr/testify/mock" ) func TestUnstake(t *testing.T) { @@ -123,16 +123,7 @@ func TestUnstake(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - cmdUtils = cmdUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.staker, tt.args.stakerErr) cmdUtilsMock.On("ApproveUnstake", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.approveHash, tt.args.approveHashErr) @@ -140,8 +131,8 @@ func TestUnstake(t *testing.T) { utilsMock.On("GetLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.lock, tt.args.lockErr) cmdUtilsMock.On("WaitForAppropriateState", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - stakeManagerUtilsMock.On("Unstake", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.unstakeTxn, tt.args.unstakeErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + stakeManagerMock.On("Unstake", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.unstakeTxn, tt.args.unstakeErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} _, gotErr := utils.Unstake(config, client, @@ -302,26 +293,14 @@ func TestExecuteUnstake(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - cmdUtils = cmdUtilsMock - transactionUtils = transactionUtilsMock - flagSetUtils = flagSetUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + SetUpMockInterfaces() + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagSetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("AssignAmountInWei", flagSet).Return(tt.args.value, tt.args.valueErr) - utilsMock.On("CheckEthBalanceIsZero", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return() utilsMock.On("AssignStakerId", flagSet, mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("GetLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32")).Return(tt.args.lock, tt.args.lockErr) cmdUtilsMock.On("Unstake", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.unstakeHash, tt.args.unstakeErr) @@ -342,9 +321,9 @@ func TestExecuteUnstake(t *testing.T) { func TestApproveUnstake(t *testing.T) { var ( - client *ethclient.Client - staker bindings.StructsStaker - txnArgs types.TransactionOptions + client *ethclient.Client + stakerTokenAddress common.Address + txnArgs types.TransactionOptions ) privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) @@ -379,19 +358,13 @@ func TestApproveUnstake(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - stakeManagerUtilsMock.On("ApproveUnstake", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.txn, tt.args.txnErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + stakeManagerMock.On("ApproveUnstake", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.txn, tt.args.txnErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) ut := &UtilsStruct{} - got, err := ut.ApproveUnstake(client, staker, txnArgs) + got, err := ut.ApproveUnstake(client, stakerTokenAddress, txnArgs) if (err != nil) != tt.wantErr { t.Errorf("ApproveUnstake() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/cmd/updateCollection.go b/cmd/updateCollection.go index 0066283c..a73c92c0 100644 --- a/cmd/updateCollection.go +++ b/cmd/updateCollection.go @@ -45,12 +45,16 @@ func (*UtilsStruct) ExecuteUpdateCollection(flagSet *pflag.FlagSet) { utils.CheckError("Error in getting address: ", err) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + collectionId, err := flagSetUtils.GetUint16CollectionId(flagSet) utils.CheckError("Error in getting collectionID: ", err) @@ -77,13 +81,13 @@ func (*UtilsStruct) ExecuteUpdateCollection(flagSet *pflag.FlagSet) { log.Debugf("ExecuteUpdateCollection: Calling UpdateCollection() with arguments collectionInput: %+v, collectionId: %d", collectionInput, collectionId) txn, err := cmdUtils.UpdateCollection(client, config, collectionInput, collectionId) utils.CheckError("Update Collection error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for updateCollection: ", err) } //This function allows the admin to update an existing collection func (*UtilsStruct) UpdateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) { - jobIds := razorUtils.ConvertUintArrayToUint16Array(collectionInput.JobIds) + jobIds := utils.ConvertUintArrayToUint16Array(collectionInput.JobIds) log.Debug("UpdateCollection: Uint16 jobIds: ", jobIds) _, err := cmdUtils.WaitIfCommitState(client, "update collection") if err != nil { @@ -99,17 +103,18 @@ func (*UtilsStruct) UpdateCollection(client *ethclient.Client, config types.Conf ContractAddress: core.CollectionManagerAddress, MethodName: "updateCollection", Parameters: []interface{}{collectionId, collectionInput.Tolerance, collectionInput.Aggregation, collectionInput.Power, jobIds}, - ABI: bindings.CollectionManagerABI, + ABI: bindings.CollectionManagerMetaData.ABI, }) + log.Info("Updating collection...") log.Debugf("Executing UpdateCollection transaction with collectionId = %d, tolerance = %d, aggregation method = %d, power = %d, jobIds = %v", collectionId, collectionInput.Tolerance, collectionInput.Aggregation, collectionInput.Power, jobIds) txn, err := assetManagerUtils.UpdateCollection(client, txnOpts, collectionId, collectionInput.Tolerance, collectionInput.Aggregation, collectionInput.Power, jobIds) if err != nil { log.Error("Error in updating collection") return core.NilHash, err } - log.Info("Updating collection...") - log.Info("Txn Hash: ", transactionUtils.Hash(txn)) - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil } func init() { @@ -122,7 +127,7 @@ func init() { Password string Power int8 JobIds []uint - Tolerance uint16 + Tolerance uint32 ) updateCollectionCmd.Flags().StringVarP(&Account, "address", "a", "", "address of the job creator") @@ -131,7 +136,7 @@ func init() { updateCollectionCmd.Flags().Int8VarP(&Power, "power", "", 0, "multiplier for the collection") updateCollectionCmd.Flags().StringVarP(&Password, "password", "", "", "password path of job creator to protect the keystore") updateCollectionCmd.Flags().UintSliceVarP(&JobIds, "jobIds", "", []uint{}, "job ids for the collection") - updateCollectionCmd.Flags().Uint16VarP(&Tolerance, "tolerance", "", 0, "tolerance") + updateCollectionCmd.Flags().Uint32VarP(&Tolerance, "tolerance", "", 0, "tolerance") collectionIdErr := updateCollectionCmd.MarkFlagRequired("collectionId") utils.CheckError("Collection Id error: ", collectionIdErr) diff --git a/cmd/updateCollection_test.go b/cmd/updateCollection_test.go index a3d0b724..bc3523f7 100644 --- a/cmd/updateCollection_test.go +++ b/cmd/updateCollection_test.go @@ -5,17 +5,17 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core" + "razor/core/types" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core" - "razor/core/types" - "testing" ) func TestUpdateCollection(t *testing.T) { @@ -82,22 +82,13 @@ func TestUpdateCollection(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - assetManagerUtilsMock := new(mocks.AssetManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - assetManagerUtils = assetManagerUtilsMock - transactionUtils = transactionUtilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() utilsMock.On("ConvertUintArrayToUint16Array", mock.Anything).Return(jobIdUint16) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) cmdUtilsMock.On("WaitIfCommitState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(WaitIfCommitStateStatus, tt.args.waitIfCommitStateErr) - assetManagerUtilsMock.On("UpdateCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.updateCollectionTxn, tt.args.updateCollectionErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + assetManagerMock.On("UpdateCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.updateCollectionTxn, tt.args.updateCollectionErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} got, err := utils.UpdateCollection(client, config, collectionInput, collectionId) @@ -291,27 +282,21 @@ func TestExecuteUpdateCollection(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - flagsetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - flagSetUtils = flagsetUtilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagsetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) - flagsetUtilsMock.On("GetUint16CollectionId", flagSet).Return(tt.args.collectionId, tt.args.collectionIdErr) - flagsetUtilsMock.On("GetUintSliceJobIds", flagSet).Return(tt.args.jobId, tt.args.jobIdErr) - flagsetUtilsMock.On("GetUint32Aggregation", flagSet).Return(tt.args.aggregation, tt.args.aggregationErr) - flagsetUtilsMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetUint16CollectionId", flagSet).Return(tt.args.collectionId, tt.args.collectionIdErr) + flagSetMock.On("GetUintSliceJobIds", flagSet).Return(tt.args.jobId, tt.args.jobIdErr) + flagSetMock.On("GetUint32Aggregation", flagSet).Return(tt.args.aggregation, tt.args.aggregationErr) + flagSetMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("UpdateCollection", mock.AnythingOfType("*ethclient.Client"), config, mock.Anything, mock.Anything).Return(tt.args.updateCollectionTxn, tt.args.updateCollectionErr) utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) - flagsetUtilsMock.On("GetUint32Tolerance", flagSet).Return(tt.args.tolerance, tt.args.toleranceErr) + flagSetMock.On("GetUint32Tolerance", flagSet).Return(tt.args.tolerance, tt.args.toleranceErr) utils := &UtilsStruct{} fatal = false diff --git a/cmd/updateCommission.go b/cmd/updateCommission.go index ec8a6af3..b5fa8e3d 100644 --- a/cmd/updateCommission.go +++ b/cmd/updateCommission.go @@ -42,12 +42,16 @@ func (*UtilsStruct) ExecuteUpdateCommission(flagSet *pflag.FlagSet) { utils.CheckError("Error in getting address: ", err) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + commission, err := flagSetUtils.GetUint8Commission(flagSet) utils.CheckError("Error in getting commission", err) @@ -99,7 +103,7 @@ func (*UtilsStruct) UpdateCommission(config types.Configurations, client *ethcli if stakerInfo.EpochCommissionLastUpdated != 0 && (stakerInfo.EpochCommissionLastUpdated+uint32(epochLimitForUpdateCommission)) >= epoch { waitFor := uint32(epochLimitForUpdateCommission) - (epoch - stakerInfo.EpochCommissionLastUpdated) + 1 - timeRemaining := int64(waitFor) * core.EpochLength + timeRemaining := uint64(waitFor) * core.EpochLength if waitFor == 1 { log.Infof("Cannot update commission now. Please wait for %d epoch! (approximately %s)", waitFor, razorUtils.SecondsToReadableTime(int(timeRemaining))) } else { @@ -115,7 +119,7 @@ func (*UtilsStruct) UpdateCommission(config types.Configurations, client *ethcli ChainId: core.ChainId, Config: config, ContractAddress: core.StakeManagerAddress, - ABI: bindings.StakeManagerABI, + ABI: bindings.StakeManagerMetaData.ABI, MethodName: "updateCommission", Parameters: []interface{}{updateCommissionInput.Commission}, } @@ -128,8 +132,8 @@ func (*UtilsStruct) UpdateCommission(config types.Configurations, client *ethcli return err } txnHash := transactionUtils.Hash(txn) - log.Infof("Transaction hash: %s", txnHash) - err = razorUtils.WaitForBlockCompletion(client, txnHash.String()) + log.Infof("Txn Hash: %s", txnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) if err != nil { log.Error("Error in WaitForBlockCompletion for updateCommission: ", err) return err diff --git a/cmd/updateCommission_test.go b/cmd/updateCommission_test.go index c9095feb..a35aac79 100644 --- a/cmd/updateCommission_test.go +++ b/cmd/updateCommission_test.go @@ -6,7 +6,6 @@ import ( "crypto/rand" "errors" "math/big" - "razor/cmd/mocks" "razor/core/types" "razor/pkg/bindings" "testing" @@ -196,24 +195,17 @@ func TestUpdateCommission(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) utilsMock.On("GetMaxCommission", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.maxCommission, tt.args.maxCommissionErr) utilsMock.On("GetEpochLimitForUpdateCommission", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epochLimitForUpdateCommission, tt.args.epochLimitForUpdateCommissionErr) utilsMock.On("SecondsToReadableTime", mock.AnythingOfType("int")).Return(tt.args.time) - stakeManagerUtilsMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionTxn, tt.args.UpdateCommissionErr) + stakeManagerMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionTxn, tt.args.UpdateCommissionErr) utils := &UtilsStruct{} gotErr := utils.UpdateCommission(config, client, types.UpdateCommissionInput{ @@ -344,20 +336,14 @@ func TestExecuteUpdateCommission(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - utilsMock := new(mocks.UtilsInterface) - flagsetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - flagSetUtils = flagsetUtilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) - flagsetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagsetUtilsMock.On("GetUint8Commission", flagSet).Return(tt.args.commission, tt.args.commissionErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetUint8Commission", flagSet).Return(tt.args.commission, tt.args.commissionErr) utilsMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionErr) diff --git a/cmd/updateJob.go b/cmd/updateJob.go index cf858abc..e75e421f 100644 --- a/cmd/updateJob.go +++ b/cmd/updateJob.go @@ -45,12 +45,16 @@ func (*UtilsStruct) ExecuteUpdateJob(flagSet *pflag.FlagSet) { utils.CheckError("Error in getting address: ", err) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + jobId, err := flagSetUtils.GetUint16JobId(flagSet) utils.CheckError("Error in getting jobId: ", err) @@ -82,7 +86,7 @@ func (*UtilsStruct) ExecuteUpdateJob(flagSet *pflag.FlagSet) { log.Debugf("ExecuteUpdateJob: Calling UpdateJob() with arguments jobInput = %+v, jobId = %d", jobInput, jobId) txn, err := cmdUtils.UpdateJob(client, config, jobInput, jobId) utils.CheckError("UpdateJob error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.String()) + err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for updateJob: ", err) } @@ -102,14 +106,18 @@ func (*UtilsStruct) UpdateJob(client *ethclient.Client, config types.Configurati ContractAddress: core.CollectionManagerAddress, MethodName: "updateJob", Parameters: []interface{}{jobId, jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Selector, jobInput.Url}, - ABI: bindings.CollectionManagerABI, + ABI: bindings.CollectionManagerMetaData.ABI, }) + log.Info("Updating Job...") log.Debugf("Executing UpdateJob transaction with arguments jobId = %d, weight = %d, power = %d, selector type = %d, selector = %s, URL = %s", jobId, jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Selector, jobInput.Url) txn, err := assetManagerUtils.UpdateJob(client, txnArgs, jobId, jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Selector, jobInput.Url) if err != nil { return core.NilHash, err } - return transactionUtils.Hash(txn), nil + txnHash := transactionUtils.Hash(txn) + log.Info("Txn Hash: ", txnHash.Hex()) + return txnHash, nil + } func init() { diff --git a/cmd/updateJob_test.go b/cmd/updateJob_test.go index 7292bcae..69b8bf06 100644 --- a/cmd/updateJob_test.go +++ b/cmd/updateJob_test.go @@ -5,17 +5,17 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "math/big" + "razor/core" + "razor/core/types" + "testing" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" - "math/big" - "razor/cmd/mocks" - "razor/core" - "razor/core/types" - "testing" ) func TestUpdateJob(t *testing.T) { @@ -77,21 +77,12 @@ func TestUpdateJob(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - assetManagerUtilsMock := new(mocks.AssetManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - assetManagerUtils = assetManagerUtilsMock - transactionUtils = transactionUtilsMock + SetUpMockInterfaces() utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) cmdUtilsMock.On("WaitIfCommitState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(WaitIfCommitStateStatus, tt.args.waitIfCommitStateErr) - assetManagerUtilsMock.On("UpdateJob", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.updateJobTxn, tt.args.updateJobErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + assetManagerMock.On("UpdateJob", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.updateJobTxn, tt.args.updateJobErr) + transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} @@ -338,24 +329,19 @@ func TestExecuteUpdateJob(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - flagsetUtilsMock := new(mocks.FlagSetInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - - razorUtils = utilsMock - flagSetUtils = flagsetUtilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagsetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) - flagsetUtilsMock.On("GetStringUrl", flagSet).Return(tt.args.url, tt.args.urlErr) - flagsetUtilsMock.On("GetStringSelector", flagSet).Return(tt.args.selector, tt.args.selectorErr) - flagsetUtilsMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) - flagsetUtilsMock.On("GetUint16JobId", flagSet).Return(tt.args.jobId, tt.args.jobIdErr) - flagsetUtilsMock.On("GetUint8Weight", flagSet).Return(tt.args.weight, tt.args.weightErr) - flagsetUtilsMock.On("GetUint8SelectorType", flagSet).Return(tt.args.selectorType, tt.args.selectorTypeErr) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetStringUrl", flagSet).Return(tt.args.url, tt.args.urlErr) + flagSetMock.On("GetStringSelector", flagSet).Return(tt.args.selector, tt.args.selectorErr) + flagSetMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) + flagSetMock.On("GetUint16JobId", flagSet).Return(tt.args.jobId, tt.args.jobIdErr) + flagSetMock.On("GetUint8Weight", flagSet).Return(tt.args.weight, tt.args.weightErr) + flagSetMock.On("GetUint8SelectorType", flagSet).Return(tt.args.selectorType, tt.args.selectorTypeErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("UpdateJob", mock.AnythingOfType("*ethclient.Client"), config, mock.Anything, mock.Anything).Return(tt.args.updateJobTxn, tt.args.updateJobErr) utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) diff --git a/cmd/vote.go b/cmd/vote.go index 292de1ce..ec740466 100644 --- a/cmd/vote.go +++ b/cmd/vote.go @@ -9,7 +9,7 @@ import ( "math/big" "os" "os/signal" - "path" + "path/filepath" "razor/accounts" "razor/core" "razor/core/types" @@ -56,12 +56,16 @@ func (*UtilsStruct) ExecuteVote(flagSet *pflag.FlagSet) { log.Debug("ExecuteVote: Address: ", address) logger.SetLoggerParameters(client, address) + log.Debug("Checking to assign log file...") - razorUtils.AssignLogFile(flagSet) + fileUtils.AssignLogFile(flagSet, config) log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) + err = razorUtils.CheckPassword(address, password) + utils.CheckError("Error in fetching private key from given password: ", err) + isRogue, err := flagSetUtils.GetBoolRogue(flagSet) utils.CheckError("Error in getting rogue status: ", err) log.Debug("ExecuteVote: IsRogue: ", isRogue) @@ -119,7 +123,7 @@ func (*UtilsStruct) HandleExit() { //This function handles all the states of voting func (*UtilsStruct) Vote(ctx context.Context, config types.Configurations, client *ethclient.Client, rogueData types.Rogue, account types.Account, backupNodeActionsToIgnore []string) error { - header, err := utils.UtilsInterface.GetLatestBlockWithRetry(client) + header, err := clientUtils.GetLatestBlockWithRetry(client) utils.CheckError("Error in getting block: ", err) for { select { @@ -127,7 +131,7 @@ func (*UtilsStruct) Vote(ctx context.Context, config types.Configurations, clien return nil default: log.Debugf("Vote: Header value: %d", header.Number) - latestHeader, err := utils.UtilsInterface.GetLatestBlockWithRetry(client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(client) if err != nil { log.Error("Error in fetching block: ", err) continue @@ -151,7 +155,7 @@ var ( //This function handles the block func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, blockNumber *big.Int, config types.Configurations, rogueData types.Rogue, backupNodeActionsToIgnore []string) { - state, err := razorUtils.GetDelayedState(client, config.BufferPercent) + state, err := razorUtils.GetBufferedState(client, config.BufferPercent) if err != nil { log.Error("Error in getting state: ", err) return @@ -178,17 +182,23 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, } stakedAmount := staker.Stake - ethBalance, err := utils.UtilsInterface.BalanceAtWithRetry(client, common.HexToAddress(account.Address)) + ethBalance, err := clientUtils.BalanceAtWithRetry(client, common.HexToAddress(account.Address)) if err != nil { log.Errorf("Error in fetching balance of the account: %s\n%v", account.Address, err) return } - actualStake, err := razorUtils.ConvertWeiToEth(stakedAmount) + + // Warning the staker if ETH balance is less than 0.1 ETH + if ethBalance.Cmp(big.NewInt(1e17)) == -1 { + log.Warn("sFuel balance is lower than 0.1 SKL, kindly add more SKL to be safe for executing transactions successfully") + } + + actualStake, err := utils.ConvertWeiToEth(stakedAmount) if err != nil { log.Error("Error in converting stakedAmount from wei denomination: ", err) return } - actualBalance, err := razorUtils.ConvertWeiToEth(ethBalance) + actualBalance, err := utils.ConvertWeiToEth(ethBalance) if err != nil { log.Error("Error in converting ethBalance from wei denomination: ", err) return @@ -204,14 +214,14 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, if sRZRBalance.Cmp(big.NewInt(0)) == 0 { sRZRInEth = big.NewFloat(0) } else { - sRZRInEth, err = razorUtils.ConvertWeiToEth(sRZRBalance) + sRZRInEth, err = utils.ConvertWeiToEth(sRZRBalance) if err != nil { log.Error(err) return } } - log.Infof("State: %s Staker ID: %d Stake: %f sRZR Balance: %f Eth Balance: %f", utils.UtilsInterface.GetStateName(state), stakerId, actualStake, sRZRInEth, actualBalance) + log.Infof("State: %s Staker ID: %d Stake: %f sRZR Balance: %f sFuel Balance: %f", utils.GetStateName(state), stakerId, actualStake, sRZRInEth, actualBalance) if staker.IsSlashed { log.Error("Staker is slashed.... cannot continue to vote!") @@ -256,7 +266,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, lastVerification = epoch - if utilsInterface.IsFlagPassed("autoClaimBounty") { + if razorUtils.IsFlagPassed("autoClaimBounty") { log.Debugf("Automatically claiming bounty") err = cmdUtils.HandleClaimBounty(client, config, account) if err != nil { @@ -277,7 +287,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, Config: config, ContractAddress: core.BlockManagerAddress, MethodName: "claimBlockReward", - ABI: bindings.BlockManagerABI, + ABI: bindings.BlockManagerMetaData.ABI, }) if err != nil { @@ -312,7 +322,7 @@ func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Config } log.Debug("InitiateCommit: Staker:", staker) stakedAmount := staker.Stake - minStakeAmount, err := utils.UtilsInterface.GetMinStakeAmount(client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(client) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err @@ -333,12 +343,12 @@ func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Config log.Debugf("Cannot commit in epoch %d because last committed epoch is %d", epoch, lastCommit) return nil } - razorPath, err := razorUtils.GetDefaultPath() + razorPath, err := pathUtils.GetDefaultPath() if err != nil { return err } log.Debugf("InitiateCommit: .razor directory path: %s", razorPath) - keystorePath := path.Join(razorPath, "keystore_files") + keystorePath := filepath.Join(razorPath, "keystore_files") log.Debugf("InitiateCommit: Keystore file path: %s", keystorePath) log.Debugf("InitiateCommit: Calling CalculateSecret() with arguments epoch = %d, keystorePath = %s, chainId = %s", epoch, keystorePath, core.ChainId) _, secret, err := cmdUtils.CalculateSecret(account, epoch, keystorePath, core.ChainId) @@ -364,17 +374,26 @@ func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Config log.Debug("InitiateCommit: Commit Data: ", commitData) log.Debug("InitiateCommit: Calling CreateMerkle() with argument Leaves = ", commitData.Leaves) - merkleTree := utils.MerkleInterface.CreateMerkle(commitData.Leaves) + merkleTree, err := merkleUtils.CreateMerkle(commitData.Leaves) + if err != nil { + return errors.New("Error in getting merkle tree: " + err.Error()) + } log.Debug("InitiateCommit: Merkle Tree: ", merkleTree) - commitTxn, err := cmdUtils.Commit(client, config, account, epoch, seed, utils.MerkleInterface.GetMerkleRoot(merkleTree)) + log.Debug("InitiateCommit: Calling GetMerkleRoot() for the merkle tree...") + merkleRoot, err := merkleUtils.GetMerkleRoot(merkleTree) + if err != nil { + return errors.New("Error in getting root: " + err.Error()) + } + log.Debug("InitiateCommit: Merkle Tree Root: ", merkleRoot) + commitTxn, err := cmdUtils.Commit(client, config, account, epoch, seed, merkleRoot) if err != nil { return errors.New("Error in committing data: " + err.Error()) } log.Debug("InitiateCommit: Commit Transaction Hash: ", commitTxn) if commitTxn != core.NilHash { - waitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, commitTxn.String()) + waitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, commitTxn.Hex()) if waitForBlockCompletionErr != nil { - log.Error("Error in WaitForBlockCompletion for commit: ", err) + log.Error("Error in WaitForBlockCompletion for commit: ", waitForBlockCompletionErr) return errors.New("error in sending commit transaction") } log.Debug("Updating GlobalCommitDataStruct with latest commitData and epoch...") @@ -383,13 +402,13 @@ func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Config } log.Debug("Saving committed data for recovery...") - fileName, err := razorUtils.GetCommitDataFileName(account.Address) + fileName, err := pathUtils.GetCommitDataFileName(account.Address) if err != nil { return errors.New("Error in getting file name to save committed data: " + err.Error()) } log.Debug("InitiateCommit: Commit data file path: ", fileName) - err = razorUtils.SaveDataToCommitJsonFile(fileName, epoch, commitData) + err = fileUtils.SaveDataToCommitJsonFile(fileName, epoch, commitData) if err != nil { return errors.New("Error in saving data to file" + fileName + ": " + err.Error()) } @@ -401,7 +420,7 @@ func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Config func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, rogueData types.Rogue) error { stakedAmount := staker.Stake log.Debug("InitiateReveal: Staked Amount: ", stakedAmount) - minStakeAmount, err := utils.UtilsInterface.GetMinStakeAmount(client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(client) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err @@ -422,8 +441,8 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config return nil } - log.Debugf("InitiateReveal: Calling HandleRevealState with arguments staker = %+v, epoch = %d", staker, epoch) - if err := cmdUtils.HandleRevealState(client, staker, epoch); err != nil { + log.Debugf("InitiateReveal: Calling CheckForLastCommitted with arguments staker = %+v, epoch = %d", staker, epoch) + if err := cmdUtils.CheckForLastCommitted(client, staker, epoch); err != nil { log.Error(err) return err } @@ -432,13 +451,13 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config if nilCommitData { log.Debug("InitiateReveal: Global commit data is nil, getting the commit data from file...") - fileName, err := razorUtils.GetCommitDataFileName(account.Address) + fileName, err := pathUtils.GetCommitDataFileName(account.Address) if err != nil { log.Error("Error in getting file name to save committed data: ", err) return err } log.Debug("InitiateReveal: Commit data file path: ", fileName) - committedDataFromFile, err := razorUtils.ReadFromCommitJsonFile(fileName) + committedDataFromFile, err := fileUtils.ReadFromCommitJsonFile(fileName) if err != nil { log.Errorf("Error in getting committed data from file %s: %v", fileName, err) return err @@ -467,12 +486,12 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config } if globalCommitDataStruct.Epoch == epoch { - razorPath, err := razorUtils.GetDefaultPath() + razorPath, err := pathUtils.GetDefaultPath() if err != nil { return err } log.Debug("InitiateReveal: .razor directory path: ", razorPath) - keystorePath := path.Join(razorPath, "keystore_files") + keystorePath := filepath.Join(razorPath, "keystore_files") log.Debug("InitiateReveal: Keystore file path: ", keystorePath) log.Debugf("InitiateReveal: Calling CalculateSecret() with argument epoch = %d, keystorePath = %s, chainId = %s", epoch, keystorePath, core.ChainId) @@ -496,7 +515,7 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config return errors.New("Reveal error: " + err.Error()) } if revealTxn != core.NilHash { - waitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, revealTxn.String()) + waitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, revealTxn.Hex()) if waitForBlockCompletionErr != nil { log.Error("Error in WaitForBlockCompletionErr for reveal: ", err) return err @@ -513,7 +532,7 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config func (*UtilsStruct) InitiatePropose(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, blockNumber *big.Int, rogueData types.Rogue) error { stakedAmount := staker.Stake log.Debug("InitiatePropose: Staked Amount: ", stakedAmount) - minStakeAmount, err := utils.UtilsInterface.GetMinStakeAmount(client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(client) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err diff --git a/cmd/vote_test.go b/cmd/vote_test.go index ee8de3c5..dd27036d 100644 --- a/cmd/vote_test.go +++ b/cmd/vote_test.go @@ -3,20 +3,19 @@ package cmd import ( "encoding/hex" "errors" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/spf13/pflag" - "github.com/stretchr/testify/mock" "math/big" "os" "path" - "razor/cmd/mocks" + "path/filepath" "razor/core/types" "razor/pkg/bindings" - "razor/utils" - mocks2 "razor/utils/mocks" "reflect" "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/spf13/pflag" + "github.com/stretchr/testify/mock" ) func TestExecuteVote(t *testing.T) { @@ -123,25 +122,17 @@ func TestExecuteVote(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + SetUpMockInterfaces() - flagSetUtilsMock := new(mocks.FlagSetInterface) - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - osMock := new(mocks.OSInterface) - - flagSetUtils = flagSetUtilsMock - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - osUtils = osMock - - utilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet")) + fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) - flagSetUtilsMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) - flagSetUtilsMock.On("GetStringSliceBackupNode", mock.Anything).Return([]string{}, nil) + utilsMock.On("CheckPassword", mock.Anything, mock.Anything).Return(nil) + flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetStringSliceBackupNode", mock.Anything).Return([]string{}, nil) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - flagSetUtilsMock.On("GetBoolRogue", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.rogueStatus, tt.args.rogueErr) - flagSetUtilsMock.On("GetStringSliceRogueMode", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.rogueMode, tt.args.rogueModeErr) + flagSetMock.On("GetBoolRogue", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.rogueStatus, tt.args.rogueErr) + flagSetMock.On("GetStringSliceRogueMode", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.rogueMode, tt.args.rogueModeErr) cmdUtilsMock.On("HandleExit").Return() cmdUtilsMock.On("Vote", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.voteErr) osMock.On("Exit", mock.AnythingOfType("int")).Return() @@ -168,7 +159,7 @@ func convertToSliceOfInterface(arr []uint32) []interface{} { func TestCalculateSecret(t *testing.T) { dir, _ := os.Getwd() razorPath := path.Dir(dir) - testKeystorePath := path.Join(razorPath, "utils/test_accounts") + testKeystorePath := filepath.Join(razorPath, "utils/test_accounts") type args struct { address string @@ -328,7 +319,9 @@ func TestInitiateCommit(t *testing.T) { commitData types.CommitData commitDataErr error merkleTree [][][]byte + merkleTreeErr error merkleRoot [32]byte + merkleRootErr error commitTxn common.Hash commitTxnErr error waitForBlockCompletionErr error @@ -504,32 +497,57 @@ func TestInitiateCommit(t *testing.T) { }, wantErr: true, }, + { + name: "Test 14: When there is an error in getting merkle tree", + args: args{ + epoch: 5, + lastCommit: 2, + secret: []byte{1}, + salt: [32]byte{}, + commitData: types.CommitData{ + AssignedCollections: nil, + SeqAllottedCollections: nil, + Leaves: nil, + }, + merkleTreeErr: errors.New("merkle tree error"), + }, + wantErr: true, + }, + { + name: "Test 15: When there is an error in getting merkle root", + args: args{ + epoch: 5, + lastCommit: 2, + secret: []byte{1}, + salt: [32]byte{}, + commitData: types.CommitData{ + AssignedCollections: nil, + SeqAllottedCollections: nil, + Leaves: nil, + }, + merkleTree: [][][]byte{}, + merkleRootErr: errors.New("root error"), + }, + wantErr: true, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - merkleInterface := new(mocks2.MerkleTreeInterface) - utilsPkgMock := new(mocks2.Utils) - - utils.MerkleInterface = merkleInterface - utils.UtilsInterface = utilsPkgMock - razorUtils = utilsMock - cmdUtils = cmdUtilsMock + SetUpMockInterfaces() utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) - utilsPkgMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) + utilsMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) utilsMock.On("GetEpochLastCommitted", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.lastCommit, tt.args.lastCommitErr) cmdUtilsMock.On("CalculateSecret", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.signature, tt.args.secret, tt.args.secretErr) cmdUtilsMock.On("GetSalt", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.salt, tt.args.saltErr) cmdUtilsMock.On("HandleCommitState", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.commitData, tt.args.commitDataErr) - merkleInterface.On("CreateMerkle", mock.Anything).Return(tt.args.merkleTree) - merkleInterface.On("GetMerkleRoot", mock.Anything).Return(tt.args.merkleRoot) - utilsMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) + merkleUtilsMock.On("CreateMerkle", mock.Anything).Return(tt.args.merkleTree, tt.args.merkleTreeErr) + merkleUtilsMock.On("GetMerkleRoot", mock.Anything).Return(tt.args.merkleRoot, tt.args.merkleRootErr) + pathMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) cmdUtilsMock.On("Commit", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.commitTxn, tt.args.commitTxnErr) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.waitForBlockCompletionErr) - utilsMock.On("GetCommitDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) - utilsMock.On("SaveDataToCommitJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveErr) + pathMock.On("GetCommitDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) + fileUtilsMock.On("SaveDataToCommitJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveErr) ut := &UtilsStruct{} if err := ut.InitiateCommit(client, config, account, tt.args.epoch, stakerId, rogueData); (err != nil) != tt.wantErr { t.Errorf("InitiateCommit() error = %v, wantErr %v", err, tt.wantErr) @@ -545,7 +563,7 @@ func TestInitiateReveal(t *testing.T) { account types.Account ) - randomNum := utils.GetRogueRandomValue(10000000) + randomNum := big.NewInt(1111) type args struct { staker bindings.StructsStaker @@ -628,11 +646,11 @@ func TestInitiateReveal(t *testing.T) { wantErr: false, }, { - name: "Test 5: When there is an error in handleRevealState", + name: "Test 5: When there is an error in CheckForLastCommitted", args: args{ epoch: 5, lastReveal: 2, - revealStateErr: errors.New("error in handleRevealState"), + revealStateErr: errors.New("error in CheckForLastCommitted"), }, wantErr: true, }, @@ -721,21 +739,15 @@ func TestInitiateReveal(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(mocks2.Utils) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - utils.UtilsInterface = utilsPkgMock + SetUpMockInterfaces() - utilsPkgMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) + utilsMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) utilsMock.On("GetEpochLastRevealed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.lastReveal, tt.args.lastRevealErr) - cmdUtilsMock.On("HandleRevealState", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.AnythingOfType("uint32")).Return(tt.args.revealStateErr) - utilsMock.On("GetCommitDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) - utilsMock.On("ReadFromCommitJsonFile", mock.Anything).Return(tt.args.committedDataFromFile, tt.args.committedDataFromFileErr) + cmdUtilsMock.On("CheckForLastCommitted", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.AnythingOfType("uint32")).Return(tt.args.revealStateErr) + pathMock.On("GetCommitDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) + fileUtilsMock.On("ReadFromCommitJsonFile", mock.Anything).Return(tt.args.committedDataFromFile, tt.args.committedDataFromFileErr) utilsMock.On("GetRogueRandomValue", mock.AnythingOfType("int")).Return(randomNum) - utilsMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) + pathMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) cmdUtilsMock.On("CalculateSecret", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.signature, tt.args.secret, tt.args.secretErr) cmdUtilsMock.On("Reveal", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.revealTxn, tt.args.revealTxnErr) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) @@ -848,15 +860,9 @@ func TestInitiatePropose(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(mocks2.Utils) + SetUpMockInterfaces() - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - utils.UtilsInterface = utilsPkgMock - - utilsPkgMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) + utilsMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) utilsMock.On("GetEpochLastProposed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.lastProposal, tt.args.lastProposalErr) utilsMock.On("GetEpochLastRevealed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.lastReveal, tt.args.lastRevealErr) cmdUtilsMock.On("Propose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.proposeTxnErr) @@ -984,6 +990,7 @@ func TestHandleBlock(t *testing.T) { epoch: 1, stateName: "commit", stakerId: 1, + sRZRBalance: big.NewInt(1000), staker: bindings.StructsStaker{Id: 1, Stake: big.NewInt(10000)}, ethBalance: big.NewInt(1000), actualStakeErr: errors.New("error in converting stakedAmount"), @@ -1216,33 +1223,20 @@ func TestHandleBlock(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.UtilsInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - utilsPkgMock := new(mocks2.Utils) - osMock := new(mocks.OSInterface) - timeMock := new(mocks.TimeInterface) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - utils.UtilsInterface = utilsPkgMock - utilsInterface = utilsPkgMock - osUtils = osMock - timeUtils = timeMock + SetUpMockInterfaces() - utilsMock.On("GetDelayedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) + utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr) utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) utilsMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) - utilsPkgMock.On("BalanceAtWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) - utilsMock.On("ConvertWeiToEth", mock.AnythingOfType("*big.Int")).Return(tt.args.actualStake, tt.args.actualStakeErr) + clientUtilsMock.On("BalanceAtWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) utilsMock.On("GetStakerSRZRBalance", mock.Anything, mock.Anything).Return(tt.args.sRZRBalance, tt.args.sRZRBalanceErr) - utilsPkgMock.On("GetStateName", mock.AnythingOfType("int64")).Return(tt.args.stateName) osMock.On("Exit", mock.AnythingOfType("int")).Return() cmdUtilsMock.On("InitiateCommit", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateCommitErr) cmdUtilsMock.On("InitiateReveal", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateRevealErr) cmdUtilsMock.On("InitiatePropose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateProposeErr) cmdUtilsMock.On("HandleDispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.handleDisputeErr) - utilsPkgMock.On("IsFlagPassed", mock.AnythingOfType("string")).Return(tt.args.isFlagPassed) + utilsMock.On("IsFlagPassed", mock.AnythingOfType("string")).Return(tt.args.isFlagPassed) cmdUtilsMock.On("HandleClaimBounty", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.handleClaimBountyErr) cmdUtilsMock.On("ClaimBlockReward", mock.Anything).Return(tt.args.claimBlockRewardTxn, tt.args.claimBlockRewardErr) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(nil) diff --git a/config.sh b/config.sh index 10c150e4..45b684be 100644 --- a/config.sh +++ b/config.sh @@ -11,6 +11,12 @@ then PROVIDER="http://127.0.0.1:8545" fi +read -rp "Alternate Provider: (http://127.0.0.1:8545) " ALTERNATE_PROVIDER +if [ -z "$ALTERNATE_PROVIDER" ]; +then + ALTERNATE_PROVIDER="http://127.0.0.1:8545" +fi + read -rp "Gas Multiplier: (1.0) " GAS_MULTIPLIER if [ -z "$GAS_MULTIPLIER" ]; then @@ -37,4 +43,19 @@ read -rp "Gas Limit Increment : (2) " GAS_LIMIT if [ -z "$GAS_LIMIT" ]; then GAS_LIMIT=2 fi -$RAZOR setConfig -p $PROVIDER -b $BUFFER -g $GAS_MULTIPLIER -w $WAIT_TIME --gasprice $GAS_PRICE --gasLimit $GAS_LIMIT --rpcTimeout 10 \ No newline at end of file + +read -rp "Log File Max Size: (200) " MAX_SIZE +if [ -z "$MAX_SIZE" ]; then + MAX_SIZE=200 +fi + +read -rp "Log Files Max Backups: (52) " MAX_BACKUPS +if [ -z "$MAX_BACKUPS" ]; then + MAX_BACKUPS=52 +fi + +read -rp "Log Files Max Age: (365) " MAX_AGE +if [ -z "$MAX_AGE" ]; then + MAX_AGE=365 +fi +$RAZOR setConfig -p $PROVIDER --alternateProvider $ALTERNATE_PROVIDER -b $BUFFER -g $GAS_MULTIPLIER -w $WAIT_TIME --gasprice $GAS_PRICE --gasLimit $GAS_LIMIT --rpcTimeout 10 --httpTimeout 10 --logFileMaxSize $MAX_SIZE --logFileMaxBackups $MAX_BACKUPS --logFileMaxAge $MAX_AGE diff --git a/core/constants.go b/core/constants.go index 42de1291..3bbeb6d7 100644 --- a/core/constants.go +++ b/core/constants.go @@ -1,21 +1,23 @@ +// This file contains constants, DO NOT MODIFY. + package core import ( - "github.com/ethereum/go-ethereum/common" "math/big" + + "github.com/ethereum/go-ethereum/common" ) -var EpochLength int64 = 1200 -var NumberOfStates int64 = 5 +var EpochLength uint64 = 1200 +var NumberOfStates uint64 = 5 var ChainId = big.NewInt(0x109B4597) -var StateLength = uint64(EpochLength / NumberOfStates) +var StateLength = EpochLength / NumberOfStates var MaxRetries uint = 8 var NilHash = common.Hash{0x00} var BlockCompletionTimeout = 30 //Following are the default config values for all the config parameters -var DefaultProvider = "http://127.0.0.1:8545" var DefaultGasMultiplier = 1.0 var DefaultBufferPercent = 20 var DefaultGasPrice = 1 @@ -23,7 +25,31 @@ var DefaultWaitTime = 1 var DefaultGasLimit = 2 var DefaultGasLimitOverride = 0 var DefaultRPCTimeout = 10 +var DefaultHTTPTimeout = 10 var DefaultLogLevel = "" +//Following are the default logFile parameters in config + +var DefaultLogFileMaxSize = 200 +var DefaultLogFileMaxBackups = 52 +var DefaultLogFileMaxAge = 365 + +//DisputeGasMultiplier is a constant gasLimitMultiplier to increase gas Limit for function `disputeCollectionIdShouldBeAbsent` and `disputeCollectionIdShouldBePresent` +var DisputeGasMultiplier float32 = 5.5 + +// Following are the constants which will be used to derive different file paths + +var DataFileDirectory = "data_files" +var CommitDataFile = "_commitData.json" +var ProposeDataFile = "_proposeData.json" +var DisputeDataFile = "_disputeData.json" +var AssetsDataFile = "assets.json" +var ConfigFile = "razor.yaml" +var LogFileDirectory = "logs" +var DefaultPathName = ".razor" + //BlockNumberInterval is the interval in seconds after which blockNumber needs to be calculated again var BlockNumberInterval = 5 + +//SwitchClientDuration is the time after which alternate client from secondary RPC will be switched back to client from primary RPC +var SwitchClientDuration = 5 * EpochLength diff --git a/core/types/configurations.go b/core/types/configurations.go index 3cff2e4e..a9864fb5 100644 --- a/core/types/configurations.go +++ b/core/types/configurations.go @@ -2,6 +2,7 @@ package types type Configurations struct { Provider string + AlternateProvider string GasMultiplier float32 BufferPercent int32 WaitTime int32 @@ -10,4 +11,8 @@ type Configurations struct { GasLimitOverride uint64 GasLimitMultiplier float32 RPCTimeout int64 + HTTPTimeout int64 + LogFileMaxSize int + LogFileMaxBackups int + LogFileMaxAge int } diff --git a/core/version.go b/core/version.go index b323cf5a..04110f3e 100644 --- a/core/version.go +++ b/core/version.go @@ -3,10 +3,10 @@ package core import "fmt" const ( - VersionMajor = 1 // Major version component of the current release - VersionMinor = 0 // Minor version component of the current release - VersionPatch = 5 // Patch version component of the current release - VersionMeta = "patch2" // Version metadata to append to the version string + VersionMajor = 1 // Major version component of the current release + VersionMinor = 0 // Minor version component of the current release + VersionPatch = 6 // Patch version component of the current release + VersionMeta = "" // Version metadata to append to the version string ) // Version holds the textual version string. diff --git a/go.mod b/go.mod index fde1ffe0..b598d3b0 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.17 require ( github.com/PaesslerAG/jsonpath v0.1.1 github.com/avast/retry-go v3.0.0+incompatible - github.com/ethereum/go-ethereum v1.10.8 + github.com/ethereum/go-ethereum v1.10.25 github.com/gocolly/colly v1.2.0 github.com/magiconair/properties v1.8.4 github.com/manifoldco/promptui v0.8.0 @@ -17,8 +17,8 @@ require ( github.com/spf13/cobra v1.1.3 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.7.1 - github.com/stretchr/testify v1.7.0 - github.com/syndtr/goleveldb v1.0.1-0.20210305035536-64b5b1c73954 + github.com/stretchr/testify v1.7.2 + github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 github.com/tidwall/gjson v1.14.0 gopkg.in/natefinch/lumberjack.v2 v2.0.0 ) @@ -33,17 +33,19 @@ require ( github.com/antchfx/xpath v1.2.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/btcsuite/btcd v0.20.1-beta // indirect + github.com/btcsuite/btcd/btcec/v2 v2.2.0 // indirect github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea // indirect + github.com/deckarep/golang-set v1.8.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect github.com/fsnotify/fsnotify v1.4.9 // indirect github.com/go-ole/go-ole v1.2.1 // indirect github.com/go-stack/stack v1.8.0 // indirect github.com/gobwas/glob v0.2.3 // indirect github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect github.com/golang/protobuf v1.5.2 // indirect - github.com/google/uuid v1.1.5 // indirect + github.com/google/uuid v1.2.0 // indirect github.com/gorilla/websocket v1.4.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect @@ -54,7 +56,7 @@ require ( github.com/mattn/go-isatty v0.0.12 // indirect github.com/mattn/go-runewidth v0.0.9 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect - github.com/mitchellh/mapstructure v1.3.3 // indirect + github.com/mitchellh/mapstructure v1.4.1 // indirect github.com/pelletier/go-toml v1.8.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.2.0 // indirect @@ -73,14 +75,14 @@ require ( github.com/tidwall/pretty v1.2.0 // indirect github.com/tklauser/go-sysconf v0.3.5 // indirect github.com/tklauser/numcpus v0.2.2 // indirect - golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect - golang.org/x/net v0.0.0-20210916014120-12bc252f5db8 // indirect - golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect - golang.org/x/text v0.3.6 // indirect + golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect + golang.org/x/net v0.0.0-20220607020251-c690dde0001d // indirect + golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect + golang.org/x/text v0.3.7 // indirect google.golang.org/appengine v1.6.6 // indirect google.golang.org/protobuf v1.26.0 // indirect gopkg.in/ini.v1 v1.62.0 // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index d777114a..c2c95589 100644 --- a/go.sum +++ b/go.sum @@ -107,6 +107,8 @@ github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+Wji github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/btcsuite/btcd v0.20.1-beta h1:Ik4hyJqN8Jfyv3S4AGBOmyouMsYE3EdYODkMbQjwPGw= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= +github.com/btcsuite/btcd/btcec/v2 v2.2.0 h1:fzn1qaOt32TuLjFlkzYSsBC35Q3KUjT1SwPxiMSCF5k= +github.com/btcsuite/btcd/btcec/v2 v2.2.0/go.mod h1:U7MHm051Al6XmscBQ0BoNydpOTsFAn707034b5nY8zU= github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= @@ -149,6 +151,11 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea h1:j4317fAZh7X6GqbFowYdYdI0L9bwxL07jyPZIdepyZ0= github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea/go.mod h1:93vsz/8Wt4joVM7c2AVqh+YRMiUSc14yDtF28KmMOgQ= +github.com/deckarep/golang-set v1.8.0 h1:sk9/l/KqpunDwP7pSjUg0keiOOLEnOBHzykLrsPppp4= +github.com/deckarep/golang-set v1.8.0/go.mod h1:5nI87KwE7wgsBU1F4GKAw2Qod7p5kyS383rP6+o6qqo= +github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= github.com/deepmap/oapi-codegen v1.6.0/go.mod h1:ryDa9AgbELGeB+YEXE1dR53yAjHwFvE9iAUlWl9Al3M= github.com/deepmap/oapi-codegen v1.8.2/go.mod h1:YLgSKSDv/bZQB7N4ws6luhozi3cEdRktEqrX88CvjIw= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= @@ -166,6 +173,8 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/ethereum/go-ethereum v1.10.8 h1:0UP5WUR8hh46ffbjJV7PK499+uGEyasRIfffS0vy06o= github.com/ethereum/go-ethereum v1.10.8/go.mod h1:pJNuIUYfX5+JKzSD/BTdNsvJSZ1TJqmz0dVyXMAbf6M= +github.com/ethereum/go-ethereum v1.10.25 h1:5dFrKJDnYf8L6/5o42abCE6a9yJm9cs4EJVRyYMr55s= +github.com/ethereum/go-ethereum v1.10.25/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 h1:FtmdgXiUlNeRsoNMFlKLDt+S+6hbjVMEW6RGQ7aUf7c= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= @@ -242,6 +251,7 @@ github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8l github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golangci/lint-1 v0.0.0-20181222135242-d2cdd8c08219/go.mod h1:/X8TswGSh1pIozq4ZwCfxS0WA5JGXguxk94ar/4c87Y= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= @@ -270,6 +280,8 @@ github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hf github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.1.5 h1:kxhtnfFVi+rYdOALN0B3k9UT86zVJKfBimRaciULW4I= github.com/google/uuid v1.1.5/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= +github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= @@ -419,6 +431,8 @@ github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:F github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8= github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= +github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= @@ -551,10 +565,13 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/syndtr/goleveldb v1.0.1-0.20210305035536-64b5b1c73954 h1:xQdMZ1WLrgkkvOZ/LDQxjVxMLdby7osSh4ZEVa5sIjs= github.com/syndtr/goleveldb v1.0.1-0.20210305035536-64b5b1c73954/go.mod h1:u2MKkTVTVJWe5D1rCvame8WqhBd88EuIwODJZ1VHCPM= +github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= github.com/temoto/robotstxt v1.1.2 h1:W2pOjSJ6SWvldyEuiFXNxz3xZ8aiWX5LbfDiOFd7Fxg= github.com/temoto/robotstxt v1.1.2/go.mod h1:+1AmkuG3IYkh1kv0d2qEB9Le88ehNO0zwOr3ujewlOo= github.com/tidwall/gjson v1.14.0 h1:6aeJ0bzojgWLa82gDQHcx3S0Lr/O51I9bJ5nv6JFx5w= @@ -607,6 +624,8 @@ golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 h1:It14KIkyBFYkHkwZ7k45minvA9aorojkyjGk9KJ5B/w= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -685,6 +704,8 @@ golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210916014120-12bc252f5db8 h1:/6y1LfuqNuQdHAm0jjtPtgRcxIxjVZgm5OTu8/QhZvk= golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d h1:4SFsTMi4UahlKoloni7L4eYzhFRifURQLw+yv0QDCx8= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -762,6 +783,8 @@ golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 h1:XfKQ4OlFl8okEOr5UvAqFRVj8pY/4yfcXrddB8qAbU0= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -773,6 +796,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -948,6 +973,8 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/logger/logger.go b/logger/logger.go index fbef860e..ab46d1a8 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -8,6 +8,7 @@ import ( "os" "razor/block" "razor/core" + "razor/core/types" "razor/path" "runtime" @@ -32,7 +33,7 @@ var Client *ethclient.Client func init() { path.PathUtilsInterface = &path.PathUtils{} path.OSUtilsInterface = &path.OSUtils{} - InitializeLogger(FileName) + InitializeLogger(FileName, types.Configurations{}) osInfo := goInfo.GetInfo() standardLogger.WithFields(logrus.Fields{ @@ -46,7 +47,7 @@ func init() { } -func InitializeLogger(fileName string) { +func InitializeLogger(fileName string, config types.Configurations) { if fileName != "" { logFilePath, err := path.PathUtilsInterface.GetLogFilePath(fileName) if err != nil { @@ -55,19 +56,19 @@ func InitializeLogger(fileName string) { lumberJackLogger := &lumberjack.Logger{ Filename: logFilePath, - MaxSize: 200, // Maximum Size of a log file - MaxBackups: 52, // Maximum number of log files - MaxAge: 365, // Maximum number of days to retain olf files + MaxSize: config.LogFileMaxSize, + MaxBackups: config.LogFileMaxBackups, + MaxAge: config.LogFileMaxAge, } + fmt.Println(config.LogFileMaxSize) + fmt.Println(config.LogFileMaxBackups) + fmt.Println(config.LogFileMaxAge) out := os.Stderr mw := io.MultiWriter(out, lumberJackLogger) - standardLogger.Formatter = &logrus.JSONFormatter{} standardLogger.SetOutput(mw) - - } else { - standardLogger.Formatter = &logrus.JSONFormatter{} } + standardLogger.Formatter = &logrus.JSONFormatter{} } func NewLogger() *StandardLogger { @@ -172,7 +173,7 @@ func SetEpochAndBlockNumber(client *ethclient.Client) { latestBlock := block.GetLatestBlock() if latestBlock != nil { BlockNumber = latestBlock.Number - epoch := latestBlock.Time / uint64(core.EpochLength) + epoch := latestBlock.Time / core.EpochLength Epoch = uint32(epoch) } } diff --git a/password.txt b/password.txt new file mode 100644 index 00000000..e69de29b diff --git a/path/path.go b/path/path.go index a32c57dc..259bf83b 100644 --- a/path/path.go +++ b/path/path.go @@ -3,7 +3,8 @@ package path import ( "os" - pathPkg "path" + "path/filepath" + "razor/core" ) //This function returns the default path @@ -12,7 +13,7 @@ func (PathUtils) GetDefaultPath() (string, error) { if err != nil { return "", err } - defaultPath := pathPkg.Join(home, ".razor") + defaultPath := filepath.Join(home, core.DefaultPathName) if _, err := OSUtilsInterface.Stat(defaultPath); OSUtilsInterface.IsNotExist(err) { mkdirErr := OSUtilsInterface.Mkdir(defaultPath, 0700) if mkdirErr != nil { @@ -28,7 +29,7 @@ func (PathUtils) GetLogFilePath(fileName string) (string, error) { if err != nil { return "", err } - defaultPath := pathPkg.Join(razorPath, "logs") + defaultPath := filepath.Join(razorPath, core.LogFileDirectory) if _, err := OSUtilsInterface.Stat(defaultPath); OSUtilsInterface.IsNotExist(err) { mkdirErr := OSUtilsInterface.Mkdir(defaultPath, 0700) if mkdirErr != nil { @@ -36,7 +37,7 @@ func (PathUtils) GetLogFilePath(fileName string) (string, error) { } } - logFilepath := pathPkg.Join(defaultPath, fileName+".log") + logFilepath := filepath.Join(defaultPath, fileName+".log") f, err := OSUtilsInterface.OpenFile(logFilepath, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { return "", err @@ -51,7 +52,7 @@ func (PathUtils) GetConfigFilePath() (string, error) { if err != nil { return "", err } - return pathPkg.Join(razorPath, "razor.yaml"), nil + return filepath.Join(razorPath, core.ConfigFile), nil } //This function returns the job file path @@ -60,7 +61,7 @@ func (PathUtils) GetJobFilePath() (string, error) { if err != nil { return "", err } - filePath := pathPkg.Join(razorPath, "assets.json") + filePath := filepath.Join(razorPath, core.AssetsDataFile) return filePath, nil } @@ -70,7 +71,7 @@ func (PathUtils) GetCommitDataFileName(address string) (string, error) { if err != nil { return "", err } - dataFileDir := pathPkg.Join(razorDir, "data_files") + dataFileDir := filepath.Join(razorDir, core.DataFileDirectory) if _, err := OSUtilsInterface.Stat(dataFileDir); OSUtilsInterface.IsNotExist(err) { mkdirErr := OSUtilsInterface.Mkdir(dataFileDir, 0700) if mkdirErr != nil { @@ -78,7 +79,7 @@ func (PathUtils) GetCommitDataFileName(address string) (string, error) { } } - return pathPkg.Join(dataFileDir, address+"_CommitData.json"), nil + return filepath.Join(dataFileDir, address+core.CommitDataFile), nil } //This function returns the file name of propose data file @@ -87,14 +88,14 @@ func (PathUtils) GetProposeDataFileName(address string) (string, error) { if err != nil { return "", err } - dataFileDir := pathPkg.Join(razorDir, "data_files") + dataFileDir := filepath.Join(razorDir, core.DataFileDirectory) if _, err := OSUtilsInterface.Stat(dataFileDir); OSUtilsInterface.IsNotExist(err) { mkdirErr := OSUtilsInterface.Mkdir(dataFileDir, 0700) if mkdirErr != nil { return "", mkdirErr } } - return pathPkg.Join(dataFileDir, address+"_proposedData.json"), nil + return filepath.Join(dataFileDir, address+core.ProposeDataFile), nil } //This function returns the file name of dispute data file @@ -103,12 +104,12 @@ func (PathUtils) GetDisputeDataFileName(address string) (string, error) { if err != nil { return "", err } - dataFileDir := pathPkg.Join(razorDir, "data_files") + dataFileDir := filepath.Join(razorDir, core.DataFileDirectory) if _, err := OSUtilsInterface.Stat(dataFileDir); OSUtilsInterface.IsNotExist(err) { mkdirErr := OSUtilsInterface.Mkdir(dataFileDir, 0700) if mkdirErr != nil { return "", mkdirErr } } - return pathPkg.Join(dataFileDir, address+"_disputeData.json"), nil + return filepath.Join(dataFileDir, address+core.DisputeDataFile), nil } diff --git a/path/path_test.go b/path/path_test.go index ca77eaa7..c5a90c28 100644 --- a/path/path_test.go +++ b/path/path_test.go @@ -321,7 +321,7 @@ func TestGetCommitDataFileName(t *testing.T) { address: "0x000000000000000000000000000000000000dead", path: "/home", }, - want: "/home/data_files/0x000000000000000000000000000000000000dead_CommitData.json", + want: "/home/data_files/0x000000000000000000000000000000000000dead_commitData.json", wantErr: nil, }, { @@ -341,7 +341,7 @@ func TestGetCommitDataFileName(t *testing.T) { statErr: errors.New("not exists"), isNotExist: true, }, - want: "/home/data_files/0x000000000000000000000000000000000000dead_CommitData.json", + want: "/home/data_files/0x000000000000000000000000000000000000dead_commitData.json", wantErr: nil, }, { @@ -411,7 +411,7 @@ func TestGetProposeDataFileName(t *testing.T) { address: "0x000000000000000000000000000000000000dead", path: "/home", }, - want: "/home/data_files/0x000000000000000000000000000000000000dead_proposedData.json", + want: "/home/data_files/0x000000000000000000000000000000000000dead_proposeData.json", wantErr: nil, }, { @@ -431,7 +431,7 @@ func TestGetProposeDataFileName(t *testing.T) { statErr: errors.New("not exists"), isNotExist: true, }, - want: "/home/data_files/0x000000000000000000000000000000000000dead_proposedData.json", + want: "/home/data_files/0x000000000000000000000000000000000000dead_proposeData.json", wantErr: nil, }, { diff --git a/utils/api.go b/utils/api.go index fb926ad5..165d0afe 100644 --- a/utils/api.go +++ b/utils/api.go @@ -3,6 +3,8 @@ package utils import ( "errors" "net/http" + "razor/cache" + "razor/core" "time" "github.com/PaesslerAG/jsonpath" @@ -10,32 +12,39 @@ import ( "github.com/gocolly/colly" ) -func (*UtilsStruct) GetDataFromAPI(url string) ([]byte, error) { +func (*UtilsStruct) GetDataFromAPI(url string, localCache *cache.LocalCache) ([]byte, error) { client := http.Client{ - Timeout: 10 * time.Second, + Timeout: time.Duration(HTTPTimeout) * time.Second, } - var body []byte - err := retry.Do( - func() error { - response, err := client.Get(url) - if err != nil { - return err - } - defer response.Body.Close() - if response.StatusCode != 200 { - log.Errorf("API: %s responded with status code %d", url, response.StatusCode) - return errors.New("unable to reach API") - } - body, err = IOInterface.ReadAll(response.Body) - if err != nil { - return err - } - return nil - }, retry.Attempts(2), retry.Delay(time.Second*2)) + cachedData, err := localCache.Read(url) if err != nil { - return nil, err + var body []byte + err := retry.Do( + func() error { + response, err := client.Get(url) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode != 200 { + log.Errorf("API: %s responded with status code %d", url, response.StatusCode) + return errors.New("unable to reach API") + } + body, err = IOInterface.ReadAll(response.Body) + if err != nil { + return err + } + return nil + }, retry.Attempts(2), retry.Delay(time.Second*2)) + if err != nil { + return nil, err + } + //Storing the data into cache + localCache.Update(body, url, time.Now().Add(time.Second*time.Duration(core.StateLength)).Unix()) + return body, nil } - return body, nil + log.Debugf("Getting Data for URL %s from local cache...", url) + return cachedData, nil } func (*UtilsStruct) GetDataFromJSON(jsonObject map[string]interface{}, selector string) (interface{}, error) { diff --git a/utils/api_test.go b/utils/api_test.go index b21e4c35..1d37fcc4 100644 --- a/utils/api_test.go +++ b/utils/api_test.go @@ -2,10 +2,13 @@ package utils import ( "errors" - "github.com/stretchr/testify/mock" + "razor/cache" "razor/utils/mocks" "reflect" "testing" + "time" + + "github.com/stretchr/testify/mock" ) func getAPIByteArray(index int) []byte { @@ -97,8 +100,8 @@ func TestGetDataFromAPI(t *testing.T) { utils := StartRazor(optionsPackageStruct) ioMock.On("ReadAll", mock.Anything).Return(tt.args.body, tt.args.bodyErr) - - got, err := utils.GetDataFromAPI(tt.args.url) + localCache := cache.NewLocalCache(time.Second * 10) + got, err := utils.GetDataFromAPI(tt.args.url, localCache) if (err != nil) != tt.wantErr { t.Errorf("GetDataFromAPI() error = %v, wantErr %v", err, tt.wantErr) return @@ -229,7 +232,7 @@ func TestGetDataFromHTML(t *testing.T) { name: "Test 1: Test data from coin market cap", args: args{ url: "https://coinmarketcap.com/all/views/all/", - selector: `/html/body/div/div[1]/div[2]/div/div[1]/h1`, + selector: `/html/body/div[1]/div[2]/div[2]/div/div[1]/h1`, }, want: "All Cryptocurrencies", wantErr: false, diff --git a/utils/array.go b/utils/array.go index fb5dca2e..58cb0128 100644 --- a/utils/array.go +++ b/utils/array.go @@ -6,6 +6,7 @@ import ( "strings" ) +// Contains is a generic function which checks a value is present in slice or not. func Contains(slice interface{}, val interface{}) bool { switch slice := slice.(type) { case []int: @@ -36,6 +37,7 @@ func Contains(slice interface{}, val interface{}) bool { return false } +// ContainsBigInteger checks whether a given bigInt is present in the bigInt array or not func ContainsBigInteger(arr []*big.Int, num *big.Int) bool { if num == nil { return false @@ -48,7 +50,8 @@ func ContainsBigInteger(arr []*big.Int, num *big.Int) bool { return false } -func IsEqual(arr1 []*big.Int, arr2 []*big.Int) (bool, int) { +// IsBigIntArrayEqual checks whether two bigInt arrays are equal or not. if not, it returns the index of incorrect element +func IsBigIntArrayEqual(arr1 []*big.Int, arr2 []*big.Int) (bool, int) { if len(arr1) > len(arr2) { return false, len(arr2) } else if len(arr1) < len(arr2) { @@ -62,7 +65,8 @@ func IsEqual(arr1 []*big.Int, arr2 []*big.Int) (bool, int) { return true, -1 } -func IsEqualByte(arr1 []byte, arr2 []byte) (bool, int) { +// IsByteArrayEqual checks whether two byte arrays are equal or not. If not, it returns index of incorrect element +func IsByteArrayEqual(arr1 []byte, arr2 []byte) (bool, int) { if len(arr1) > len(arr2) { return false, len(arr2) } else if len(arr1) < len(arr2) { @@ -76,8 +80,8 @@ func IsEqualByte(arr1 []byte, arr2 []byte) (bool, int) { return true, -1 } -// IsMissing checks for elements present in 1st array but not in second -func IsMissing(arr1 []uint16, arr2 []uint16) (bool, int, uint16) { +// CheckValueMissingInArray checks for elements present in 1st array but not in second +func CheckValueMissingInArray(arr1 []uint16, arr2 []uint16) (bool, int, uint16) { arrayMap := make(map[uint16]bool) for i := 0; i < len(arr2); i++ { arrayMap[arr2[i]] = true @@ -90,6 +94,7 @@ func IsMissing(arr1 []uint16, arr2 []uint16) (bool, int, uint16) { return false, -1, 0 } +// IsSorted checks weather array is sorted or not. If not, it returns the index of incorrect elements func IsSorted(values []uint16) (bool, int, int) { if values == nil { return true, -1, -1 @@ -102,6 +107,7 @@ func IsSorted(values []uint16) (bool, int, int) { return true, -1, -1 } +// IndexOf returns index of element in the array func IndexOf(array []uint32, value uint32) int { for arrayIndex, arrayVal := range array { if arrayVal == value { @@ -111,6 +117,7 @@ func IndexOf(array []uint32, value uint32) int { return -1 } +// GetDataInBytes converts bigInt array to bytes array func GetDataInBytes(data []*big.Int) [][]byte { if len(data) == 0 { return nil @@ -122,6 +129,7 @@ func GetDataInBytes(data []*big.Int) [][]byte { return dataInBytes } +// ConvertUint32ArrayToBigIntArray converts uint32 array to bigInt array func ConvertUint32ArrayToBigIntArray(uint32Array []uint32) []*big.Int { var arr []*big.Int for _, datum := range uint32Array { @@ -130,6 +138,7 @@ func ConvertUint32ArrayToBigIntArray(uint32Array []uint32) []*big.Int { return arr } +// CalculateWeightedSum returns the weighted sum for given data and weights func CalculateWeightedSum(data []*big.Int, weight []uint8) *big.Int { sum := big.NewInt(0) for index, datum := range data { @@ -139,6 +148,7 @@ func CalculateWeightedSum(data []*big.Int, weight []uint8) *big.Int { return sum } +// CalculateSumOfUint8Array return sum of all elements in uint8 array func CalculateSumOfUint8Array(data []uint8) uint { sum := uint(0) if len(data) == 0 { @@ -150,6 +160,7 @@ func CalculateSumOfUint8Array(data []uint8) uint { return sum } +// ConvertUintArrayToUint16Array converts uint array to uint16 array func ConvertUintArrayToUint16Array(uintArr []uint) []uint16 { var arr []uint16 for _, datum := range uintArr { @@ -158,6 +169,7 @@ func ConvertUintArrayToUint16Array(uintArr []uint) []uint16 { return arr } +// ContainsStringFromArray checks whether given string is present in string array or not func ContainsStringFromArray(source string, subStringArray []string) bool { for i := 0; i < len(subStringArray); i++ { if strings.Contains(source, subStringArray[i]) { diff --git a/utils/array_test.go b/utils/array_test.go index f3833328..67b747a1 100644 --- a/utils/array_test.go +++ b/utils/array_test.go @@ -171,7 +171,7 @@ func TestGetDataInBytes(t *testing.T) { } } -func TestIsEqual(t *testing.T) { +func TestIsBigIntArrayEqual(t *testing.T) { type args struct { arr1 []*big.Int arr2 []*big.Int @@ -231,12 +231,12 @@ func TestIsEqual(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, got1 := IsEqual(tt.args.arr1, tt.args.arr2) + got, got1 := IsBigIntArrayEqual(tt.args.arr1, tt.args.arr2) if got != tt.want { - t.Errorf("IsEqualUint32() got = %v, want %v", got, tt.want) + t.Errorf("IsBigIntArrayEqual() got = %v, want %v", got, tt.want) } if got1 != tt.want1 { - t.Errorf("IsEqualUint32() got1 = %v, want %v", got1, tt.want1) + t.Errorf("IsBigIntArrayEqual() got1 = %v, want %v", got1, tt.want1) } }) } @@ -414,7 +414,7 @@ func TestContainsStringFromArray(t *testing.T) { } } -func TestIsMissing(t *testing.T) { +func TestCheckValueMissingInArray(t *testing.T) { type args struct { arr1 []uint16 arr2 []uint16 @@ -510,15 +510,15 @@ func TestIsMissing(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, got1, got2 := IsMissing(tt.args.arr1, tt.args.arr2) + got, got1, got2 := CheckValueMissingInArray(tt.args.arr1, tt.args.arr2) if got != tt.want { - t.Errorf("IsMissing() got = %v, want %v", got, tt.want) + t.Errorf("CheckValueMissingInArray() got = %v, want %v", got, tt.want) } if got1 != tt.want1 { - t.Errorf("IsMissing() got1 = %v, want %v", got1, tt.want1) + t.Errorf("CheckValueMissingInArray() got1 = %v, want %v", got1, tt.want1) } if got2 != tt.want2 { - t.Errorf("IsMissing() got2 = %v, want %v", got2, tt.want2) + t.Errorf("CheckValueMissingInArray() got2 = %v, want %v", got2, tt.want2) } }) } @@ -634,7 +634,7 @@ func TestIndexOf(t *testing.T) { } } -func TestIsEqualByte(t *testing.T) { +func TestIsByteArrayEqual(t *testing.T) { type args struct { arr1 []byte arr2 []byte @@ -694,12 +694,12 @@ func TestIsEqualByte(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, got1 := IsEqualByte(tt.args.arr1, tt.args.arr2) + got, got1 := IsByteArrayEqual(tt.args.arr1, tt.args.arr2) if got != tt.want { - t.Errorf("IsEqualByte() got = %v, want %v", got, tt.want) + t.Errorf("IsByteArrayEqual() got = %v, want %v", got, tt.want) } if got1 != tt.want1 { - t.Errorf("IsEqualByte() got1 = %v, want %v", got1, tt.want1) + t.Errorf("IsByteArrayEqual() got1 = %v, want %v", got1, tt.want1) } }) } diff --git a/utils/asset.go b/utils/asset.go index 41e3be35..5ffd8f0e 100644 --- a/utils/asset.go +++ b/utils/asset.go @@ -6,6 +6,7 @@ import ( "errors" "math/big" "os" + "razor/cache" "razor/core" "razor/core/types" "razor/path" @@ -138,21 +139,21 @@ func (*UtilsStruct) GetActiveCollectionIds(client *ethclient.Client) ([]uint16, return activeCollectionIds, nil } -func (*UtilsStruct) GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32) (*big.Int, error) { +func (*UtilsStruct) GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32, localCache *cache.LocalCache) (*big.Int, error) { activeCollection, err := UtilsInterface.GetActiveCollection(client, collectionId) if err != nil { log.Error(err) return nil, err } //Supply previous epoch to Aggregate in case if last reported value is required. - collectionData, aggregationError := UtilsInterface.Aggregate(client, epoch-1, activeCollection) + collectionData, aggregationError := UtilsInterface.Aggregate(client, epoch-1, activeCollection, localCache) if aggregationError != nil { return nil, aggregationError } return collectionData, nil } -func (*UtilsStruct) Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection) (*big.Int, error) { +func (*UtilsStruct) Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, localCache *cache.LocalCache) (*big.Int, error) { var jobs []bindings.StructsJob var overriddenJobIds []uint16 @@ -187,6 +188,9 @@ func (*UtilsStruct) Aggregate(client *ethclient.Client, previousEpoch uint32, co // Also adding custom jobs to jobs array customJobs := GetCustomJobsFromJSONFile(collection.Name, dataString) + if len(customJobs) != 0 { + log.Debugf("Got Custom Jobs from asset.json file: %+v", customJobs) + } jobs = append(jobs, customJobs...) } @@ -206,8 +210,7 @@ func (*UtilsStruct) Aggregate(client *ethclient.Client, previousEpoch uint32, co if len(jobs) == 0 { return nil, errors.New("no jobs present in the collection") } - - dataToCommit, weight, err := UtilsInterface.GetDataToCommitFromJobs(jobs) + dataToCommit, weight, err := UtilsInterface.GetDataToCommitFromJobs(jobs, localCache) if err != nil || len(dataToCommit) == 0 { prevCommitmentData, err := UtilsInterface.FetchPreviousValue(client, previousEpoch, collection.Id) if err != nil { @@ -249,13 +252,13 @@ func (*UtilsStruct) GetActiveCollection(client *ethclient.Client, collectionId u return collection, nil } -func (*UtilsStruct) GetDataToCommitFromJobs(jobs []bindings.StructsJob) ([]*big.Int, []uint8, error) { +func (*UtilsStruct) GetDataToCommitFromJobs(jobs []bindings.StructsJob, localCache *cache.LocalCache) ([]*big.Int, []uint8, error) { var ( data []*big.Int weight []uint8 ) for _, job := range jobs { - dataToAppend, err := UtilsInterface.GetDataToCommitFromJob(job) + dataToAppend, err := UtilsInterface.GetDataToCommitFromJob(job, localCache) if err != nil { continue } @@ -266,7 +269,7 @@ func (*UtilsStruct) GetDataToCommitFromJobs(jobs []bindings.StructsJob) ([]*big. return data, weight, nil } -func (*UtilsStruct) GetDataToCommitFromJob(job bindings.StructsJob) (*big.Int, error) { +func (*UtilsStruct) GetDataToCommitFromJob(job bindings.StructsJob, localCache *cache.LocalCache) (*big.Int, error) { var parsedJSON map[string]interface{} var ( response []byte @@ -277,7 +280,7 @@ func (*UtilsStruct) GetDataToCommitFromJob(job bindings.StructsJob) (*big.Int, e var parsedData interface{} if job.SelectorType == 0 { start := time.Now() - response, apiErr = UtilsInterface.GetDataFromAPI(job.Url) + response, apiErr = UtilsInterface.GetDataFromAPI(job.Url, localCache) if apiErr != nil { log.Errorf("Error in fetching data from API %s: %v", job.Url, apiErr) return nil, apiErr @@ -303,7 +306,7 @@ func (*UtilsStruct) GetDataToCommitFromJob(job bindings.StructsJob) (*big.Int, e return nil, err } // remove "," and currency symbols - parsedData = regexp.MustCompile(`[\p{Sc},]`).ReplaceAllString(dataPoint, "") + parsedData = regexp.MustCompile(`[\p{Sc}, ]`).ReplaceAllString(dataPoint, "") } datum, err := UtilsInterface.ConvertToNumber(parsedData) @@ -392,26 +395,36 @@ func (*UtilsStruct) GetCollectionIdFromLeafId(client *ethclient.Client, leafId u func GetCustomJobsFromJSONFile(collection string, jsonFileData string) []bindings.StructsJob { var collectionCustomJobs []bindings.StructsJob + var customJob types.CustomJob collectionCustomJobsPath := "assets.collection." + collection + ".custom jobs" - customJobs := gjson.Get(jsonFileData, collectionCustomJobsPath).Array() - if len(customJobs) == 0 { - return nil - } - - for i := 0; i < len(customJobs); i++ { - customJobsData := customJobs[i].String() - url := gjson.Get(customJobsData, "URL").String() - selector := gjson.Get(customJobsData, "selector").String() - power := int8(gjson.Get(customJobsData, "power").Int()) - weight := uint8(gjson.Get(customJobsData, "weight").Int()) - job := ConvertCustomJobToStructJob(types.CustomJob{ - URL: url, - Power: power, - Selector: selector, - Weight: weight, - }) - collectionCustomJobs = append(collectionCustomJobs, job) + customJobsJSONResult := gjson.Get(jsonFileData, collectionCustomJobsPath) + if customJobsJSONResult.Exists() { + customJobs := customJobsJSONResult.Array() + if len(customJobs) == 0 { + return nil + } + for i := 0; i < len(customJobs); i++ { + customJobsData := customJobs[i].String() + url := gjson.Get(customJobsData, "URL") + if url.Exists() { + customJob.URL = url.String() + } + selector := gjson.Get(customJobsData, "selector") + if selector.Exists() { + customJob.Selector = selector.String() + } + power := gjson.Get(customJobsData, "power") + if power.Exists() { + customJob.Power = int8(power.Int()) + } + weight := gjson.Get(customJobsData, "weight") + if weight.Exists() { + customJob.Weight = uint8(weight.Int()) + } + job := ConvertCustomJobToStructJob(customJob) + collectionCustomJobs = append(collectionCustomJobs, job) + } } return collectionCustomJobs @@ -435,19 +448,34 @@ func (*UtilsStruct) HandleOfficialJobsFromJSONFile(client *ethclient.Client, col for i := 0; i < len(jobIds); i++ { officialJobsPath := "assets.collection." + collectionName + ".official jobs." + strconv.Itoa(int(jobIds[i])) - officialJobs := gjson.Get(dataString, officialJobsPath).String() - if officialJobs != "" { - job, err := UtilsInterface.GetActiveJob(client, jobIds[i]) - if err != nil { - continue + officialJobsJSONResult := gjson.Get(dataString, officialJobsPath) + if officialJobsJSONResult.Exists() { + officialJobs := officialJobsJSONResult.String() + if officialJobs != "" { + job, err := UtilsInterface.GetActiveJob(client, jobIds[i]) + if err != nil { + continue + } + log.Debugf("Overriding job %s having jobId %d from official job present in assets.json file...", job.Url, job.Id) + url := gjson.Get(officialJobs, "URL") + if url.Exists() { + job.Url = url.String() + } + selector := gjson.Get(officialJobs, "selector") + if selector.Exists() { + job.Selector = selector.String() + } + weight := gjson.Get(officialJobs, "weight") + if weight.Exists() { + job.Weight = uint8(weight.Int()) + } + power := gjson.Get(officialJobs, "power") + if power.Exists() { + job.Power = int8(power.Int()) + } + overrideJobs = append(overrideJobs, job) + overriddenJobIds = append(overriddenJobIds, jobIds[i]) } - job.Url = gjson.Get(officialJobs, "URL").String() - job.Selector = gjson.Get(officialJobs, "selector").String() - job.Weight = uint8(gjson.Get(officialJobs, "weight").Int()) - job.Power = int8(gjson.Get(officialJobs, "power").Int()) - - overrideJobs = append(overrideJobs, job) - overriddenJobIds = append(overriddenJobIds, jobIds[i]) } else { continue } diff --git a/utils/asset_test.go b/utils/asset_test.go index ae626c28..51886801 100644 --- a/utils/asset_test.go +++ b/utils/asset_test.go @@ -5,6 +5,7 @@ import ( "io/fs" "math/big" "os" + "razor/cache" "razor/core/types" "razor/path" pathMocks "razor/path/mocks" @@ -181,7 +182,7 @@ func TestAggregate(t *testing.T) { utils := StartRazor(optionsPackageStruct) utilsMock.On("GetActiveJob", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint16")).Return(tt.args.activeJob, tt.args.activeJobErr) - utilsMock.On("GetDataToCommitFromJobs", mock.Anything).Return(tt.args.dataToCommit, tt.args.weight, tt.args.dataToCommitErr) + utilsMock.On("GetDataToCommitFromJobs", mock.Anything, mock.Anything).Return(tt.args.dataToCommit, tt.args.weight, tt.args.dataToCommitErr) utilsMock.On("FetchPreviousValue", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint16")).Return(tt.args.prevCommitmentData, tt.args.prevCommitmentDataErr) pathUtilsMock.On("GetJobFilePath").Return(tt.args.assetFilePath, tt.args.assetFilePathErr) osUtilsMock.On("Stat", mock.Anything).Return(fileInfo, tt.args.statErr) @@ -189,7 +190,7 @@ func TestAggregate(t *testing.T) { ioMock.On("ReadAll", mock.Anything).Return(tt.args.fileData, tt.args.fileDataErr) utilsMock.On("HandleOfficialJobsFromJSONFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.overrrideJobs, tt.args.overrideJobIds) - got, err := utils.Aggregate(client, previousEpoch, tt.args.collection) + got, err := utils.Aggregate(client, previousEpoch, tt.args.collection, &cache.LocalCache{}) if (err != nil) != tt.wantErr { t.Errorf("Aggregate() error = %v, wantErr %v", err, tt.wantErr) return @@ -630,9 +631,9 @@ func TestGetDataToCommitFromJobs(t *testing.T) { pathMock.On("GetJobFilePath").Return(tt.args.jobPath, tt.args.jobPathErr) utilsMock.On("ReadJSONData", mock.AnythingOfType("string")).Return(tt.args.overrideJobData, tt.args.overrideJobDataErr) - utilsMock.On("GetDataToCommitFromJob", mock.Anything).Return(tt.args.dataToAppend, tt.args.dataToAppendErr) + utilsMock.On("GetDataToCommitFromJob", mock.Anything, mock.Anything).Return(tt.args.dataToAppend, tt.args.dataToAppendErr) - got, _, err := utils.GetDataToCommitFromJobs(jobsArray) + got, _, err := utils.GetDataToCommitFromJobs(jobsArray, &cache.LocalCache{}) if (err != nil) != tt.wantErr { t.Errorf("GetDataToCommitFromJobs() error = %v, wantErr %v", err, tt.wantErr) return @@ -785,12 +786,12 @@ func TestGetDataToCommitFromJob(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetDataFromAPI", mock.AnythingOfType("string")).Return(tt.args.response, tt.args.responseErr) + utilsMock.On("GetDataFromAPI", mock.AnythingOfType("string"), mock.Anything).Return(tt.args.response, tt.args.responseErr) utilsMock.On("GetDataFromJSON", mock.Anything, mock.AnythingOfType("string")).Return(tt.args.parsedData, tt.args.parsedDataErr) utilsMock.On("GetDataFromXHTML", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(tt.args.dataPoint, tt.args.dataPointErr) utilsMock.On("ConvertToNumber", mock.Anything).Return(tt.args.datum, tt.args.datumErr) - got, err := utils.GetDataToCommitFromJob(tt.args.job) + got, err := utils.GetDataToCommitFromJob(tt.args.job, &cache.LocalCache{}) if (err != nil) != tt.wantErr { t.Errorf("GetDataToCommitFromJob() error = %v, wantErr %v", err, tt.wantErr) return @@ -1119,6 +1120,11 @@ func TestHandleOfficialJobsFromJSONFile(t *testing.T) { AggregationMethod: 2, JobIDs: []uint16{1}, Name: "ethCollection", } + ethCollection1 := bindings.StructsCollection{ + Active: true, Id: 7, Power: 2, + AggregationMethod: 2, JobIDs: []uint16{1, 2, 3}, Name: "ethCollection", + } + type args struct { collection bindings.StructsCollection dataString string @@ -1173,6 +1179,37 @@ func TestHandleOfficialJobsFromJSONFile(t *testing.T) { want: nil, wantOverrideJobIds: nil, }, + { + name: "Test 4: When multiple jobIds are needed to be overridden from official jobs", + args: args{ + collection: ethCollection1, + dataString: jsonDataString, + job: bindings.StructsJob{ + Id: 1, + Url: "http://kraken.com/eth1", + Selector: "data.ETH", + Power: 3, + Weight: 1, + }, + }, + want: []bindings.StructsJob{ + { + Id: 1, + Url: "http://kucoin.com/eth1", + Selector: "eth1", + Power: 2, + Weight: 2, + }, + { + Id: 1, + Url: "http://api.coinbase.com/eth2", + Selector: "eth2", + Power: 3, + Weight: 2, + }, + }, + wantOverrideJobIds: []uint16{1, 2}, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -1287,9 +1324,9 @@ func TestGetAggregatedDataOfCollection(t *testing.T) { utils := StartRazor(optionsPackageStruct) utilsMock.On("GetActiveCollection", mock.Anything, mock.Anything).Return(tt.args.activeCollection, tt.args.activeCollectionErr) - utilsMock.On("Aggregate", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionData, tt.args.aggregationErr) + utilsMock.On("Aggregate", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionData, tt.args.aggregationErr) - got, err := utils.GetAggregatedDataOfCollection(client, collectionId, epoch) + got, err := utils.GetAggregatedDataOfCollection(client, collectionId, epoch, &cache.LocalCache{}) if (err != nil) != tt.wantErr { t.Errorf("GetAggregatedDataOfCollection() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/block.go b/utils/block.go index 6c7b62d5..80f30342 100644 --- a/utils/block.go +++ b/utils/block.go @@ -1,11 +1,10 @@ package utils import ( + "errors" "math/big" - "razor/core" "razor/pkg/bindings" - "github.com/avast/retry-go" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/ethclient" ) @@ -15,43 +14,19 @@ func (*UtilsStruct) GetBlockManagerWithOpts(client *ethclient.Client) (*bindings } func (*UtilsStruct) GetNumberOfProposedBlocks(client *ethclient.Client, epoch uint32) (uint8, error) { - var ( - numProposedBlocks uint8 - err error - ) - err = retry.Do( - func() error { - numProposedBlocks, err = BlockManagerInterface.GetNumProposedBlocks(client, epoch) - if err != nil { - log.Error("Error in fetching numProposedBlocks.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetNumProposedBlocks", client, epoch) if err != nil { return 0, err } - return numProposedBlocks, nil + return returnedValues[0].Interface().(uint8), nil } func (*UtilsStruct) GetProposedBlock(client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) { - var ( - proposedBlock bindings.StructsBlock - err error - ) - err = retry.Do( - func() error { - proposedBlock, err = BlockManagerInterface.GetProposedBlock(client, epoch, proposedBlockId) - if err != nil { - log.Error("Error in fetching proposed block.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetProposedBlock", client, epoch, proposedBlockId) if err != nil { return bindings.StructsBlock{}, err } - return proposedBlock, nil + return returnedValues[0].Interface().(bindings.StructsBlock), nil } func (*UtilsStruct) FetchPreviousValue(client *ethclient.Client, epoch uint32, assetId uint16) (*big.Int, error) { @@ -59,108 +34,51 @@ func (*UtilsStruct) FetchPreviousValue(client *ethclient.Client, epoch uint32, a if err != nil { return big.NewInt(0), err } + if len(block.Medians) < int(assetId) { + return big.NewInt(0), errors.New("value not found in previous block") + } return block.Medians[assetId-1], nil } func (*UtilsStruct) GetBlock(client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) { - var ( - block bindings.StructsBlock - err error - ) - err = retry.Do( - func() error { - block, err = BlockManagerInterface.GetBlock(client, epoch) - if err != nil { - log.Error("Error in fetching proposed block.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetBlock", client, epoch) if err != nil { return bindings.StructsBlock{}, err } - return block, nil + return returnedValues[0].Interface().(bindings.StructsBlock), nil } func (*UtilsStruct) GetMinStakeAmount(client *ethclient.Client) (*big.Int, error) { - var ( - minStake *big.Int - err error - ) - err = retry.Do( - func() error { - minStake, err = BlockManagerInterface.MinStake(client) - if err != nil { - log.Error("Error in fetching minimum stake amount.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "MinStake", client) if err != nil { return nil, err } - return minStake, nil + return returnedValues[0].Interface().(*big.Int), nil } func (*UtilsStruct) GetStateBuffer(client *ethclient.Client) (uint64, error) { - var ( - stateBuffer uint64 - err error - ) - err = retry.Do( - func() error { - stateBufferUint8, err := BlockManagerInterface.StateBuffer(client) - stateBuffer = uint64(stateBufferUint8) - if err != nil { - log.Error("Error in fetching state buffer.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "StateBuffer", client) if err != nil { return 0, err } - return stateBuffer, nil + stateBufferUint8 := returnedValues[0].Interface().(uint8) + return uint64(stateBufferUint8), nil } func (*UtilsStruct) GetMaxAltBlocks(client *ethclient.Client) (uint8, error) { - var ( - maxAltBlocks uint8 - err error - ) - err = retry.Do( - func() error { - maxAltBlocks, err = BlockManagerInterface.MaxAltBlocks(client) - if err != nil { - log.Error("Error in fetching max alt blocks.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "MaxAltBlocks", client) if err != nil { return 0, err } - return maxAltBlocks, nil + return returnedValues[0].Interface().(uint8), nil } func (*UtilsStruct) GetSortedProposedBlockId(client *ethclient.Client, epoch uint32, index *big.Int) (uint32, error) { - var ( - sortedProposedBlockId uint32 - err error - ) - err = retry.Do( - func() error { - sortedProposedBlockId, err = BlockManagerInterface.SortedProposedBlockIds(client, epoch, index) - if err != nil { - log.Error("Error in fetching sorted proposed blockId.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "SortedProposedBlockIds", client, epoch, index) if err != nil { return 0, err } - return sortedProposedBlockId, nil + return returnedValues[0].Interface().(uint32), nil } func (*UtilsStruct) GetSortedProposedBlockIds(client *ethclient.Client, epoch uint32) ([]uint32, error) { @@ -182,41 +100,17 @@ func (*UtilsStruct) GetSortedProposedBlockIds(client *ethclient.Client, epoch ui } func (*UtilsStruct) GetBlockIndexToBeConfirmed(client *ethclient.Client) (int8, error) { - var ( - blockIndex int8 - err error - ) - err = retry.Do( - func() error { - blockIndex, err = BlockManagerInterface.GetBlockIndexToBeConfirmed(client) - if err != nil { - log.Error("Error in fetching salt....Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetBlockIndexToBeConfirmed", client) if err != nil { return 0, err } - return blockIndex, nil + return returnedValues[0].Interface().(int8), nil } func (*UtilsStruct) GetEpochLastProposed(client *ethclient.Client, stakerId uint32) (uint32, error) { - var ( - epochLastProposed uint32 - err error - ) - err = retry.Do( - func() error { - epochLastProposed, err = BlockManagerInterface.GetEpochLastProposed(client, stakerId) - if err != nil { - log.Error("Error in fetching epoch last proposed....Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetEpochLastProposed", client, stakerId) if err != nil { return 0, err } - return epochLastProposed, nil + return returnedValues[0].Interface().(uint32), nil } diff --git a/utils/client_methods.go b/utils/client_methods.go index 731ba786..a840898b 100644 --- a/utils/client_methods.go +++ b/utils/client_methods.go @@ -2,131 +2,59 @@ package utils import ( "context" - "github.com/avast/retry-go" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "math/big" - "razor/core" ) -func (*UtilsStruct) GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (uint64, error) { - var ( - nonce uint64 - err error - ) - err = retry.Do( - func() error { - nonce, err = ClientInterface.NonceAt(client, context.Background(), accountAddress) - if err != nil { - log.Error("Error in fetching nonce.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) +func (*ClientStruct) GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (uint64, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "NonceAt", client, context.Background(), accountAddress) if err != nil { return 0, err } - return nonce, nil + return returnedValues[0].Interface().(uint64), nil } -func (*UtilsStruct) GetLatestBlockWithRetry(client *ethclient.Client) (*types.Header, error) { - var ( - latestHeader *types.Header - err error - ) - err = retry.Do( - func() error { - latestHeader, err = ClientInterface.HeaderByNumber(client, context.Background(), nil) - if err != nil { - log.Error("Error in fetching latest block.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) +func (*ClientStruct) GetLatestBlockWithRetry(client *ethclient.Client) (*types.Header, error) { + var blockNumberArgument *big.Int + returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "HeaderByNumber", client, context.Background(), blockNumberArgument) if err != nil { return nil, err } - return latestHeader, nil + return returnedValues[0].Interface().(*types.Header), nil } -func (o *UtilsStruct) SuggestGasPriceWithRetry(client *ethclient.Client) (*big.Int, error) { - var ( - gasPrice *big.Int - err error - ) - err = retry.Do( - func() error { - gasPrice, err = ClientInterface.SuggestGasPrice(client, context.Background()) - if err != nil { - log.Error("Error in fetching gas price.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(3)) +func (*ClientStruct) SuggestGasPriceWithRetry(client *ethclient.Client) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "SuggestGasPrice", client, context.Background()) if err != nil { return nil, err } - return gasPrice, nil + return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) EstimateGasWithRetry(client *ethclient.Client, message ethereum.CallMsg) (uint64, error) { - var ( - gasLimit uint64 - err error - ) - err = retry.Do( - func() error { - gasLimit, err = ClientInterface.EstimateGas(client, context.Background(), message) - if err != nil { - log.Error("Error in estimating gas limit.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(3)) +func (*ClientStruct) EstimateGasWithRetry(client *ethclient.Client, message ethereum.CallMsg) (uint64, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "EstimateGas", client, context.Background(), message) if err != nil { return 0, err } - return gasLimit, nil + return returnedValues[0].Interface().(uint64), nil } -func (*UtilsStruct) FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]types.Log, error) { - var ( - logs []types.Log - err error - ) - err = retry.Do( - func() error { - logs, err = ClientInterface.FilterLogs(client, context.Background(), query) - if err != nil { - log.Error("Error in fetching logs.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) +func (*ClientStruct) FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]types.Log, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "FilterLogs", client, context.Background(), query) if err != nil { return nil, err } - return logs, nil + return returnedValues[0].Interface().([]types.Log), nil } -func (*UtilsStruct) BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) { - var ( - balance *big.Int - err error - ) - err = retry.Do( - func() error { - balance, err = ClientInterface.BalanceAt(client, context.Background(), account, nil) - if err != nil { - log.Error("Error in fetching logs.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) +func (*ClientStruct) BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) { + var blockNumberArgument *big.Int + returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "BalanceAt", client, context.Background(), account, blockNumberArgument) if err != nil { return nil, err } - return balance, nil + return returnedValues[0].Interface().(*big.Int), nil } diff --git a/utils/client_methods_test.go b/utils/client_methods_test.go index 120a5629..ac879bb2 100644 --- a/utils/client_methods_test.go +++ b/utils/client_methods_test.go @@ -3,16 +3,17 @@ package utils import ( "context" "errors" + "math/big" + "razor/utils/mocks" + "reflect" + "testing" + "github.com/avast/retry-go" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" - "math/big" - "razor/utils/mocks" - "reflect" - "testing" ) func TestOptionUtilsStruct_SuggestGasPriceWithRetry(t *testing.T) { @@ -55,12 +56,13 @@ func TestOptionUtilsStruct_SuggestGasPriceWithRetry(t *testing.T) { ClientInterface: clientMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) clientMock.On("SuggestGasPrice", mock.AnythingOfType("*ethclient.Client"), context.Background()).Return(tt.args.gasPrice, tt.args.gasPriceErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.SuggestGasPriceWithRetry(client) + clientUtils := ClientStruct{} + got, err := clientUtils.SuggestGasPriceWithRetry(client) if (err != nil) != tt.wantErr { t.Errorf("SuggestGasPriceWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -113,11 +115,12 @@ func TestUtilsStruct_BalanceAtWithRetry(t *testing.T) { ClientInterface: clientMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) clientMock.On("BalanceAt", mock.AnythingOfType("*ethclient.Client"), context.Background(), mock.AnythingOfType("common.Address"), mock.AnythingOfType("*big.Int")).Return(tt.args.balance, tt.args.balanceErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.BalanceAtWithRetry(client, account) + clientUtils := ClientStruct{} + got, err := clientUtils.BalanceAtWithRetry(client, account) if (err != nil) != tt.wantErr { t.Errorf("BalanceAtWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -170,11 +173,12 @@ func TestUtilsStruct_EstimateGasWithRetry(t *testing.T) { ClientInterface: clientMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) clientMock.On("EstimateGas", mock.AnythingOfType("*ethclient.Client"), context.Background(), mock.AnythingOfType("ethereum.CallMsg")).Return(tt.args.gasLimit, tt.args.gasLimitErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.EstimateGasWithRetry(client, message) + clientUtils := ClientStruct{} + got, err := clientUtils.EstimateGasWithRetry(client, message) if (err != nil) != tt.wantErr { t.Errorf("EstimateGasWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -226,11 +230,12 @@ func TestUtilsStruct_FilterLogsWithRetry(t *testing.T) { ClientInterface: clientMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) clientMock.On("FilterLogs", mock.AnythingOfType("*ethclient.Client"), context.Background(), mock.AnythingOfType("ethereum.FilterQuery")).Return(tt.args.logs, tt.args.logsErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.FilterLogsWithRetry(client, query) + clientUtils := ClientStruct{} + got, err := clientUtils.FilterLogsWithRetry(client, query) if (err != nil) != tt.wantErr { t.Errorf("FilterLogsWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -281,11 +286,12 @@ func TestUtilsStruct_GetLatestBlockWithRetry(t *testing.T) { ClientInterface: clientMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) clientMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), context.Background(), mock.AnythingOfType("*big.Int")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetLatestBlockWithRetry(client) + clientUtils := ClientStruct{} + got, err := clientUtils.GetLatestBlockWithRetry(client) if (err != nil) != tt.wantErr { t.Errorf("GetLatestBlockWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -337,11 +343,12 @@ func TestUtilsStruct_GetNonceAtWithRetry(t *testing.T) { ClientInterface: clientMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) clientMock.On("NonceAt", mock.AnythingOfType("*ethclient.Client"), context.Background(), mock.AnythingOfType("common.Address")).Return(tt.args.nonce, tt.args.nonceErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetNonceAtWithRetry(client, accountAddress) + clientUtils := ClientStruct{} + got, err := clientUtils.GetNonceAtWithRetry(client, accountAddress) if (err != nil) != tt.wantErr { t.Errorf("GetNonceAtWithRetry() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/common.go b/utils/common.go index c326d3b4..164c3a74 100644 --- a/utils/common.go +++ b/utils/common.go @@ -5,11 +5,14 @@ import ( "errors" "math/big" "os" + "path/filepath" "razor/core" "razor/core/types" "razor/logger" "time" + "github.com/avast/retry-go" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" solsha3 "github.com/miguelmota/go-solidity-sha3" @@ -26,14 +29,30 @@ func (*UtilsStruct) ConnectToClient(provider string) *ethclient.Client { } func (*UtilsStruct) FetchBalance(client *ethclient.Client, accountAddress string) (*big.Int, error) { - address := common.HexToAddress(accountAddress) - coinContract := UtilsInterface.GetTokenManager(client) - opts := UtilsInterface.GetOptions() - return CoinInterface.BalanceOf(coinContract, &opts, address) + var ( + balance *big.Int + err error + ) + err = retry.Do( + func() error { + address := common.HexToAddress(accountAddress) + erc20Contract := UtilsInterface.GetTokenManager(client) + opts := UtilsInterface.GetOptions() + balance, err = CoinInterface.BalanceOf(erc20Contract, &opts, address) + if err != nil { + log.Error("Error in fetching balance....Retrying") + return err + } + return nil + }, RetryInterface.RetryAttempts(core.MaxRetries)) + if err != nil { + return big.NewInt(0), err + } + return balance, nil } -func (*UtilsStruct) GetDelayedState(client *ethclient.Client, buffer int32) (int64, error) { - block, err := UtilsInterface.GetLatestBlockWithRetry(client) +func (*UtilsStruct) GetBufferedState(client *ethclient.Client, buffer int32) (int64, error) { + block, err := ClientInterface.GetLatestBlockWithRetry(client) if err != nil { return -1, err } @@ -41,14 +60,13 @@ func (*UtilsStruct) GetDelayedState(client *ethclient.Client, buffer int32) (int if err != nil { return -1, err } - blockTime := uint64(block.Time) lowerLimit := (core.StateLength * uint64(buffer)) / 100 upperLimit := core.StateLength - (core.StateLength*uint64(buffer))/100 - if blockTime%(core.StateLength) > upperLimit-stateBuffer || blockTime%(core.StateLength) < lowerLimit+stateBuffer { + if block.Time%(core.StateLength) > upperLimit-stateBuffer || block.Time%(core.StateLength) < lowerLimit+stateBuffer { return -1, nil } - state := blockTime / core.StateLength - return int64(state) % core.NumberOfStates, nil + state := block.Time / core.StateLength + return int64(state % core.NumberOfStates), nil } func (*UtilsStruct) CheckTransactionReceipt(client *ethclient.Client, _txHash string) int { @@ -92,6 +110,21 @@ func CheckError(msg string, err error) { } } +func IsValidAddress(address string) bool { + if !common.IsHexAddress(address) { + log.Error("Invalid Address") + return false + } + return true +} + +func ValidateAddress(address string) (string, error) { + if !IsValidAddress(address) { + return "", errors.New("invalid address") + } + return address, nil +} + func (*UtilsStruct) IsFlagPassed(name string) bool { found := false for _, arg := range os.Args { @@ -103,16 +136,16 @@ func (*UtilsStruct) IsFlagPassed(name string) bool { } func (*UtilsStruct) CheckEthBalanceIsZero(client *ethclient.Client, address string) { - ethBalance, err := ClientInterface.BalanceAt(client, context.Background(), common.HexToAddress(address), nil) + ethBalance, err := ClientInterface.BalanceAtWithRetry(client, common.HexToAddress(address)) if err != nil { - log.Fatalf("Error in fetching eth balance of the account: %s\n%s", address, err) + log.Fatalf("Error in fetching sFuel balance of the account: %s\n%s", address, err) } if ethBalance.Cmp(big.NewInt(0)) == 0 { - log.Fatal("Eth balance is 0, Aborting...") + log.Fatal("sFuel balance is 0, Aborting...") } } -func (*UtilsStruct) GetStateName(stateNumber int64) string { +func GetStateName(stateNumber int64) string { var stateName string switch stateNumber { case 0: @@ -126,7 +159,7 @@ func (*UtilsStruct) GetStateName(stateNumber int64) string { case 4: stateName = "Confirm" default: - stateName = "-1" + stateName = "Buffer" } return stateName } @@ -139,17 +172,17 @@ func (*UtilsStruct) AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Cli } func (*UtilsStruct) GetEpoch(client *ethclient.Client) (uint32, error) { - latestHeader, err := UtilsInterface.GetLatestBlockWithRetry(client) + latestHeader, err := ClientInterface.GetLatestBlockWithRetry(client) if err != nil { log.Error("Error in fetching block: ", err) return 0, err } - epoch := uint64(latestHeader.Time) / uint64(core.EpochLength) + epoch := latestHeader.Time / core.EpochLength return uint32(epoch), nil } func (*UtilsStruct) CalculateBlockTime(client *ethclient.Client) int64 { - latestBlock, err := UtilsInterface.GetLatestBlockWithRetry(client) + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(client) if err != nil { log.Fatalf("Error in fetching latest Block: %s", err) } @@ -162,7 +195,7 @@ func (*UtilsStruct) CalculateBlockTime(client *ethclient.Client) int64 { } func (*UtilsStruct) GetRemainingTimeOfCurrentState(client *ethclient.Client, bufferPercent int32) (int64, error) { - block, err := UtilsInterface.GetLatestBlockWithRetry(client) + block, err := ClientInterface.GetLatestBlockWithRetry(client) if err != nil { return 0, err } @@ -189,13 +222,13 @@ func (*UtilsStruct) Prng(max uint32, prngHashes []byte) *big.Int { return sum.Mod(sum, maxBigInt) } -func (*UtilsStruct) CalculateBlockNumberAtEpochBeginning(client *ethclient.Client, epochLength int64, currentBlockNumber *big.Int) (*big.Int, error) { +func (*UtilsStruct) EstimateBlockNumberAtEpochBeginning(client *ethclient.Client, currentBlockNumber *big.Int) (*big.Int, error) { block, err := ClientInterface.HeaderByNumber(client, context.Background(), currentBlockNumber) if err != nil { log.Error("Error in fetching block: ", err) return nil, err } - current_epoch := block.Time / uint64(core.EpochLength) + currentEpoch := block.Time / core.EpochLength previousBlockNumber := block.Number.Uint64() - core.StateLength previousBlock, err := ClientInterface.HeaderByNumber(client, context.Background(), big.NewInt(int64(previousBlockNumber))) @@ -204,17 +237,17 @@ func (*UtilsStruct) CalculateBlockNumberAtEpochBeginning(client *ethclient.Clien return nil, err } previousBlockActualTimestamp := previousBlock.Time - previousBlockAssumedTimestamp := block.Time - uint64(core.EpochLength) - previous_epoch := previousBlockActualTimestamp / uint64(core.EpochLength) - if previousBlockActualTimestamp > previousBlockAssumedTimestamp && previous_epoch != current_epoch-1 { - return UtilsInterface.CalculateBlockNumberAtEpochBeginning(client, core.EpochLength, big.NewInt(int64(previousBlockNumber))) + previousBlockAssumedTimestamp := block.Time - core.EpochLength + previousEpoch := previousBlockActualTimestamp / core.EpochLength + if previousBlockActualTimestamp > previousBlockAssumedTimestamp && previousEpoch != currentEpoch-1 { + return UtilsInterface.EstimateBlockNumberAtEpochBeginning(client, big.NewInt(int64(previousBlockNumber))) } return big.NewInt(int64(previousBlockNumber)), nil } -func (*UtilsStruct) SaveDataToCommitJsonFile(filePath string, epoch uint32, commitData types.CommitData) error { +func (*FileStruct) SaveDataToCommitJsonFile(filePath string, epoch uint32, commitData types.CommitData) error { var data types.CommitFileData data.Epoch = epoch @@ -234,7 +267,7 @@ func (*UtilsStruct) SaveDataToCommitJsonFile(filePath string, epoch uint32, comm return nil } -func (*UtilsStruct) ReadFromCommitJsonFile(filePath string) (types.CommitFileData, error) { +func (*FileStruct) ReadFromCommitJsonFile(filePath string) (types.CommitFileData, error) { jsonFile, err := OS.Open(filePath) if err != nil { log.Error("Error in opening json file: ", err) @@ -255,20 +288,20 @@ func (*UtilsStruct) ReadFromCommitJsonFile(filePath string) (types.CommitFileDat return commitedData, nil } -func (*UtilsStruct) AssignLogFile(flagSet *pflag.FlagSet) { +func (*FileStruct) AssignLogFile(flagSet *pflag.FlagSet, configurations types.Configurations) { if UtilsInterface.IsFlagPassed("logFile") { fileName, err := FlagSetInterface.GetLogFileName(flagSet) if err != nil { log.Fatal("Error in getting file name: ", err) } log.Debug("Log file name: ", fileName) - logger.InitializeLogger(fileName) + logger.InitializeLogger(fileName, configurations) } else { log.Debug("No `logFile` flag passed, not storing logs in any file") } } -func (*UtilsStruct) SaveDataToProposeJsonFile(filePath string, proposeData types.ProposeFileData) error { +func (*FileStruct) SaveDataToProposeJsonFile(filePath string, proposeData types.ProposeFileData) error { var data types.ProposeFileData data.Epoch = proposeData.Epoch @@ -288,7 +321,7 @@ func (*UtilsStruct) SaveDataToProposeJsonFile(filePath string, proposeData types return nil } -func (*UtilsStruct) ReadFromProposeJsonFile(filePath string) (types.ProposeFileData, error) { +func (*FileStruct) ReadFromProposeJsonFile(filePath string) (types.ProposeFileData, error) { jsonFile, err := OS.Open(filePath) if err != nil { log.Error("Error in opening json file: ", err) @@ -309,7 +342,7 @@ func (*UtilsStruct) ReadFromProposeJsonFile(filePath string) (types.ProposeFileD return proposedData, nil } -func (*UtilsStruct) SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []uint32) error { +func (*FileStruct) SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []uint32) error { var data types.DisputeFileData data.BountyIdQueue = bountyIdQueue @@ -325,7 +358,7 @@ func (*UtilsStruct) SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []u return nil } -func (*UtilsStruct) ReadFromDisputeJsonFile(filePath string) (types.DisputeFileData, error) { +func (*FileStruct) ReadFromDisputeJsonFile(filePath string) (types.DisputeFileData, error) { jsonFile, err := OS.Open(filePath) if err != nil { log.Error("Error in opening json file: ", err) @@ -345,3 +378,19 @@ func (*UtilsStruct) ReadFromDisputeJsonFile(filePath string) (types.DisputeFileD } return disputeData, nil } + +func (*UtilsStruct) CheckPassword(address string, password string) error { + razorPath, err := PathInterface.GetDefaultPath() + if err != nil { + log.Error("CheckPassword: Error in getting .razor path: ", err) + return err + } + keystorePath := filepath.Join(razorPath, "keystore_files") + _, err = AccountsInterface.GetPrivateKey(address, password, keystorePath) + if err != nil { + log.Info("Kindly check your password!") + log.Error("CheckPassword: Error in getting private key: ", err) + return err + } + return nil +} diff --git a/utils/common_test.go b/utils/common_test.go index 0ffff85b..0e952f60 100644 --- a/utils/common_test.go +++ b/utils/common_test.go @@ -2,11 +2,6 @@ package utils import ( "errors" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/spf13/pflag" - "github.com/stretchr/testify/mock" "math/big" "os" Types "razor/core/types" @@ -14,6 +9,13 @@ import ( "razor/utils/mocks" "reflect" "testing" + + "github.com/avast/retry-go" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/spf13/pflag" + "github.com/stretchr/testify/mock" ) func TestCheckError(t *testing.T) { @@ -102,17 +104,15 @@ func TestCalculateBlockTime(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.Utils) - clientMock := new(mocks.ClientUtils) + clientUtilsMock := new(mocks.ClientUtils) optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, - ClientInterface: clientMock, + ClientInterface: clientUtilsMock, } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestBlock, tt.args.latestBlockErr) - clientMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.lastSecondBlock, tt.args.lastSecondBlockErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestBlock, tt.args.latestBlockErr) + clientUtilsMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.lastSecondBlock, tt.args.lastSecondBlockErr) fatal = false @@ -174,7 +174,7 @@ func TestCheckEthBalanceIsZero(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - clientMock.On("BalanceAt", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) + clientMock.On("BalanceAtWithRetry", mock.Anything, mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) fatal = false @@ -301,67 +301,66 @@ func TestFetchBalance(t *testing.T) { var callOpts bind.CallOpts type args struct { - coinContract *bindings.RAZOR - balance *big.Int - balanceErr error + erc20Contract *bindings.RAZOR + balance *big.Int + balanceErr error } tests := []struct { - name string - args args - expectedFatal bool - wantErr error + name string + args args + want *big.Int + wantErr bool }{ { name: "When FetchBalance() executes successfully", args: args{ - coinContract: &bindings.RAZOR{}, - balance: big.NewInt(1), + erc20Contract: &bindings.RAZOR{}, + balance: big.NewInt(1), }, - expectedFatal: false, - wantErr: nil, + want: big.NewInt(1), + wantErr: false, + }, + { + name: "When there is an error in fetching balance", + args: args{ + erc20Contract: &bindings.RAZOR{}, + balanceErr: errors.New("error in fetching balance"), + }, + want: big.NewInt(0), + wantErr: true, }, } - - defer func() { log.ExitFunc = nil }() - var fatal bool - log.ExitFunc = func(int) { fatal = true } - for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.Utils) - coinMock := new(mocks.CoinUtils) + erc20Mock := new(mocks.CoinUtils) + retryMock := new(mocks.RetryUtils) optionsPackageStruct := OptionsPackageStruct{ UtilsInterface: utilsMock, - CoinInterface: coinMock, + CoinInterface: erc20Mock, + RetryInterface: retryMock, } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetTokenManager", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.coinContract) + utilsMock.On("GetTokenManager", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.erc20Contract) utilsMock.On("GetOptions").Return(callOpts) - coinMock.On("BalanceOf", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.balance, tt.args.balanceErr) - - fatal = false + erc20Mock.On("BalanceOf", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.balance, tt.args.balanceErr) + retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - _, err := utils.FetchBalance(client, accountAddress) - if fatal != tt.expectedFatal { - t.Error("The FetchBalance function didn't execute as expected") + got, err := utils.FetchBalance(client, accountAddress) + if (err != nil) != tt.wantErr { + t.Errorf("FetchBalance() error = %v, wantErr %v", err, tt.wantErr) + return } - if err == nil || tt.wantErr == nil { - if err != tt.wantErr { - t.Errorf("Error for FetchBalance function, got = %v, want = %v", err, tt.wantErr) - } - } else { - if err.Error() != tt.wantErr.Error() { - t.Errorf("Error for fetchBalance function, got = %v, want = %v", err, tt.wantErr) - } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FetchBalance() got = %v, want %v", got, tt.want) } }) } } -func TestGetDelayedState(t *testing.T) { +func TestGetBufferedState(t *testing.T) { var client *ethclient.Client type args struct { @@ -378,7 +377,7 @@ func TestGetDelayedState(t *testing.T) { wantErr bool }{ { - name: "Test 1: When GetDelayedState() executes successfully", + name: "Test 1: When GetBufferedState() executes successfully", args: args{ block: &types.Header{ Time: 100, @@ -414,7 +413,7 @@ func TestGetDelayedState(t *testing.T) { wantErr: false, }, { - name: "Test 4: When GetDelayedState() executes successfully and state we get is other than 0", + name: "Test 4: When GetBufferedState() executes successfully and state we get is other than 0", args: args{ block: &types.Header{ Time: 900, @@ -444,23 +443,25 @@ func TestGetDelayedState(t *testing.T) { t.Run(tt.name, func(t *testing.T) { utilsMock := new(mocks.Utils) + clientUtilsMock := new(mocks.ClientUtils) optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, + UtilsInterface: utilsMock, + ClientInterface: clientUtilsMock, } utils := StartRazor(optionsPackageStruct) utilsMock.On("GetStateBuffer", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.stateBuffer, tt.args.stateBufferErr) - utilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.block, tt.args.blockErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.block, tt.args.blockErr) - got, err := utils.GetDelayedState(client, tt.args.buffer) + got, err := utils.GetBufferedState(client, tt.args.buffer) if (err != nil) != tt.wantErr { - t.Errorf("GetDelayedState() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("GetBufferedState() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { - t.Errorf("GetDelayedState() got = %v, want %v", got, tt.want) + t.Errorf("GetBufferedState() got = %v, want %v", got, tt.want) } }) } @@ -503,14 +504,14 @@ func TestGetEpoch(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.Utils) + clientUtilsMock := new(mocks.ClientUtils) optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, + ClientInterface: clientUtilsMock, } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) got, err := utils.GetEpoch(client) if (err != nil) != tt.wantErr { @@ -573,18 +574,12 @@ func TestGetStateName(t *testing.T) { args: args{ stateNumber: 5, }, - want: "-1", + want: "Buffer", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.Utils) - - optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, - } - utils := StartRazor(optionsPackageStruct) - if got := utils.GetStateName(tt.args.stateNumber); got != tt.want { + if got := GetStateName(tt.args.stateNumber); got != tt.want { t.Errorf("GetStateName() = %v, want %v", got, tt.want) } }) @@ -717,6 +712,100 @@ func TestWaitTillNextNSecs(t *testing.T) { } } +func TestIsValidAddress(t *testing.T) { + type args struct { + address string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "Test 1: When correct address is passed", + args: args{ + address: "0x8797EA6306881D74c4311C08C0Ca2C0a76dDC90e", + }, + want: true, + }, + { + name: "Test 2: When incorrect address is passed", + args: args{ + address: "0x8797EA6306881D74c4311C08C0Ca2C0a76dDC90z", + }, + want: false, + }, + { + name: "Test 2: When nil is passed", + args: args{ + address: "", + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := IsValidAddress(tt.args.address); got != tt.want { + t.Errorf("IsValidAddress() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestIsValidateAddress(t *testing.T) { + type args struct { + address string + } + tests := []struct { + name string + args args + wantAddress string + wantErr error + }{ + { + name: "Test 1: When correct address is passed", + args: args{ + address: "0x8797EA6306881D74c4311C08C0Ca2C0a76dDC90e", + }, + wantAddress: "0x8797EA6306881D74c4311C08C0Ca2C0a76dDC90e", + wantErr: nil, + }, + { + name: "Test 2: When incorrect address is passed", + args: args{ + address: "0x8797EA6306881D74c4311C08C0Ca2C0a76dDC90z", + }, + wantAddress: "", + wantErr: errors.New("invalid address"), + }, + { + name: "Test 2: When nil is passed", + args: args{ + address: "", + }, + wantAddress: "", + wantErr: errors.New("invalid address"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, gotErr := ValidateAddress(tt.args.address) + if got != tt.wantAddress { + t.Errorf("ValidateAddress() returns address = %v, want address = %v", got, tt.wantAddress) + } + if gotErr == nil || tt.wantErr == nil { + if gotErr != tt.wantErr { + t.Errorf("Error for ValidateAddress(), got error = %v, want error = %v", gotErr, tt.wantErr) + } + } else { + if gotErr.Error() != tt.wantErr.Error() { + t.Errorf("Error for ValidateAddress(), got error = %v, want error = %v", gotErr, tt.wantErr) + } + } + }) + } +} + func TestAssignStakerId(t *testing.T) { var flagSet *pflag.FlagSet var client *ethclient.Client @@ -844,13 +933,14 @@ func TestAssignLogFile(t *testing.T) { UtilsInterface: utilsMock, FlagSetInterface: flagSetMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) fatal = false utilsMock.On("IsFlagPassed", mock.Anything).Return(tt.args.isFlagPassed) flagSetMock.On("GetLogFileName", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.fileName, tt.args.fileNameErr) - utils.AssignLogFile(flagSet) + fileUtils := FileStruct{} + fileUtils.AssignLogFile(flagSet, Types.Configurations{}) if fatal != tt.expectedFatal { t.Error("The AssignLogFile function didn't execute as expected") } @@ -905,14 +995,16 @@ func TestGetRemainingTimeOfCurrentState(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { utilsMock := new(mocks.Utils) + clientUtilsMock := new(mocks.ClientUtils) optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, + UtilsInterface: utilsMock, + ClientInterface: clientUtilsMock, } utils := StartRazor(optionsPackageStruct) utilsMock.On("GetStateBuffer", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.stateBuffer, tt.args.stateBufferErr) - utilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.block, tt.args.blockErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.block, tt.args.blockErr) got, err := utils.GetRemainingTimeOfCurrentState(client, bufferPercent) if (err != nil) != tt.wantErr { t.Errorf("GetRemainingTimeOfCurrentState() error = %v, wantErr %v", err, tt.wantErr) @@ -983,10 +1075,9 @@ func TestPrng(t *testing.T) { } } -func TestCalculateBlockNumberAtEpochBeginning(t *testing.T) { +func TestEstimateBlockNumberAtEpochBeginning(t *testing.T) { var ( client *ethclient.Client - epochLength int64 currentBlockNumber *big.Int ) type args struct { @@ -1002,7 +1093,7 @@ func TestCalculateBlockNumberAtEpochBeginning(t *testing.T) { wantErr bool }{ { - name: "Test 1: When CalculateBlockNumberAtEpochBeginning() is executed successfully", + name: "Test 1: When EstimateBlockNumberAtEpochBeginning() is executed successfully", args: args{ block: &types.Header{Time: 1, Number: big.NewInt(1)}, previousBlock: &types.Header{Time: 20, Number: big.NewInt(1)}, @@ -1032,13 +1123,13 @@ func TestCalculateBlockNumberAtEpochBeginning(t *testing.T) { clientMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.block, tt.args.blockErr) clientMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.previousBlock, tt.args.previousBlockErr) - got, err := utils.CalculateBlockNumberAtEpochBeginning(client, epochLength, currentBlockNumber) + got, err := utils.EstimateBlockNumberAtEpochBeginning(client, currentBlockNumber) if (err != nil) != tt.wantErr { - t.Errorf("CalculateBlockNumberAtEpochBeginning() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("EstimateBlockNumberAtEpochBeginning() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { - t.Errorf("CalculateBlockNumberAtEpochBeginning() got = %v, want %v", got, tt.want) + t.Errorf("EstimateBlockNumberAtEpochBeginning() got = %v, want %v", got, tt.want) } }) } @@ -1092,12 +1183,13 @@ func TestSaveDataToCommitJsonFile(t *testing.T) { JsonInterface: jsonMock, OS: osMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) jsonMock.On("Marshal", mock.Anything).Return(tt.args.jsonData, tt.args.jsonDataErr) osMock.On("WriteFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.writeFileErr) - if err := utils.SaveDataToCommitJsonFile(filePath, epoch, commitData); (err != nil) != tt.wantErr { + fileUtils := FileStruct{} + if err := fileUtils.SaveDataToCommitJsonFile(filePath, epoch, commitData); (err != nil) != tt.wantErr { t.Errorf("SaveDataToCommitJsonFile() error = %v, wantErr %v", err, tt.wantErr) } }) @@ -1152,11 +1244,13 @@ func TestSaveDataToProposeJsonFile(t *testing.T) { JsonInterface: jsonMock, OS: osMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) jsonMock.On("Marshal", mock.Anything).Return(tt.args.jsonData, tt.args.jsonDataErr) osMock.On("WriteFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.writeFileErr) - if err := utils.SaveDataToProposeJsonFile(filePath, proposeData); (err != nil) != tt.wantErr { + + fileUtils := FileStruct{} + if err := fileUtils.SaveDataToProposeJsonFile(filePath, proposeData); (err != nil) != tt.wantErr { t.Errorf("SaveDataToProposeJsonFile() error = %v, wantErr %v", err, tt.wantErr) } }) @@ -1210,11 +1304,13 @@ func TestSaveDataToDisputeJsonFile(t *testing.T) { JsonInterface: jsonMock, OS: osMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) jsonMock.On("Marshal", mock.Anything).Return(tt.args.jsonData, tt.args.jsonDataErr) osMock.On("WriteFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.writeFileErr) - if err := utils.SaveDataToDisputeJsonFile(filePath, bountyIdQueue); (err != nil) != tt.wantErr { + + fileUtils := FileStruct{} + if err := fileUtils.SaveDataToDisputeJsonFile(filePath, bountyIdQueue); (err != nil) != tt.wantErr { t.Errorf("SaveDataToDisputeJsonFile() error = %v, wantErr %v", err, tt.wantErr) } }) @@ -1284,11 +1380,13 @@ func TestReadFromCommitJsonFile(t *testing.T) { OS: osMock, IOInterface: ioMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) osMock.On("Open", mock.Anything).Return(tt.args.jsonFile, tt.args.jsonFileErr) ioMock.On("ReadAll", mock.Anything).Return(tt.args.byteValue, tt.args.byteValueErr) jsonMock.On("Unmarshal", mock.Anything, mock.Anything).Return(tt.args.unmarshalErr) - got, err := utils.ReadFromCommitJsonFile(filePath) + + fileUtils := FileStruct{} + got, err := fileUtils.ReadFromCommitJsonFile(filePath) if (err != nil) != tt.wantErr { t.Errorf("ReadFromCommitJsonFile() error = %v, wantErr %v", err, tt.wantErr) return @@ -1363,12 +1461,13 @@ func TestReadFromProposeJsonFile(t *testing.T) { OS: osMock, IOInterface: ioMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) osMock.On("Open", mock.Anything).Return(tt.args.jsonFile, tt.args.jsonFileErr) ioMock.On("ReadAll", mock.Anything).Return(tt.args.byteValue, tt.args.byteValueErr) jsonMock.On("Unmarshal", mock.Anything, mock.Anything).Return(tt.args.unmarshalErr) - got, err := utils.ReadFromProposeJsonFile(filePath) + fileUtils := FileStruct{} + got, err := fileUtils.ReadFromProposeJsonFile(filePath) if (err != nil) != tt.wantErr { t.Errorf("ReadFromProposeJsonFile() error = %v, wantErr %v", err, tt.wantErr) return @@ -1443,12 +1542,13 @@ func TestReadFromDisputeJsonFile(t *testing.T) { OS: osMock, IOInterface: ioMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) osMock.On("Open", mock.Anything).Return(tt.args.jsonFile, tt.args.jsonFileErr) ioMock.On("ReadAll", mock.Anything).Return(tt.args.byteValue, tt.args.byteValueErr) jsonMock.On("Unmarshal", mock.Anything, mock.Anything).Return(tt.args.unmarshalErr) - got, err := utils.ReadFromDisputeJsonFile(filePath) + fileUtils := FileStruct{} + got, err := fileUtils.ReadFromDisputeJsonFile(filePath) if (err != nil) != tt.wantErr { t.Errorf("ReadFromDisputeJsonFile() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/contract-manager.go b/utils/contract-manager.go index 41ba56fb..b3a71eb6 100644 --- a/utils/contract-manager.go +++ b/utils/contract-manager.go @@ -10,11 +10,11 @@ import ( ) func (*UtilsStruct) GetTokenManager(client *ethclient.Client) *bindings.RAZOR { - coinContract, err := BindingsInterface.NewRAZOR(common.HexToAddress(core.RAZORAddress), client) + erc20Contract, err := BindingsInterface.NewRAZOR(common.HexToAddress(core.RAZORAddress), client) if err != nil { log.Fatal(err) } - return coinContract + return erc20Contract } func (*UtilsStruct) GetStakeManager(client *ethclient.Client) *bindings.StakeManager { diff --git a/utils/interface.go b/utils/interface.go index 541f7f7f..3fbde6b2 100644 --- a/utils/interface.go +++ b/utils/interface.go @@ -1,13 +1,13 @@ package utils import ( - "bufio" "context" "crypto/ecdsa" "io" "io/fs" "math/big" "os" + "razor/cache" "razor/core/types" "razor/pkg/bindings" "time" @@ -27,7 +27,6 @@ import ( //go:generate mockery --name ClientUtils --output ./mocks --case=underscore //go:generate mockery --name TimeUtils --output ./mocks --case=underscore //go:generate mockery --name OSUtils --output ./mocks --case=underscore -//go:generate mockery --name BufioUtils --output ./mocks --case=underscore //go:generate mockery --name CoinUtils --output ./mocks --case=underscore //go:generate mockery --name IOUtils --output ./mocks --case=underscore //go:generate mockery --name ABIUtils --output ./mocks --case=underscore @@ -44,13 +43,14 @@ import ( //go:generate mockery --name RetryUtils --output ./mocks --case=underscore //go:generate mockery --name MerkleTreeInterface --output ./mocks --case=underscore //go:generate mockery --name FlagSetUtils --output ./mocks --case=underscore +//go:generate mockery --name GasUtils --output ./mocks --case=underscore +//go:generate mockery --name FileUtils --output ./mocks --case=underscore var UtilsInterface Utils var EthClient EthClientUtils var ClientInterface ClientUtils var Time TimeUtils var OS OSUtils -var Bufio BufioUtils var CoinInterface CoinUtils var IOInterface IOUtils var ABIInterface ABIUtils @@ -67,19 +67,12 @@ var StakedTokenInterface StakedTokenUtils var RetryInterface RetryUtils var MerkleInterface MerkleTreeInterface var FlagSetInterface FlagSetUtils +var FileInterface FileUtils +var GasInterface GasUtils type Utils interface { - SuggestGasPriceWithRetry(client *ethclient.Client) (*big.Int, error) MultiplyFloatAndBigInt(bigIntVal *big.Int, floatingVal float64) *big.Int - GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (uint64, error) - GetGasPrice(client *ethclient.Client, config types.Configurations) *big.Int GetTxnOpts(transactionData types.TransactionOptions) *bind.TransactOpts - GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) - EstimateGasWithRetry(client *ethclient.Client, message ethereum.CallMsg) (uint64, error) - IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) - GetLatestBlockWithRetry(client *ethclient.Client) (*Types.Header, error) - FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]Types.Log, error) - BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) GetBlockManager(client *ethclient.Client) *bindings.BlockManager GetOptions() bind.CallOpts GetNumberOfProposedBlocks(client *ethclient.Client, epoch uint32) (uint8, error) @@ -119,35 +112,29 @@ type Utils interface { GetActiveJob(client *ethclient.Client, jobId uint16) (bindings.StructsJob, error) GetCollection(client *ethclient.Client, collectionId uint16) (bindings.StructsCollection, error) GetActiveCollection(client *ethclient.Client, collectionId uint16) (bindings.StructsCollection, error) - Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection) (*big.Int, error) - GetDataToCommitFromJobs(jobs []bindings.StructsJob) ([]*big.Int, []uint8, error) - GetDataToCommitFromJob(job bindings.StructsJob) (*big.Int, error) + Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, localCache *cache.LocalCache) (*big.Int, error) + GetDataToCommitFromJobs(jobs []bindings.StructsJob, localCache *cache.LocalCache) ([]*big.Int, []uint8, error) + GetDataToCommitFromJob(job bindings.StructsJob, localCache *cache.LocalCache) (*big.Int, error) GetAssignedCollections(client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) GetLeafIdOfACollection(client *ethclient.Client, collectionId uint16) (uint16, error) GetCollectionIdFromIndex(client *ethclient.Client, medianIndex uint16) (uint16, error) GetCollectionIdFromLeafId(client *ethclient.Client, leafId uint16) (uint16, error) GetNumActiveCollections(client *ethclient.Client) (uint16, error) - GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32) (*big.Int, error) + GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32, localCache *cache.LocalCache) (*big.Int, error) GetJobs(client *ethclient.Client) ([]bindings.StructsJob, error) GetAllCollections(client *ethclient.Client) ([]bindings.StructsCollection, error) GetActiveCollectionIds(client *ethclient.Client) ([]uint16, error) - GetDataFromAPI(url string) ([]byte, error) + GetDataFromAPI(url string, localCache *cache.LocalCache) ([]byte, error) GetDataFromJSON(jsonObject map[string]interface{}, selector string) (interface{}, error) HandleOfficialJobsFromJSONFile(client *ethclient.Client, collection bindings.StructsCollection, dataString string) ([]bindings.StructsJob, []uint16) GetDataFromXHTML(url string, selector string) (string, error) ConnectToClient(provider string) *ethclient.Client FetchBalance(client *ethclient.Client, accountAddress string) (*big.Int, error) - GetDelayedState(client *ethclient.Client, buffer int32) (int64, error) + GetBufferedState(client *ethclient.Client, buffer int32) (int64, error) WaitForBlockCompletion(client *ethclient.Client, hashToRead string) error CheckEthBalanceIsZero(client *ethclient.Client, address string) AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) GetEpoch(client *ethclient.Client) (uint32, error) - SaveDataToCommitJsonFile(filePath string, epoch uint32, commitData types.CommitData) error - ReadFromCommitJsonFile(filePath string) (types.CommitFileData, error) - SaveDataToProposeJsonFile(filePath string, proposeData types.ProposeFileData) error - ReadFromProposeJsonFile(filePath string) (types.ProposeFileData, error) - SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []uint32) error - ReadFromDisputeJsonFile(filePath string) (types.DisputeFileData, error) CalculateBlockTime(client *ethclient.Client) int64 IsFlagPassed(name string) bool GetTokenManager(client *ethclient.Client) *bindings.RAZOR @@ -162,15 +149,19 @@ type Utils interface { CalculateSalt(epoch uint32, medians []*big.Int) [32]byte ToAssign(client *ethclient.Client) (uint16, error) Prng(max uint32, prngHashes []byte) *big.Int - GetSaltFromBlockchain(client *ethclient.Client) ([32]byte, error) - GetStakerSRZRBalance(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) GetRemainingTimeOfCurrentState(client *ethclient.Client, bufferPercent int32) (int64, error) ConvertToNumber(num interface{}) (*big.Float, error) SecondsToReadableTime(input int) string - AssignLogFile(flagSet *pflag.FlagSet) - CalculateBlockNumberAtEpochBeginning(client *ethclient.Client, epochLength int64, currentBlockNumber *big.Int) (*big.Int, error) - GetStateName(stateNumber int64) string + EstimateBlockNumberAtEpochBeginning(client *ethclient.Client, currentBlockNumber *big.Int) (*big.Int, error) GetEpochLastProposed(client *ethclient.Client, stakerId uint32) (uint32, error) + CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) *big.Int + PasswordPrompt() string + AssignPassword(flagSet *pflag.FlagSet) string + PrivateKeyPrompt() string + GetRogueRandomValue(value int) *big.Int + GetStakedTokenManagerWithOpts(client *ethclient.Client, tokenAddress common.Address) (*bindings.StakedToken, bind.CallOpts) + GetStakerSRZRBalance(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) + CheckPassword(address string, password string) error } type EthClientUtils interface { @@ -185,6 +176,12 @@ type ClientUtils interface { SuggestGasPrice(client *ethclient.Client, ctx context.Context) (*big.Int, error) EstimateGas(client *ethclient.Client, ctx context.Context, msg ethereum.CallMsg) (uint64, error) FilterLogs(client *ethclient.Client, ctx context.Context, q ethereum.FilterQuery) ([]Types.Log, error) + SuggestGasPriceWithRetry(client *ethclient.Client) (*big.Int, error) + EstimateGasWithRetry(client *ethclient.Client, message ethereum.CallMsg) (uint64, error) + GetLatestBlockWithRetry(client *ethclient.Client) (*Types.Header, error) + FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]Types.Log, error) + BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) + GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (uint64, error) } type TimeUtils interface { @@ -198,18 +195,14 @@ type OSUtils interface { ReadFile(filename string) ([]byte, error) } -type BufioUtils interface { - NewScanner(r io.Reader) *bufio.Scanner -} - type CoinUtils interface { - BalanceOf(coinContract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) + BalanceOf(erc20Contract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) } type MerkleTreeInterface interface { - CreateMerkle(values []*big.Int) [][][]byte + CreateMerkle(values []*big.Int) ([][][]byte, error) GetProofPath(tree [][][]byte, assetId uint16) [][32]byte - GetMerkleRoot(tree [][][]byte) [32]byte + GetMerkleRoot(tree [][][]byte) ([32]byte, error) } type IOUtils interface { ReadAll(body io.ReadCloser) ([]byte, error) @@ -296,7 +289,7 @@ type JsonUtils interface { } type StakedTokenUtils interface { - BalanceOf(stakedToken *bindings.StakedToken, callOpts *bind.CallOpts, address common.Address) (*big.Int, error) + BalanceOf(client *ethclient.Client, tokenAddress common.Address, address common.Address) (*big.Int, error) } type RetryUtils interface { @@ -307,12 +300,27 @@ type FlagSetUtils interface { GetLogFileName(flagSet *pflag.FlagSet) (string, error) } +type FileUtils interface { + SaveDataToCommitJsonFile(filePath string, epoch uint32, commitData types.CommitData) error + ReadFromCommitJsonFile(filePath string) (types.CommitFileData, error) + SaveDataToProposeJsonFile(filePath string, proposeData types.ProposeFileData) error + ReadFromProposeJsonFile(filePath string) (types.ProposeFileData, error) + SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []uint32) error + ReadFromDisputeJsonFile(filePath string) (types.DisputeFileData, error) + AssignLogFile(flagSet *pflag.FlagSet, configurations types.Configurations) +} + +type GasUtils interface { + GetGasPrice(client *ethclient.Client, config types.Configurations) *big.Int + GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) + IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) +} + type UtilsStruct struct{} type EthClientStruct struct{} type ClientStruct struct{} type TimeStruct struct{} type OSStruct struct{} -type BufioStruct struct{} type CoinStruct struct{} type IOStruct struct{} type ABIStruct struct{} @@ -329,6 +337,8 @@ type StakedTokenStruct struct{} type RetryStruct struct{} type MerkleTreeStruct struct{} type FlagSetStruct struct{} +type FileStruct struct{} +type GasStruct struct{} type OptionsPackageStruct struct { UtilsInterface Utils @@ -336,7 +346,6 @@ type OptionsPackageStruct struct { ClientInterface ClientUtils Time TimeUtils OS OSUtils - Bufio BufioUtils CoinInterface CoinUtils IOInterface IOUtils ABIInterface ABIUtils @@ -353,4 +362,6 @@ type OptionsPackageStruct struct { RetryInterface RetryUtils MerkleInterface MerkleTreeInterface FlagSetInterface FlagSetUtils + FileInterface FileUtils + GasInterface GasUtils } diff --git a/utils/math.go b/utils/math.go index c908806d..24595715 100644 --- a/utils/math.go +++ b/utils/math.go @@ -65,7 +65,7 @@ func AllZero(bytesValue [32]byte) bool { return true } -func CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) *big.Int { +func (*UtilsStruct) CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) *big.Int { if amountInWei.Cmp(balance) > 0 { log.Fatal("Not enough razor balance") } @@ -154,7 +154,7 @@ func ConvertSRZRToRZR(sAmount *big.Int, currentStake *big.Int, totalSupply *big. return big.NewInt(1).Div(big.NewInt(1).Mul(sAmount, currentStake), totalSupply) } -func GetRogueRandomValue(value int) *big.Int { +func (*UtilsStruct) GetRogueRandomValue(value int) *big.Int { if value <= 0 { return big.NewInt(0) } diff --git a/utils/math_test.go b/utils/math_test.go index da98982e..7bb1e393 100644 --- a/utils/math_test.go +++ b/utils/math_test.go @@ -251,7 +251,8 @@ func TestCheckAmountAndBalance(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fatal = false - got := CheckAmountAndBalance(tt.args.amount, tt.args.balance) + ut := &UtilsStruct{} + got := ut.CheckAmountAndBalance(tt.args.amount, tt.args.balance) if tt.expectedFatal { assert.Equal(t, tt.expectedFatal, fatal) } @@ -868,7 +869,8 @@ func TestGetRogueRandomValue(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := GetRogueRandomValue(tt.args.value) + ut := UtilsStruct{} + got := ut.GetRogueRandomValue(tt.args.value) if got.Cmp(tt.want) > 0 { t.Errorf("GetRogueRandomValue() = %v, want %v", got, tt.want) } diff --git a/utils/merkle.go b/utils/merkle.go index 63f87313..31ac3387 100644 --- a/utils/merkle.go +++ b/utils/merkle.go @@ -1,13 +1,14 @@ package utils import ( + "errors" solsha3 "github.com/miguelmota/go-solidity-sha3" "math/big" ) -func (*MerkleTreeStruct) CreateMerkle(values []*big.Int) [][][]byte { +func (*MerkleTreeStruct) CreateMerkle(values []*big.Int) ([][][]byte, error) { if len(values) == 0 { - return [][][]byte{} + return [][][]byte{}, errors.New("values are nil, cannot create merkle tree") } var tree [][][]byte var leaves [][]byte @@ -37,7 +38,7 @@ func (*MerkleTreeStruct) CreateMerkle(values []*big.Int) [][][]byte { tree[i], tree[j] = tree[j], tree[i] } - return tree + return tree, nil } func (*MerkleTreeStruct) GetProofPath(tree [][][]byte, assetId uint16) [][32]byte { @@ -61,8 +62,14 @@ func (*MerkleTreeStruct) GetProofPath(tree [][][]byte, assetId uint16) [][32]byt return compactProofPath } -func (*MerkleTreeStruct) GetMerkleRoot(tree [][][]byte) [32]byte { +func (*MerkleTreeStruct) GetMerkleRoot(tree [][][]byte) ([32]byte, error) { var root [32]byte + if tree == nil { + return root, errors.New("tree is nil") + } copy(root[:], tree[0][0]) - return root + if root == [32]byte{} { + return root, errors.New("root is nil") + } + return root, nil } diff --git a/utils/merkle_test.go b/utils/merkle_test.go index d2dc2e48..3811e721 100644 --- a/utils/merkle_test.go +++ b/utils/merkle_test.go @@ -11,66 +11,78 @@ func TestMerkleTreeStructCreateMerkle(t *testing.T) { values []*big.Int } tests := []struct { - name string - args args - want [][][]byte + name string + args args + want [][][]byte + wantErr bool }{ { name: "Test 1: When CreateMerkle() executes successfully", args: args{ values: []*big.Int{big.NewInt(1)}, }, - want: [][][]byte{{{177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}}}, + want: [][][]byte{{{177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}}}, + wantErr: false, }, { name: "Test 2: When it contains multiple values", args: args{ values: []*big.Int{big.NewInt(1), big.NewInt(1), big.NewInt(1)}, }, - want: [][][]byte{{{52, 34, 71, 138, 66, 123, 171, 13, 20, 101, 234, 111, 34, 80, 119, 150, 191, 7, 189, 164, 50, 31, 68, 19, 51, 45, 101, 139, 128, 81, 172, 181}}, {{182, 253, 152, 238, 183, 224, 143, 197, 33, 241, 21, 17, 40, 154, 254, 77, 142, 135, 63, 215, 163, 251, 118, 171, 117, 127, 164, 124, 35, 245, 150, 233}, {177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}}, {{177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}, {177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}, {177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}}}, + want: [][][]byte{{{52, 34, 71, 138, 66, 123, 171, 13, 20, 101, 234, 111, 34, 80, 119, 150, 191, 7, 189, 164, 50, 31, 68, 19, 51, 45, 101, 139, 128, 81, 172, 181}}, {{182, 253, 152, 238, 183, 224, 143, 197, 33, 241, 21, 17, 40, 154, 254, 77, 142, 135, 63, 215, 163, 251, 118, 171, 117, 127, 164, 124, 35, 245, 150, 233}, {177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}}, {{177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}, {177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}, {177, 14, 45, 82, 118, 18, 7, 59, 38, 238, 205, 253, 113, 126, 106, 50, 12, 244, 75, 74, 250, 194, 176, 115, 45, 159, 203, 226, 183, 250, 12, 246}}}, + wantErr: false, }, { name: "Test 3: When CreateMerkle() executes successfully and it contain even value", args: args{ values: []*big.Int{big.NewInt(2)}, }, - want: [][][]byte{{{64, 87, 135, 250, 18, 168, 35, 224, 242, 183, 99, 28, 196, 27, 59, 168, 130, 139, 51, 33, 202, 129, 17, 17, 250, 117, 205, 58, 163, 187, 90, 206}}}, + want: [][][]byte{{{64, 87, 135, 250, 18, 168, 35, 224, 242, 183, 99, 28, 196, 27, 59, 168, 130, 139, 51, 33, 202, 129, 17, 17, 250, 117, 205, 58, 163, 187, 90, 206}}}, + wantErr: false, }, { name: "Test 4: When CreateMerkle() executes successfully and it contain odd value", args: args{ values: []*big.Int{big.NewInt(3)}, }, - want: [][][]byte{{{194, 87, 90, 14, 158, 89, 60, 0, 249, 89, 248, 201, 47, 18, 219, 40, 105, 195, 57, 90, 59, 5, 2, 208, 94, 37, 22, 68, 111, 113, 248, 91}}}, + want: [][][]byte{{{194, 87, 90, 14, 158, 89, 60, 0, 249, 89, 248, 201, 47, 18, 219, 40, 105, 195, 57, 90, 59, 5, 2, 208, 94, 37, 22, 68, 111, 113, 248, 91}}}, + wantErr: false, }, { name: "Test 5: When CreateMerkle() executes successfully and if the value is zero", args: args{ values: []*big.Int{big.NewInt(0)}, }, - want: [][][]byte{{{41, 13, 236, 217, 84, 139, 98, 168, 214, 3, 69, 169, 136, 56, 111, 200, 75, 166, 188, 149, 72, 64, 8, 246, 54, 47, 147, 22, 14, 243, 229, 99}}}, + want: [][][]byte{{{41, 13, 236, 217, 84, 139, 98, 168, 214, 3, 69, 169, 136, 56, 111, 200, 75, 166, 188, 149, 72, 64, 8, 246, 54, 47, 147, 22, 14, 243, 229, 99}}}, + wantErr: false, }, { name: "Test 6: When CreateMerkle() contains no values", args: args{ values: []*big.Int{}, }, - want: [][][]byte{}, + want: [][][]byte{}, + wantErr: true, }, { name: "Test 7: When CreateMerkle() contains nil values", args: args{ values: nil, }, - want: [][][]byte{}, + want: [][][]byte{}, + wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { me := &MerkleTreeStruct{} - if got := me.CreateMerkle(tt.args.values); !reflect.DeepEqual(got, tt.want) { + got, gotErr := me.CreateMerkle(tt.args.values) + if !reflect.DeepEqual(got, tt.want) { t.Errorf("CreateMerkle() = %v, want %v", got, tt.want) } + if (gotErr != nil) != tt.wantErr { + t.Errorf("CreateMerkle() error = %v, wantErr %v", gotErr, tt.wantErr) + } }) } } @@ -80,31 +92,46 @@ func TestMerkleTreeStructGetMerkleRoot(t *testing.T) { tree [][][]byte } tests := []struct { - name string - args args - want [32]byte + name string + args args + want [32]byte + wantErr bool }{ { name: "When GetMerkleRoot() executes successfully", args: args{ tree: [][][]byte{{{2}, {1}, {3}}}, }, - want: [32]byte{2}, + want: [32]byte{2}, + wantErr: false, }, { - name: "When tree is nil or it does not contain any element", + name: "When tree does not contain any element", args: args{ tree: [][][]byte{{{}, {}, {}}}, }, - want: [32]byte{}, + want: [32]byte{}, + wantErr: true, + }, + { + name: "When tree is nil", + args: args{ + tree: nil, + }, + want: [32]byte{}, + wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { me := &MerkleTreeStruct{} - if got := me.GetMerkleRoot(tt.args.tree); !reflect.DeepEqual(got, tt.want) { + got, gotErr := me.GetMerkleRoot(tt.args.tree) + if !reflect.DeepEqual(got, tt.want) { t.Errorf("GetMerkleRoot() = %v, want %v", got, tt.want) } + if (gotErr != nil) != tt.wantErr { + t.Errorf("GetMerkleRoot() error = %v, wantErr %v", gotErr, tt.wantErr) + } }) } } diff --git a/utils/mocks/bufio_utils.go b/utils/mocks/bufio_utils.go deleted file mode 100644 index d1c4dd0a..00000000 --- a/utils/mocks/bufio_utils.go +++ /dev/null @@ -1,46 +0,0 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. - -package mocks - -import ( - bufio "bufio" - io "io" - - mock "github.com/stretchr/testify/mock" -) - -// BufioUtils is an autogenerated mock type for the BufioUtils type -type BufioUtils struct { - mock.Mock -} - -// NewScanner provides a mock function with given fields: r -func (_m *BufioUtils) NewScanner(r io.Reader) *bufio.Scanner { - ret := _m.Called(r) - - var r0 *bufio.Scanner - if rf, ok := ret.Get(0).(func(io.Reader) *bufio.Scanner); ok { - r0 = rf(r) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*bufio.Scanner) - } - } - - return r0 -} - -type mockConstructorTestingTNewBufioUtils interface { - mock.TestingT - Cleanup(func()) -} - -// NewBufioUtils creates a new instance of BufioUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewBufioUtils(t mockConstructorTestingTNewBufioUtils) *BufioUtils { - mock := &BufioUtils{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/utils/mocks/client_utils.go b/utils/mocks/client_utils.go index 8c8eda1d..703c4b5e 100644 --- a/utils/mocks/client_utils.go +++ b/utils/mocks/client_utils.go @@ -45,6 +45,29 @@ func (_m *ClientUtils) BalanceAt(client *ethclient.Client, ctx context.Context, return r0, r1 } +// BalanceAtWithRetry provides a mock function with given fields: client, account +func (_m *ClientUtils) BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) { + ret := _m.Called(client, account) + + var r0 *big.Int + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) *big.Int); ok { + r0 = rf(client, account) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address) error); ok { + r1 = rf(client, account) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // EstimateGas provides a mock function with given fields: client, ctx, msg func (_m *ClientUtils) EstimateGas(client *ethclient.Client, ctx context.Context, msg ethereum.CallMsg) (uint64, error) { ret := _m.Called(client, ctx, msg) @@ -66,6 +89,27 @@ func (_m *ClientUtils) EstimateGas(client *ethclient.Client, ctx context.Context return r0, r1 } +// EstimateGasWithRetry provides a mock function with given fields: client, message +func (_m *ClientUtils) EstimateGasWithRetry(client *ethclient.Client, message ethereum.CallMsg) (uint64, error) { + ret := _m.Called(client, message) + + var r0 uint64 + if rf, ok := ret.Get(0).(func(*ethclient.Client, ethereum.CallMsg) uint64); ok { + r0 = rf(client, message) + } else { + r0 = ret.Get(0).(uint64) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*ethclient.Client, ethereum.CallMsg) error); ok { + r1 = rf(client, message) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // FilterLogs provides a mock function with given fields: client, ctx, q func (_m *ClientUtils) FilterLogs(client *ethclient.Client, ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) { ret := _m.Called(client, ctx, q) @@ -89,6 +133,73 @@ func (_m *ClientUtils) FilterLogs(client *ethclient.Client, ctx context.Context, return r0, r1 } +// FilterLogsWithRetry provides a mock function with given fields: client, query +func (_m *ClientUtils) FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]types.Log, error) { + ret := _m.Called(client, query) + + var r0 []types.Log + if rf, ok := ret.Get(0).(func(*ethclient.Client, ethereum.FilterQuery) []types.Log); ok { + r0 = rf(client, query) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]types.Log) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(*ethclient.Client, ethereum.FilterQuery) error); ok { + r1 = rf(client, query) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetLatestBlockWithRetry provides a mock function with given fields: client +func (_m *ClientUtils) GetLatestBlockWithRetry(client *ethclient.Client) (*types.Header, error) { + ret := _m.Called(client) + + var r0 *types.Header + if rf, ok := ret.Get(0).(func(*ethclient.Client) *types.Header); ok { + r0 = rf(client) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Header) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { + r1 = rf(client) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetNonceAtWithRetry provides a mock function with given fields: client, accountAddress +func (_m *ClientUtils) GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (uint64, error) { + ret := _m.Called(client, accountAddress) + + var r0 uint64 + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) uint64); ok { + r0 = rf(client, accountAddress) + } else { + r0 = ret.Get(0).(uint64) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address) error); ok { + r1 = rf(client, accountAddress) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // HeaderByNumber provides a mock function with given fields: client, ctx, number func (_m *ClientUtils) HeaderByNumber(client *ethclient.Client, ctx context.Context, number *big.Int) (*types.Header, error) { ret := _m.Called(client, ctx, number) @@ -156,6 +267,29 @@ func (_m *ClientUtils) SuggestGasPrice(client *ethclient.Client, ctx context.Con return r0, r1 } +// SuggestGasPriceWithRetry provides a mock function with given fields: client +func (_m *ClientUtils) SuggestGasPriceWithRetry(client *ethclient.Client) (*big.Int, error) { + ret := _m.Called(client) + + var r0 *big.Int + if rf, ok := ret.Get(0).(func(*ethclient.Client) *big.Int); ok { + r0 = rf(client) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { + r1 = rf(client) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // TransactionReceipt provides a mock function with given fields: client, ctx, txHash func (_m *ClientUtils) TransactionReceipt(client *ethclient.Client, ctx context.Context, txHash common.Hash) (*types.Receipt, error) { ret := _m.Called(client, ctx, txHash) diff --git a/utils/mocks/coin_utils.go b/utils/mocks/coin_utils.go index 44954ea8..b885937b 100644 --- a/utils/mocks/coin_utils.go +++ b/utils/mocks/coin_utils.go @@ -18,13 +18,13 @@ type CoinUtils struct { mock.Mock } -// BalanceOf provides a mock function with given fields: coinContract, opts, account -func (_m *CoinUtils) BalanceOf(coinContract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) { - ret := _m.Called(coinContract, opts, account) +// BalanceOf provides a mock function with given fields: erc20Contract, opts, account +func (_m *CoinUtils) BalanceOf(erc20Contract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) { + ret := _m.Called(erc20Contract, opts, account) var r0 *big.Int if rf, ok := ret.Get(0).(func(*bindings.RAZOR, *bind.CallOpts, common.Address) *big.Int); ok { - r0 = rf(coinContract, opts, account) + r0 = rf(erc20Contract, opts, account) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) @@ -33,7 +33,7 @@ func (_m *CoinUtils) BalanceOf(coinContract *bindings.RAZOR, opts *bind.CallOpts var r1 error if rf, ok := ret.Get(1).(func(*bindings.RAZOR, *bind.CallOpts, common.Address) error); ok { - r1 = rf(coinContract, opts, account) + r1 = rf(erc20Contract, opts, account) } else { r1 = ret.Error(1) } diff --git a/utils/mocks/file_utils.go b/utils/mocks/file_utils.go new file mode 100644 index 00000000..d107eada --- /dev/null +++ b/utils/mocks/file_utils.go @@ -0,0 +1,140 @@ +// Code generated by mockery v2.14.0. DO NOT EDIT. + +package mocks + +import ( + pflag "github.com/spf13/pflag" + mock "github.com/stretchr/testify/mock" + + types "razor/core/types" +) + +// FileUtils is an autogenerated mock type for the FileUtils type +type FileUtils struct { + mock.Mock +} + +// AssignLogFile provides a mock function with given fields: flagSet, configurations +func (_m *FileUtils) AssignLogFile(flagSet *pflag.FlagSet, configurations types.Configurations) { + _m.Called(flagSet, configurations) +} + +// ReadFromCommitJsonFile provides a mock function with given fields: filePath +func (_m *FileUtils) ReadFromCommitJsonFile(filePath string) (types.CommitFileData, error) { + ret := _m.Called(filePath) + + var r0 types.CommitFileData + if rf, ok := ret.Get(0).(func(string) types.CommitFileData); ok { + r0 = rf(filePath) + } else { + r0 = ret.Get(0).(types.CommitFileData) + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(filePath) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ReadFromDisputeJsonFile provides a mock function with given fields: filePath +func (_m *FileUtils) ReadFromDisputeJsonFile(filePath string) (types.DisputeFileData, error) { + ret := _m.Called(filePath) + + var r0 types.DisputeFileData + if rf, ok := ret.Get(0).(func(string) types.DisputeFileData); ok { + r0 = rf(filePath) + } else { + r0 = ret.Get(0).(types.DisputeFileData) + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(filePath) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ReadFromProposeJsonFile provides a mock function with given fields: filePath +func (_m *FileUtils) ReadFromProposeJsonFile(filePath string) (types.ProposeFileData, error) { + ret := _m.Called(filePath) + + var r0 types.ProposeFileData + if rf, ok := ret.Get(0).(func(string) types.ProposeFileData); ok { + r0 = rf(filePath) + } else { + r0 = ret.Get(0).(types.ProposeFileData) + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(filePath) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SaveDataToCommitJsonFile provides a mock function with given fields: filePath, epoch, commitData +func (_m *FileUtils) SaveDataToCommitJsonFile(filePath string, epoch uint32, commitData types.CommitData) error { + ret := _m.Called(filePath, epoch, commitData) + + var r0 error + if rf, ok := ret.Get(0).(func(string, uint32, types.CommitData) error); ok { + r0 = rf(filePath, epoch, commitData) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SaveDataToDisputeJsonFile provides a mock function with given fields: filePath, bountyIdQueue +func (_m *FileUtils) SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []uint32) error { + ret := _m.Called(filePath, bountyIdQueue) + + var r0 error + if rf, ok := ret.Get(0).(func(string, []uint32) error); ok { + r0 = rf(filePath, bountyIdQueue) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SaveDataToProposeJsonFile provides a mock function with given fields: filePath, proposeData +func (_m *FileUtils) SaveDataToProposeJsonFile(filePath string, proposeData types.ProposeFileData) error { + ret := _m.Called(filePath, proposeData) + + var r0 error + if rf, ok := ret.Get(0).(func(string, types.ProposeFileData) error); ok { + r0 = rf(filePath, proposeData) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewFileUtils interface { + mock.TestingT + Cleanup(func()) +} + +// NewFileUtils creates a new instance of FileUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewFileUtils(t mockConstructorTestingTNewFileUtils) *FileUtils { + mock := &FileUtils{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/utils/mocks/gas_utils.go b/utils/mocks/gas_utils.go new file mode 100644 index 00000000..59351797 --- /dev/null +++ b/utils/mocks/gas_utils.go @@ -0,0 +1,92 @@ +// Code generated by mockery v2.14.0. DO NOT EDIT. + +package mocks + +import ( + big "math/big" + + bind "github.com/ethereum/go-ethereum/accounts/abi/bind" + ethclient "github.com/ethereum/go-ethereum/ethclient" + + mock "github.com/stretchr/testify/mock" + + types "razor/core/types" +) + +// GasUtils is an autogenerated mock type for the GasUtils type +type GasUtils struct { + mock.Mock +} + +// GetGasLimit provides a mock function with given fields: transactionData, txnOpts +func (_m *GasUtils) GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { + ret := _m.Called(transactionData, txnOpts) + + var r0 uint64 + if rf, ok := ret.Get(0).(func(types.TransactionOptions, *bind.TransactOpts) uint64); ok { + r0 = rf(transactionData, txnOpts) + } else { + r0 = ret.Get(0).(uint64) + } + + var r1 error + if rf, ok := ret.Get(1).(func(types.TransactionOptions, *bind.TransactOpts) error); ok { + r1 = rf(transactionData, txnOpts) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetGasPrice provides a mock function with given fields: client, config +func (_m *GasUtils) GetGasPrice(client *ethclient.Client, config types.Configurations) *big.Int { + ret := _m.Called(client, config) + + var r0 *big.Int + if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations) *big.Int); ok { + r0 = rf(client, config) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + return r0 +} + +// IncreaseGasLimitValue provides a mock function with given fields: client, gasLimit, gasLimitMultiplier +func (_m *GasUtils) IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { + ret := _m.Called(client, gasLimit, gasLimitMultiplier) + + var r0 uint64 + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint64, float32) uint64); ok { + r0 = rf(client, gasLimit, gasLimitMultiplier) + } else { + r0 = ret.Get(0).(uint64) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*ethclient.Client, uint64, float32) error); ok { + r1 = rf(client, gasLimit, gasLimitMultiplier) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewGasUtils interface { + mock.TestingT + Cleanup(func()) +} + +// NewGasUtils creates a new instance of GasUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewGasUtils(t mockConstructorTestingTNewGasUtils) *GasUtils { + mock := &GasUtils{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/utils/mocks/merkle_tree_interface.go b/utils/mocks/merkle_tree_interface.go index 26ea7f41..60b8654f 100644 --- a/utils/mocks/merkle_tree_interface.go +++ b/utils/mocks/merkle_tree_interface.go @@ -14,7 +14,7 @@ type MerkleTreeInterface struct { } // CreateMerkle provides a mock function with given fields: values -func (_m *MerkleTreeInterface) CreateMerkle(values []*big.Int) [][][]byte { +func (_m *MerkleTreeInterface) CreateMerkle(values []*big.Int) ([][][]byte, error) { ret := _m.Called(values) var r0 [][][]byte @@ -26,11 +26,18 @@ func (_m *MerkleTreeInterface) CreateMerkle(values []*big.Int) [][][]byte { } } - return r0 + var r1 error + if rf, ok := ret.Get(1).(func([]*big.Int) error); ok { + r1 = rf(values) + } else { + r1 = ret.Error(1) + } + + return r0, r1 } // GetMerkleRoot provides a mock function with given fields: tree -func (_m *MerkleTreeInterface) GetMerkleRoot(tree [][][]byte) [32]byte { +func (_m *MerkleTreeInterface) GetMerkleRoot(tree [][][]byte) ([32]byte, error) { ret := _m.Called(tree) var r0 [32]byte @@ -42,7 +49,14 @@ func (_m *MerkleTreeInterface) GetMerkleRoot(tree [][][]byte) [32]byte { } } - return r0 + var r1 error + if rf, ok := ret.Get(1).(func([][][]byte) error); ok { + r1 = rf(tree) + } else { + r1 = ret.Error(1) + } + + return r0, r1 } // GetProofPath provides a mock function with given fields: tree, assetId diff --git a/utils/mocks/staked_token_utils.go b/utils/mocks/staked_token_utils.go index dac0c594..a502ee96 100644 --- a/utils/mocks/staked_token_utils.go +++ b/utils/mocks/staked_token_utils.go @@ -4,11 +4,9 @@ package mocks import ( big "math/big" - bindings "razor/pkg/bindings" - - bind "github.com/ethereum/go-ethereum/accounts/abi/bind" common "github.com/ethereum/go-ethereum/common" + ethclient "github.com/ethereum/go-ethereum/ethclient" mock "github.com/stretchr/testify/mock" ) @@ -18,13 +16,13 @@ type StakedTokenUtils struct { mock.Mock } -// BalanceOf provides a mock function with given fields: stakedToken, callOpts, address -func (_m *StakedTokenUtils) BalanceOf(stakedToken *bindings.StakedToken, callOpts *bind.CallOpts, address common.Address) (*big.Int, error) { - ret := _m.Called(stakedToken, callOpts, address) +// BalanceOf provides a mock function with given fields: client, tokenAddress, address +func (_m *StakedTokenUtils) BalanceOf(client *ethclient.Client, tokenAddress common.Address, address common.Address) (*big.Int, error) { + ret := _m.Called(client, tokenAddress, address) var r0 *big.Int - if rf, ok := ret.Get(0).(func(*bindings.StakedToken, *bind.CallOpts, common.Address) *big.Int); ok { - r0 = rf(stakedToken, callOpts, address) + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, common.Address) *big.Int); ok { + r0 = rf(client, tokenAddress, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) @@ -32,8 +30,8 @@ func (_m *StakedTokenUtils) BalanceOf(stakedToken *bindings.StakedToken, callOpt } var r1 error - if rf, ok := ret.Get(1).(func(*bindings.StakedToken, *bind.CallOpts, common.Address) error); ok { - r1 = rf(stakedToken, callOpts, address) + if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address, common.Address) error); ok { + r1 = rf(client, tokenAddress, address) } else { r1 = ret.Error(1) } diff --git a/utils/mocks/utils.go b/utils/mocks/utils.go index cf68ec9f..3f4032dd 100644 --- a/utils/mocks/utils.go +++ b/utils/mocks/utils.go @@ -8,14 +8,12 @@ import ( bind "github.com/ethereum/go-ethereum/accounts/abi/bind" - common "github.com/ethereum/go-ethereum/common" + cache "razor/cache" - coretypes "github.com/ethereum/go-ethereum/core/types" + common "github.com/ethereum/go-ethereum/common" ethclient "github.com/ethereum/go-ethereum/ethclient" - ethereum "github.com/ethereum/go-ethereum" - mock "github.com/stretchr/testify/mock" pflag "github.com/spf13/pflag" @@ -42,13 +40,13 @@ func (_m *Utils) AddJobToJSON(fileName string, job *types.StructsJob) error { return r0 } -// Aggregate provides a mock function with given fields: client, previousEpoch, collection -func (_m *Utils) Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection) (*big.Int, error) { - ret := _m.Called(client, previousEpoch, collection) +// Aggregate provides a mock function with given fields: client, previousEpoch, collection, localCache +func (_m *Utils) Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, localCache *cache.LocalCache) (*big.Int, error) { + ret := _m.Called(client, previousEpoch, collection, localCache) var r0 *big.Int - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, bindings.StructsCollection) *big.Int); ok { - r0 = rf(client, previousEpoch, collection) + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, bindings.StructsCollection, *cache.LocalCache) *big.Int); ok { + r0 = rf(client, previousEpoch, collection, localCache) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) @@ -56,8 +54,8 @@ func (_m *Utils) Aggregate(client *ethclient.Client, previousEpoch uint32, colle } var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, bindings.StructsCollection) error); ok { - r1 = rf(client, previousEpoch, collection) + if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, bindings.StructsCollection, *cache.LocalCache) error); ok { + r1 = rf(client, previousEpoch, collection, localCache) } else { r1 = ret.Error(1) } @@ -65,9 +63,18 @@ func (_m *Utils) Aggregate(client *ethclient.Client, previousEpoch uint32, colle return r0, r1 } -// AssignLogFile provides a mock function with given fields: flagSet -func (_m *Utils) AssignLogFile(flagSet *pflag.FlagSet) { - _m.Called(flagSet) +// AssignPassword provides a mock function with given fields: flagSet +func (_m *Utils) AssignPassword(flagSet *pflag.FlagSet) string { + ret := _m.Called(flagSet) + + var r0 string + if rf, ok := ret.Get(0).(func(*pflag.FlagSet) string); ok { + r0 = rf(flagSet) + } else { + r0 = ret.Get(0).(string) + } + + return r0 } // AssignStakerId provides a mock function with given fields: flagSet, client, address @@ -91,52 +98,6 @@ func (_m *Utils) AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Client return r0, r1 } -// BalanceAtWithRetry provides a mock function with given fields: client, account -func (_m *Utils) BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) { - ret := _m.Called(client, account) - - var r0 *big.Int - if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) *big.Int); ok { - r0 = rf(client, account) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address) error); ok { - r1 = rf(client, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// CalculateBlockNumberAtEpochBeginning provides a mock function with given fields: client, epochLength, currentBlockNumber -func (_m *Utils) CalculateBlockNumberAtEpochBeginning(client *ethclient.Client, epochLength int64, currentBlockNumber *big.Int) (*big.Int, error) { - ret := _m.Called(client, epochLength, currentBlockNumber) - - var r0 *big.Int - if rf, ok := ret.Get(0).(func(*ethclient.Client, int64, *big.Int) *big.Int); ok { - r0 = rf(client, epochLength, currentBlockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, int64, *big.Int) error); ok { - r1 = rf(client, epochLength, currentBlockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // CalculateBlockTime provides a mock function with given fields: client func (_m *Utils) CalculateBlockTime(client *ethclient.Client) int64 { ret := _m.Called(client) @@ -167,11 +128,41 @@ func (_m *Utils) CalculateSalt(epoch uint32, medians []*big.Int) [32]byte { return r0 } +// CheckAmountAndBalance provides a mock function with given fields: amountInWei, balance +func (_m *Utils) CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) *big.Int { + ret := _m.Called(amountInWei, balance) + + var r0 *big.Int + if rf, ok := ret.Get(0).(func(*big.Int, *big.Int) *big.Int); ok { + r0 = rf(amountInWei, balance) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + return r0 +} + // CheckEthBalanceIsZero provides a mock function with given fields: client, address func (_m *Utils) CheckEthBalanceIsZero(client *ethclient.Client, address string) { _m.Called(client, address) } +// CheckPassword provides a mock function with given fields: address, password +func (_m *Utils) CheckPassword(address string, password string) error { + ret := _m.Called(address, password) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string) error); ok { + r0 = rf(address, password) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // CheckTransactionReceipt provides a mock function with given fields: client, _txHash func (_m *Utils) CheckTransactionReceipt(client *ethclient.Client, _txHash string) int { ret := _m.Called(client, _txHash) @@ -239,20 +230,22 @@ func (_m *Utils) DeleteJobFromJSON(fileName string, jobId string) error { return r0 } -// EstimateGasWithRetry provides a mock function with given fields: client, message -func (_m *Utils) EstimateGasWithRetry(client *ethclient.Client, message ethereum.CallMsg) (uint64, error) { - ret := _m.Called(client, message) +// EstimateBlockNumberAtEpochBeginning provides a mock function with given fields: client, currentBlockNumber +func (_m *Utils) EstimateBlockNumberAtEpochBeginning(client *ethclient.Client, currentBlockNumber *big.Int) (*big.Int, error) { + ret := _m.Called(client, currentBlockNumber) - var r0 uint64 - if rf, ok := ret.Get(0).(func(*ethclient.Client, ethereum.CallMsg) uint64); ok { - r0 = rf(client, message) + var r0 *big.Int + if rf, ok := ret.Get(0).(func(*ethclient.Client, *big.Int) *big.Int); ok { + r0 = rf(client, currentBlockNumber) } else { - r0 = ret.Get(0).(uint64) + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } } var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, ethereum.CallMsg) error); ok { - r1 = rf(client, message) + if rf, ok := ret.Get(1).(func(*ethclient.Client, *big.Int) error); ok { + r1 = rf(client, currentBlockNumber) } else { r1 = ret.Error(1) } @@ -306,29 +299,6 @@ func (_m *Utils) FetchPreviousValue(client *ethclient.Client, epoch uint32, asse return r0, r1 } -// FilterLogsWithRetry provides a mock function with given fields: client, query -func (_m *Utils) FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]coretypes.Log, error) { - ret := _m.Called(client, query) - - var r0 []coretypes.Log - if rf, ok := ret.Get(0).(func(*ethclient.Client, ethereum.FilterQuery) []coretypes.Log); ok { - r0 = rf(client, query) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]coretypes.Log) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, ethereum.FilterQuery) error); ok { - r1 = rf(client, query) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // GetActiveCollection provides a mock function with given fields: client, collectionId func (_m *Utils) GetActiveCollection(client *ethclient.Client, collectionId uint16) (bindings.StructsCollection, error) { ret := _m.Called(client, collectionId) @@ -394,13 +364,13 @@ func (_m *Utils) GetActiveJob(client *ethclient.Client, jobId uint16) (bindings. return r0, r1 } -// GetAggregatedDataOfCollection provides a mock function with given fields: client, collectionId, epoch -func (_m *Utils) GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32) (*big.Int, error) { - ret := _m.Called(client, collectionId, epoch) +// GetAggregatedDataOfCollection provides a mock function with given fields: client, collectionId, epoch, localCache +func (_m *Utils) GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32, localCache *cache.LocalCache) (*big.Int, error) { + ret := _m.Called(client, collectionId, epoch, localCache) var r0 *big.Int - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16, uint32) *big.Int); ok { - r0 = rf(client, collectionId, epoch) + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16, uint32, *cache.LocalCache) *big.Int); ok { + r0 = rf(client, collectionId, epoch, localCache) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) @@ -408,8 +378,8 @@ func (_m *Utils) GetAggregatedDataOfCollection(client *ethclient.Client, collect } var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16, uint32) error); ok { - r1 = rf(client, collectionId, epoch) + if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16, uint32, *cache.LocalCache) error); ok { + r1 = rf(client, collectionId, epoch, localCache) } else { r1 = ret.Error(1) } @@ -553,6 +523,27 @@ func (_m *Utils) GetBlockManagerWithOpts(client *ethclient.Client) (*bindings.Bl return r0, r1 } +// GetBufferedState provides a mock function with given fields: client, buffer +func (_m *Utils) GetBufferedState(client *ethclient.Client, buffer int32) (int64, error) { + ret := _m.Called(client, buffer) + + var r0 int64 + if rf, ok := ret.Get(0).(func(*ethclient.Client, int32) int64); ok { + r0 = rf(client, buffer) + } else { + r0 = ret.Get(0).(int64) + } + + var r1 error + if rf, ok := ret.Get(1).(func(*ethclient.Client, int32) error); ok { + r1 = rf(client, buffer) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetCollection provides a mock function with given fields: client, collectionId func (_m *Utils) GetCollection(client *ethclient.Client, collectionId uint16) (bindings.StructsCollection, error) { ret := _m.Called(client, collectionId) @@ -678,13 +669,13 @@ func (_m *Utils) GetCommitments(client *ethclient.Client, address string) ([32]b return r0, r1 } -// GetDataFromAPI provides a mock function with given fields: url -func (_m *Utils) GetDataFromAPI(url string) ([]byte, error) { - ret := _m.Called(url) +// GetDataFromAPI provides a mock function with given fields: url, localCache +func (_m *Utils) GetDataFromAPI(url string, localCache *cache.LocalCache) ([]byte, error) { + ret := _m.Called(url, localCache) var r0 []byte - if rf, ok := ret.Get(0).(func(string) []byte); ok { - r0 = rf(url) + if rf, ok := ret.Get(0).(func(string, *cache.LocalCache) []byte); ok { + r0 = rf(url, localCache) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) @@ -692,8 +683,8 @@ func (_m *Utils) GetDataFromAPI(url string) ([]byte, error) { } var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(url) + if rf, ok := ret.Get(1).(func(string, *cache.LocalCache) error); ok { + r1 = rf(url, localCache) } else { r1 = ret.Error(1) } @@ -745,13 +736,13 @@ func (_m *Utils) GetDataFromXHTML(url string, selector string) (string, error) { return r0, r1 } -// GetDataToCommitFromJob provides a mock function with given fields: job -func (_m *Utils) GetDataToCommitFromJob(job bindings.StructsJob) (*big.Int, error) { - ret := _m.Called(job) +// GetDataToCommitFromJob provides a mock function with given fields: job, localCache +func (_m *Utils) GetDataToCommitFromJob(job bindings.StructsJob, localCache *cache.LocalCache) (*big.Int, error) { + ret := _m.Called(job, localCache) var r0 *big.Int - if rf, ok := ret.Get(0).(func(bindings.StructsJob) *big.Int); ok { - r0 = rf(job) + if rf, ok := ret.Get(0).(func(bindings.StructsJob, *cache.LocalCache) *big.Int); ok { + r0 = rf(job, localCache) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) @@ -759,8 +750,8 @@ func (_m *Utils) GetDataToCommitFromJob(job bindings.StructsJob) (*big.Int, erro } var r1 error - if rf, ok := ret.Get(1).(func(bindings.StructsJob) error); ok { - r1 = rf(job) + if rf, ok := ret.Get(1).(func(bindings.StructsJob, *cache.LocalCache) error); ok { + r1 = rf(job, localCache) } else { r1 = ret.Error(1) } @@ -768,13 +759,13 @@ func (_m *Utils) GetDataToCommitFromJob(job bindings.StructsJob) (*big.Int, erro return r0, r1 } -// GetDataToCommitFromJobs provides a mock function with given fields: jobs -func (_m *Utils) GetDataToCommitFromJobs(jobs []bindings.StructsJob) ([]*big.Int, []uint8, error) { - ret := _m.Called(jobs) +// GetDataToCommitFromJobs provides a mock function with given fields: jobs, localCache +func (_m *Utils) GetDataToCommitFromJobs(jobs []bindings.StructsJob, localCache *cache.LocalCache) ([]*big.Int, []uint8, error) { + ret := _m.Called(jobs, localCache) var r0 []*big.Int - if rf, ok := ret.Get(0).(func([]bindings.StructsJob) []*big.Int); ok { - r0 = rf(jobs) + if rf, ok := ret.Get(0).(func([]bindings.StructsJob, *cache.LocalCache) []*big.Int); ok { + r0 = rf(jobs, localCache) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*big.Int) @@ -782,8 +773,8 @@ func (_m *Utils) GetDataToCommitFromJobs(jobs []bindings.StructsJob) ([]*big.Int } var r1 []uint8 - if rf, ok := ret.Get(1).(func([]bindings.StructsJob) []uint8); ok { - r1 = rf(jobs) + if rf, ok := ret.Get(1).(func([]bindings.StructsJob, *cache.LocalCache) []uint8); ok { + r1 = rf(jobs, localCache) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]uint8) @@ -791,8 +782,8 @@ func (_m *Utils) GetDataToCommitFromJobs(jobs []bindings.StructsJob) ([]*big.Int } var r2 error - if rf, ok := ret.Get(2).(func([]bindings.StructsJob) error); ok { - r2 = rf(jobs) + if rf, ok := ret.Get(2).(func([]bindings.StructsJob, *cache.LocalCache) error); ok { + r2 = rf(jobs, localCache) } else { r2 = ret.Error(2) } @@ -800,27 +791,6 @@ func (_m *Utils) GetDataToCommitFromJobs(jobs []bindings.StructsJob) ([]*big.Int return r0, r1, r2 } -// GetDelayedState provides a mock function with given fields: client, buffer -func (_m *Utils) GetDelayedState(client *ethclient.Client, buffer int32) (int64, error) { - ret := _m.Called(client, buffer) - - var r0 int64 - if rf, ok := ret.Get(0).(func(*ethclient.Client, int32) int64); ok { - r0 = rf(client, buffer) - } else { - r0 = ret.Get(0).(int64) - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, int32) error); ok { - r1 = rf(client, buffer) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // GetEpoch provides a mock function with given fields: client func (_m *Utils) GetEpoch(client *ethclient.Client) (uint32, error) { ret := _m.Called(client) @@ -926,43 +896,6 @@ func (_m *Utils) GetEpochLimitForUpdateCommission(client *ethclient.Client) (uin return r0, r1 } -// GetGasLimit provides a mock function with given fields: transactionData, txnOpts -func (_m *Utils) GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { - ret := _m.Called(transactionData, txnOpts) - - var r0 uint64 - if rf, ok := ret.Get(0).(func(types.TransactionOptions, *bind.TransactOpts) uint64); ok { - r0 = rf(transactionData, txnOpts) - } else { - r0 = ret.Get(0).(uint64) - } - - var r1 error - if rf, ok := ret.Get(1).(func(types.TransactionOptions, *bind.TransactOpts) error); ok { - r1 = rf(transactionData, txnOpts) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetGasPrice provides a mock function with given fields: client, config -func (_m *Utils) GetGasPrice(client *ethclient.Client, config types.Configurations) *big.Int { - ret := _m.Called(client, config) - - var r0 *big.Int - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations) *big.Int); ok { - r0 = rf(client, config) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - return r0 -} - // GetInfluenceSnapshot provides a mock function with given fields: client, stakerId, epoch func (_m *Utils) GetInfluenceSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { ret := _m.Called(client, stakerId, epoch) @@ -1009,29 +942,6 @@ func (_m *Utils) GetJobs(client *ethclient.Client) ([]bindings.StructsJob, error return r0, r1 } -// GetLatestBlockWithRetry provides a mock function with given fields: client -func (_m *Utils) GetLatestBlockWithRetry(client *ethclient.Client) (*coretypes.Header, error) { - ret := _m.Called(client) - - var r0 *coretypes.Header - if rf, ok := ret.Get(0).(func(*ethclient.Client) *coretypes.Header); ok { - r0 = rf(client) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*coretypes.Header) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // GetLeafIdOfACollection provides a mock function with given fields: client, collectionId func (_m *Utils) GetLeafIdOfACollection(client *ethclient.Client, collectionId uint16) (uint16, error) { ret := _m.Called(client, collectionId) @@ -1162,27 +1072,6 @@ func (_m *Utils) GetMinStakeAmount(client *ethclient.Client) (*big.Int, error) { return r0, r1 } -// GetNonceAtWithRetry provides a mock function with given fields: client, accountAddress -func (_m *Utils) GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (uint64, error) { - ret := _m.Called(client, accountAddress) - - var r0 uint64 - if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) uint64); ok { - r0 = rf(client, accountAddress) - } else { - r0 = ret.Get(0).(uint64) - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address) error); ok { - r1 = rf(client, accountAddress) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // GetNumActiveCollections provides a mock function with given fields: client func (_m *Utils) GetNumActiveCollections(client *ethclient.Client) (uint16, error) { ret := _m.Called(client) @@ -1323,27 +1212,20 @@ func (_m *Utils) GetRemainingTimeOfCurrentState(client *ethclient.Client, buffer return r0, r1 } -// GetSaltFromBlockchain provides a mock function with given fields: client -func (_m *Utils) GetSaltFromBlockchain(client *ethclient.Client) ([32]byte, error) { - ret := _m.Called(client) +// GetRogueRandomValue provides a mock function with given fields: value +func (_m *Utils) GetRogueRandomValue(value int) *big.Int { + ret := _m.Called(value) - var r0 [32]byte - if rf, ok := ret.Get(0).(func(*ethclient.Client) [32]byte); ok { - r0 = rf(client) + var r0 *big.Int + if rf, ok := ret.Get(0).(func(int) *big.Int); ok { + r0 = rf(value) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([32]byte) + r0 = ret.Get(0).(*big.Int) } } - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) - } else { - r1 = ret.Error(1) - } - - return r0, r1 + return r0 } // GetSortedProposedBlockId provides a mock function with given fields: client, epoch, index @@ -1491,6 +1373,29 @@ func (_m *Utils) GetStakedToken(client *ethclient.Client, tokenAddress common.Ad return r0 } +// GetStakedTokenManagerWithOpts provides a mock function with given fields: client, tokenAddress +func (_m *Utils) GetStakedTokenManagerWithOpts(client *ethclient.Client, tokenAddress common.Address) (*bindings.StakedToken, bind.CallOpts) { + ret := _m.Called(client, tokenAddress) + + var r0 *bindings.StakedToken + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) *bindings.StakedToken); ok { + r0 = rf(client, tokenAddress) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*bindings.StakedToken) + } + } + + var r1 bind.CallOpts + if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address) bind.CallOpts); ok { + r1 = rf(client, tokenAddress) + } else { + r1 = ret.Get(1).(bind.CallOpts) + } + + return r0, r1 +} + // GetStaker provides a mock function with given fields: client, stakerId func (_m *Utils) GetStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { ret := _m.Called(client, stakerId) @@ -1577,20 +1482,6 @@ func (_m *Utils) GetStateBuffer(client *ethclient.Client) (uint64, error) { return r0, r1 } -// GetStateName provides a mock function with given fields: stateNumber -func (_m *Utils) GetStateName(stateNumber int64) string { - ret := _m.Called(stateNumber) - - var r0 string - if rf, ok := ret.Get(0).(func(int64) string); ok { - r0 = rf(stateNumber) - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - // GetTokenManager provides a mock function with given fields: client func (_m *Utils) GetTokenManager(client *ethclient.Client) *bindings.RAZOR { ret := _m.Called(client) @@ -1775,27 +1666,6 @@ func (_m *Utils) HandleOfficialJobsFromJSONFile(client *ethclient.Client, collec return r0, r1 } -// IncreaseGasLimitValue provides a mock function with given fields: client, gasLimit, gasLimitMultiplier -func (_m *Utils) IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { - ret := _m.Called(client, gasLimit, gasLimitMultiplier) - - var r0 uint64 - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint64, float32) uint64); ok { - r0 = rf(client, gasLimit, gasLimitMultiplier) - } else { - r0 = ret.Get(0).(uint64) - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint64, float32) error); ok { - r1 = rf(client, gasLimit, gasLimitMultiplier) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // IsFlagPassed provides a mock function with given fields: name func (_m *Utils) IsFlagPassed(name string) bool { ret := _m.Called(name) @@ -1826,83 +1696,48 @@ func (_m *Utils) MultiplyFloatAndBigInt(bigIntVal *big.Int, floatingVal float64) return r0 } -// Prng provides a mock function with given fields: max, prngHashes -func (_m *Utils) Prng(max uint32, prngHashes []byte) *big.Int { - ret := _m.Called(max, prngHashes) +// PasswordPrompt provides a mock function with given fields: +func (_m *Utils) PasswordPrompt() string { + ret := _m.Called() - var r0 *big.Int - if rf, ok := ret.Get(0).(func(uint32, []byte) *big.Int); ok { - r0 = rf(max, prngHashes) + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } + r0 = ret.Get(0).(string) } return r0 } -// ReadFromCommitJsonFile provides a mock function with given fields: filePath -func (_m *Utils) ReadFromCommitJsonFile(filePath string) (types.CommitFileData, error) { - ret := _m.Called(filePath) - - var r0 types.CommitFileData - if rf, ok := ret.Get(0).(func(string) types.CommitFileData); ok { - r0 = rf(filePath) - } else { - r0 = ret.Get(0).(types.CommitFileData) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(filePath) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ReadFromDisputeJsonFile provides a mock function with given fields: filePath -func (_m *Utils) ReadFromDisputeJsonFile(filePath string) (types.DisputeFileData, error) { - ret := _m.Called(filePath) - - var r0 types.DisputeFileData - if rf, ok := ret.Get(0).(func(string) types.DisputeFileData); ok { - r0 = rf(filePath) - } else { - r0 = ret.Get(0).(types.DisputeFileData) - } +// PrivateKeyPrompt provides a mock function with given fields: +func (_m *Utils) PrivateKeyPrompt() string { + ret := _m.Called() - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(filePath) + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() } else { - r1 = ret.Error(1) + r0 = ret.Get(0).(string) } - return r0, r1 + return r0 } -// ReadFromProposeJsonFile provides a mock function with given fields: filePath -func (_m *Utils) ReadFromProposeJsonFile(filePath string) (types.ProposeFileData, error) { - ret := _m.Called(filePath) - - var r0 types.ProposeFileData - if rf, ok := ret.Get(0).(func(string) types.ProposeFileData); ok { - r0 = rf(filePath) - } else { - r0 = ret.Get(0).(types.ProposeFileData) - } +// Prng provides a mock function with given fields: max, prngHashes +func (_m *Utils) Prng(max uint32, prngHashes []byte) *big.Int { + ret := _m.Called(max, prngHashes) - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(filePath) + var r0 *big.Int + if rf, ok := ret.Get(0).(func(uint32, []byte) *big.Int); ok { + r0 = rf(max, prngHashes) } else { - r1 = ret.Error(1) + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } } - return r0, r1 + return r0 } // ReadJSONData provides a mock function with given fields: fileName @@ -1928,48 +1763,6 @@ func (_m *Utils) ReadJSONData(fileName string) (map[string]*types.StructsJob, er return r0, r1 } -// SaveDataToCommitJsonFile provides a mock function with given fields: filePath, epoch, commitData -func (_m *Utils) SaveDataToCommitJsonFile(filePath string, epoch uint32, commitData types.CommitData) error { - ret := _m.Called(filePath, epoch, commitData) - - var r0 error - if rf, ok := ret.Get(0).(func(string, uint32, types.CommitData) error); ok { - r0 = rf(filePath, epoch, commitData) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// SaveDataToDisputeJsonFile provides a mock function with given fields: filePath, bountyIdQueue -func (_m *Utils) SaveDataToDisputeJsonFile(filePath string, bountyIdQueue []uint32) error { - ret := _m.Called(filePath, bountyIdQueue) - - var r0 error - if rf, ok := ret.Get(0).(func(string, []uint32) error); ok { - r0 = rf(filePath, bountyIdQueue) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// SaveDataToProposeJsonFile provides a mock function with given fields: filePath, proposeData -func (_m *Utils) SaveDataToProposeJsonFile(filePath string, proposeData types.ProposeFileData) error { - ret := _m.Called(filePath, proposeData) - - var r0 error - if rf, ok := ret.Get(0).(func(string, types.ProposeFileData) error); ok { - r0 = rf(filePath, proposeData) - } else { - r0 = ret.Error(0) - } - - return r0 -} - // SecondsToReadableTime provides a mock function with given fields: input func (_m *Utils) SecondsToReadableTime(input int) string { ret := _m.Called(input) @@ -1984,45 +1777,6 @@ func (_m *Utils) SecondsToReadableTime(input int) string { return r0 } -// Shuffle provides a mock function with given fields: slice -func (_m *Utils) Shuffle(slice []uint32) []uint32 { - ret := _m.Called(slice) - - var r0 []uint32 - if rf, ok := ret.Get(0).(func([]uint32) []uint32); ok { - r0 = rf(slice) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]uint32) - } - } - - return r0 -} - -// SuggestGasPriceWithRetry provides a mock function with given fields: client -func (_m *Utils) SuggestGasPriceWithRetry(client *ethclient.Client) (*big.Int, error) { - ret := _m.Called(client) - - var r0 *big.Int - if rf, ok := ret.Get(0).(func(*ethclient.Client) *big.Int); ok { - r0 = rf(client) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // ToAssign provides a mock function with given fields: client func (_m *Utils) ToAssign(client *ethclient.Client) (uint16, error) { ret := _m.Called(client) diff --git a/utils/options.go b/utils/options.go index 4c21ba19..6b7e5be6 100644 --- a/utils/options.go +++ b/utils/options.go @@ -3,7 +3,7 @@ package utils import ( "context" "errors" - "path" + "path/filepath" "razor/core/types" "strings" @@ -30,26 +30,26 @@ func (*UtilsStruct) GetTxnOpts(transactionData types.TransactionOptions) *bind.T log.Debug("Getting transaction options...") defaultPath, err := PathInterface.GetDefaultPath() CheckError("Error in fetching default path: ", err) - keystorePath := path.Join(defaultPath, "keystore_files") + keystorePath := filepath.Join(defaultPath, "keystore_files") privateKey, err := AccountsInterface.GetPrivateKey(transactionData.AccountAddress, transactionData.Password, keystorePath) if privateKey == nil || err != nil { CheckError("Error in fetching private key: ", errors.New(transactionData.AccountAddress+" not present in razor-go")) } - nonce, err := UtilsInterface.GetNonceAtWithRetry(transactionData.Client, common.HexToAddress(transactionData.AccountAddress)) + nonce, err := ClientInterface.GetNonceAtWithRetry(transactionData.Client, common.HexToAddress(transactionData.AccountAddress)) CheckError("Error in fetching nonce: ", err) - gasPrice := UtilsInterface.GetGasPrice(transactionData.Client, transactionData.Config) + gasPrice := GasInterface.GetGasPrice(transactionData.Client, transactionData.Config) txnOpts, err := BindInterface.NewKeyedTransactorWithChainID(privateKey, transactionData.ChainId) CheckError("Error in getting transactor: ", err) txnOpts.Nonce = big.NewInt(int64(nonce)) txnOpts.GasPrice = gasPrice txnOpts.Value = transactionData.EtherValue - gasLimit, err := UtilsInterface.GetGasLimit(transactionData, txnOpts) + gasLimit, err := GasInterface.GetGasLimit(transactionData, txnOpts) if err != nil { errString := err.Error() if ContainsStringFromArray(errString, []string{"500", "501", "502", "503", "504"}) || errString == errors.New("intrinsic gas too low").Error() { - latestBlock, err := UtilsInterface.GetLatestBlockWithRetry(transactionData.Client) + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(transactionData.Client) CheckError("Error in fetching block: ", err) txnOpts.GasLimit = latestBlock.GasLimit @@ -64,7 +64,7 @@ func (*UtilsStruct) GetTxnOpts(transactionData types.TransactionOptions) *bind.T return txnOpts } -func (*UtilsStruct) GetGasPrice(client *ethclient.Client, config types.Configurations) *big.Int { +func (*GasStruct) GetGasPrice(client *ethclient.Client, config types.Configurations) *big.Int { var gas *big.Int if config.GasPrice != 0 { gas = big.NewInt(1).Mul(big.NewInt(int64(config.GasPrice)), big.NewInt(1e9)) @@ -72,7 +72,7 @@ func (*UtilsStruct) GetGasPrice(client *ethclient.Client, config types.Configura gas = big.NewInt(0) } var err error - suggestedGasPrice, err := UtilsInterface.SuggestGasPriceWithRetry(client) + suggestedGasPrice, err := ClientInterface.SuggestGasPriceWithRetry(client) if err != nil { log.Error(err) return UtilsInterface.MultiplyFloatAndBigInt(gas, float64(config.GasMultiplier)) @@ -87,7 +87,7 @@ func (*UtilsStruct) GetGasPrice(client *ethclient.Client, config types.Configura return gasPrice } -func (*UtilsStruct) GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { +func (*GasStruct) GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { if transactionData.Config.GasLimitOverride != 0 { log.Debugf("Taking the gas limit value = %d from config", transactionData.Config.GasLimitOverride) return transactionData.Config.GasLimitOverride, nil @@ -113,22 +113,22 @@ func (*UtilsStruct) GetGasLimit(transactionData types.TransactionOptions, txnOpt Value: txnOpts.Value, Data: inputData, } - gasLimit, err := UtilsInterface.EstimateGasWithRetry(transactionData.Client, msg) + gasLimit, err := ClientInterface.EstimateGasWithRetry(transactionData.Client, msg) if err != nil { return 0, err } log.Debug("Estimated Gas: ", gasLimit) - return UtilsInterface.IncreaseGasLimitValue(transactionData.Client, gasLimit, transactionData.Config.GasLimitMultiplier) + return GasInterface.IncreaseGasLimitValue(transactionData.Client, gasLimit, transactionData.Config.GasLimitMultiplier) } -func (*UtilsStruct) IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { +func (*GasStruct) IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { if gasLimit == 0 || gasLimitMultiplier <= 0 { return gasLimit, nil } gasLimitIncremented := float64(gasLimitMultiplier) * float64(gasLimit) gasLimit = uint64(gasLimitIncremented) - latestBlock, err := UtilsInterface.GetLatestBlockWithRetry(client) + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(client) if err != nil { log.Error("Error in fetching block: ", err) return 0, err diff --git a/utils/options_test.go b/utils/options_test.go index b48bf082..5c23c3d5 100644 --- a/utils/options_test.go +++ b/utils/options_test.go @@ -110,17 +110,20 @@ func Test_getGasPrice(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { UtilsMock := new(mocks.Utils) + clientUtilsMock := new(mocks.ClientUtils) - UtilsMock.On("SuggestGasPriceWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.suggestedGasPrice, tt.args.suggestedGasPriceErr) + clientUtilsMock.On("SuggestGasPriceWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.suggestedGasPrice, tt.args.suggestedGasPriceErr) UtilsMock.On("MultiplyFloatAndBigInt", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("float64")).Return(tt.args.multipliedGasPrice) fatal = false optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: UtilsMock, + UtilsInterface: UtilsMock, + ClientInterface: clientUtilsMock, } - utils := StartRazor(optionsPackageStruct) - got := utils.GetGasPrice(client, tt.args.config) + StartRazor(optionsPackageStruct) + gasUtils := GasStruct{} + got := gasUtils.GetGasPrice(client, tt.args.config) if fatal != tt.expectedFatal { if got.Cmp(tt.want) != 0 { t.Errorf("getGasPrice() = %v, want %v", got, tt.want) @@ -274,25 +277,29 @@ func Test_utils_GetTxnOpts(t *testing.T) { pathMock := new(mocks.PathUtils) bindMock := new(mocks.BindUtils) accountsMock := new(mocks.AccountsUtils) + clientMock := new(mocks.ClientUtils) + gasMock := new(mocks.GasUtils) optionsPackageStruct := OptionsPackageStruct{ UtilsInterface: utilsMock, PathInterface: pathMock, BindInterface: bindMock, AccountsInterface: accountsMock, + ClientInterface: clientMock, + GasInterface: gasMock, } utils := StartRazor(optionsPackageStruct) pathMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) accountsMock.On("GetPrivateKey", mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(tt.args.privateKey, nil) - utilsMock.On("GetNonceAtWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("common.Address")).Return(tt.args.nonce, tt.args.nonceErr) - utilsMock.On("GetGasPrice", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("types.Configurations")).Return(gasPrice) + clientMock.On("GetNonceAtWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("common.Address")).Return(tt.args.nonce, tt.args.nonceErr) + gasMock.On("GetGasPrice", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("types.Configurations")).Return(gasPrice) bindMock.On("NewKeyedTransactorWithChainID", mock.AnythingOfType("*ecdsa.PrivateKey"), mock.AnythingOfType("*big.Int")).Return(tt.args.txnOpts, tt.args.txnOptsErr) - utilsMock.On("GetGasLimit", transactionData, txnOpts).Return(tt.args.gasLimit, tt.args.gasLimitErr) - utilsMock.On("SuggestGasPriceWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(big.NewInt(1), nil) + gasMock.On("GetGasLimit", transactionData, txnOpts).Return(tt.args.gasLimit, tt.args.gasLimitErr) + clientMock.On("SuggestGasPriceWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(big.NewInt(1), nil) utilsMock.On("MultiplyFloatAndBigInt", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("float64")).Return(big.NewInt(1)) - utilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + clientMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) fatal = false got := utils.GetTxnOpts(transactionData) @@ -402,19 +409,25 @@ func TestUtilsStruct_GetGasLimit(t *testing.T) { utilsMock := new(mocks.Utils) abiMock := new(mocks.ABIUtils) + clientUtilsMock := new(mocks.ClientUtils) + gasUtilsMock := new(mocks.GasUtils) optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, - ABIInterface: abiMock, + UtilsInterface: utilsMock, + ABIInterface: abiMock, + ClientInterface: clientUtilsMock, + GasInterface: gasUtilsMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) abiMock.On("Parse", reader).Return(tt.args.parsedData, tt.args.parseErr) abiMock.On("Pack", parsedData, mock.AnythingOfType("string"), mock.Anything).Return(tt.args.inputData, tt.args.packErr) - utilsMock.On("EstimateGasWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.CallMsg")).Return(tt.args.gasLimit, tt.args.gasLimitErr) - utilsMock.On("IncreaseGasLimitValue", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint64"), mock.AnythingOfType("float32")).Return(tt.args.increaseGasLimit, tt.args.increaseGasLimitErr) - got, err := utils.GetGasLimit(tt.args.transactionData, txnOpts) + clientUtilsMock.On("EstimateGasWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.CallMsg")).Return(tt.args.gasLimit, tt.args.gasLimitErr) + gasUtilsMock.On("IncreaseGasLimitValue", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint64"), mock.AnythingOfType("float32")).Return(tt.args.increaseGasLimit, tt.args.increaseGasLimitErr) + + gasUtils := GasStruct{} + got, err := gasUtils.GetGasLimit(tt.args.transactionData, txnOpts) if got != tt.want { t.Errorf("getGasLimit() got = %v, want %v", got, tt.want) } @@ -501,17 +514,18 @@ func TestUtilsStruct_IncreaseGasLimitValue(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.Utils) + clientUtilsMock := new(mocks.ClientUtils) optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, + ClientInterface: clientUtilsMock, } - utils := StartRazor(optionsPackageStruct) + StartRazor(optionsPackageStruct) - utilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestBlock, tt.args.blockErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestBlock, tt.args.blockErr) - got, err := utils.IncreaseGasLimitValue(client, tt.args.gasLimit, tt.args.gasLimitMultiplier) + gasUtils := GasStruct{} + got, err := gasUtils.IncreaseGasLimitValue(client, tt.args.gasLimit, tt.args.gasLimitMultiplier) if got != tt.want { t.Errorf("increaseGasLimitValue() got = %v, want %v", got, tt.want) } diff --git a/utils/password.go b/utils/password.go index cade81b7..62486ea2 100644 --- a/utils/password.go +++ b/utils/password.go @@ -3,13 +3,14 @@ package utils import ( "bufio" "errors" - "github.com/manifoldco/promptui" - "github.com/spf13/pflag" "os" "unicode" + + "github.com/manifoldco/promptui" + "github.com/spf13/pflag" ) -func PasswordPrompt() string { +func (*UtilsStruct) PasswordPrompt() string { prompt := promptui.Prompt{ Label: "Password", Validate: validate, @@ -22,7 +23,7 @@ func PasswordPrompt() string { return password } -func PrivateKeyPrompt() string { +func (*UtilsStruct) PrivateKeyPrompt() string { prompt := promptui.Prompt{ Label: "🔑 Private Key", Validate: validatePrivateKey, @@ -67,14 +68,14 @@ func GetPasswordFromFile(path string) string { return "" } -func AssignPassword(flagSet *pflag.FlagSet) string { +func (*UtilsStruct) AssignPassword(flagSet *pflag.FlagSet) string { if UtilsInterface.IsFlagPassed("password") { log.Warn("Password flag is passed") log.Warn("This is a unsecure way to use razor-go") passwordPath, _ := flagSet.GetString("password") return GetPasswordFromFile(passwordPath) } - return PasswordPrompt() + return UtilsInterface.PasswordPrompt() } //This function checks if the password is strong enough or not diff --git a/utils/stake.go b/utils/stake.go index 2b318374..2e31ded3 100644 --- a/utils/stake.go +++ b/utils/stake.go @@ -2,12 +2,9 @@ package utils import ( "math/big" - "razor/core" "razor/core/types" "razor/pkg/bindings" - "github.com/avast/retry-go" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" @@ -18,83 +15,36 @@ func (*UtilsStruct) GetStakeManagerWithOpts(client *ethclient.Client) (*bindings } func (*UtilsStruct) GetStakerId(client *ethclient.Client, address string) (uint32, error) { - var ( - stakerId uint32 - stakerErr error - ) - stakerErr = retry.Do( - func() error { - stakerId, stakerErr = StakeManagerInterface.GetStakerId(client, common.HexToAddress(address)) - if stakerErr != nil { - log.Error("Error in fetching staker id.... Retrying") - return stakerErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if stakerErr != nil { - return 0, stakerErr + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "GetStakerId", client, common.HexToAddress(address)) + if err != nil { + return 0, err } - return stakerId, nil + return returnedValues[0].Interface().(uint32), nil } func (*UtilsStruct) GetStake(client *ethclient.Client, stakerId uint32) (*big.Int, error) { - var ( - staker bindings.StructsStaker - stakerErr error - ) - stakerErr = retry.Do( - func() error { - staker, stakerErr = UtilsInterface.GetStaker(client, stakerId) - if stakerErr != nil { - log.Error("Error in fetching staker ... Retrying") - return stakerErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if stakerErr != nil { - return nil, stakerErr + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "GetStaker", client, stakerId) + if err != nil { + return nil, err } + staker := returnedValues[0].Interface().(bindings.StructsStaker) return staker.Stake, nil } func (*UtilsStruct) GetStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { - var ( - staker bindings.StructsStaker - stakerErr error - ) - stakerErr = retry.Do( - func() error { - staker, stakerErr = StakeManagerInterface.GetStaker(client, stakerId) - if stakerErr != nil { - log.Error("Error in fetching staker id.... Retrying") - return stakerErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if stakerErr != nil { - return bindings.StructsStaker{}, stakerErr + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "GetStaker", client, stakerId) + if err != nil { + return bindings.StructsStaker{}, err } - return staker, nil + return returnedValues[0].Interface().(bindings.StructsStaker), nil } func (*UtilsStruct) GetNumberOfStakers(client *ethclient.Client) (uint32, error) { - var ( - numStakers uint32 - stakerErr error - ) - stakerErr = retry.Do( - func() error { - numStakers, stakerErr = StakeManagerInterface.GetNumStakers(client) - if stakerErr != nil { - log.Error("Error in fetching number of stakers.... Retrying") - return stakerErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if stakerErr != nil { - return 0, stakerErr + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "GetNumStakers", client) + if err != nil { + return 0, err } - return numStakers, nil + return returnedValues[0].Interface().(uint32), nil } func (*UtilsStruct) GetLock(client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) { @@ -102,111 +52,41 @@ func (*UtilsStruct) GetLock(client *ethclient.Client, address string, stakerId u if err != nil { return types.Locks{}, err } - var ( - locks types.Locks - lockErr error - ) - lockErr = retry.Do( - func() error { - locks, lockErr = StakeManagerInterface.Locks(client, common.HexToAddress(address), staker.TokenAddress, lockType) - if lockErr != nil { - log.Error("Error in fetching locks.... Retrying") - return lockErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if lockErr != nil { - return types.Locks{}, lockErr + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "Locks", client, common.HexToAddress(address), staker.TokenAddress, lockType) + if err != nil { + return types.Locks{}, err } - return locks, nil + return returnedValues[0].Interface().(types.Locks), nil } func (*UtilsStruct) GetWithdrawInitiationPeriod(client *ethclient.Client) (uint16, error) { - var ( - withdrawReleasePeriod uint16 - err error - ) - err = retry.Do( - func() error { - withdrawReleasePeriod, err = StakeManagerInterface.WithdrawInitiationPeriod(client) - if err != nil { - log.Error("Error in fetching withdraw release period.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "WithdrawInitiationPeriod", client) if err != nil { return 0, err } - return withdrawReleasePeriod, nil + return returnedValues[0].Interface().(uint16), nil } func (*UtilsStruct) GetMaxCommission(client *ethclient.Client) (uint8, error) { - var ( - maxCommission uint8 - err error - ) - err = retry.Do(func() error { - maxCommission, err = StakeManagerInterface.MaxCommission(client) - if err != nil { - log.Error("Error in fetching max commission.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "MaxCommission", client) if err != nil { return 0, err } - return maxCommission, nil + return returnedValues[0].Interface().(uint8), nil } func (*UtilsStruct) GetEpochLimitForUpdateCommission(client *ethclient.Client) (uint16, error) { - var ( - epochLimitForUpdateCommission uint16 - err error - ) - err = retry.Do(func() error { - epochLimitForUpdateCommission, err = StakeManagerInterface.EpochLimitForUpdateCommission(client) - if err != nil { - log.Error("Error in fetching epoch limit for update commission") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "EpochLimitForUpdateCommission", client) if err != nil { return 0, err } - return epochLimitForUpdateCommission, nil -} - -func (*UtilsStruct) GetStakerSRZRBalance(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) { - stakedToken := UtilsInterface.GetStakedToken(client, staker.TokenAddress) - callOpts := UtilsInterface.GetOptions() - - sRZRBalance, err := StakedTokenInterface.BalanceOf(stakedToken, &callOpts, staker.Address) - if err != nil { - log.Error("Error in getting sRZRBalance: ", err) - return nil, err - } - return sRZRBalance, nil + return returnedValues[0].Interface().(uint16), nil } func (*UtilsStruct) GetMinSafeRazor(client *ethclient.Client) (*big.Int, error) { - var ( - minSafeRazor *big.Int - err error - ) - err = retry.Do( - func() error { - minSafeRazor, err = StakeManagerInterface.MinSafeRazor(client) - if err != nil { - log.Error("Error in fetching minimum safe razor.... Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "MinSafeRazor", client) if err != nil { return nil, err } - return minSafeRazor, nil + return returnedValues[0].Interface().(*big.Int), nil } diff --git a/utils/stake_test.go b/utils/stake_test.go index 209775d8..142fde45 100644 --- a/utils/stake_test.go +++ b/utils/stake_test.go @@ -302,14 +302,16 @@ func TestGetStake(t *testing.T) { t.Run(tt.name, func(t *testing.T) { retryMock := new(mocks.RetryUtils) utilsMock := new(mocks.Utils) + stakeManagerMock := new(mocks.StakeManagerUtils) optionsPackageStruct := OptionsPackageStruct{ - RetryInterface: retryMock, - UtilsInterface: utilsMock, + RetryInterface: retryMock, + UtilsInterface: utilsMock, + StakeManagerInterface: stakeManagerMock, } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) + stakeManagerMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) got, err := utils.GetStake(client, stakerId) @@ -524,68 +526,6 @@ func TestGetStakeManagerWithOpts(t *testing.T) { } } -func TestGetStakerSRZRBalance(t *testing.T) { - var ( - client *ethclient.Client - staker bindings.StructsStaker - callOpts bind.CallOpts - stakedToken *bindings.StakedToken - ) - - type args struct { - sRZR *big.Int - sRZRErr error - } - tests := []struct { - name string - args args - want *big.Int - wantErr bool - }{ - { - name: "Test 1: When GetStakerSRZRBalance executes successfully", - args: args{ - sRZR: big.NewInt(2000), - sRZRErr: nil, - }, - want: big.NewInt(2000), - wantErr: false, - }, - { - name: "Test 2: When there is an error from BalanceOf()", - args: args{ - sRZRErr: errors.New("sRZR error"), - }, - want: nil, - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.Utils) - stakedTokenMock := new(mocks.StakedTokenUtils) - - utilsMock.On("GetStakedToken", mock.Anything, mock.Anything).Return(stakedToken) - utilsMock.On("GetOptions").Return(callOpts) - stakedTokenMock.On("BalanceOf", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.sRZR, tt.args.sRZRErr) - - utils := StartRazor(OptionsPackageStruct{ - UtilsInterface: utilsMock, - StakedTokenInterface: stakedTokenMock, - }) - - got, err := utils.GetStakerSRZRBalance(client, staker) - if (err != nil) != tt.wantErr { - t.Errorf("GetStakerSRZRBalance() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("GetStakerSRZRBalance() got = %v, want %v", got, tt.want) - } - }) - } -} - func TestGetMinSafeRazor(t *testing.T) { var client *ethclient.Client type args struct { diff --git a/utils/stakedToken.go b/utils/stakedToken.go new file mode 100644 index 00000000..9b0b6908 --- /dev/null +++ b/utils/stakedToken.go @@ -0,0 +1,22 @@ +package utils + +import ( + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient" + "math/big" + "razor/pkg/bindings" +) + +func (*UtilsStruct) GetStakedTokenManagerWithOpts(client *ethclient.Client, tokenAddress common.Address) (*bindings.StakedToken, bind.CallOpts) { + return UtilsInterface.GetStakedToken(client, tokenAddress), UtilsInterface.GetOptions() +} + +func (*UtilsStruct) GetStakerSRZRBalance(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(StakedTokenInterface, "BalanceOf", client, staker.TokenAddress, staker.Address) + if err != nil { + log.Error("Error in getting sRZRBalance: ", err) + return nil, err + } + return returnedValues[0].Interface().(*big.Int), nil +} diff --git a/utils/stakedToken_test.go b/utils/stakedToken_test.go new file mode 100644 index 00000000..4440e9d0 --- /dev/null +++ b/utils/stakedToken_test.go @@ -0,0 +1,74 @@ +package utils + +import ( + "errors" + "github.com/avast/retry-go" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/stretchr/testify/mock" + "math/big" + "razor/pkg/bindings" + "razor/utils/mocks" + "reflect" + "testing" +) + +func TestGetStakerSRZRBalance(t *testing.T) { + var ( + client *ethclient.Client + staker bindings.StructsStaker + ) + + type args struct { + sRZR *big.Int + sRZRErr error + } + tests := []struct { + name string + args args + want *big.Int + wantErr bool + }{ + { + name: "Test 1: When GetStakerSRZRBalance executes successfully", + args: args{ + sRZR: big.NewInt(2000), + sRZRErr: nil, + }, + want: big.NewInt(2000), + wantErr: false, + }, + { + name: "Test 2: When there is an error from BalanceOf()", + args: args{ + sRZRErr: errors.New("sRZR error"), + }, + want: nil, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + utilsMock := new(mocks.Utils) + stakedTokenMock := new(mocks.StakedTokenUtils) + retryMock := new(mocks.RetryUtils) + + utils := StartRazor(OptionsPackageStruct{ + UtilsInterface: utilsMock, + StakedTokenInterface: stakedTokenMock, + RetryInterface: retryMock, + }) + + stakedTokenMock.On("BalanceOf", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.sRZR, tt.args.sRZRErr) + retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) + + got, err := utils.GetStakerSRZRBalance(client, staker) + if (err != nil) != tt.wantErr { + t.Errorf("GetStakerSRZRBalance() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetStakerSRZRBalance() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/utils/struct-utils.go b/utils/struct-utils.go index 154bd5ed..ed80fa60 100644 --- a/utils/struct-utils.go +++ b/utils/struct-utils.go @@ -1,7 +1,6 @@ package utils import ( - "bufio" "context" "crypto/ecdsa" "encoding/json" @@ -11,6 +10,8 @@ import ( "math/big" "os" "razor/accounts" + "razor/client" + "razor/core" coretypes "razor/core/types" "razor/path" "razor/pkg/bindings" @@ -28,6 +29,7 @@ import ( ) var RPCTimeout int64 +var HTTPTimeout int64 func StartRazor(optionsPackageStruct OptionsPackageStruct) Utils { UtilsInterface = optionsPackageStruct.UtilsInterface @@ -35,7 +37,6 @@ func StartRazor(optionsPackageStruct OptionsPackageStruct) Utils { ClientInterface = optionsPackageStruct.ClientInterface Time = optionsPackageStruct.Time OS = optionsPackageStruct.OS - Bufio = optionsPackageStruct.Bufio CoinInterface = optionsPackageStruct.CoinInterface IOInterface = optionsPackageStruct.IOInterface ABIInterface = optionsPackageStruct.ABIInterface @@ -52,6 +53,8 @@ func StartRazor(optionsPackageStruct OptionsPackageStruct) Utils { RetryInterface = optionsPackageStruct.RetryInterface MerkleInterface = optionsPackageStruct.MerkleInterface FlagSetInterface = optionsPackageStruct.FlagSetInterface + FileInterface = optionsPackageStruct.FileInterface + GasInterface = optionsPackageStruct.GasInterface return &UtilsStruct{} } @@ -110,6 +113,42 @@ func CheckIfAnyError(result []reflect.Value) error { return nil } +func InvokeFunctionWithRetryAttempts(interfaceName interface{}, methodName string, args ...interface{}) ([]reflect.Value, error) { + var returnedValues []reflect.Value + var err error + inputs := make([]reflect.Value, len(args)) + for i := range args { + inputs[i] = reflect.ValueOf(args[i]) + } + alternateProvider := client.GetAlternateProvider() + switchToAlternateClient := client.GetSwitchToAlternateClientStatus() + if switchToAlternateClient && alternateProvider != "" { + // Changing client argument to alternate client + log.Debug("Making this RPC call using alternate RPC provider!") + inputs = client.ReplaceClientWithAlternateClient(inputs) + } + err = retry.Do( + func() error { + returnedValues = reflect.ValueOf(interfaceName).MethodByName(methodName).Call(inputs) + err = CheckIfAnyError(returnedValues) + if err != nil { + log.Debug("Function to retry: ", methodName) + log.Errorf("Error in %v....Retrying", methodName) + return err + } + return nil + }, RetryInterface.RetryAttempts(core.MaxRetries)) + if err != nil { + if !switchToAlternateClient && alternateProvider != "" { + log.Errorf("%v error after retries: %v", methodName, err) + log.Info("Switching RPC to alternate RPC") + client.SetSwitchToAlternateClientStatus(true) + go client.StartTimerForAlternateClient(core.SwitchClientDuration) + } + } + return returnedValues, err +} + func (b BlockManagerStruct) GetBlockIndexToBeConfirmed(client *ethclient.Client) (int8, error) { blockManager, opts := UtilsInterface.GetBlockManagerWithOpts(client) returnedValues := InvokeFunctionWithTimeout(blockManager, "BlockIndexToBeConfirmed", &opts) @@ -491,6 +530,16 @@ func (v VoteManagerStruct) GetEpochLastRevealed(client *ethclient.Client, staker return returnedValues[0].Interface().(uint32), nil } +func (s StakedTokenStruct) BalanceOf(client *ethclient.Client, tokenAddress common.Address, address common.Address) (*big.Int, error) { + stakedToken, opts := UtilsInterface.GetStakedTokenManagerWithOpts(client, tokenAddress) + returnedValues := InvokeFunctionWithTimeout(stakedToken, "BalanceOf", &opts, address) + returnedError := CheckIfAnyError(returnedValues) + if returnedError != nil { + return nil, returnedError + } + return returnedValues[0].Interface().(*big.Int), nil +} + func (b BindingsStruct) NewCollectionManager(address common.Address, client *ethclient.Client) (*bindings.CollectionManager, error) { return bindings.NewCollectionManager(address, client) } @@ -619,12 +668,8 @@ func (c ClientStruct) FilterLogs(client *ethclient.Client, ctx context.Context, return returnedValues[0].Interface().([]types.Log), nil } -func (b BufioStruct) NewScanner(r io.Reader) *bufio.Scanner { - return bufio.NewScanner(r) -} - -func (c CoinStruct) BalanceOf(coinContract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) { - returnedValues := InvokeFunctionWithTimeout(coinContract, "BalanceOf", opts, account) +func (c CoinStruct) BalanceOf(erc20Contract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) { + returnedValues := InvokeFunctionWithTimeout(erc20Contract, "BalanceOf", opts, account) returnedError := CheckIfAnyError(returnedValues) if returnedError != nil { return nil, returnedError @@ -652,15 +697,6 @@ func (b BindStruct) NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainID return bind.NewKeyedTransactorWithChainID(key, chainID) } -func (s StakedTokenStruct) BalanceOf(stakedToken *bindings.StakedToken, callOpts *bind.CallOpts, address common.Address) (*big.Int, error) { - returnedValues := InvokeFunctionWithTimeout(stakedToken, "BalanceOf", callOpts, address) - returnedError := CheckIfAnyError(returnedValues) - if returnedError != nil { - return nil, returnedError - } - return returnedValues[0].Interface().(*big.Int), nil -} - func (r RetryStruct) RetryAttempts(numberOfAttempts uint) retry.Option { return retry.Attempts(numberOfAttempts) } diff --git a/utils/vote.go b/utils/vote.go index d9910881..59248704 100644 --- a/utils/vote.go +++ b/utils/vote.go @@ -2,12 +2,9 @@ package utils import ( "math/big" - "razor/core" "razor/core/types" "razor/pkg/bindings" - "github.com/avast/retry-go" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/ethclient" ) @@ -21,181 +18,66 @@ func (*UtilsStruct) GetCommitments(client *ethclient.Client, address string) ([3 if err != nil { return [32]byte{}, err } - var ( - commitments types.Commitment - commitmentErr error - ) - commitmentErr = retry.Do( - func() error { - commitments, commitmentErr = VoteManagerInterface.Commitments(client, stakerId) - if commitmentErr != nil { - log.Error("Error in fetching commitment....Retrying") - return commitmentErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if commitmentErr != nil { + returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "Commitments", client, stakerId) + if err != nil { return [32]byte{}, err } - return commitments.CommitmentHash, nil + commitment := returnedValues[0].Interface().(types.Commitment) + return commitment.CommitmentHash, nil } func (*UtilsStruct) GetVoteValue(client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) { - var ( - voteValue *big.Int - voteValueErr error - ) - voteValueErr = retry.Do( - func() error { - voteValue, voteValueErr = VoteManagerInterface.GetVoteValue(client, epoch, stakerId, medianIndex) - if voteValueErr != nil { - log.Error("Error in fetching last vote value....Retrying") - return voteValueErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if voteValueErr != nil { - return big.NewInt(0), voteValueErr + returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetVoteValue", client, epoch, stakerId, medianIndex) + if err != nil { + return big.NewInt(0), err } - return voteValue, nil + return returnedValues[0].Interface().(*big.Int), nil } func (*UtilsStruct) GetInfluenceSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - var ( - influenceSnapshot *big.Int - influenceErr error - ) - influenceErr = retry.Do( - func() error { - influenceSnapshot, influenceErr = VoteManagerInterface.GetInfluenceSnapshot(client, epoch, stakerId) - if influenceErr != nil { - log.Error("Error in fetching influence snapshot....Retrying") - return influenceErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if influenceErr != nil { - return nil, influenceErr + returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetInfluenceSnapshot", client, epoch, stakerId) + if err != nil { + return nil, err } - return influenceSnapshot, nil + return returnedValues[0].Interface().(*big.Int), nil } func (*UtilsStruct) GetStakeSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - var ( - stakeSnapshot *big.Int - snapshotErr error - ) - snapshotErr = retry.Do( - func() error { - stakeSnapshot, snapshotErr = VoteManagerInterface.GetStakeSnapshot(client, epoch, stakerId) - if snapshotErr != nil { - log.Error("Error in fetching stake snapshot....Retrying") - return snapshotErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if snapshotErr != nil { - return nil, snapshotErr + returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetStakeSnapshot", client, epoch, stakerId) + if err != nil { + return nil, err } - return stakeSnapshot, nil + return returnedValues[0].Interface().(*big.Int), nil } func (*UtilsStruct) GetTotalInfluenceRevealed(client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) { - var ( - totalInfluenceRevealed *big.Int - influenceErr error - ) - influenceErr = retry.Do( - func() error { - totalInfluenceRevealed, influenceErr = VoteManagerInterface.GetTotalInfluenceRevealed(client, epoch, medianIndex) - if influenceErr != nil { - log.Error("Error in fetching total influence revealed....Retrying") - return influenceErr - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if influenceErr != nil { - return nil, influenceErr + returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetTotalInfluenceRevealed", client, epoch, medianIndex) + if err != nil { + return nil, err } - return totalInfluenceRevealed, nil + return returnedValues[0].Interface().(*big.Int), nil } func (*UtilsStruct) GetEpochLastCommitted(client *ethclient.Client, stakerId uint32) (uint32, error) { - var ( - epochLastCommitted uint32 - err error - ) - err = retry.Do( - func() error { - epochLastCommitted, err = VoteManagerInterface.GetEpochLastCommitted(client, stakerId) - if err != nil { - log.Error("Error in fetching epoch last committed....Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetEpochLastCommitted", client, stakerId) if err != nil { return 0, err } - return epochLastCommitted, nil + return returnedValues[0].Interface().(uint32), nil } func (*UtilsStruct) GetEpochLastRevealed(client *ethclient.Client, stakerId uint32) (uint32, error) { - var ( - epochLastRevealed uint32 - err error - ) - err = retry.Do( - func() error { - epochLastRevealed, err = VoteManagerInterface.GetEpochLastRevealed(client, stakerId) - if err != nil { - log.Error("Error in fetching epoch last revealed....Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetEpochLastRevealed", client, stakerId) if err != nil { return 0, err } - return epochLastRevealed, nil + return returnedValues[0].Interface().(uint32), nil } func (*UtilsStruct) ToAssign(client *ethclient.Client) (uint16, error) { - var ( - toAssign uint16 - err error - ) - err = retry.Do( - func() error { - toAssign, err = VoteManagerInterface.ToAssign(client) - if err != nil { - log.Error("Error in fetching toAssign....Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) + returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "ToAssign", client) if err != nil { return 0, err } - return toAssign, nil -} - -func (*UtilsStruct) GetSaltFromBlockchain(client *ethclient.Client) ([32]byte, error) { - var ( - salt [32]byte - err error - ) - err = retry.Do( - func() error { - salt, err = VoteManagerInterface.GetSaltFromBlockchain(client) - if err != nil { - log.Error("Error in fetching salt....Retrying") - return err - } - return nil - }, RetryInterface.RetryAttempts(core.MaxRetries)) - if err != nil { - return [32]byte{}, err - } - return salt, nil + return returnedValues[0].Interface().(uint16), nil } diff --git a/utils/vote_test.go b/utils/vote_test.go index 10cf9fbf..145777a9 100644 --- a/utils/vote_test.go +++ b/utils/vote_test.go @@ -57,7 +57,7 @@ func TestGetCommitments(t *testing.T) { commitmentErr: errors.New("commitments error"), }, want: [32]byte{}, - wantErr: false, + wantErr: true, }, } for _, tt := range tests { @@ -153,7 +153,6 @@ func TestGetEpochLastCommitted(t *testing.T) { func TestGetEpochLastRevealed(t *testing.T) { var client *ethclient.Client - var callOpts bind.CallOpts var stakerId uint32 type args struct { @@ -196,7 +195,6 @@ func TestGetEpochLastRevealed(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetOptions").Return(callOpts) voteManagerMock.On("GetEpochLastRevealed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.epochLastRevealed, tt.args.epochLastRevealedErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) @@ -543,58 +541,3 @@ func TestToAssign(t *testing.T) { }) } } - -func TestGetSaltFromBlockchain(t *testing.T) { - var client *ethclient.Client - type args struct { - salt [32]byte - saltErr error - } - tests := []struct { - name string - args args - want [32]byte - wantErr bool - }{ - { - name: "Test 1: When GetSaltFromBlockChain() executes successfully", - args: args{ - salt: [32]byte{}, - }, - want: [32]byte{}, - wantErr: false, - }, - { - name: "Test 2: When there is an error in getting salt", - args: args{ - saltErr: errors.New("error in getting salt"), - }, - want: [32]byte{}, - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - retryMock := new(mocks.RetryUtils) - voteManagerMock := new(mocks.VoteManagerUtils) - - optionsPackageStruct := OptionsPackageStruct{ - RetryInterface: retryMock, - VoteManagerInterface: voteManagerMock, - } - utils := StartRazor(optionsPackageStruct) - - voteManagerMock.On("GetSaltFromBlockchain", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.salt, tt.args.saltErr) - retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - - got, err := utils.GetSaltFromBlockchain(client) - if (err != nil) != tt.wantErr { - t.Errorf("GetSaltFromBlockchain() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("GetSaltFromBlockchain() got = %v, want %v", got, tt.want) - } - }) - } -}