From 9711f31c7713c8e18204b7dd8dad7f3a9ed0b459 Mon Sep 17 00:00:00 2001 From: Javad Rajabzadeh Date: Sun, 27 Oct 2024 11:11:51 +0330 Subject: [PATCH] fix(other): add varnamelen linter to improve name convations (#1568) --- .golangci.yml | 35 +- cmd/cmd.go | 14 +- cmd/cmd_test.go | 58 +-- cmd/daemon/import.go | 12 +- cmd/daemon/prune.go | 6 +- cmd/gtk/dialog_wallet_create_address.go | 14 +- cmd/gtk/main.go | 8 +- cmd/gtk/main_window.go | 24 +- cmd/gtk/model_node.go | 4 +- cmd/gtk/model_wallet.go | 14 +- cmd/gtk/startup_assistant.go | 10 +- cmd/gtk/widget_node.go | 12 +- cmd/gtk/widget_wallet.go | 18 +- cmd/importer.go | 28 +- cmd/shell/main.go | 26 +- cmd/wallet/history.go | 8 +- cmd/wallet/tx.go | 40 +- committee/committee.go | 12 +- config/config_test.go | 17 +- consensus/config_test.go | 16 +- consensus/consensus.go | 156 +++--- consensus/consensus_test.go | 262 +++++----- consensus/cp.go | 58 +-- consensus/cp_test.go | 206 ++++---- consensus/height_test.go | 26 +- consensus/interface.go | 4 +- consensus/log/log.go | 36 +- consensus/log/log_test.go | 57 +-- consensus/log/messages.go | 16 +- consensus/manager.go | 72 +-- consensus/manager_test.go | 105 ++-- consensus/mediator.go | 6 +- consensus/mock.go | 8 +- consensus/precommit_test.go | 62 +-- consensus/prepare.go | 6 +- consensus/prepare_test.go | 12 +- consensus/propose_test.go | 18 +- consensus/voteset/binary_voteset.go | 14 +- consensus/voteset/block_voteset.go | 24 +- consensus/voteset/vote_box.go | 6 +- consensus/voteset/voteset.go | 6 +- consensus/voteset/voteset_test.go | 323 ++++++------ crypto/address.go | 10 +- crypto/address_test.go | 38 +- crypto/bls/bls.go | 8 +- crypto/bls/bls_test.go | 6 +- crypto/bls/hdkeychain/extendedkey.go | 64 +-- crypto/bls/hdkeychain/extendedkey_test.go | 96 ++-- crypto/bls/private_key.go | 14 +- crypto/bls/private_key_test.go | 26 +- crypto/bls/public_key_test.go | 36 +- crypto/bls/signature_test.go | 36 +- crypto/ed25519/ed25519_test.go | 10 +- crypto/ed25519/hdkeychain/extendedkey.go | 32 +- crypto/ed25519/hdkeychain/extendedkey_test.go | 54 +- crypto/ed25519/private_key_test.go | 12 +- crypto/ed25519/public_key_test.go | 28 +- crypto/ed25519/signature_test.go | 28 +- execution/execution.go | 30 +- execution/execution_test.go | 162 +++--- execution/executor/bond.go | 34 +- execution/executor/bond_test.go | 76 +-- execution/executor/executor.go | 16 +- execution/executor/executor_test.go | 16 +- execution/executor/sortition.go | 28 +- execution/executor/sortition_test.go | 118 ++--- execution/executor/transfer.go | 16 +- execution/executor/transfer_test.go | 14 +- execution/executor/unbond.go | 18 +- execution/executor/unbond_test.go | 32 +- execution/executor/withdraw.go | 18 +- execution/executor/withdraw_test.go | 24 +- genesis/genesis.go | 4 +- network/config_test.go | 33 +- network/gossip.go | 45 +- network/mdns.go | 10 +- network/mock.go | 4 +- network/network.go | 18 +- network/network_test.go | 8 +- network/notifee.go | 16 +- network/peermgr.go | 38 +- network/stream.go | 6 +- network/utils_test.go | 44 +- node/node.go | 18 +- node/node_test.go | 18 +- sandbox/mock.go | 10 +- sandbox/sandbox.go | 28 +- sandbox/sandbox_test.go | 162 +++--- sortition/vrf.go | 4 +- sortition/vrf_test.go | 6 +- state/execution.go | 16 +- state/facade.go | 4 +- state/lastinfo/last_info.go | 14 +- state/lastinfo/last_info_test.go | 14 +- state/mock.go | 18 +- state/score/score_test.go | 36 +- state/state.go | 114 ++--- state/state_test.go | 66 +-- store/block.go | 18 +- store/config_test.go | 16 +- store/interface.go | 4 +- store/mock.go | 18 +- store/store.go | 58 +-- store/store_test.go | 38 +- store/tx.go | 26 +- sync/bundle/bundle_test.go | 26 +- sync/bundle/message/block_announce_test.go | 16 +- sync/bundle/message/blocks_request_test.go | 20 +- sync/bundle/message/blocks_response_test.go | 64 +-- sync/bundle/message/hello_ack_test.go | 8 +- sync/bundle/message/hello_test.go | 44 +- sync/bundle/message/message.go | 6 +- sync/bundle/message/message_test.go | 12 +- sync/bundle/message/proposal_test.go | 12 +- sync/bundle/message/query_proposal_test.go | 14 +- sync/bundle/message/query_votes_test.go | 14 +- sync/bundle/message/transactions_test.go | 14 +- sync/bundle/message/vote_test.go | 18 +- sync/cache/cache.go | 8 +- sync/cache/cache_test.go | 10 +- sync/firewall/firewall.go | 20 +- sync/firewall/firewall_test.go | 30 +- sync/handler_blocks_request.go | 18 +- sync/handler_blocks_response_test.go | 142 +++--- sync/handler_hello.go | 12 +- sync/handler_hello_test.go | 16 +- sync/handler_proposal_test.go | 2 +- sync/handler_query_proposal_test.go | 2 +- sync/handler_query_votes_test.go | 6 +- sync/mock.go | 12 +- sync/peerset/peer/peer_test.go | 34 +- sync/peerset/peer/service/services_test.go | 12 +- sync/peerset/peer_set.go | 26 +- sync/peerset/peer_set_test.go | 140 +++--- sync/sync.go | 80 +-- sync/sync_test.go | 20 +- tests/main_test.go | 6 +- txpool/config_test.go | 42 +- txpool/interface.go | 6 +- txpool/mock.go | 12 +- txpool/txpool.go | 34 +- txpool/txpool_test.go | 58 +-- types/account/account.go | 6 +- types/account/account_test.go | 12 +- types/amount/amount.go | 10 +- types/amount/amount_test.go | 62 +-- types/block/block.go | 36 +- types/block/block_test.go | 79 +-- types/certificate/block_certificate.go | 8 +- types/certificate/certificate.go | 14 +- types/certificate/certificate_test.go | 10 +- types/certificate/vote_certificate.go | 10 +- types/proposal/proposal_test.go | 60 ++- types/tx/payload/bond_test.go | 22 +- types/tx/payload/sortition_test.go | 22 +- types/tx/payload/transfer_test.go | 26 +- types/tx/tx.go | 30 +- types/tx/tx_test.go | 42 +- types/validator/validator.go | 14 +- types/validator/validator_test.go | 22 +- types/vote/vote.go | 36 +- types/vote/vote_test.go | 185 +++---- util/bech32m/bech32m.go | 18 +- util/bech32m/bech32m_test.go | 150 +++--- util/downloader/downloader.go | 24 +- util/downloader/downloader_test.go | 27 +- util/encoding/encoding.go | 94 ++-- util/encoding/encoding_test.go | 136 ++--- util/io.go | 76 +-- util/linkedlist/linkedlist.go | 164 +++--- util/linkedlist/linkedlist_test.go | 212 ++++---- util/linkedmap/linkedmap.go | 58 +-- util/linkedmap/linkedmap_test.go | 472 +++++++++--------- util/logger/logger.go | 45 +- util/logger/logger_test.go | 14 +- util/pairslice/pairslice_test.go | 134 ++--- util/persistentmerkle/merkle.go | 14 +- util/ratelimit/ratelimit_test.go | 24 +- util/shell/shell.go | 48 +- util/simplemerkle/merkle.go | 23 +- util/simplemerkle/merkle_test.go | 52 +- util/slice.go | 68 ++- util/slice_test.go | 76 +-- util/testsuite/testsuite.go | 151 +++--- util/time_test.go | 62 ++- util/utils.go | 34 +- util/utils_test.go | 16 +- version/version.go | 22 +- version/version_test.go | 10 +- wallet/addresspath/path_test.go | 12 +- wallet/client.go | 4 +- wallet/encrypter/encrypter.go | 16 +- wallet/encrypter/encrypter_test.go | 49 +- wallet/encrypter/params_test.go | 30 +- wallet/manager.go | 8 +- wallet/vault/utils_test.go | 6 +- wallet/vault/vault.go | 6 +- wallet/vault/vault_test.go | 6 +- wallet/wallet.go | 20 +- www/grpc/basicauth/basicauth_test.go | 10 +- www/grpc/blockchain.go | 24 +- www/grpc/blockchain_test.go | 38 +- www/grpc/gateway.go | 8 +- www/grpc/network.go | 74 +-- www/grpc/network_test.go | 14 +- www/grpc/server.go | 10 +- www/grpc/wallet.go | 16 +- www/grpc/wallet_test.go | 8 +- www/http/blockchain.go | 144 +++--- www/http/blockchain_test.go | 27 +- www/http/middleware_test.go | 27 +- www/http/network.go | 126 ++--- www/http/transaction.go | 44 +- www/nanomsg/event/event.go | 21 +- www/nanomsg/server.go | 6 +- 215 files changed, 4320 insertions(+), 4271 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 7ea149a5b..74a30010a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -75,6 +75,7 @@ linters: - whitespace # - wrapcheck - zerologlint + - varnamelen linters-settings: gosimple: @@ -128,6 +129,9 @@ linters-settings: - name: "function-result-limit" disabled: true + - name: "import-shadowing" + disabled: true + - name: unhandled-error arguments: - "fmt.Printf" @@ -177,7 +181,7 @@ linters-settings: disabled-checks: - ifElseChain - unnamedResult - - builtinShadow + - importShadow enabled-tags: - diagnostic - style @@ -188,6 +192,27 @@ linters-settings: # Default: 5 min-complexity: 6 + varnamelen: + ignore-names: + - ok + - ip + - no + - tt # table tests + - i # for simple loops + - j # for simple loops + - l + - h + - il + - r # reader + - w # writer + + ignore-decls: + - wg sync.WaitGroup + - ts *testsuite.TestSuite + - td *testData + - ma multiaddr.Multiaddr + - db *leveldb.DB + issues: exclude-use-default: false exclude-rules: @@ -198,6 +223,8 @@ issues: - gocognit - forbidigo - - linters: - - govet - text: "shadow: declaration of \"err\" shadows" + exclude: + - "shadow: declaration of \"err\" shadows" + - "builtinShadow: shadowing of predeclared identifier: min" + - "builtinShadow: shadowing of predeclared identifier: max" + - "builtinShadow: shadowing of predeclared identifier: len" diff --git a/cmd/cmd.go b/cmd/cmd.go index 7aad0a63b..34403ea66 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -189,13 +189,13 @@ func FatalErrorCheck(err error) { } } -func PrintErrorMsgf(format string, a ...any) { +func PrintErrorMsgf(format string, args ...any) { format = "[ERROR] " + format if terminalSupported { // Print error msg with red color format = fmt.Sprintf("\033[31m%s\033[0m", format) } - fmt.Printf(format+"\n", a...) + fmt.Printf(format+"\n", args...) } func PrintSuccessMsgf(format string, a ...any) { @@ -408,21 +408,21 @@ func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string, return nil, nil, err } - nd, err := node.NewNode(gen, conf, valKeys, rewardAddrs) + node, err := node.NewNode(gen, conf, valKeys, rewardAddrs) if err != nil { return nil, nil, err } - err = nd.Start() + err = node.Start() if err != nil { return nil, nil, err } - return nd, walletInstance, nil + return node, walletInstance, nil } // makeLocalGenesis makes genesis file for the local network. -func makeLocalGenesis(w wallet.Wallet) *genesis.Genesis { +func makeLocalGenesis(wlt wallet.Wallet) *genesis.Genesis { // Treasury account acc := account.NewAccount(0) acc.AddToBalance(21 * 1e14) @@ -433,7 +433,7 @@ func makeLocalGenesis(w wallet.Wallet) *genesis.Genesis { genValNum := 4 vals := make([]*validator.Validator, genValNum) for i := 0; i < genValNum; i++ { - info := w.AddressInfo(w.AddressInfos()[i].Address) + info := wlt.AddressInfo(wlt.AddressInfos()[i].Address) pub, _ := bls.PublicKeyFromString(info.PublicKey) vals[i] = validator.NewValidator(pub, int32(i)) } diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index 991dc5cca..7d09875c6 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -69,25 +69,25 @@ func TestMakeConfig(t *testing.T) { } // captureOutput is a helper function to capture the printed output of a function. -func captureOutput(f func()) string { +func captureOutput(fun func()) string { // Redirect stdout to a buffer oldStdout := os.Stdout - r, w, _ := os.Pipe() - os.Stdout = w + reader, writer, _ := os.Pipe() + os.Stdout = writer // Capture the printed output outC := make(chan string) go func() { var buf bytes.Buffer - _, _ = io.Copy(&buf, r) + _, _ = io.Copy(&buf, reader) outC <- buf.String() }() // Execute the function - f() + fun() // Reset stdout - _ = w.Close() + _ = writer.Close() os.Stdout = oldStdout out := <-outC @@ -167,16 +167,16 @@ func TestPathsUnix(t *testing.T) { }, } - for _, test := range tests { - walletDir := PactusWalletDir(test.home) - defaultWalletPath := PactusDefaultWalletPath(test.home) - genesisPath := PactusGenesisPath(test.home) - configPath := PactusConfigPath(test.home) + for _, tt := range tests { + walletDir := PactusWalletDir(tt.home) + defaultWalletPath := PactusDefaultWalletPath(tt.home) + genesisPath := PactusGenesisPath(tt.home) + configPath := PactusConfigPath(tt.home) - assert.Equal(t, test.expectedWalletDir, walletDir) - assert.Equal(t, test.expectedDefaultWalletPath, defaultWalletPath) - assert.Equal(t, test.expectedGenesisPath, genesisPath) - assert.Equal(t, test.expectedConfigPath, configPath) + assert.Equal(t, tt.expectedWalletDir, walletDir) + assert.Equal(t, tt.expectedDefaultWalletPath, defaultWalletPath) + assert.Equal(t, tt.expectedGenesisPath, genesisPath) + assert.Equal(t, tt.expectedConfigPath, configPath) } } @@ -207,16 +207,16 @@ func TestPathsWindows(t *testing.T) { }, } - for _, test := range tests { - walletDir := PactusWalletDir(test.home) - defaultWalletPath := PactusDefaultWalletPath(test.home) - genesisPath := PactusGenesisPath(test.home) - configPath := PactusConfigPath(test.home) + for _, tt := range tests { + walletDir := PactusWalletDir(tt.home) + defaultWalletPath := PactusDefaultWalletPath(tt.home) + genesisPath := PactusGenesisPath(tt.home) + configPath := PactusConfigPath(tt.home) - assert.Equal(t, test.expectedWalletDir, walletDir) - assert.Equal(t, test.expectedDefaultWalletPath, defaultWalletPath) - assert.Equal(t, test.expectedGenesisPath, genesisPath) - assert.Equal(t, test.expectedConfigPath, configPath) + assert.Equal(t, tt.expectedWalletDir, walletDir) + assert.Equal(t, tt.expectedDefaultWalletPath, defaultWalletPath) + assert.Equal(t, tt.expectedGenesisPath, genesisPath) + assert.Equal(t, tt.expectedConfigPath, configPath) } } @@ -364,16 +364,16 @@ func TestCreateNode(t *testing.T) { }, } - for _, test := range tests { + for _, tt := range tests { validatorAddrs, rewardAddrs, err := CreateNode( - test.numValidators, test.chain, test.workingDir, test.mnemonic, "") + tt.numValidators, tt.chain, tt.workingDir, tt.mnemonic, "") - if test.withErr { + if tt.withErr { assert.Error(t, err) } else { assert.NoError(t, err) - assert.Equal(t, test.validatorAddrs, validatorAddrs) - assert.Equal(t, test.rewardAddrs, rewardAddrs) + assert.Equal(t, tt.validatorAddrs, validatorAddrs) + assert.Equal(t, tt.rewardAddrs, rewardAddrs) } } } diff --git a/cmd/daemon/import.go b/cmd/daemon/import.go index 91e66d3b5..af7b5cc35 100644 --- a/cmd/daemon/import.go +++ b/cmd/daemon/import.go @@ -22,7 +22,7 @@ func buildImportCmd(parentCmd *cobra.Command) { serverAddrOpt := importCmd.Flags().String("server-addr", cmd.DefaultSnapshotURL, "import server address") - importCmd.Run = func(c *cobra.Command, _ []string) { + importCmd.Run = func(cobra *cobra.Command, _ []string) { workingDir, err := filepath.Abs(*workingDirOpt) cmd.FatalErrorCheck(err) @@ -54,15 +54,15 @@ func buildImportCmd(parentCmd *cobra.Command) { ) cmd.FatalErrorCheck(err) - metadata, err := importer.GetMetadata(c.Context()) + metadata, err := importer.GetMetadata(cobra.Context()) cmd.FatalErrorCheck(err) snapshots := make([]string, 0, len(metadata)) - for _, m := range metadata { + for _, md := range metadata { item := fmt.Sprintf("snapshot %s (%s)", - m.CreatedAtTime().Format("2006-01-02"), - util.FormatBytesToHumanReadable(m.Data.Size), + md.CreatedAtTime().Format("2006-01-02"), + util.FormatBytesToHumanReadable(md.Data.Size), ) snapshots = append(snapshots, item) @@ -81,7 +81,7 @@ func buildImportCmd(parentCmd *cobra.Command) { cmd.PrintLine() - err = importer.Download(c.Context(), &selected, downloadProgressBar) + err = importer.Download(cobra.Context(), &selected, downloadProgressBar) cmd.FatalErrorCheck(err) cmd.PrintLine() diff --git a/cmd/daemon/prune.go b/cmd/daemon/prune.go index 82b917061..ca9f7dd44 100644 --- a/cmd/daemon/prune.go +++ b/cmd/daemon/prune.go @@ -59,7 +59,7 @@ func buildPruneCmd(parentCmd *cobra.Command) { } cmd.PrintLine() - str, err := store.NewStore(conf.Store) + store, err := store.NewStore(conf.Store) cmd.FatalErrorCheck(err) prunedCount := uint32(0) @@ -73,7 +73,7 @@ func buildPruneCmd(parentCmd *cobra.Command) { <-closed }) - err = str.Prune(func(pruned bool, pruningHeight uint32) bool { + err = store.Prune(func(pruned bool, pruningHeight uint32) bool { if pruned { prunedCount++ } else { @@ -108,7 +108,7 @@ func buildPruneCmd(parentCmd *cobra.Command) { cmd.PrintInfoMsgf("./pactus-daemon start -w %v", workingDir) } - str.Close() + store.Close() _ = fileLock.Unlock() closed <- true diff --git a/cmd/gtk/dialog_wallet_create_address.go b/cmd/gtk/dialog_wallet_create_address.go index 4a5bac9da..c1a7f15e2 100644 --- a/cmd/gtk/dialog_wallet_create_address.go +++ b/cmd/gtk/dialog_wallet_create_address.go @@ -12,7 +12,7 @@ import ( //go:embed assets/ui/dialog_wallet_create_address.ui var uiWalletCreateAddressDialog []byte -func createAddress(ww *widgetWallet) { +func createAddress(wdgWallet *widgetWallet) { builder, err := gtk.BuilderNewFromString(string(uiWalletCreateAddressDialog)) fatalErrorCheck(err) @@ -38,24 +38,24 @@ func createAddress(ww *widgetWallet) { switch walletAddressType { case wallet.AddressTypeEd25519Account: - password, ok := getWalletPassword(ww.model.wallet) + password, ok := getWalletPassword(wdgWallet.model.wallet) if !ok { return } - _, err = ww.model.wallet.NewEd25519AccountAddress(walletAddressLabel, password) + _, err = wdgWallet.model.wallet.NewEd25519AccountAddress(walletAddressLabel, password) case wallet.AddressTypeBLSAccount: - _, err = ww.model.wallet.NewBLSAccountAddress(walletAddressLabel) + _, err = wdgWallet.model.wallet.NewBLSAccountAddress(walletAddressLabel) case wallet.AddressTypeValidator: - _, err = ww.model.wallet.NewValidatorAddress(walletAddressLabel) + _, err = wdgWallet.model.wallet.NewValidatorAddress(walletAddressLabel) } errorCheck(err) - err = ww.model.wallet.Save() + err = wdgWallet.model.wallet.Save() errorCheck(err) - ww.model.rebuildModel() + wdgWallet.model.rebuildModel() dlg.Close() } diff --git a/cmd/gtk/main.go b/cmd/gtk/main.go index d2d880bcd..5f0fcc505 100644 --- a/cmd/gtk/main.go +++ b/cmd/gtk/main.go @@ -87,7 +87,7 @@ func main() { log.Println("application startup") }) - nd, wlt, err := newNode(workingDir) + node, wlt, err := newNode(workingDir) fatalErrorCheck(err) // Connect function to application activate event @@ -114,7 +114,7 @@ func main() { // Running the run-up logic in a separate goroutine glib.TimeoutAdd(uint(100), func() bool { - run(nd, wlt, app) + run(node, wlt, app) splashDlg.Destroy() // Ensures the function is not called again @@ -125,14 +125,14 @@ func main() { // Connect function to application shutdown event, this is not required. app.Connect("shutdown", func() { log.Println("Application shutdown") - nd.Stop() + node.Stop() _ = fileLock.Unlock() }) cmd.TrapSignal(func() { cmd.PrintInfoMsgf("Exiting...") - nd.Stop() + node.Stop() _ = fileLock.Unlock() }) diff --git a/cmd/gtk/main_window.go b/cmd/gtk/main_window.go index 2dc225f9a..0eea7c354 100644 --- a/cmd/gtk/main_window.go +++ b/cmd/gtk/main_window.go @@ -40,31 +40,31 @@ func buildMainWindow(nodeModel *nodeModel, walletModel *walletModel) *mainWindow boxNode.Add(widgetNode) boxDefaultWallet.Add(widgetWallet) - mw := &mainWindow{ + mainWnd := &mainWindow{ ApplicationWindow: appWindow, widgetNode: widgetNode, widgetWallet: widgetWallet, } explorerItemMenu := getMenuItem(builder, "id_explorer_menu") - explorerItemMenu.Connect("activate", mw.onMenuItemActivateExplorer) + explorerItemMenu.Connect("activate", mainWnd.onMenuItemActivateExplorer) websiteItemMenu := getMenuItem(builder, "id_website_menu") - websiteItemMenu.Connect("activate", mw.onMenuItemActivateWebsite) + websiteItemMenu.Connect("activate", mainWnd.onMenuItemActivateWebsite) documentationItemMenu := getMenuItem(builder, "id_documentation_menu") - documentationItemMenu.Connect("activate", mw.onMenuItemActivateDocumentation) + documentationItemMenu.Connect("activate", mainWnd.onMenuItemActivateDocumentation) // Map the handlers to callback functions, and connect the signals // to the Builder. signals := map[string]any{ - "on_about_gtk": mw.onAboutGtk, - "on_about": mw.onAbout, - "on_quit": mw.onQuit, - "on_transaction_transfer": mw.OnTransactionTransfer, - "on_transaction_bond": mw.OnTransactionBond, - "on_transaction_unbond": mw.OnTransactionUnbond, - "on_transaction_withdraw": mw.OnTransactionWithdraw, + "on_about_gtk": mainWnd.onAboutGtk, + "on_about": mainWnd.onAbout, + "on_quit": mainWnd.onQuit, + "on_transaction_transfer": mainWnd.OnTransactionTransfer, + "on_transaction_bond": mainWnd.OnTransactionBond, + "on_transaction_unbond": mainWnd.OnTransactionUnbond, + "on_transaction_withdraw": mainWnd.OnTransactionWithdraw, } builder.ConnectSignals(signals) @@ -80,7 +80,7 @@ func buildMainWindow(nodeModel *nodeModel, walletModel *walletModel) *mainWindow gtk.AddProviderForScreen(screen, provider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) - return mw + return mainWnd } func (mw *mainWindow) onQuit() { diff --git a/cmd/gtk/model_node.go b/cmd/gtk/model_node.go index 1e04c4e9c..8aec23ab6 100644 --- a/cmd/gtk/model_node.go +++ b/cmd/gtk/model_node.go @@ -10,8 +10,8 @@ type nodeModel struct { node *node.Node } -func newNodeModel(nde *node.Node) *nodeModel { +func newNodeModel(node *node.Node) *nodeModel { return &nodeModel{ - node: nde, + node: node, } } diff --git a/cmd/gtk/model_wallet.go b/cmd/gtk/model_wallet.go index e02276513..d52625a56 100644 --- a/cmd/gtk/model_wallet.go +++ b/cmd/gtk/model_wallet.go @@ -75,7 +75,7 @@ func (model *walletModel) rebuildModel() { glib.IdleAdd(func() bool { model.listStore.Clear() - for _, d := range data { + for _, item := range data { iter := model.listStore.Append() err := model.listStore.Set(iter, []int{ @@ -87,12 +87,12 @@ func (model *walletModel) rebuildModel() { IDAddressesColumnAvailabilityScore, }, []any{ - d[0], - d[1], - d[2], - d[3], - d[4], - d[5], + item[0], + item[1], + item[2], + item[3], + item[4], + item[5], }) errorCheck(err) diff --git a/cmd/gtk/startup_assistant.go b/cmd/gtk/startup_assistant.go index a4a83620c..6843aaa35 100644 --- a/cmd/gtk/startup_assistant.go +++ b/cmd/gtk/startup_assistant.go @@ -746,7 +746,7 @@ func assistantPageComplete(assistant *gtk.Assistant, page gtk.IWidget, completed func getMetadata( ctx context.Context, - dm *cmd.Importer, + importer *cmd.Importer, listBox *gtk.ListBox, ) <-chan []cmd.Metadata { mdCh := make(chan []cmd.Metadata, 1) @@ -761,7 +761,7 @@ func getMetadata( children = children.Next() } - metadata, err := dm.GetMetadata(ctx) + metadata, err := importer.GetMetadata(ctx) if err != nil { mdCh <- nil @@ -769,15 +769,15 @@ func getMetadata( } for _, md := range metadata { - listBoxRow, err := gtk.ListBoxRowNew() - fatalErrorCheck(err) - label, err := gtk.LabelNew(fmt.Sprintf("snapshot %s (%s)", md.CreatedAtTime().Format("2006-01-02"), util.FormatBytesToHumanReadable(md.Data.Size), )) fatalErrorCheck(err) + listBoxRow, err := gtk.ListBoxRowNew() + fatalErrorCheck(err) + listBoxRow.Add(label) listBox.Add(listBoxRow) } diff --git a/cmd/gtk/widget_node.go b/cmd/gtk/widget_node.go index f518d5978..45cd2bbe0 100644 --- a/cmd/gtk/widget_node.go +++ b/cmd/gtk/widget_node.go @@ -60,7 +60,7 @@ func buildWidgetNode(model *nodeModel) (*widgetNode, error) { labelMoniker.SetText(model.node.Sync().Moniker()) labelIsPrune.SetText(strconv.FormatBool(model.node.State().IsPruned())) - w := &widgetNode{ + wdgNode := &widgetNode{ Box: box, model: model, genesisTime: model.node.State().Genesis().GenesisTime(), @@ -81,14 +81,14 @@ func buildWidgetNode(model *nodeModel) (*widgetNode, error) { signals := map[string]any{} builder.ConnectSignals(signals) - glib.TimeoutAdd(1000, w.timeout1) - glib.TimeoutAdd(10000, w.timeout10) + glib.TimeoutAdd(1000, wdgNode.timeout1) + glib.TimeoutAdd(10000, wdgNode.timeout10) // Update widget for the first time - w.timeout1() - w.timeout10() + wdgNode.timeout1() + wdgNode.timeout10() - return w, nil + return wdgNode, nil } func (wn *widgetNode) timeout1() bool { diff --git a/cmd/gtk/widget_wallet.go b/cmd/gtk/widget_wallet.go index cc2b0a624..3216ff1f2 100644 --- a/cmd/gtk/widget_wallet.go +++ b/cmd/gtk/widget_wallet.go @@ -87,7 +87,7 @@ func buildWidgetWallet(model *walletModel) (*widgetWallet, error) { treeViewWallet.AppendColumn(colScore) treeViewWallet.SetModel(model.ToTreeModel()) - w := &widgetWallet{ + wdgWallet := &widgetWallet{ Box: box, treeViewWallet: treeViewWallet, labelTotalBalance: labelTotalBalance, @@ -104,7 +104,7 @@ func buildWidgetWallet(model *walletModel) (*widgetWallet, error) { item.SetUseUnderline(true) item.Show() item.Connect("activate", func(_ *gtk.MenuItem) bool { - w.onUpdateLabel() + wdgWallet.onUpdateLabel() return false }) @@ -117,7 +117,7 @@ func buildWidgetWallet(model *walletModel) (*widgetWallet, error) { item.SetUseUnderline(true) item.Show() item.Connect("activate", func(_ *gtk.MenuItem) bool { - w.onShowDetails() + wdgWallet.onShowDetails() return false }) @@ -130,7 +130,7 @@ func buildWidgetWallet(model *walletModel) (*widgetWallet, error) { item.SetUseUnderline(true) item.Show() item.Connect("activate", func(_ *gtk.MenuItem) bool { - w.onShowPrivateKey() + wdgWallet.onShowPrivateKey() return false }) @@ -148,15 +148,15 @@ func buildWidgetWallet(model *walletModel) (*widgetWallet, error) { }) signals := map[string]any{ - "on_new_address": w.onNewAddress, - "on_change_password": w.onChangePassword, - "on_show_seed": w.onShowSeed, + "on_new_address": wdgWallet.onNewAddress, + "on_change_password": wdgWallet.onChangePassword, + "on_show_seed": wdgWallet.onShowSeed, } builder.ConnectSignals(signals) - glib.TimeoutAdd(15000, w.timeout) // each 15 seconds + glib.TimeoutAdd(15000, wdgWallet.timeout) // each 15 seconds - return w, nil + return wdgWallet, nil } func (ww *widgetWallet) onChangePassword() { diff --git a/cmd/importer.go b/cmd/importer.go index a7e6b3372..c38e0cb9f 100644 --- a/cmd/importer.go +++ b/cmd/importer.go @@ -140,11 +140,11 @@ func (i *Importer) Download(ctx context.Context, metadata *Metadata, i.dataFileName = fileName filePath := fmt.Sprintf("%s/%s", i.tempDir, fileName) - d := downloader.New(dlLink, filePath, metadata.Data.Sha) - d.Start(ctx) + downloader := downloader.New(dlLink, filePath, metadata.Data.Sha) + downloader.Start(ctx) go func() { - err := <-d.Errors() + err := <-downloader.Errors() if err != nil { log.Printf("download encountered an error: %s\n", err) done <- err @@ -152,7 +152,7 @@ func (i *Importer) Download(ctx context.Context, metadata *Metadata, }() go func() { - for state := range d.Stats() { + for state := range downloader.Stats() { stateFunc(fileName, state.TotalSize, state.Downloaded, state.Percent) if state.Completed { log.Println("download completed") @@ -172,16 +172,16 @@ func (i *Importer) Cleanup() error { func (i *Importer) ExtractAndStoreFiles() error { zipPath := filepath.Join(i.tempDir, i.dataFileName) - r, err := zip.OpenReader(zipPath) + reader, err := zip.OpenReader(zipPath) if err != nil { return fmt.Errorf("failed to open zip file: %w", err) } defer func() { - _ = r.Close() + _ = reader.Close() }() - for _, f := range r.File { - if err := i.extractAndWriteFile(f); err != nil { + for _, file := range reader.File { + if err := i.extractAndWriteFile(file); err != nil { return err } } @@ -189,21 +189,21 @@ func (i *Importer) ExtractAndStoreFiles() error { return nil } -func (i *Importer) extractAndWriteFile(f *zip.File) error { - rc, err := f.Open() +func (i *Importer) extractAndWriteFile(file *zip.File) error { + reader, err := file.Open() if err != nil { return fmt.Errorf("failed to open file in zip archive: %w", err) } defer func() { - _ = rc.Close() + _ = reader.Close() }() - fPath, err := util.SanitizeArchivePath(i.tempDir, f.Name) + fPath, err := util.SanitizeArchivePath(i.tempDir, file.Name) if err != nil { return fmt.Errorf("failed to make archive path: %w", err) } - if f.FileInfo().IsDir() { + if file.FileInfo().IsDir() { return util.Mkdir(fPath) } @@ -220,7 +220,7 @@ func (i *Importer) extractAndWriteFile(f *zip.File) error { }() // Use a limited reader to prevent DoS attacks via decompression bomb - lr := &io.LimitedReader{R: rc, N: maxDecompressedSize} + lr := &io.LimitedReader{R: reader, N: maxDecompressedSize} written, err := io.Copy(outFile, lr) if err != nil { return fmt.Errorf("failed to copy file contents: %w", err) diff --git a/cmd/shell/main.go b/cmd/shell/main.go index ed858be9c..e0f20a1f1 100644 --- a/cmd/shell/main.go +++ b/cmd/shell/main.go @@ -37,7 +37,7 @@ func main() { Long: `pactus-shell is a command line tool for interacting with the Pactus blockchain using gRPC`, } - sh := shell.New(rootCmd, nil, + shell := shell.New(rootCmd, nil, prompt.OptionSuggestionBGColor(prompt.Black), prompt.OptionSuggestionTextColor(prompt.Green), prompt.OptionDescriptionBGColor(prompt.Black), @@ -50,14 +50,14 @@ func main() { fs.StringVar(&password, namer("auth-password"), "", "password for gRPC basic authentication") }) - sh.Flags().StringVar(&serverAddr, "server-addr", defaultServerAddr, "gRPC server address") - sh.Flags().StringVar(&username, "auth-username", "", + shell.Flags().StringVar(&serverAddr, "server-addr", defaultServerAddr, "gRPC server address") + shell.Flags().StringVar(&username, "auth-username", "", "username for gRPC basic authentication") - sh.Flags().StringVar(&password, "auth-password", "", + shell.Flags().StringVar(&password, "auth-password", "", "username for gRPC basic authentication") - sh.PreRun = func(_ *cobra.Command, _ []string) { + shell.PreRun = func(_ *cobra.Command, _ []string) { cls() cmd.PrintInfoMsgf("Welcome to PactusBlockchain shell\n\n- Home: https://pactus.org\n- " + "Docs: https://docs.pactus.org") @@ -65,7 +65,7 @@ func main() { _prefix = fmt.Sprintf("pactus@%s > ", serverAddr) } - sh.PersistentPreRun = func(cmd *cobra.Command, _ []string) { + shell.PersistentPreRun = func(cmd *cobra.Command, _ []string) { setAuthContext(cmd, username, password) } @@ -73,14 +73,14 @@ func main() { setAuthContext(cmd, username, password) } - changeDefaultParameters := func(c *cobra.Command) *cobra.Command { - _ = c.PersistentFlags().Lookup("server-addr").Value.Set(defaultServerAddr) - c.PersistentFlags().Lookup("server-addr").DefValue = defaultServerAddr + changeDefaultParameters := func(cobra *cobra.Command) *cobra.Command { + _ = cobra.PersistentFlags().Lookup("server-addr").Value.Set(defaultServerAddr) + cobra.PersistentFlags().Lookup("server-addr").DefValue = defaultServerAddr - _ = c.PersistentFlags().Lookup("response-format").Value.Set(defaultResponseFormat) - c.PersistentFlags().Lookup("response-format").DefValue = defaultResponseFormat + _ = cobra.PersistentFlags().Lookup("response-format").Value.Set(defaultResponseFormat) + cobra.PersistentFlags().Lookup("response-format").DefValue = defaultResponseFormat - return c + return cobra } rootCmd.AddCommand(changeDefaultParameters(pb.BlockchainClientCommand())) @@ -88,7 +88,7 @@ func main() { rootCmd.AddCommand(changeDefaultParameters(pb.TransactionClientCommand())) rootCmd.AddCommand(changeDefaultParameters(pb.WalletClientCommand())) rootCmd.AddCommand(clearScreen()) - rootCmd.AddCommand(sh) + rootCmd.AddCommand(shell) err := rootCmd.Execute() if err != nil { diff --git a/cmd/wallet/history.go b/cmd/wallet/history.go index 4fd8306c7..6245c70f7 100644 --- a/cmd/wallet/history.go +++ b/cmd/wallet/history.go @@ -64,13 +64,13 @@ func buildShowHistoryCmd(parentCmd *cobra.Command) { cmd.FatalErrorCheck(err) history := wlt.History(addr) - for i, h := range history { - if h.Time != nil { + for i, item := range history { + if item.Time != nil { cmd.PrintInfoMsgf("%d %v %v %v %s\t%v", - i+1, h.Time.Format(time.RFC822), h.TxID, h.PayloadType, h.Desc, h.Amount) + i+1, item.Time.Format(time.RFC822), item.TxID, item.PayloadType, item.Desc, item.Amount) } else { cmd.PrintInfoMsgf("%d %v %s\t%v", - i+1, h.TxID, h.Desc, h.Amount) + i+1, item.TxID, item.Desc, item.Amount) } } } diff --git a/cmd/wallet/tx.go b/cmd/wallet/tx.go index ea8a428f1..674206169 100644 --- a/cmd/wallet/tx.go +++ b/cmd/wallet/tx.go @@ -35,8 +35,8 @@ func buildTransferTxCmd(parentCmd *cobra.Command) { passOpt := addPasswordOption(transferCmd) transferCmd.Run = func(_ *cobra.Command, args []string) { - from := args[0] - to := args[1] + sender := args[0] + receiver := args[1] amt, err := amount.FromString(args[2]) cmd.FatalErrorCheck(err) @@ -52,13 +52,13 @@ func buildTransferTxCmd(parentCmd *cobra.Command) { wallet.OptionMemo(*memoOpt), } - trx, err := wlt.MakeTransferTx(from, to, amt, opts...) + trx, err := wlt.MakeTransferTx(sender, receiver, amt, opts...) cmd.FatalErrorCheck(err) cmd.PrintLine() cmd.PrintInfoMsgf("You are going to sign this \033[1mTransfer\033[0m transition:") - cmd.PrintInfoMsgf("From : %s", from) - cmd.PrintInfoMsgf("To : %s", to) + cmd.PrintInfoMsgf("From : %s", sender) + cmd.PrintInfoMsgf("To : %s", receiver) cmd.PrintInfoMsgf("Amount: %s", amt) cmd.PrintInfoMsgf("Fee : %s", trx.Fee()) cmd.PrintInfoMsgf("Memo : %s", trx.Memo()) @@ -81,8 +81,8 @@ func buildBondTxCmd(parentCmd *cobra.Command) { passOpt := addPasswordOption(bondCmd) bondCmd.Run = func(_ *cobra.Command, args []string) { - from := args[0] - to := args[1] + sender := args[0] + receiver := args[1] amt, err := amount.FromString(args[2]) cmd.FatalErrorCheck(err) @@ -98,13 +98,13 @@ func buildBondTxCmd(parentCmd *cobra.Command) { wallet.OptionMemo(*memoOpt), } - trx, err := wlt.MakeBondTx(from, to, *pubKeyOpt, amt, opts...) + trx, err := wlt.MakeBondTx(sender, receiver, *pubKeyOpt, amt, opts...) cmd.FatalErrorCheck(err) cmd.PrintLine() cmd.PrintInfoMsgf("You are going to sign this \033[1mBond\033[0m transition:") - cmd.PrintInfoMsgf("Account : %s", from) - cmd.PrintInfoMsgf("Validator: %s", to) + cmd.PrintInfoMsgf("Account : %s", sender) + cmd.PrintInfoMsgf("Validator: %s", receiver) cmd.PrintInfoMsgf("Stake : %s", amt) cmd.PrintInfoMsgf("Fee : %s", trx.Fee()) cmd.PrintInfoMsgf("Memo : %s", trx.Memo()) @@ -166,8 +166,8 @@ func buildWithdrawTxCmd(parentCmd *cobra.Command) { passOpt := addPasswordOption(withdrawCmd) withdrawCmd.Run = func(_ *cobra.Command, args []string) { - from := args[0] - to := args[1] + sender := args[0] + receiver := args[1] amt, err := amount.FromString(args[2]) cmd.FatalErrorCheck(err) @@ -183,13 +183,13 @@ func buildWithdrawTxCmd(parentCmd *cobra.Command) { wallet.OptionMemo(*memoOpt), } - trx, err := wlt.MakeWithdrawTx(from, to, amt, opts...) + trx, err := wlt.MakeWithdrawTx(sender, receiver, amt, opts...) cmd.FatalErrorCheck(err) cmd.PrintLine() cmd.PrintInfoMsgf("You are going to sign this \033[1mWithdraw\033[0m transition:") - cmd.PrintInfoMsgf("Validator: %s", from) - cmd.PrintInfoMsgf("Account : %s", to) + cmd.PrintInfoMsgf("Validator: %s", sender) + cmd.PrintInfoMsgf("Account : %s", receiver) cmd.PrintInfoMsgf("Amount : %s", amt) cmd.PrintInfoMsgf("Fee : %s", trx.Fee()) cmd.PrintInfoMsgf("Memo : %s", trx.Memo()) @@ -198,17 +198,17 @@ func buildWithdrawTxCmd(parentCmd *cobra.Command) { } } -func addCommonTxOptions(c *cobra.Command) (*int, *float64, *string, *bool) { - lockTimeOpt := c.Flags().Int("lock-time", 0, +func addCommonTxOptions(cobra *cobra.Command) (*int, *float64, *string, *bool) { + lockTimeOpt := cobra.Flags().Int("lock-time", 0, "transaction lock-time, if not specified will be the current height") - feeOpt := c.Flags().Float64("fee", 0, + feeOpt := cobra.Flags().Float64("fee", 0, "transaction fee in PAC, if not specified will calculate from the amount") - memoOpt := c.Flags().String("memo", "", + memoOpt := cobra.Flags().String("memo", "", "transaction memo, maximum should be 64 character") - noConfirmOpt := c.Flags().Bool("no-confirm", false, + noConfirmOpt := cobra.Flags().Bool("no-confirm", false, "no confirmation question") return lockTimeOpt, feeOpt, memoOpt, noConfirmOpt diff --git a/committee/committee.go b/committee/committee.go index 614442b5d..5a91bf5de 100644 --- a/committee/committee.go +++ b/committee/committee.go @@ -43,14 +43,14 @@ func NewCommittee(validators []*validator.Validator, committeeSize int, } func (c *committee) TotalPower() int64 { - p := int64(0) + power := int64(0) c.iterate(func(v *validator.Validator) bool { - p += v.Power() + power += v.Power() return false }) - return p + return power } func (c *committee) Update(lastRound int16, joined []*validator.Validator) { @@ -97,14 +97,14 @@ func (c *committee) Update(lastRound int16, joined []*validator.Validator) { } adjust := c.validatorList.Length() - c.committeeSize - for n := 0; n < adjust; n++ { - if oldestFirst[n] == c.proposerPos { + for j := 0; j < adjust; j++ { + if oldestFirst[j] == c.proposerPos { c.proposerPos = c.proposerPos.Next if c.proposerPos == nil { c.proposerPos = c.validatorList.Head } } - c.validatorList.Delete(oldestFirst[n]) + c.validatorList.Delete(oldestFirst[j]) } } diff --git a/config/config_test.go b/config/config_test.go index a849eb807..34d6e3df4 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -157,7 +157,7 @@ func TestNodeConfigBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) randValAddr := ts.RandValAddress() - testCases := []struct { + tests := []struct { name string expectedErr error updateFn func(c *NodeConfig) @@ -205,17 +205,18 @@ func TestNodeConfigBasicCheck(t *testing.T) { }, } - for i, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { + for no, tt := range tests { + t.Run(tt.name, func(t *testing.T) { conf := DefaultNodeConfig() - tc.updateFn(conf) - if tc.expectedErr != nil { + tt.updateFn(conf) + if tt.expectedErr != nil { err := conf.BasicCheck() - assert.ErrorIs(t, tc.expectedErr, err, - "Expected error not matched for test %d-%s, expected: %s, got: %s", i, tc.name, tc.expectedErr, err) + assert.ErrorIs(t, tt.expectedErr, err, + "Expected error not matched for test %d-%s, expected: %s, got: %s", + no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() - assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", i, tc.name, err) + assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } diff --git a/consensus/config_test.go b/consensus/config_test.go index 49a2f61f6..7620bfc4e 100644 --- a/consensus/config_test.go +++ b/consensus/config_test.go @@ -8,7 +8,7 @@ import ( ) func TestConfigBasicCheck(t *testing.T) { - testCases := []struct { + tests := []struct { name string expectedErr error updateFn func(c *Config) @@ -55,17 +55,17 @@ func TestConfigBasicCheck(t *testing.T) { }, } - for i, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { + for no, tt := range tests { + t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() - tc.updateFn(conf) - if tc.expectedErr != nil { + tt.updateFn(conf) + if tt.expectedErr != nil { err := conf.BasicCheck() - assert.ErrorIs(t, tc.expectedErr, err, - "Expected error not matched for test %d-%s, expected: %s, got: %s", i, tc.name, tc.expectedErr, err) + assert.ErrorIs(t, tt.expectedErr, err, + "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() - assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", i, tc.name, err) + assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } diff --git a/consensus/consensus.go b/consensus/consensus.go index 0f9d4bd43..e01d499eb 100644 --- a/consensus/consensus.go +++ b/consensus/consensus.go @@ -76,7 +76,7 @@ func makeConsensus( broadcaster broadcaster, mediator mediator, ) *consensus { - cs := &consensus{ + cons := &consensus{ config: conf, bcState: bcState, broadcaster: broadcaster, @@ -84,34 +84,34 @@ func makeConsensus( } // Update height later, See enterNewHeight. - cs.log = log.NewLog() - cs.logger = logger.NewSubLogger("_consensus", cs) - cs.rewardAddr = rewardAddr - - cs.changeProposer = &changeProposer{cs} - cs.newHeightState = &newHeightState{cs} - cs.proposeState = &proposeState{cs} - cs.prepareState = &prepareState{cs, false} - cs.precommitState = &precommitState{cs, false} - cs.commitState = &commitState{cs} - cs.cpPreVoteState = &cpPreVoteState{cs.changeProposer} - cs.cpMainVoteState = &cpMainVoteState{cs.changeProposer} - cs.cpDecideState = &cpDecideState{cs.changeProposer} - cs.currentState = cs.newHeightState - cs.mediator = mediator - - cs.height = 0 - cs.round = 0 - cs.active = false - cs.mediator = mediator - - mediator.Register(cs) + cons.log = log.NewLog() + cons.logger = logger.NewSubLogger("_consensus", cons) + cons.rewardAddr = rewardAddr + + cons.changeProposer = &changeProposer{cons} + cons.newHeightState = &newHeightState{cons} + cons.proposeState = &proposeState{cons} + cons.prepareState = &prepareState{cons, false} + cons.precommitState = &precommitState{cons, false} + cons.commitState = &commitState{cons} + cons.cpPreVoteState = &cpPreVoteState{cons.changeProposer} + cons.cpMainVoteState = &cpMainVoteState{cons.changeProposer} + cons.cpDecideState = &cpDecideState{cons.changeProposer} + cons.currentState = cons.newHeightState + cons.mediator = mediator + + cons.height = 0 + cons.round = 0 + cons.active = false + cons.mediator = mediator + + mediator.Register(cons) logger.Info("consensus instance created", "validator address", valKey.Address().String(), "reward address", rewardAddr.String()) - return cs + return cons } func (cs *consensus) Start() { @@ -184,34 +184,34 @@ func (cs *consensus) moveToNewHeight() { } func (cs *consensus) scheduleTimeout(duration time.Duration, height uint32, round int16, target tickerTarget) { - ti := &ticker{duration, height, round, target} + ticker := &ticker{duration, height, round, target} timer := time.NewTimer(duration) cs.logger.Trace("new timer scheduled ⏱️", "duration", duration, "height", height, "round", round, "target", target) go func() { <-timer.C - cs.handleTimeout(ti) + cs.handleTimeout(ticker) }() } -func (cs *consensus) handleTimeout(t *ticker) { +func (cs *consensus) handleTimeout(ticker *ticker) { cs.lk.Lock() defer cs.lk.Unlock() - cs.logger.Trace("handle ticker", "ticker", t) + cs.logger.Trace("handle ticker", "ticker", ticker) // Old tickers might be triggered now. Ignore them. - if cs.height != t.Height || cs.round != t.Round { - cs.logger.Trace("stale ticker", "ticker", t) + if cs.height != ticker.Height || cs.round != ticker.Round { + cs.logger.Trace("stale ticker", "ticker", ticker) return } - cs.logger.Debug("timer expired", "ticker", t) - cs.currentState.onTimeout(t) + cs.logger.Debug("timer expired", "ticker", ticker) + cs.currentState.onTimeout(ticker) } -func (cs *consensus) SetProposal(p *proposal.Proposal) { +func (cs *consensus) SetProposal(prop *proposal.Proposal) { cs.lk.Lock() defer cs.lk.Unlock() @@ -219,62 +219,62 @@ func (cs *consensus) SetProposal(p *proposal.Proposal) { return } - if p.Height() != cs.height { + if prop.Height() != cs.height { return } - if p.Round() < cs.round { - cs.logger.Debug("proposal for expired round", "proposal", p) + if prop.Round() < cs.round { + cs.logger.Debug("proposal for expired round", "proposal", prop) return } - if err := p.BasicCheck(); err != nil { - cs.logger.Warn("invalid proposal", "proposal", p, "error", err) + if err := prop.BasicCheck(); err != nil { + cs.logger.Warn("invalid proposal", "proposal", prop, "error", err) return } - roundProposal := cs.log.RoundProposal(p.Round()) + roundProposal := cs.log.RoundProposal(prop.Round()) if roundProposal != nil { - cs.logger.Trace("this round has proposal", "proposal", p) + cs.logger.Trace("this round has proposal", "proposal", prop) return } - if p.Height() == cs.bcState.LastBlockHeight() { + if prop.Height() == cs.bcState.LastBlockHeight() { // A slow node might receive a proposal after committing the proposed block. // In this case, we accept the proposal and allow nodes to continue. // By doing so, we enable the validator to broadcast its votes and // prevent it from being marked as absent in the block certificate. - cs.logger.Warn("block committed before receiving proposal", "proposal", p) - if p.Block().Hash() != cs.bcState.LastBlockHash() { - cs.logger.Warn("proposal is not for the committed block", "proposal", p) + cs.logger.Warn("block committed before receiving proposal", "proposal", prop) + if prop.Block().Hash() != cs.bcState.LastBlockHash() { + cs.logger.Warn("proposal is not for the committed block", "proposal", prop) return } } else { - proposer := cs.proposer(p.Round()) - if err := p.Verify(proposer.PublicKey()); err != nil { - cs.logger.Warn("proposal is invalid", "proposal", p, "error", err) + proposer := cs.proposer(prop.Round()) + if err := prop.Verify(proposer.PublicKey()); err != nil { + cs.logger.Warn("proposal is invalid", "proposal", prop, "error", err) return } - if err := cs.bcState.ValidateBlock(p.Block(), p.Round()); err != nil { - cs.logger.Warn("invalid block", "proposal", p, "error", err) + if err := cs.bcState.ValidateBlock(prop.Block(), prop.Round()); err != nil { + cs.logger.Warn("invalid block", "proposal", prop, "error", err) return } } - cs.logger.Info("proposal set", "proposal", p) - cs.log.SetRoundProposal(p.Round(), p) + cs.logger.Info("proposal set", "proposal", prop) + cs.log.SetRoundProposal(prop.Round(), prop) - cs.currentState.onSetProposal(p) + cs.currentState.onSetProposal(prop) } -func (cs *consensus) AddVote(v *vote.Vote) { +func (cs *consensus) AddVote(vte *vote.Vote) { cs.lk.Lock() defer cs.lk.Unlock() @@ -282,39 +282,39 @@ func (cs *consensus) AddVote(v *vote.Vote) { return } - if v.Height() != cs.height { + if vte.Height() != cs.height { return } - if v.Round() < cs.round { - cs.logger.Debug("vote for expired round", "vote", v) + if vte.Round() < cs.round { + cs.logger.Debug("vote for expired round", "vote", vte) return } - if v.Type() == vote.VoteTypeCPPreVote || - v.Type() == vote.VoteTypeCPMainVote || - v.Type() == vote.VoteTypeCPDecided { - err := cs.changeProposer.checkJust(v) + if vte.Type() == vote.VoteTypeCPPreVote || + vte.Type() == vote.VoteTypeCPMainVote || + vte.Type() == vote.VoteTypeCPDecided { + err := cs.changeProposer.checkJust(vte) if err != nil { - cs.logger.Error("error on adding a cp vote", "vote", v, "error", err) + cs.logger.Error("error on adding a cp vote", "vote", vte, "error", err) return } } - added, err := cs.log.AddVote(v) + added, err := cs.log.AddVote(vte) if err != nil { - cs.logger.Error("error on adding a vote", "vote", v, "error", err) + cs.logger.Error("error on adding a vote", "vote", vte, "error", err) } if added { - cs.logger.Info("new vote added", "vote", v) + cs.logger.Info("new vote added", "vote", vte) - cs.currentState.onAddVote(v) + cs.currentState.onAddVote(vte) - if v.Type() == vote.VoteTypeCPDecided { - if v.Round() > cs.round { - cs.changeProposer.cpDecide(v.Round(), v.CPValue()) + if vte.Type() == vote.VoteTypeCPDecided { + if vte.Round() > cs.round { + cs.changeProposer.cpDecide(vte.Round(), vte.CPValue()) } } } @@ -369,16 +369,16 @@ func (cs *consensus) signAddPrecommitVote(h hash.Hash) { cs.signAddVote(v) } -func (cs *consensus) signAddVote(v *vote.Vote) { - sig := cs.valKey.Sign(v.SignBytes()) - v.SetSignature(sig) - cs.logger.Info("our vote signed and broadcasted", "vote", v) +func (cs *consensus) signAddVote(vte *vote.Vote) { + sig := cs.valKey.Sign(vte.SignBytes()) + vte.SetSignature(sig) + cs.logger.Info("our vote signed and broadcasted", "vote", vte) - _, err := cs.log.AddVote(v) + _, err := cs.log.AddVote(vte) if err != nil { - cs.logger.Warn("error on adding our vote", "error", err, "vote", v) + cs.logger.Warn("error on adding our vote", "error", err, "vote", vte) } - cs.broadcastVote(v) + cs.broadcastVote(vte) } // queryProposal requests any missing proposal from other validators. @@ -430,9 +430,9 @@ func (cs *consensus) signersInfo(votes map[crypto.Address]*vote.Vote) ([]int32, sigs := make([]*bls.Signature, 0) for i, val := range vals { - vte := votes[val.Address()] - if vte != nil { - sigs = append(sigs, vte.Signature()) + vote := votes[val.Address()] + if vote != nil { + sigs = append(sigs, vote.Signature()) } else { absentees = append(absentees, val.Number()) } diff --git a/consensus/consensus_test.go b/consensus/consensus_test.go index 3a1af2996..21aeee152 100644 --- a/consensus/consensus_test.go +++ b/consensus/consensus_test.go @@ -93,16 +93,16 @@ func setupWithSeed(t *testing.T, seed int64) *testData { getTime := util.RoundNow(params.BlockIntervalInSecond). Add(time.Duration(params.BlockIntervalInSecond) * time.Second) genDoc := genesis.MakeGenesis(getTime, accs, vals, params) - stX, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexX]}, + stateX, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexX]}, store.MockingStore(ts), txPool, nil) require.NoError(t, err) - stY, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexY]}, + stateY, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexY]}, store.MockingStore(ts), txPool, nil) require.NoError(t, err) - stB, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexB]}, + stateB, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexB]}, store.MockingStore(ts), txPool, nil) require.NoError(t, err) - stP, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexP]}, + stateP, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexP]}, store.MockingStore(ts), txPool, nil) require.NoError(t, err) @@ -121,13 +121,13 @@ func setupWithSeed(t *testing.T, seed int64) *testData { message: msg, }) } - td.consX = makeConsensus(testConfig(), stX, valKeys[tIndexX], + td.consX = makeConsensus(testConfig(), stateX, valKeys[tIndexX], valKeys[tIndexX].PublicKey().AccountAddress(), broadcasterFunc, newConcreteMediator()) - td.consY = makeConsensus(testConfig(), stY, valKeys[tIndexY], + td.consY = makeConsensus(testConfig(), stateY, valKeys[tIndexY], valKeys[tIndexY].PublicKey().AccountAddress(), broadcasterFunc, newConcreteMediator()) - td.consB = makeConsensus(testConfig(), stB, valKeys[tIndexB], + td.consB = makeConsensus(testConfig(), stateB, valKeys[tIndexB], valKeys[tIndexB].PublicKey().AccountAddress(), broadcasterFunc, newConcreteMediator()) - td.consP = makeConsensus(testConfig(), stP, valKeys[tIndexP], + td.consP = makeConsensus(testConfig(), stateP, valKeys[tIndexP], valKeys[tIndexP].PublicKey().AccountAddress(), broadcasterFunc, newConcreteMediator()) // ------------------------------- @@ -148,14 +148,14 @@ func setupWithSeed(t *testing.T, seed int64) *testData { return td } -func (td *testData) shouldPublishBlockAnnounce(t *testing.T, cons *consensus, h hash.Hash) { +func (td *testData) shouldPublishBlockAnnounce(t *testing.T, cons *consensus, hash hash.Hash) { t.Helper() for _, consMsg := range td.consMessages { if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeBlockAnnounce { m := consMsg.message.(*message.BlockAnnounceMessage) - assert.Equal(t, h, m.Block.Hash()) + assert.Equal(t, hash, m.Block.Hash()) return } @@ -231,7 +231,7 @@ func (td *testData) shouldPublishQueryVote(t *testing.T, cons *consensus, height require.NoError(t, fmt.Errorf("Not found")) } -func (td *testData) shouldPublishVote(t *testing.T, cons *consensus, voteType vote.Type, h hash.Hash) *vote.Vote { +func (td *testData) shouldPublishVote(t *testing.T, cons *consensus, voteType vote.Type, hash hash.Hash) *vote.Vote { t.Helper() for i := len(td.consMessages) - 1; i >= 0; i-- { @@ -240,7 +240,7 @@ func (td *testData) shouldPublishVote(t *testing.T, cons *consensus, voteType vo consMsg.message.Type() == message.TypeVote { m := consMsg.message.(*message.VoteMessage) if m.Vote.Type() == voteType && - m.Vote.BlockHash() == h { + m.Vote.BlockHash() == hash { return m.Vote } } @@ -346,11 +346,11 @@ func (td *testData) commitBlockForAllStates(t *testing.T) (*block.Block, *certif prop := td.makeProposal(t, height+1, 0) cert := certificate.NewBlockCertificate(height+1, 0) - sb := cert.SignBytes(prop.Block().Hash()) - sig1 := td.consX.valKey.Sign(sb) - sig2 := td.consY.valKey.Sign(sb) - sig3 := td.consB.valKey.Sign(sb) - sig4 := td.consP.valKey.Sign(sb) + signBytes := cert.SignBytes(prop.Block().Hash()) + sig1 := td.consX.valKey.Sign(signBytes) + sig2 := td.consY.valKey.Sign(signBytes) + sig3 := td.consB.valKey.Sign(signBytes) + sig4 := td.consP.valKey.Sign(signBytes) sig := bls.SignatureAggregate(sig1, sig2, sig3, sig4) cert.SetSignature([]int32{tIndexX, tIndexY, tIndexB, tIndexP}, []int32{}, sig) @@ -371,31 +371,31 @@ func (td *testData) commitBlockForAllStates(t *testing.T) (*block.Block, *certif func (td *testData) makeProposal(t *testing.T, height uint32, round int16) *proposal.Proposal { t.Helper() - var p *proposal.Proposal + var prop *proposal.Proposal switch (height % 4) + uint32(round%4) { case 1: blk, err := td.consX.bcState.ProposeBlock(td.consX.valKey, td.consX.rewardAddr) require.NoError(t, err) - p = proposal.NewProposal(height, round, blk) - td.HelperSignProposal(td.consX.valKey, p) + prop = proposal.NewProposal(height, round, blk) + td.HelperSignProposal(td.consX.valKey, prop) case 2: blk, err := td.consY.bcState.ProposeBlock(td.consY.valKey, td.consY.rewardAddr) require.NoError(t, err) - p = proposal.NewProposal(height, round, blk) - td.HelperSignProposal(td.consY.valKey, p) + prop = proposal.NewProposal(height, round, blk) + td.HelperSignProposal(td.consY.valKey, prop) case 3: blk, err := td.consB.bcState.ProposeBlock(td.consB.valKey, td.consB.rewardAddr) require.NoError(t, err) - p = proposal.NewProposal(height, round, blk) - td.HelperSignProposal(td.consB.valKey, p) + prop = proposal.NewProposal(height, round, blk) + td.HelperSignProposal(td.consB.valKey, prop) case 0, 4: blk, err := td.consP.bcState.ProposeBlock(td.consP.valKey, td.consP.rewardAddr) require.NoError(t, err) - p = proposal.NewProposal(height, round, blk) - td.HelperSignProposal(td.consP.valKey, p) + prop = proposal.NewProposal(height, round, blk) + td.HelperSignProposal(td.consP.valKey, prop) } - return p + return prop } func TestStart(t *testing.T) { @@ -409,12 +409,12 @@ func TestNotInCommittee(t *testing.T) { td := setup(t) valKey := td.RandValKey() - str := store.MockingStore(td.TestSuite) + store := store.MockingStore(td.TestSuite) - st, _ := state.LoadOrNewState(td.genDoc, []*bls.ValidatorKey{valKey}, str, td.txPool, nil) - consInst := NewConsensus(testConfig(), st, valKey, valKey.Address(), make(chan message.Message, 100), + state, _ := state.LoadOrNewState(td.genDoc, []*bls.ValidatorKey{valKey}, store, td.txPool, nil) + consInt := NewConsensus(testConfig(), state, valKey, valKey.Address(), make(chan message.Message, 100), newConcreteMediator()) - cons := consInst.(*consensus) + cons := consInt.(*consensus) td.enterNewHeight(cons) td.newHeightTimeout(cons) @@ -458,18 +458,18 @@ func TestConsensusNormalCase(t *testing.T) { td.enterNewHeight(td.consX) td.checkHeightRound(t, td.consX, 2, 0) - p := td.makeProposal(t, 2, 0) - td.consX.SetProposal(p) + prop := td.makeProposal(t, 2, 0) + td.consX.SetProposal(prop) - td.addPrepareVote(td.consX, p.Block().Hash(), 2, 0, tIndexY) - td.addPrepareVote(td.consX, p.Block().Hash(), 2, 0, tIndexP) - td.shouldPublishVote(t, td.consX, vote.VoteTypePrepare, p.Block().Hash()) + td.addPrepareVote(td.consX, prop.Block().Hash(), 2, 0, tIndexY) + td.addPrepareVote(td.consX, prop.Block().Hash(), 2, 0, tIndexP) + td.shouldPublishVote(t, td.consX, vote.VoteTypePrepare, prop.Block().Hash()) - td.addPrecommitVote(td.consX, p.Block().Hash(), 2, 0, tIndexY) - td.addPrecommitVote(td.consX, p.Block().Hash(), 2, 0, tIndexP) - td.shouldPublishVote(t, td.consX, vote.VoteTypePrecommit, p.Block().Hash()) + td.addPrecommitVote(td.consX, prop.Block().Hash(), 2, 0, tIndexY) + td.addPrecommitVote(td.consX, prop.Block().Hash(), 2, 0, tIndexP) + td.shouldPublishVote(t, td.consX, vote.VoteTypePrecommit, prop.Block().Hash()) - td.shouldPublishBlockAnnounce(t, td.consX, p.Block().Hash()) + td.shouldPublishBlockAnnounce(t, td.consX, prop.Block().Hash()) } func TestConsensusAddVote(t *testing.T) { @@ -478,23 +478,23 @@ func TestConsensusAddVote(t *testing.T) { td.enterNewHeight(td.consP) td.enterNextRound(td.consP) - v1 := td.addPrepareVote(td.consP, td.RandHash(), 1, 0, tIndexX) - v2 := td.addPrepareVote(td.consP, td.RandHash(), 1, 2, tIndexX) - v3 := td.addPrepareVote(td.consP, td.RandHash(), 1, 1, tIndexX) - v4 := td.addPrecommitVote(td.consP, td.RandHash(), 1, 1, tIndexX) - v5 := td.addPrepareVote(td.consP, td.RandHash(), 2, 0, tIndexX) - v6, _ := td.GenerateTestPrepareVote(1, 0) - td.consP.AddVote(v6) - - assert.False(t, td.consP.HasVote(v1.Hash())) // previous round - assert.True(t, td.consP.HasVote(v2.Hash())) // next round - assert.True(t, td.consP.HasVote(v3.Hash())) - assert.True(t, td.consP.HasVote(v4.Hash())) - assert.False(t, td.consP.HasVote(v5.Hash())) // valid votes for the next height - assert.False(t, td.consP.HasVote(v6.Hash())) // invalid votes - - assert.Equal(t, []*vote.Vote{v3, v4}, td.consP.AllVotes()) - assert.NotContains(t, td.consP.AllVotes(), v2) + vote1 := td.addPrepareVote(td.consP, td.RandHash(), 1, 0, tIndexX) + vote2 := td.addPrepareVote(td.consP, td.RandHash(), 1, 2, tIndexX) + vote3 := td.addPrepareVote(td.consP, td.RandHash(), 1, 1, tIndexX) + vote4 := td.addPrecommitVote(td.consP, td.RandHash(), 1, 1, tIndexX) + vote5 := td.addPrepareVote(td.consP, td.RandHash(), 2, 0, tIndexX) + vote6, _ := td.GenerateTestPrepareVote(1, 0) + td.consP.AddVote(vote6) + + assert.False(t, td.consP.HasVote(vote1.Hash())) // previous round + assert.True(t, td.consP.HasVote(vote2.Hash())) // next round + assert.True(t, td.consP.HasVote(vote3.Hash())) + assert.True(t, td.consP.HasVote(vote4.Hash())) + assert.False(t, td.consP.HasVote(vote5.Hash())) // valid votes for the next height + assert.False(t, td.consP.HasVote(vote6.Hash())) // invalid votes + + assert.Equal(t, []*vote.Vote{vote3, vote4}, td.consP.AllVotes()) + assert.NotContains(t, td.consP.AllVotes(), vote2) } // TestConsensusLateProposal tests the scenario where a slow node receives a proposal @@ -506,17 +506,17 @@ func TestConsensusLateProposal(t *testing.T) { td.enterNewHeight(td.consP) - h := uint32(2) - r := int16(0) - p := td.makeProposal(t, h, r) - require.NotNil(t, p) + height := uint32(2) + round := int16(0) + prop := td.makeProposal(t, height, round) + require.NotNil(t, prop) td.commitBlockForAllStates(t) // height 2 // Partitioned node receives proposal now - td.consP.SetProposal(p) + td.consP.SetProposal(prop) - td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, p.Block().Hash()) + td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, prop.Block().Hash()) } // TestSetProposalOnPrepare tests the scenario where a slow node receives a proposal @@ -528,20 +528,20 @@ func TestSetProposalOnPrepare(t *testing.T) { td.enterNewHeight(td.consP) - h := uint32(2) - r := int16(0) - p := td.makeProposal(t, h, r) - require.NotNil(t, p) + height := uint32(2) + round := int16(0) + prop := td.makeProposal(t, height, round) + require.NotNil(t, prop) // The partitioned node receives all the votes first - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexY) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexB) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) // Partitioned node receives proposal now - td.consP.SetProposal(p) + td.consP.SetProposal(prop) - td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, p.Block().Hash()) + td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) } // TestSetProposalOnPrecommit tests the scenario where a slow node receives a proposal @@ -553,25 +553,25 @@ func TestSetProposalOnPrecommit(t *testing.T) { td.enterNewHeight(td.consP) - h := uint32(2) - r := int16(0) - p := td.makeProposal(t, h, r) - require.NotNil(t, p) + height := uint32(2) + round := int16(0) + prop := td.makeProposal(t, height, round) + require.NotNil(t, prop) // The partitioned node receives all the votes first - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexY) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexB) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) - td.addPrecommitVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrecommitVote(td.consP, p.Block().Hash(), h, r, tIndexY) - td.addPrecommitVote(td.consP, p.Block().Hash(), h, r, tIndexB) + td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexY) + td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexB) // Partitioned node receives proposal now - td.consP.SetProposal(p) + td.consP.SetProposal(prop) - td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, p.Block().Hash()) - td.shouldPublishBlockAnnounce(t, td.consP, p.Block().Hash()) + td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) + td.shouldPublishBlockAnnounce(t, td.consP, prop.Block().Hash()) } func TestHandleQueryVote(t *testing.T) { @@ -584,13 +584,13 @@ func TestHandleQueryVote(t *testing.T) { // === make valid certificate preVoteCommitters := []int32{} preVoteSigs := []*bls.Signature{} - for i, val := range td.consP.validators { + for index, val := range td.consP.validators { preVoteJust := &vote.JustInitYes{} preVote := vote.NewCPPreVote(hash.UndefHash, 1, 0, cpRound, vote.CPValueYes, preVoteJust, val.Address()) sbPreVote := preVote.SignBytes() preVoteCommitters = append(preVoteCommitters, val.Number()) - preVoteSigs = append(preVoteSigs, td.valKeys[i].Sign(sbPreVote)) + preVoteSigs = append(preVoteSigs, td.valKeys[index].Sign(sbPreVote)) } preVoteAggSig := bls.SignatureAggregate(preVoteSigs...) certPreVote := certificate.NewVoteCertificate(1, 0) @@ -598,7 +598,7 @@ func TestHandleQueryVote(t *testing.T) { mainVoteCommitters := []int32{} mainVoteSigs := []*bls.Signature{} - for i, val := range td.consP.validators { + for index, val := range td.consP.validators { mainVoteJust := &vote.JustMainVoteNoConflict{ QCert: certPreVote, } @@ -606,7 +606,7 @@ func TestHandleQueryVote(t *testing.T) { sbMainVote := mainVote.SignBytes() mainVoteCommitters = append(mainVoteCommitters, val.Number()) - mainVoteSigs = append(mainVoteSigs, td.valKeys[i].Sign(sbMainVote)) + mainVoteSigs = append(mainVoteSigs, td.valKeys[index].Sign(sbMainVote)) } mainVoteAggSig := bls.SignatureAggregate(mainVoteSigs...) certMainVote := certificate.NewVoteCertificate(1, 0) @@ -706,30 +706,30 @@ func TestDuplicateProposal(t *testing.T) { td.enterNewHeight(td.consX) - h := uint32(4) - r := int16(0) - p1 := td.makeProposal(t, h, r) - trx := tx.NewTransferTx(h, td.consX.rewardAddr, td.RandAccAddress(), 1000, + height := uint32(4) + round := int16(0) + prop1 := td.makeProposal(t, height, round) + trx := tx.NewTransferTx(height, td.consX.rewardAddr, td.RandAccAddress(), 1000, 1000, tx.WithMemo("proposal changer")) td.HelperSignTransaction(td.consX.valKey.PrivateKey(), trx) assert.NoError(t, td.txPool.AppendTx(trx)) - p2 := td.makeProposal(t, h, r) - assert.NotEqual(t, p1.Hash(), p2.Hash()) + p2 := td.makeProposal(t, height, round) + assert.NotEqual(t, prop1.Hash(), p2.Hash()) - td.consX.SetProposal(p1) + td.consX.SetProposal(prop1) td.consX.SetProposal(p2) - assert.Equal(t, p1.Hash(), td.consX.Proposal().Hash()) + assert.Equal(t, prop1.Hash(), td.consX.Proposal().Hash()) } func TestNonActiveValidator(t *testing.T) { td := setup(t) valKey := td.RandValKey() - consInst := NewConsensus(testConfig(), state.MockingState(td.TestSuite), + consInt := NewConsensus(testConfig(), state.MockingState(td.TestSuite), valKey, valKey.Address(), make(chan message.Message, 100), newConcreteMediator()) - nonActiveCons := consInst.(*consensus) + nonActiveCons := consInt.(*consensus) t.Run("non-active instances should be in new-height state", func(t *testing.T) { nonActiveCons.MoveToNewHeight() @@ -796,9 +796,9 @@ func TestInvalidProposal(t *testing.T) { td.enterNewHeight(td.consP) - p := td.makeProposal(t, 1, 0) - p.SetSignature(nil) // Make proposal invalid - td.consP.SetProposal(p) + prop := td.makeProposal(t, 1, 0) + prop.SetSignature(nil) // Make proposal invalid + td.consP.SetProposal(prop) assert.Nil(t, td.consP.Proposal()) } @@ -815,8 +815,8 @@ func TestCases(t *testing.T) { {1697887970998950590, 1, "consP & consB: Change Proposer, consX & consY: Commit (2 block announces)"}, } - for i, test := range tests { - td := setupWithSeed(t, test.seed) + for no, tt := range tests { + td := setupWithSeed(t, tt.seed) td.commitBlockForAllStates(t) td.enterNewHeight(td.consX) @@ -826,10 +826,10 @@ func TestCases(t *testing.T) { cert, err := checkConsensus(td, 2, nil) require.NoError(t, err, - "test %v failed: %s", i+1, err) - require.Equal(t, test.round, cert.Round(), + "test %v failed: %s", no+1, err) + require.Equal(t, tt.round, cert.Round(), "test %v failed. round not matched (expected %d, got %d)", - i+1, test.round, cert.Round()) + no+1, tt.round, cert.Round()) } } @@ -866,20 +866,20 @@ func TestByzantine(t *testing.T) { td.commitBlockForAllStates(t) } - h := uint32(7) - r := int16(0) - p1 := td.makeProposal(t, h, r) + height := uint32(7) + round := int16(0) + prop1 := td.makeProposal(t, height, round) // ================================= // X, Y votes td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) - td.consX.SetProposal(p1) - td.consY.SetProposal(p1) + td.consX.SetProposal(prop1) + td.consY.SetProposal(prop1) - voteX := td.shouldPublishVote(t, td.consX, vote.VoteTypePrepare, p1.Block().Hash()) - voteY := td.shouldPublishVote(t, td.consY, vote.VoteTypePrepare, p1.Block().Hash()) + voteX := td.shouldPublishVote(t, td.consX, vote.VoteTypePrepare, prop1.Block().Hash()) + voteY := td.shouldPublishVote(t, td.consY, vote.VoteTypePrepare, prop1.Block().Hash()) // Byzantine node doesn't broadcast the prepare vote // X and Y request to change proposer @@ -896,38 +896,38 @@ func TestByzantine(t *testing.T) { // B votes td.enterNewHeight(td.consB) - td.consB.SetProposal(p1) + td.consB.SetProposal(prop1) td.consB.AddVote(voteX) td.consB.AddVote(voteY) - td.shouldPublishVote(t, td.consB, vote.VoteTypePrepare, p1.Block().Hash()) - td.shouldPublishVote(t, td.consB, vote.VoteTypePrecommit, p1.Block().Hash()) + td.shouldPublishVote(t, td.consB, vote.VoteTypePrepare, prop1.Block().Hash()) + td.shouldPublishVote(t, td.consB, vote.VoteTypePrecommit, prop1.Block().Hash()) td.changeProposerTimeout(td.consB) // B requests to NOT change the proposer - byzVote1 := td.shouldPublishVote(t, td.consB, vote.VoteTypeCPPreVote, p1.Block().Hash()) + byzVote1 := td.shouldPublishVote(t, td.consB, vote.VoteTypeCPPreVote, prop1.Block().Hash()) // ================================= // P votes // Byzantine node create the second proposal and send it to the partitioned node P - byzTrx := tx.NewTransferTx(h, + byzTrx := tx.NewTransferTx(height, td.consB.rewardAddr, td.RandAccAddress(), 1000, 1000) td.HelperSignTransaction(td.consB.valKey.PrivateKey(), byzTrx) assert.NoError(t, td.txPool.AppendTx(byzTrx)) - p2 := td.makeProposal(t, h, r) + prop2 := td.makeProposal(t, height, round) - require.NotEqual(t, p1.Block().Hash(), p2.Block().Hash()) - require.Equal(t, td.consB.valKey.Address(), p1.Block().Header().ProposerAddress()) - require.Equal(t, td.consB.valKey.Address(), p2.Block().Header().ProposerAddress()) + require.NotEqual(t, prop1.Block().Hash(), prop2.Block().Hash()) + require.Equal(t, td.consB.valKey.Address(), prop1.Block().Header().ProposerAddress()) + require.Equal(t, td.consB.valKey.Address(), prop2.Block().Header().ProposerAddress()) td.enterNewHeight(td.consP) // P receives the Seconds proposal - td.consP.SetProposal(p2) + td.consP.SetProposal(prop2) - td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, p2.Block().Hash()) - byzVote2 := td.addPrepareVote(td.consP, p2.Block().Hash(), h, r, tIndexB) + td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, prop2.Block().Hash()) + byzVote2 := td.addPrepareVote(td.consP, prop2.Block().Hash(), height, round, tIndexB) // Request to change proposer td.changeProposerTimeout(td.consP) @@ -938,9 +938,9 @@ func TestByzantine(t *testing.T) { // ================================= - td.checkHeightRound(t, td.consX, h, r) - td.checkHeightRound(t, td.consY, h, r) - td.checkHeightRound(t, td.consP, h, r) + td.checkHeightRound(t, td.consX, height, round) + td.checkHeightRound(t, td.consY, height, round) + td.checkHeightRound(t, td.consP, height, round) // Let's make Byzantine node happy by removing his votes from the log for j := len(td.consMessages) - 1; j >= 0; j-- { @@ -952,10 +952,10 @@ func TestByzantine(t *testing.T) { // ================================= // Now, Partition heals fmt.Println("== Partition heals") - cert, err := checkConsensus(td, h, []*vote.Vote{byzVote1, byzVote2}) + cert, err := checkConsensus(td, height, []*vote.Vote{byzVote1, byzVote2}) require.NoError(t, err) - require.Equal(t, h, cert.Height()) + require.Equal(t, height, cert.Height()) require.Contains(t, cert.Absentees(), int32(tIndexB)) } diff --git a/consensus/cp.go b/consensus/cp.go index b23256ca9..1756b9933 100644 --- a/consensus/cp.go +++ b/consensus/cp.go @@ -23,16 +23,16 @@ func (cp *changeProposer) onTimeout(t *ticker) { } } -func (*changeProposer) checkCPValue(vte *vote.Vote, allowedValues ...vote.CPValue) error { +func (*changeProposer) checkCPValue(vote *vote.Vote, allowedValues ...vote.CPValue) error { for _, v := range allowedValues { - if vte.CPValue() == v { + if vote.CPValue() == v { return nil } } return InvalidJustificationError{ - JustType: vte.CPJust().Type(), - Reason: fmt.Sprintf("invalid value: %v", vte.CPValue()), + JustType: vote.CPJust().Type(), + Reason: fmt.Sprintf("invalid value: %v", vote.CPValue()), } } @@ -191,20 +191,20 @@ func (cp *changeProposer) checkJustMainVoteConflict(just vote.Just, } //nolint:exhaustive // refactor me; check just by just_type, not vote_type -func (cp *changeProposer) checkJustPreVote(v *vote.Vote) error { - just := v.CPJust() - if v.CPRound() == 0 { +func (cp *changeProposer) checkJustPreVote(vte *vote.Vote) error { + just := vte.CPJust() + if vte.CPRound() == 0 { switch just.Type() { case vote.JustTypeInitNo: - err := cp.checkCPValue(v, vote.CPValueNo) + err := cp.checkCPValue(vte, vote.CPValueNo) if err != nil { return err } - return cp.checkJustInitZero(just, v.BlockHash()) + return cp.checkJustInitZero(just, vte.BlockHash()) case vote.JustTypeInitYes: - err := cp.checkCPValue(v, vote.CPValueYes) + err := cp.checkCPValue(vte, vote.CPValueYes) if err != nil { return err } @@ -219,20 +219,20 @@ func (cp *changeProposer) checkJustPreVote(v *vote.Vote) error { } else { switch just.Type() { case vote.JustTypePreVoteSoft: - err := cp.checkCPValue(v, vote.CPValueNo, vote.CPValueYes) + err := cp.checkCPValue(vte, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } - return cp.checkJustPreVoteSoft(just, v.BlockHash(), v.CPRound()) + return cp.checkJustPreVoteSoft(just, vte.BlockHash(), vte.CPRound()) case vote.JustTypePreVoteHard: - err := cp.checkCPValue(v, vote.CPValueNo, vote.CPValueYes) + err := cp.checkCPValue(vte, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } - return cp.checkJustPreVoteHard(just, v.BlockHash(), v.CPRound(), v.CPValue()) + return cp.checkJustPreVoteHard(just, vte.BlockHash(), vte.CPRound(), vte.CPValue()) default: return InvalidJustificationError{ @@ -244,24 +244,24 @@ func (cp *changeProposer) checkJustPreVote(v *vote.Vote) error { } //nolint:exhaustive // refactor me; check just by just_type, not vote_type -func (cp *changeProposer) checkJustMainVote(v *vote.Vote) error { - just := v.CPJust() +func (cp *changeProposer) checkJustMainVote(vte *vote.Vote) error { + just := vte.CPJust() switch just.Type() { case vote.JustTypeMainVoteNoConflict: - err := cp.checkCPValue(v, vote.CPValueNo, vote.CPValueYes) + err := cp.checkCPValue(vte, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } - return cp.checkJustMainVoteNoConflict(just, v.BlockHash(), v.CPRound(), v.CPValue()) + return cp.checkJustMainVoteNoConflict(just, vte.BlockHash(), vte.CPRound(), vte.CPValue()) case vote.JustTypeMainVoteConflict: - err := cp.checkCPValue(v, vote.CPValueAbstain) + err := cp.checkCPValue(vte, vote.CPValueAbstain) if err != nil { return err } - return cp.checkJustMainVoteConflict(just, v.BlockHash(), v.CPRound()) + return cp.checkJustMainVoteConflict(just, vte.BlockHash(), vte.CPRound()) default: return InvalidJustificationError{ @@ -271,12 +271,12 @@ func (cp *changeProposer) checkJustMainVote(v *vote.Vote) error { } } -func (cp *changeProposer) checkJustDecide(v *vote.Vote) error { - err := cp.checkCPValue(v, vote.CPValueNo, vote.CPValueYes) +func (cp *changeProposer) checkJustDecide(vte *vote.Vote) error { + err := cp.checkCPValue(vte, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } - j, ok := v.CPJust().(*vote.JustDecided) + j, ok := vte.CPJust().(*vote.JustDecided) if !ok { return InvalidJustificationError{ JustType: j.Type(), @@ -285,7 +285,7 @@ func (cp *changeProposer) checkJustDecide(v *vote.Vote) error { } err = j.QCert.ValidateCPMainVote(cp.validators, - v.BlockHash(), v.CPRound(), byte(v.CPValue())) + vte.BlockHash(), vte.CPRound(), byte(vte.CPValue())) if err != nil { return InvalidJustificationError{ JustType: j.Type(), @@ -297,14 +297,14 @@ func (cp *changeProposer) checkJustDecide(v *vote.Vote) error { } //nolint:exhaustive // refactor me; check just by just_type, not vote_type -func (cp *changeProposer) checkJust(v *vote.Vote) error { - switch v.Type() { +func (cp *changeProposer) checkJust(vte *vote.Vote) error { + switch vte.Type() { case vote.VoteTypeCPPreVote: - return cp.checkJustPreVote(v) + return cp.checkJustPreVote(vte) case vote.VoteTypeCPMainVote: - return cp.checkJustMainVote(v) + return cp.checkJustMainVote(vte) case vote.VoteTypeCPDecided: - return cp.checkJustDecide(v) + return cp.checkJustDecide(vte) default: panic("unreachable") } diff --git a/consensus/cp_test.go b/consensus/cp_test.go index 83953c8ff..4398db819 100644 --- a/consensus/cp_test.go +++ b/consensus/cp_test.go @@ -37,23 +37,23 @@ func TestSetProposalAfterChangeProposer(t *testing.T) { func TestChangeProposerAgreement1(t *testing.T) { td := setup(t) - h := uint32(1) - r := int16(0) + height := uint32(1) + round := int16(0) td.enterNewHeight(td.consP) - td.checkHeightRound(t, td.consP, h, r) + td.checkHeightRound(t, td.consP, height, round) td.changeProposerTimeout(td.consP) preVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) - td.addCPPreVote(td.consP, hash.UndefHash, h, r, vote.CPValueYes, preVote0.CPJust(), tIndexX) - td.addCPPreVote(td.consP, hash.UndefHash, h, r, vote.CPValueYes, preVote0.CPJust(), tIndexY) + td.addCPPreVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, preVote0.CPJust(), tIndexX) + td.addCPPreVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, preVote0.CPJust(), tIndexY) mainVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPMainVote, hash.UndefHash) - td.addCPMainVote(td.consP, hash.UndefHash, h, r, vote.CPValueYes, mainVote0.CPJust(), tIndexX) - td.addCPMainVote(td.consP, hash.UndefHash, h, r, vote.CPValueYes, mainVote0.CPJust(), tIndexY) + td.addCPMainVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, mainVote0.CPJust(), tIndexX) + td.addCPMainVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, mainVote0.CPJust(), tIndexY) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPDecided, hash.UndefHash) - td.checkHeightRound(t, td.consP, h, r+1) + td.checkHeightRound(t, td.consP, height, round+1) } func TestChangeProposerAgreement0(t *testing.T) { @@ -61,33 +61,33 @@ func TestChangeProposerAgreement0(t *testing.T) { td.commitBlockForAllStates(t) // height 1 - h := uint32(2) - r := int16(1) + height := uint32(2) + round := int16(1) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) - td.checkHeightRound(t, td.consP, h, r) + td.checkHeightRound(t, td.consP, height, round) - p := td.makeProposal(t, h, r) + prop := td.makeProposal(t, height, round) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexY) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexB) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) td.changeProposerTimeout(td.consP) - preVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, p.Block().Hash()) - td.addCPPreVote(td.consP, p.Block().Hash(), h, r, vote.CPValueNo, preVote0.CPJust(), tIndexX) - td.addCPPreVote(td.consP, p.Block().Hash(), h, r, vote.CPValueNo, preVote0.CPJust(), tIndexY) + preVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, prop.Block().Hash()) + td.addCPPreVote(td.consP, prop.Block().Hash(), height, round, vote.CPValueNo, preVote0.CPJust(), tIndexX) + td.addCPPreVote(td.consP, prop.Block().Hash(), height, round, vote.CPValueNo, preVote0.CPJust(), tIndexY) - mainVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPMainVote, p.Block().Hash()) - td.addCPMainVote(td.consP, p.Block().Hash(), h, r, vote.CPValueNo, mainVote0.CPJust(), tIndexX) - td.addCPMainVote(td.consP, p.Block().Hash(), h, r, vote.CPValueNo, mainVote0.CPJust(), tIndexY) + mainVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPMainVote, prop.Block().Hash()) + td.addCPMainVote(td.consP, prop.Block().Hash(), height, round, vote.CPValueNo, mainVote0.CPJust(), tIndexX) + td.addCPMainVote(td.consP, prop.Block().Hash(), height, round, vote.CPValueNo, mainVote0.CPJust(), tIndexY) - td.shouldPublishVote(t, td.consP, vote.VoteTypeCPDecided, p.Block().Hash()) - td.shouldPublishQueryProposal(t, td.consP, h) - td.addPrecommitVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrecommitVote(td.consP, p.Block().Hash(), h, r, tIndexY) - td.checkHeightRound(t, td.consP, h, r) + td.shouldPublishVote(t, td.consP, vote.VoteTypeCPDecided, prop.Block().Hash()) + td.shouldPublishQueryProposal(t, td.consP, height) + td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexY) + td.checkHeightRound(t, td.consP, height, round) } // ConsP receives all PRE-VOTE:0 votes before receiving a proposal or prepare votes. @@ -97,29 +97,29 @@ func TestCrashOnTestnet(t *testing.T) { td.commitBlockForAllStates(t) // height 1 - h := uint32(2) - r := int16(0) + height := uint32(2) + round := int16(0) td.consP.MoveToNewHeight() blockHash := td.RandHash() - v1 := vote.NewPrepareVote(blockHash, h, r, td.consX.valKey.Address()) - v2 := vote.NewPrepareVote(blockHash, h, r, td.consY.valKey.Address()) - v3 := vote.NewPrepareVote(blockHash, h, r, td.consB.valKey.Address()) + vote1 := vote.NewPrepareVote(blockHash, height, round, td.consX.valKey.Address()) + vote2 := vote.NewPrepareVote(blockHash, height, round, td.consY.valKey.Address()) + vote3 := vote.NewPrepareVote(blockHash, height, round, td.consB.valKey.Address()) - td.HelperSignVote(td.consX.valKey, v1) - td.HelperSignVote(td.consY.valKey, v2) - td.HelperSignVote(td.consB.valKey, v3) + td.HelperSignVote(td.consX.valKey, vote1) + td.HelperSignVote(td.consY.valKey, vote2) + td.HelperSignVote(td.consB.valKey, vote3) votes := map[crypto.Address]*vote.Vote{} - votes[v1.Signer()] = v1 - votes[v2.Signer()] = v2 - votes[v3.Signer()] = v3 + votes[vote1.Signer()] = vote1 + votes[vote2.Signer()] = vote2 + votes[vote3.Signer()] = vote3 qCert := td.consP.makeVoteCertificate(votes) just0 := &vote.JustInitNo{QCert: qCert} - td.addCPPreVote(td.consP, blockHash, h, r, vote.CPValueNo, just0, tIndexX) - td.addCPPreVote(td.consP, blockHash, h, r, vote.CPValueNo, just0, tIndexY) - td.addCPPreVote(td.consP, blockHash, h, r, vote.CPValueNo, just0, tIndexB) + td.addCPPreVote(td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexX) + td.addCPPreVote(td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexY) + td.addCPPreVote(td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexB) td.newHeightTimeout(td.consP) td.changeProposerTimeout(td.consP) @@ -134,14 +134,14 @@ func TestInvalidJustInitOne(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) - h := uint32(1) - r := int16(0) + height := uint32(1) + round := int16(0) just := &vote.JustInitYes{} t.Run("invalid value: no", func(t *testing.T) { - v := vote.NewCPPreVote(hash.UndefHash, h, r, 0, vote.CPValueNo, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: no", @@ -149,9 +149,9 @@ func TestInvalidJustInitOne(t *testing.T) { }) t.Run("invalid block hash", func(t *testing.T) { - v := vote.NewCPPreVote(hash.UndefHash, h, r, 1, vote.CPValueYes, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, 1, vote.CPValueYes, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", @@ -160,9 +160,9 @@ func TestInvalidJustInitOne(t *testing.T) { t.Run("with main-vote justification", func(t *testing.T) { invJust := &vote.JustMainVoteNoConflict{} - v := vote.NewCPPreVote(td.RandHash(), h, r, 0, vote.CPValueYes, invJust, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueYes, invJust, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: invJust.Type(), Reason: "invalid pre-vote justification", @@ -174,14 +174,14 @@ func TestInvalidJustInitZero(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) - h := uint32(1) - r := int16(0) + height := uint32(1) + round := int16(0) just := &vote.JustInitNo{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), } t.Run("invalid value: yes", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 0, vote.CPValueYes, just, td.consB.valKey.Address()) + v := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) assert.ErrorIs(t, err, InvalidJustificationError{ @@ -191,9 +191,9 @@ func TestInvalidJustInitZero(t *testing.T) { }) t.Run("cp-round should be zero", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 1, vote.CPValueNo, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", @@ -201,9 +201,9 @@ func TestInvalidJustInitZero(t *testing.T) { }) t.Run("invalid certificate", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 0, vote.CPValueNo, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), @@ -215,16 +215,16 @@ func TestInvalidJustPreVoteHard(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) - h := uint32(1) - r := int16(0) + height := uint32(1) + round := int16(0) just := &vote.JustPreVoteHard{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: abstain", @@ -232,9 +232,9 @@ func TestInvalidJustPreVoteHard(t *testing.T) { }) t.Run("cp-round should not be zero", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 0, vote.CPValueNo, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", @@ -242,9 +242,9 @@ func TestInvalidJustPreVoteHard(t *testing.T) { }) t.Run("invalid certificate", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 1, vote.CPValueNo, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), @@ -256,16 +256,16 @@ func TestInvalidJustPreVoteSoft(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) - h := uint32(1) - r := int16(0) + height := uint32(1) + round := int16(0) just := &vote.JustPreVoteSoft{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: abstain", @@ -273,9 +273,9 @@ func TestInvalidJustPreVoteSoft(t *testing.T) { }) t.Run("cp-round should not be zero", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 0, vote.CPValueNo, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", @@ -283,9 +283,9 @@ func TestInvalidJustPreVoteSoft(t *testing.T) { }) t.Run("invalid certificate", func(t *testing.T) { - v := vote.NewCPPreVote(td.RandHash(), h, r, 1, vote.CPValueNo, just, td.consB.valKey.Address()) + cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), @@ -297,14 +297,14 @@ func TestInvalidJustMainVoteNoConflict(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) - h := uint32(1) - r := int16(0) + height := uint32(1) + round := int16(0) just := &vote.JustMainVoteNoConflict{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { - v := vote.NewCPMainVote(td.RandHash(), h, r, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) + v := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) assert.ErrorIs(t, err, InvalidJustificationError{ @@ -314,9 +314,9 @@ func TestInvalidJustMainVoteNoConflict(t *testing.T) { }) t.Run("invalid certificate", func(t *testing.T) { - v := vote.NewCPMainVote(td.RandHash(), h, r, 1, vote.CPValueNo, just, td.consB.valKey.Address()) + cpVote := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), @@ -328,17 +328,17 @@ func TestInvalidJustMainVoteConflict(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) - h := uint32(1) - r := int16(0) + height := uint32(1) + round := int16(0) t.Run("invalid value: no", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustInitNo{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), }, JustYes: &vote.JustInitYes{}, } - v := vote.NewCPMainVote(td.RandHash(), h, r, 0, vote.CPValueNo, just, td.consB.valKey.Address()) + v := vote.NewCPMainVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) assert.ErrorIs(t, err, InvalidJustificationError{ @@ -350,11 +350,11 @@ func TestInvalidJustMainVoteConflict(t *testing.T) { t.Run("invalid value: yes", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustInitNo{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), }, JustYes: &vote.JustInitYes{}, } - v := vote.NewCPMainVote(td.RandHash(), h, r, 0, vote.CPValueYes, just, td.consB.valKey.Address()) + v := vote.NewCPMainVote(td.RandHash(), height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) assert.ErrorIs(t, err, InvalidJustificationError{ @@ -366,11 +366,11 @@ func TestInvalidJustMainVoteConflict(t *testing.T) { t.Run("invalid value: unexpected justification (just0)", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustPreVoteSoft{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), }, JustYes: &vote.JustInitYes{}, } - v := vote.NewCPMainVote(td.RandHash(), h, r, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) + v := vote.NewCPMainVote(td.RandHash(), height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) assert.ErrorIs(t, err, InvalidJustificationError{ @@ -382,13 +382,13 @@ func TestInvalidJustMainVoteConflict(t *testing.T) { t.Run("invalid value: unexpected justification", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustInitNo{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), }, JustYes: &vote.JustPreVoteSoft{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), }, } - v := vote.NewCPMainVote(td.RandHash(), h, r, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) + v := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) assert.ErrorIs(t, err, InvalidJustificationError{ @@ -399,15 +399,15 @@ func TestInvalidJustMainVoteConflict(t *testing.T) { t.Run("invalid certificate", func(t *testing.T) { just0 := &vote.JustInitNo{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), } just := &vote.JustMainVoteConflict{ JustNo: just0, JustYes: &vote.JustInitYes{}, } - v := vote.NewCPMainVote(td.RandHash(), h, r, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) + cpVote := vote.NewCPMainVote(td.RandHash(), height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just0.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just0.QCert.Committers()), @@ -416,17 +416,17 @@ func TestInvalidJustMainVoteConflict(t *testing.T) { t.Run("invalid certificate", func(t *testing.T) { just0 := &vote.JustPreVoteSoft{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), } just := &vote.JustMainVoteConflict{ JustNo: just0, JustYes: &vote.JustPreVoteSoft{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), }, } - v := vote.NewCPMainVote(td.RandHash(), h, r, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) + cpVote := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) - err := td.consX.changeProposer.checkJust(v) + err := td.consX.changeProposer.checkJust(cpVote) assert.ErrorIs(t, err, InvalidJustificationError{ JustType: just0.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just0.QCert.Committers()), @@ -438,14 +438,14 @@ func TestInvalidJustDecided(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) - h := uint32(1) - r := int16(0) + height := uint32(1) + round := int16(0) just := &vote.JustDecided{ - QCert: td.GenerateTestPrepareCertificate(h), + QCert: td.GenerateTestPrepareCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { - v := vote.NewCPDecidedVote(td.RandHash(), h, r, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) + v := vote.NewCPDecidedVote(td.RandHash(), height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) assert.ErrorIs(t, err, InvalidJustificationError{ @@ -455,7 +455,7 @@ func TestInvalidJustDecided(t *testing.T) { }) t.Run("invalid certificate", func(t *testing.T) { - v := vote.NewCPDecidedVote(td.RandHash(), h, r, 0, vote.CPValueYes, just, td.consB.valKey.Address()) + v := vote.NewCPDecidedVote(td.RandHash(), height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) assert.ErrorIs(t, err, InvalidJustificationError{ diff --git a/consensus/height_test.go b/consensus/height_test.go index b1f0f4eeb..4f53b01ed 100644 --- a/consensus/height_test.go +++ b/consensus/height_test.go @@ -13,14 +13,14 @@ func TestNewHeightTimeout(t *testing.T) { td.enterNewHeight(td.consY) td.commitBlockForAllStates(t) - s := &newHeightState{td.consY} - s.enter() + consState := &newHeightState{td.consY} + consState.enter() // Invalid target - s.onTimeout(&ticker{Height: 2, Target: -1}) + consState.onTimeout(&ticker{Height: 2, Target: -1}) td.checkHeightRound(t, td.consY, 2, 0) - s.onTimeout(&ticker{Height: 2, Target: tickerTargetNewHeight}) + consState.onTimeout(&ticker{Height: 2, Target: tickerTargetNewHeight}) td.checkHeightRound(t, td.consY, 2, 0) td.shouldPublishProposal(t, td.consY, 2, 0) } @@ -47,15 +47,15 @@ func TestNewHeightTimeBehindNetwork(t *testing.T) { td.commitBlockForAllStates(t) td.consP.MoveToNewHeight() - h := uint32(2) - r := int16(0) - p := td.makeProposal(t, h, r) + height := uint32(2) + round := int16(0) + prop := td.makeProposal(t, height, round) - td.consP.SetProposal(p) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexY) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexB) + td.consP.SetProposal(prop) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) - td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, p.Block().Hash()) - td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, p.Block().Hash()) + td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, prop.Block().Hash()) + td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) } diff --git a/consensus/interface.go b/consensus/interface.go index 27543f552..0a90dbe41 100644 --- a/consensus/interface.go +++ b/consensus/interface.go @@ -24,7 +24,7 @@ type Consensus interface { Start() MoveToNewHeight() - AddVote(vte *vote.Vote) + AddVote(vote *vote.Vote) SetProposal(prop *proposal.Proposal) } @@ -43,6 +43,6 @@ type Manager interface { Start() error Stop() MoveToNewHeight() - AddVote(vte *vote.Vote) + AddVote(vote *vote.Vote) SetProposal(prop *proposal.Proposal) } diff --git a/consensus/log/log.go b/consensus/log/log.go index 87834bf7e..33c1ba7c6 100644 --- a/consensus/log/log.go +++ b/consensus/log/log.go @@ -36,55 +36,55 @@ func (log *Log) HasVote(h hash.Hash) bool { } func (log *Log) mustGetRoundMessages(round int16) *Messages { - rm, ok := log.roundMessages[round] + msgs, ok := log.roundMessages[round] if !ok { - rm = &Messages{ + msgs = &Messages{ prepareVotes: voteset.NewPrepareVoteSet(round, log.totalPower, log.validators), precommitVotes: voteset.NewPrecommitVoteSet(round, log.totalPower, log.validators), cpPreVotes: voteset.NewCPPreVoteVoteSet(round, log.totalPower, log.validators), cpMainVotes: voteset.NewCPMainVoteVoteSet(round, log.totalPower, log.validators), cpDecidedVotes: voteset.NewCPDecidedVoteSet(round, log.totalPower, log.validators), } - log.roundMessages[round] = rm + log.roundMessages[round] = msgs } - return rm + return msgs } func (log *Log) AddVote(v *vote.Vote) (bool, error) { - m := log.mustGetRoundMessages(v.Round()) + msgs := log.mustGetRoundMessages(v.Round()) - return m.addVote(v) + return msgs.addVote(v) } func (log *Log) PrepareVoteSet(round int16) *voteset.BlockVoteSet { - m := log.mustGetRoundMessages(round) + msgs := log.mustGetRoundMessages(round) - return m.prepareVotes + return msgs.prepareVotes } func (log *Log) PrecommitVoteSet(round int16) *voteset.BlockVoteSet { - m := log.mustGetRoundMessages(round) + msgs := log.mustGetRoundMessages(round) - return m.precommitVotes + return msgs.precommitVotes } func (log *Log) CPPreVoteVoteSet(round int16) *voteset.BinaryVoteSet { - m := log.mustGetRoundMessages(round) + msgs := log.mustGetRoundMessages(round) - return m.cpPreVotes + return msgs.cpPreVotes } func (log *Log) CPMainVoteVoteSet(round int16) *voteset.BinaryVoteSet { - m := log.mustGetRoundMessages(round) + msgs := log.mustGetRoundMessages(round) - return m.cpMainVotes + return msgs.cpMainVotes } func (log *Log) CPDecidedVoteSet(round int16) *voteset.BinaryVoteSet { - m := log.mustGetRoundMessages(round) + msgs := log.mustGetRoundMessages(round) - return m.cpDecidedVotes + return msgs.cpDecidedVotes } func (log *Log) HasRoundProposal(round int16) bool { @@ -101,8 +101,8 @@ func (log *Log) RoundProposal(round int16) *proposal.Proposal { } func (log *Log) SetRoundProposal(round int16, prop *proposal.Proposal) { - m := log.mustGetRoundMessages(round) - m.proposal = prop + msgs := log.mustGetRoundMessages(round) + msgs.proposal = prop } func (log *Log) MoveToNewHeight(validators []*validator.Validator) { diff --git a/consensus/log/log_test.go b/consensus/log/log_test.go index 8658e6980..971b960f2 100644 --- a/consensus/log/log_test.go +++ b/consensus/log/log_test.go @@ -24,20 +24,20 @@ func TestAddValidVote(t *testing.T) { cmt, valKeys := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) - h := ts.RandHeight() - r := ts.RandRound() + height := ts.RandHeight() + round := ts.RandRound() - prepares := log.PrepareVoteSet(r) - precommits := log.PrecommitVoteSet(r) - preVotes := log.CPPreVoteVoteSet(r) - mainVotes := log.CPMainVoteVoteSet(r) + prepares := log.PrepareVoteSet(round) + precommits := log.PrecommitVoteSet(round) + preVotes := log.CPPreVoteVoteSet(round) + mainVotes := log.CPMainVoteVoteSet(round) - v1 := vote.NewPrepareVote(ts.RandHash(), h, r, valKeys[0].Address()) - v2 := vote.NewPrecommitVote(ts.RandHash(), h, r, valKeys[0].Address()) - v3 := vote.NewCPPreVote(ts.RandHash(), h, r, 0, vote.CPValueYes, &vote.JustInitYes{}, valKeys[0].Address()) - v4 := vote.NewCPMainVote(ts.RandHash(), h, r, 0, vote.CPValueNo, &vote.JustInitYes{}, valKeys[0].Address()) + vote1 := vote.NewPrepareVote(ts.RandHash(), height, round, valKeys[0].Address()) + vote2 := vote.NewPrecommitVote(ts.RandHash(), height, round, valKeys[0].Address()) + vote3 := vote.NewCPPreVote(ts.RandHash(), height, round, 0, vote.CPValueYes, &vote.JustInitYes{}, valKeys[0].Address()) + vote4 := vote.NewCPMainVote(ts.RandHash(), height, round, 0, vote.CPValueNo, &vote.JustInitYes{}, valKeys[0].Address()) - for _, v := range []*vote.Vote{v1, v2, v3, v4} { + for _, v := range []*vote.Vote{vote1, vote2, vote3, vote4} { ts.HelperSignVote(valKeys[0], v) added, err := log.AddVote(v) @@ -45,16 +45,16 @@ func TestAddValidVote(t *testing.T) { assert.True(t, added) } - assert.True(t, log.HasVote(v1.Hash())) - assert.True(t, log.HasVote(v2.Hash())) - assert.True(t, log.HasVote(v3.Hash())) - assert.True(t, log.HasVote(v4.Hash())) + assert.True(t, log.HasVote(vote1.Hash())) + assert.True(t, log.HasVote(vote2.Hash())) + assert.True(t, log.HasVote(vote3.Hash())) + assert.True(t, log.HasVote(vote4.Hash())) assert.False(t, log.HasVote(ts.RandHash())) - assert.Contains(t, prepares.AllVotes(), v1) - assert.Contains(t, precommits.AllVotes(), v2) - assert.Contains(t, preVotes.AllVotes(), v3) - assert.Contains(t, mainVotes.AllVotes(), v4) + assert.Contains(t, prepares.AllVotes(), vote1) + assert.Contains(t, precommits.AllVotes(), vote2) + assert.Contains(t, preVotes.AllVotes(), vote3) + assert.Contains(t, mainVotes.AllVotes(), vote4) } func TestAddInvalidVoteType(t *testing.T) { @@ -79,17 +79,18 @@ func TestAddInvalidVoteType(t *testing.T) { func TestSetRoundProposal(t *testing.T) { ts := testsuite.NewTestSuite(t) - cmt, _ := ts.GenerateTestCommittee(4) - prop, _ := ts.GenerateTestProposal(101, 0) + height := ts.RandHeight() + round := ts.RandRound() + + cmt, _ := ts.GenerateTestCommittee(7) + prop := ts.GenerateTestProposal(height, round) log := NewLog() log.MoveToNewHeight(cmt.Validators()) - log.SetRoundProposal(4, prop) - assert.False(t, log.HasRoundProposal(0)) - assert.True(t, log.HasRoundProposal(4)) - assert.True(t, log.HasRoundProposal(4)) - assert.Nil(t, log.RoundProposal(0)) - assert.Nil(t, log.RoundProposal(5)) - assert.Equal(t, prop.Hash(), log.RoundProposal(4).Hash()) + log.SetRoundProposal(round, prop) + assert.False(t, log.HasRoundProposal(round+1)) + assert.True(t, log.HasRoundProposal(round)) + assert.Nil(t, log.RoundProposal(round+1)) + assert.Equal(t, prop.Hash(), log.RoundProposal(round).Hash()) } func TestCanVote(t *testing.T) { diff --git a/consensus/log/messages.go b/consensus/log/messages.go index fa9070a0b..fefa931a7 100644 --- a/consensus/log/messages.go +++ b/consensus/log/messages.go @@ -18,21 +18,21 @@ type Messages struct { proposal *proposal.Proposal } -func (m *Messages) addVote(v *vote.Vote) (bool, error) { - switch v.Type() { +func (m *Messages) addVote(vte *vote.Vote) (bool, error) { + switch vte.Type() { case vote.VoteTypePrepare: - return m.prepareVotes.AddVote(v) + return m.prepareVotes.AddVote(vte) case vote.VoteTypePrecommit: - return m.precommitVotes.AddVote(v) + return m.precommitVotes.AddVote(vte) case vote.VoteTypeCPPreVote: - return m.cpPreVotes.AddVote(v) + return m.cpPreVotes.AddVote(vte) case vote.VoteTypeCPMainVote: - return m.cpMainVotes.AddVote(v) + return m.cpMainVotes.AddVote(vte) case vote.VoteTypeCPDecided: - return m.cpDecidedVotes.AddVote(v) + return m.cpDecidedVotes.AddVote(vte) } - return false, fmt.Errorf("unexpected vote type: %v", v.Type()) + return false, fmt.Errorf("unexpected vote type: %v", vte.Type()) } func (m *Messages) HasVote(h hash.Hash) bool { diff --git a/consensus/manager.go b/consensus/manager.go index 24400c81a..7e114435f 100644 --- a/consensus/manager.go +++ b/consensus/manager.go @@ -27,7 +27,7 @@ type manager struct { // It is not thread-safe. func NewManager( conf *Config, - st state.Facade, + state state.Facade, valKeys []*bls.ValidatorKey, rewardAddrs []crypto.Address, broadcastCh chan message.Message, @@ -36,12 +36,12 @@ func NewManager( instances: make([]Consensus, len(valKeys)), upcomingVotes: make([]*vote.Vote, 0), upcomingProposals: make([]*proposal.Proposal, 0), - state: st, + state: state, } mediatorConcrete := newConcreteMediator() for i, key := range valKeys { - cons := NewConsensus(conf, st, key, rewardAddrs[i], broadcastCh, mediatorConcrete) + cons := NewConsensus(conf, state, key, rewardAddrs[i], broadcastCh, mediatorConcrete) mgr.instances[i] = cons } @@ -119,81 +119,81 @@ func (mgr *manager) MoveToNewHeight() { cons.MoveToNewHeight() } - inst := mgr.getBestInstance() - curHeight, _ := inst.HeightRound() - for i := len(mgr.upcomingProposals) - 1; i >= 0; i-- { - p := mgr.upcomingProposals[i] + cons := mgr.getBestInstance() + curHeight, _ := cons.HeightRound() + for index := len(mgr.upcomingProposals) - 1; index >= 0; index-- { + prop := mgr.upcomingProposals[index] switch { - case p.Height() < curHeight: + case prop.Height() < curHeight: // Ignore old proposals - case p.Height() > curHeight: + case prop.Height() > curHeight: // keep this vote continue - case p.Height() == curHeight: + case prop.Height() == curHeight: logger.Debug("upcoming proposal processed", "height", curHeight) for _, cons := range mgr.instances { - cons.SetProposal(p) + cons.SetProposal(prop) } } - mgr.upcomingProposals = slices.Delete(mgr.upcomingProposals, i, i+1) + mgr.upcomingProposals = slices.Delete(mgr.upcomingProposals, index, index+1) } - for i := len(mgr.upcomingVotes) - 1; i >= 0; i-- { - v := mgr.upcomingVotes[i] + for index := len(mgr.upcomingVotes) - 1; index >= 0; index-- { + vote := mgr.upcomingVotes[index] switch { - case v.Height() < curHeight: + case vote.Height() < curHeight: // Ignore old votes - case v.Height() > curHeight: + case vote.Height() > curHeight: // keep this vote continue - case v.Height() == curHeight: + case vote.Height() == curHeight: logger.Debug("upcoming votes processed", "height", curHeight) for _, cons := range mgr.instances { - cons.AddVote(v) + cons.AddVote(vote) } } - mgr.upcomingVotes = slices.Delete(mgr.upcomingVotes, i, i+1) + mgr.upcomingVotes = slices.Delete(mgr.upcomingVotes, index, index+1) } } // AddVote adds a vote to all consensus instances. -func (mgr *manager) AddVote(v *vote.Vote) { - inst := mgr.getBestInstance() - curHeight, _ := inst.HeightRound() +func (mgr *manager) AddVote(vote *vote.Vote) { + cons := mgr.getBestInstance() + curHeight, _ := cons.HeightRound() switch { - case v.Height() < curHeight: - _ = mgr.state.UpdateLastCertificate(v) + case vote.Height() < curHeight: + _ = mgr.state.UpdateLastCertificate(vote) - case v.Height() > curHeight: - mgr.upcomingVotes = append(mgr.upcomingVotes, v) + case vote.Height() > curHeight: + mgr.upcomingVotes = append(mgr.upcomingVotes, vote) - case v.Height() == curHeight: + case vote.Height() == curHeight: for _, cons := range mgr.instances { - cons.AddVote(v) + cons.AddVote(vote) } } } // SetProposal sets the proposal for all consensus instances. -func (mgr *manager) SetProposal(p *proposal.Proposal) { - inst := mgr.getBestInstance() - curHeight, _ := inst.HeightRound() +func (mgr *manager) SetProposal(prop *proposal.Proposal) { + cons := mgr.getBestInstance() + curHeight, _ := cons.HeightRound() switch { - case p.Height() < curHeight: + case prop.Height() < curHeight: // discard the old proposal - case p.Height() > curHeight: - mgr.upcomingProposals = append(mgr.upcomingProposals, p) + case prop.Height() > curHeight: + mgr.upcomingProposals = append(mgr.upcomingProposals, prop) - case p.Height() == curHeight: + case prop.Height() == curHeight: for _, cons := range mgr.instances { - cons.SetProposal(p) + cons.SetProposal(prop) } } } diff --git a/consensus/manager_test.go b/consensus/manager_test.go index 61c939f47..d0c4c2092 100644 --- a/consensus/manager_test.go +++ b/consensus/manager_test.go @@ -18,19 +18,19 @@ import ( func TestManager(t *testing.T) { ts := testsuite.NewTestSuite(t) - st := state.MockingState(ts) - st.TestCommittee.Validators() + state := state.MockingState(ts) + state.TestCommittee.Validators() rewardAddrs := []crypto.Address{ts.RandAccAddress(), ts.RandAccAddress()} - valKeys := []*bls.ValidatorKey{st.TestValKeys[0], ts.RandValKey()} + valKeys := []*bls.ValidatorKey{state.TestValKeys[0], ts.RandValKey()} broadcastCh := make(chan message.Message, 500) randomHeight := ts.RandHeight() - blk, cert := ts.GenerateTestBlock(randomHeight) - st.TestStore.SaveBlock(blk, cert) + rndBlk, rndCert := ts.GenerateTestBlock(randomHeight) + state.TestStore.SaveBlock(rndBlk, rndCert) - mgrInst := NewManager(testConfig(), st, valKeys, rewardAddrs, broadcastCh) - mgr := mgrInst.(*manager) + mgrInt := NewManager(testConfig(), state, valKeys, rewardAddrs, broadcastCh) + mgr := mgrInt.(*manager) consA := mgr.instances[0].(*consensus) // active consB := mgr.instances[1].(*consensus) // inactive @@ -54,31 +54,31 @@ func TestManager(t *testing.T) { t.Run("Testing add vote", func(t *testing.T) { consHeight, _ := mgr.HeightRound() - v := vote.NewPrepareVote(ts.RandHash(), consHeight, 0, valKeys[0].Address()) - ts.HelperSignVote(valKeys[0], v) + vote := vote.NewPrepareVote(ts.RandHash(), consHeight, 0, valKeys[0].Address()) + ts.HelperSignVote(valKeys[0], vote) - mgr.AddVote(v) + mgr.AddVote(vote) - assert.True(t, consA.HasVote(v.Hash())) - assert.False(t, consB.HasVote(v.Hash())) + assert.True(t, consA.HasVote(vote.Hash())) + assert.False(t, consB.HasVote(vote.Hash())) }) t.Run("Testing set proposal", func(t *testing.T) { consHeight, _ := mgr.HeightRound() - b, _ := st.ProposeBlock(valKeys[0], valKeys[0].Address()) - p := proposal.NewProposal(consHeight, 0, b) - ts.HelperSignProposal(valKeys[0], p) + blk, _ := state.ProposeBlock(valKeys[0], valKeys[0].Address()) + prop := proposal.NewProposal(consHeight, 0, blk) + ts.HelperSignProposal(valKeys[0], prop) - mgr.SetProposal(p) + mgr.SetProposal(prop) - assert.Equal(t, p, consA.Proposal()) + assert.Equal(t, prop, consA.Proposal()) assert.Nil(t, consB.Proposal()) }) t.Run("Check discarding old votes", func(t *testing.T) { consHeight, _ := mgr.HeightRound() - v := vote.NewPrepareVote(ts.RandHash(), consHeight-1, 0, st.TestValKeys[2].Address()) - ts.HelperSignVote(st.TestValKeys[2], v) + v := vote.NewPrepareVote(ts.RandHash(), consHeight-1, 0, state.TestValKeys[2].Address()) + ts.HelperSignVote(state.TestValKeys[2], v) mgr.AddVote(v) assert.Empty(t, mgr.upcomingVotes) @@ -86,36 +86,36 @@ func TestManager(t *testing.T) { t.Run("Check discarding old proposals", func(t *testing.T) { consHeight, _ := mgr.HeightRound() - b, _ := st.ProposeBlock(valKeys[0], valKeys[0].Address()) - p := proposal.NewProposal(consHeight-1, 1, b) - ts.HelperSignProposal(valKeys[0], p) + blk, _ := state.ProposeBlock(valKeys[0], valKeys[0].Address()) + prop := proposal.NewProposal(consHeight-1, 1, blk) + ts.HelperSignProposal(valKeys[0], prop) - mgr.SetProposal(p) + mgr.SetProposal(prop) assert.Empty(t, mgr.upcomingProposals) }) t.Run("Processing upcoming votes", func(t *testing.T) { consHeight, _ := mgr.HeightRound() - v1 := vote.NewPrepareVote(ts.RandHash(), consHeight+1, 0, valKeys[0].Address()) - v2 := vote.NewPrepareVote(ts.RandHash(), consHeight+2, 0, valKeys[0].Address()) - v3 := vote.NewPrepareVote(ts.RandHash(), consHeight+3, 0, valKeys[0].Address()) + vote1 := vote.NewPrepareVote(ts.RandHash(), consHeight+1, 0, valKeys[0].Address()) + vote2 := vote.NewPrepareVote(ts.RandHash(), consHeight+2, 0, valKeys[0].Address()) + vote3 := vote.NewPrepareVote(ts.RandHash(), consHeight+3, 0, valKeys[0].Address()) - ts.HelperSignVote(valKeys[0], v1) - ts.HelperSignVote(valKeys[0], v2) - ts.HelperSignVote(valKeys[0], v3) + ts.HelperSignVote(valKeys[0], vote1) + ts.HelperSignVote(valKeys[0], vote2) + ts.HelperSignVote(valKeys[0], vote3) - mgr.AddVote(v1) - mgr.AddVote(v2) - mgr.AddVote(v3) + mgr.AddVote(vote1) + mgr.AddVote(vote2) + mgr.AddVote(vote3) assert.Len(t, mgr.upcomingVotes, 3) blk1, cert1 := ts.GenerateTestBlock(consHeight) - err := st.CommitBlock(blk1, cert1) + err := state.CommitBlock(blk1, cert1) assert.NoError(t, err) blk2, cert2 := ts.GenerateTestBlock(consHeight + 1) - err = st.CommitBlock(blk2, cert2) + err = state.CommitBlock(blk2, cert2) assert.NoError(t, err) mgr.MoveToNewHeight() @@ -125,31 +125,22 @@ func TestManager(t *testing.T) { t.Run("Processing upcoming proposal", func(t *testing.T) { consHeight, _ := mgr.HeightRound() - b1, _ := st.ProposeBlock(valKeys[0], valKeys[0].Address()) - p1 := proposal.NewProposal(consHeight+1, 0, b1) - - b2, _ := st.ProposeBlock(valKeys[0], valKeys[0].Address()) - p2 := proposal.NewProposal(consHeight+2, 0, b2) - - b3, _ := st.ProposeBlock(valKeys[0], valKeys[0].Address()) - p3 := proposal.NewProposal(consHeight+3, 0, b3) - - ts.HelperSignProposal(valKeys[0], p1) - ts.HelperSignProposal(valKeys[0], p2) - ts.HelperSignProposal(valKeys[0], p3) + prop1 := ts.GenerateTestProposal(consHeight+1, 0) + prop2 := ts.GenerateTestProposal(consHeight+2, 0) + prop3 := ts.GenerateTestProposal(consHeight+3, 0) - mgr.SetProposal(p1) - mgr.SetProposal(p2) - mgr.SetProposal(p3) + mgr.SetProposal(prop1) + mgr.SetProposal(prop2) + mgr.SetProposal(prop3) assert.Len(t, mgr.upcomingProposals, 3) blk1, cert1 := ts.GenerateTestBlock(consHeight) - err := st.CommitBlock(blk1, cert1) + err := state.CommitBlock(blk1, cert1) assert.NoError(t, err) blk2, cert2 := ts.GenerateTestBlock(consHeight + 1) - err = st.CommitBlock(blk2, cert2) + err = state.CommitBlock(blk2, cert2) assert.NoError(t, err) mgr.MoveToNewHeight() @@ -161,10 +152,10 @@ func TestManager(t *testing.T) { func TestMediator(t *testing.T) { ts := testsuite.NewTestSuite(t) - st := state.MockingState(ts) + state := state.MockingState(ts) cmt, valKeys := ts.GenerateTestCommittee(4) - st.TestCommittee = cmt - st.TestParams.BlockIntervalInSecond = 1 + state.TestCommittee = cmt + state.TestParams.BlockIntervalInSecond = 1 rewardAddrs := []crypto.Address{ ts.RandAccAddress(), ts.RandAccAddress(), @@ -174,10 +165,10 @@ func TestMediator(t *testing.T) { stateHeight := ts.RandHeight() blk, cert := ts.GenerateTestBlock(stateHeight) - st.TestStore.SaveBlock(blk, cert) + state.TestStore.SaveBlock(blk, cert) - mgrInst := NewManager(testConfig(), st, valKeys, rewardAddrs, broadcastCh) - mgr := mgrInst.(*manager) + mgrInt := NewManager(testConfig(), state, valKeys, rewardAddrs, broadcastCh) + mgr := mgrInt.(*manager) mgr.MoveToNewHeight() diff --git a/consensus/mediator.go b/consensus/mediator.go index 2091aa442..89932d5c1 100644 --- a/consensus/mediator.go +++ b/consensus/mediator.go @@ -9,7 +9,7 @@ import ( // between independent consensus instances. type mediator interface { OnPublishProposal(from Consensus, prop *proposal.Proposal) - OnPublishVote(from Consensus, vte *vote.Vote) + OnPublishVote(from Consensus, vote *vote.Vote) OnBlockAnnounce(from Consensus) Register(cons Consensus) } @@ -31,10 +31,10 @@ func (m *ConcreteMediator) OnPublishProposal(from Consensus, prop *proposal.Prop } } -func (m *ConcreteMediator) OnPublishVote(from Consensus, vte *vote.Vote) { +func (m *ConcreteMediator) OnPublishVote(from Consensus, vote *vote.Vote) { for _, cons := range m.instances { if cons != from { - cons.AddVote(vte) + cons.AddVote(vote) } } } diff --git a/consensus/mock.go b/consensus/mock.go index 3baed042e..bbb80a171 100644 --- a/consensus/mock.go +++ b/consensus/mock.go @@ -24,13 +24,13 @@ type MockConsensus struct { Round int16 } -func MockingManager(ts *testsuite.TestSuite, st *state.MockState, +func MockingManager(ts *testsuite.TestSuite, state *state.MockState, valKeys []*bls.ValidatorKey, ) (Manager, []*MockConsensus) { mocks := make([]*MockConsensus, len(valKeys)) instances := make([]Consensus, len(valKeys)) for i, key := range valKeys { - cons := MockingConsensus(ts, st, key) + cons := MockingConsensus(ts, state, key) mocks[i] = cons instances[i] = cons } @@ -42,10 +42,10 @@ func MockingManager(ts *testsuite.TestSuite, st *state.MockState, }, mocks } -func MockingConsensus(ts *testsuite.TestSuite, st *state.MockState, valKey *bls.ValidatorKey) *MockConsensus { +func MockingConsensus(ts *testsuite.TestSuite, state *state.MockState, valKey *bls.ValidatorKey) *MockConsensus { return &MockConsensus{ ts: ts, - State: st, + State: state, ValKey: valKey, } } diff --git a/consensus/precommit_test.go b/consensus/precommit_test.go index 20f21afc3..3b0c84781 100644 --- a/consensus/precommit_test.go +++ b/consensus/precommit_test.go @@ -13,61 +13,61 @@ func TestPrecommitQueryProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) - h := uint32(2) - r := int16(0) + height := uint32(2) + round := int16(0) td.enterNewHeight(td.consP) - p := td.makeProposal(t, h, r) + prop := td.makeProposal(t, height, round) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexY) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexB) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) - td.addPrecommitVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrecommitVote(td.consP, p.Block().Hash(), h, r, tIndexY) - td.addPrecommitVote(td.consP, p.Block().Hash(), h, r, tIndexB) + td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexY) + td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexB) - td.shouldPublishQueryProposal(t, td.consP, h) + td.shouldPublishQueryProposal(t, td.consP, height) } func TestPrecommitDuplicatedProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) - h := uint32(2) - r := int16(0) + height := uint32(2) + round := int16(0) - p1 := td.makeProposal(t, h, r) - trx := tx.NewTransferTx(h, td.consX.rewardAddr, + prop1 := td.makeProposal(t, height, round) + trx := tx.NewTransferTx(height, td.consX.rewardAddr, td.RandAccAddress(), 1000, 1000, tx.WithMemo("invalid proposal")) td.HelperSignTransaction(td.consX.valKey.PrivateKey(), trx) assert.NoError(t, td.txPool.AppendTx(trx)) - p2 := td.makeProposal(t, h, r) - assert.NotEqual(t, p1.Hash(), p2.Hash()) + prop2 := td.makeProposal(t, height, round) + assert.NotEqual(t, prop1.Hash(), prop2.Hash()) td.enterNewHeight(td.consP) // Byzantine node sends second proposal to Partitioned node // in prepare step - td.consP.SetProposal(p2) + td.consP.SetProposal(prop2) assert.NotNil(t, td.consP.Proposal()) - td.addPrepareVote(td.consP, p1.Block().Hash(), h, r, tIndexX) - td.addPrepareVote(td.consP, p1.Block().Hash(), h, r, tIndexY) - td.addPrepareVote(td.consP, p1.Block().Hash(), h, r, tIndexB) + td.addPrepareVote(td.consP, prop1.Block().Hash(), height, round, tIndexX) + td.addPrepareVote(td.consP, prop1.Block().Hash(), height, round, tIndexY) + td.addPrepareVote(td.consP, prop1.Block().Hash(), height, round, tIndexB) assert.Nil(t, td.consP.Proposal()) - td.shouldPublishQueryProposal(t, td.consP, h) + td.shouldPublishQueryProposal(t, td.consP, height) // Byzantine node sends second proposal to Partitioned node, // in precommit step - td.consP.SetProposal(p2) + td.consP.SetProposal(prop2) assert.Nil(t, td.consP.Proposal()) - td.shouldPublishQueryProposal(t, td.consP, h) + td.shouldPublishQueryProposal(t, td.consP, height) - td.consP.SetProposal(p1) + td.consP.SetProposal(prop1) assert.NotNil(t, td.consP.Proposal()) } @@ -75,18 +75,18 @@ func TestGoToChangeProposerFromPrecommit(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) - h := uint32(2) - r := int16(0) + height := uint32(2) + round := int16(0) td.enterNewHeight(td.consP) blockHash := td.RandHash() - td.addPrepareVote(td.consP, blockHash, h, r, tIndexX) - td.addPrepareVote(td.consP, blockHash, h, r, tIndexY) - td.addPrepareVote(td.consP, blockHash, h, r, tIndexB) + td.addPrepareVote(td.consP, blockHash, height, round, tIndexX) + td.addPrepareVote(td.consP, blockHash, height, round, tIndexY) + td.addPrepareVote(td.consP, blockHash, height, round, tIndexB) - td.addCPPreVote(td.consP, hash.UndefHash, h, r, vote.CPValueYes, &vote.JustInitYes{}, tIndexX) - td.addCPPreVote(td.consP, hash.UndefHash, h, r, vote.CPValueYes, &vote.JustInitYes{}, tIndexY) + td.addCPPreVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, &vote.JustInitYes{}, tIndexX) + td.addCPPreVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, &vote.JustInitYes{}, tIndexY) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, blockHash) } diff --git a/consensus/prepare.go b/consensus/prepare.go index 6643d7286..9b6a2eff1 100644 --- a/consensus/prepare.go +++ b/consensus/prepare.go @@ -59,8 +59,8 @@ func (s *prepareState) vote() { s.hasVoted = true } -func (s *prepareState) onTimeout(t *ticker) { - if t.Target == tickerTargetQueryProposal { +func (s *prepareState) onTimeout(ticker *ticker) { + if ticker.Target == tickerTargetQueryProposal { roundProposal := s.log.RoundProposal(s.round) if roundProposal == nil { s.queryProposal() @@ -68,7 +68,7 @@ func (s *prepareState) onTimeout(t *ticker) { if s.isProposer() { s.queryVote() } - } else if t.Target == tickerTargetChangeProposer { + } else if ticker.Target == tickerTargetChangeProposer { s.startChangingProposer() } } diff --git a/consensus/prepare_test.go b/consensus/prepare_test.go index 75f26f0a9..e6805ec69 100644 --- a/consensus/prepare_test.go +++ b/consensus/prepare_test.go @@ -21,13 +21,13 @@ func TestQueryProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) - h := uint32(2) + height := uint32(2) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) td.queryProposalTimeout(td.consP) - td.shouldPublishQueryProposal(t, td.consP, h) + td.shouldPublishQueryProposal(t, td.consP, height) td.shouldNotPublish(t, td.consP, message.TypeQueryVote) } @@ -36,16 +36,16 @@ func TestQueryVote(t *testing.T) { td.commitBlockForAllStates(t) td.commitBlockForAllStates(t) - h := uint32(3) - r := int16(1) + height := uint32(3) + round := int16(1) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) // consP is the proposer for this round, but there are not enough votes. td.queryProposalTimeout(td.consP) - td.shouldPublishProposal(t, td.consP, h, r) - td.shouldPublishQueryVote(t, td.consP, h, r) + td.shouldPublishProposal(t, td.consP, height, round) + td.shouldPublishQueryVote(t, td.consP, height, round) td.shouldNotPublish(t, td.consP, message.TypeQueryProposal) } diff --git a/consensus/propose_test.go b/consensus/propose_test.go index cd2094161..ecd09732c 100644 --- a/consensus/propose_test.go +++ b/consensus/propose_test.go @@ -69,22 +69,22 @@ func TestNetworkLagging(t *testing.T) { td.enterNewHeight(td.consP) - h := uint32(1) - r := int16(0) - p := td.makeProposal(t, h, r) + height := uint32(1) + round := int16(0) + prop := td.makeProposal(t, height, round) // consP doesn't have the proposal, but it has received prepared votes from other peers - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexX) - td.addPrepareVote(td.consP, p.Block().Hash(), h, r, tIndexY) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) + td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.queryProposalTimeout(td.consP) - td.shouldPublishQueryProposal(t, td.consP, h) + td.shouldPublishQueryProposal(t, td.consP, height) // Proposal is received now - td.consP.SetProposal(p) + td.consP.SetProposal(prop) - td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, p.Block().Hash()) - td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, p.Block().Hash()) + td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, prop.Block().Hash()) + td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) } func TestProposalNextRound(t *testing.T) { diff --git a/consensus/voteset/binary_voteset.go b/consensus/voteset/binary_voteset.go index 4acbce419..aca2838bd 100644 --- a/consensus/voteset/binary_voteset.go +++ b/consensus/voteset/binary_voteset.go @@ -89,16 +89,16 @@ func (vs *BinaryVoteSet) AllVotes() []*vote.Vote { } // AddVote attempts to add a vote to the VoteSet. Returns an error if the vote is invalid. -func (vs *BinaryVoteSet) AddVote(v *vote.Vote) (bool, error) { - power, err := vs.voteSet.verifyVote(v) +func (vs *BinaryVoteSet) AddVote(vote *vote.Vote) (bool, error) { + power, err := vs.voteSet.verifyVote(vote) if err != nil { return false, err } - roundVotes := vs.mustGetRoundVotes(v.CPRound()) - existingVote, ok := roundVotes.allVotes[v.Signer()] + roundVotes := vs.mustGetRoundVotes(vote.CPRound()) + existingVote, ok := roundVotes.allVotes[vote.Signer()] if ok { - if existingVote.Hash() == v.Hash() { + if existingVote.Hash() == vote.Hash() { // The vote is already added return false, nil } @@ -106,11 +106,11 @@ func (vs *BinaryVoteSet) AddVote(v *vote.Vote) (bool, error) { // It is a duplicated vote err = ErrDuplicatedVote } else { - roundVotes.allVotes[v.Signer()] = v + roundVotes.allVotes[vote.Signer()] = vote roundVotes.votedPower += power } - roundVotes.addVote(v, power) + roundVotes.addVote(vote, power) return true, err } diff --git a/consensus/voteset/block_voteset.go b/consensus/voteset/block_voteset.go index 87229839b..eb5e6cd0e 100644 --- a/consensus/voteset/block_voteset.go +++ b/consensus/voteset/block_voteset.go @@ -49,13 +49,13 @@ func (vs *BlockVoteSet) BlockVotes(blockHash hash.Hash) map[crypto.Address]*vote } func (vs *BlockVoteSet) mustGetBlockVotes(blockHash hash.Hash) *voteBox { - bv, exists := vs.blockVotes[blockHash] + box, exists := vs.blockVotes[blockHash] if !exists { - bv = newVoteBox() - vs.blockVotes[blockHash] = bv + box = newVoteBox() + vs.blockVotes[blockHash] = box } - return bv + return box } // AllVotes returns a list of all votes in the VoteSet. @@ -69,15 +69,15 @@ func (vs *BlockVoteSet) AllVotes() []*vote.Vote { } // AddVote attempts to add a vote to the VoteSet. Returns an error if the vote is invalid. -func (vs *BlockVoteSet) AddVote(v *vote.Vote) (bool, error) { - power, err := vs.voteSet.verifyVote(v) +func (vs *BlockVoteSet) AddVote(vote *vote.Vote) (bool, error) { + power, err := vs.voteSet.verifyVote(vote) if err != nil { return false, err } - existingVote, ok := vs.allVotes[v.Signer()] + existingVote, ok := vs.allVotes[vote.Signer()] if ok { - if existingVote.Hash() == v.Hash() { + if existingVote.Hash() == vote.Hash() { // The vote is already added return false, nil } @@ -85,13 +85,13 @@ func (vs *BlockVoteSet) AddVote(v *vote.Vote) (bool, error) { // It is a duplicated vote err = ErrDuplicatedVote } else { - vs.allVotes[v.Signer()] = v + vs.allVotes[vote.Signer()] = vote } - blockVotes := vs.mustGetBlockVotes(v.BlockHash()) - blockVotes.addVote(v, power) + blockVotes := vs.mustGetBlockVotes(vote.BlockHash()) + blockVotes.addVote(vote, power) if vs.isTwoThirdOfTotalPower(blockVotes.votedPower) { - h := v.BlockHash() + h := vote.BlockHash() vs.quorumHash = &h } diff --git a/consensus/voteset/vote_box.go b/consensus/voteset/vote_box.go index fbf0866a7..f789fad19 100644 --- a/consensus/voteset/vote_box.go +++ b/consensus/voteset/vote_box.go @@ -17,9 +17,9 @@ func newVoteBox() *voteBox { } } -func (vs *voteBox) addVote(vte *vote.Vote, power int64) { - if vs.votes[vte.Signer()] == nil { - vs.votes[vte.Signer()] = vte +func (vs *voteBox) addVote(vote *vote.Vote, power int64) { + if vs.votes[vote.Signer()] == nil { + vs.votes[vote.Signer()] = vote vs.votedPower += power } } diff --git a/consensus/voteset/voteset.go b/consensus/voteset/voteset.go index 33a2666a4..e2e6b56e0 100644 --- a/consensus/voteset/voteset.go +++ b/consensus/voteset/voteset.go @@ -29,8 +29,8 @@ func (vs *voteSet) Round() int16 { // verifyVote checks if the given vote is valid. // It returns the voting power of if valid, or an error if not. -func (vs *voteSet) verifyVote(v *vote.Vote) (int64, error) { - signer := v.Signer() +func (vs *voteSet) verifyVote(vote *vote.Vote) (int64, error) { + signer := vote.Signer() val := vs.validators[signer] if val == nil { return 0, IneligibleVoterError{ @@ -38,7 +38,7 @@ func (vs *voteSet) verifyVote(v *vote.Vote) (int64, error) { } } - if err := v.Verify(val.PublicKey()); err != nil { + if err := vote.Verify(val.PublicKey()); err != nil { return 0, err } diff --git a/consensus/voteset/voteset_test.go b/consensus/voteset/voteset_test.go index 37d03d056..7ed5d42c0 100644 --- a/consensus/voteset/voteset_test.go +++ b/consensus/voteset/voteset_test.go @@ -42,33 +42,33 @@ func TestAddBlockVote(t *testing.T) { round := ts.RandRound() invKey := ts.RandValKey() valKey := valKeys[0] - vs := NewPrecommitVoteSet(round, totalPower, valsMap) + voteSet := NewPrecommitVoteSet(round, totalPower, valsMap) - v1 := vote.NewPrecommitVote(hash1, height, round, invKey.Address()) - v2 := vote.NewPrecommitVote(hash1, height, round, valKey.Address()) - v3 := vote.NewPrecommitVote(hash2, height, round, valKey.Address()) + vote1 := vote.NewPrecommitVote(hash1, height, round, invKey.Address()) + vote2 := vote.NewPrecommitVote(hash1, height, round, valKey.Address()) + vote3 := vote.NewPrecommitVote(hash2, height, round, valKey.Address()) - ts.HelperSignVote(invKey, v1) - added, err := vs.AddVote(v1) - assert.ErrorIs(t, err, IneligibleVoterError{Address: v1.Signer()}) // unknown validator + ts.HelperSignVote(invKey, vote1) + added, err := voteSet.AddVote(vote1) + assert.ErrorIs(t, err, IneligibleVoterError{Address: vote1.Signer()}) // unknown validator assert.False(t, added) - ts.HelperSignVote(invKey, v2) - added, err = vs.AddVote(v2) + ts.HelperSignVote(invKey, vote2) + added, err = voteSet.AddVote(vote2) assert.ErrorIs(t, err, crypto.ErrInvalidSignature) // invalid signature assert.False(t, added) - ts.HelperSignVote(valKey, v2) - added, err = vs.AddVote(v2) + ts.HelperSignVote(valKey, vote2) + added, err = voteSet.AddVote(vote2) assert.NoError(t, err) // ok assert.True(t, added) - added, err = vs.AddVote(v2) // Adding again + added, err = voteSet.AddVote(vote2) // Adding again assert.False(t, added) assert.NoError(t, err) - ts.HelperSignVote(valKey, v3) - added, err = vs.AddVote(v3) + ts.HelperSignVote(valKey, vote3) + added, err = voteSet.AddVote(vote3) assert.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) } @@ -87,33 +87,33 @@ func TestAddBinaryVote(t *testing.T) { just := &vote.JustInitYes{} invKey := ts.RandValKey() valKey := valKeys[0] - vs := NewCPPreVoteVoteSet(round, totalPower, valsMap) + voteSet := NewCPPreVoteVoteSet(round, totalPower, valsMap) - v1 := vote.NewCPPreVote(hash1, height, round, cpRound, vote.CPValue(cpVal), just, invKey.Address()) - v2 := vote.NewCPPreVote(hash1, height, round, cpRound, vote.CPValue(cpVal), just, valKey.Address()) - v3 := vote.NewCPPreVote(hash2, height, round, cpRound, vote.CPValue(cpVal), just, valKey.Address()) + vote1 := vote.NewCPPreVote(hash1, height, round, cpRound, vote.CPValue(cpVal), just, invKey.Address()) + vote2 := vote.NewCPPreVote(hash1, height, round, cpRound, vote.CPValue(cpVal), just, valKey.Address()) + vote3 := vote.NewCPPreVote(hash2, height, round, cpRound, vote.CPValue(cpVal), just, valKey.Address()) - ts.HelperSignVote(invKey, v1) - added, err := vs.AddVote(v1) - assert.ErrorIs(t, err, IneligibleVoterError{Address: v1.Signer()}) // unknown validator + ts.HelperSignVote(invKey, vote1) + added, err := voteSet.AddVote(vote1) + assert.ErrorIs(t, err, IneligibleVoterError{Address: vote1.Signer()}) // unknown validator assert.False(t, added) - ts.HelperSignVote(invKey, v2) - added, err = vs.AddVote(v2) + ts.HelperSignVote(invKey, vote2) + added, err = voteSet.AddVote(vote2) assert.ErrorIs(t, err, crypto.ErrInvalidSignature) // invalid signature assert.False(t, added) - ts.HelperSignVote(valKey, v2) - added, err = vs.AddVote(v2) + ts.HelperSignVote(valKey, vote2) + added, err = voteSet.AddVote(vote2) assert.NoError(t, err) // ok assert.True(t, added) - added, err = vs.AddVote(v2) // Adding again + added, err = voteSet.AddVote(vote2) // Adding again assert.False(t, added) assert.NoError(t, err) - ts.HelperSignVote(valKey, v3) - added, err = vs.AddVote(v3) + ts.HelperSignVote(valKey, vote3) + added, err = voteSet.AddVote(vote3) assert.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) } @@ -123,40 +123,40 @@ func TestDuplicateBlockVote(t *testing.T) { valsMap, valKeys, totalPower := setupCommittee(ts, 1, 1, 1, 1) - h1 := ts.RandHash() - h2 := ts.RandHash() - h3 := ts.RandHash() + hash1 := ts.RandHash() + hash2 := ts.RandHash() + hash3 := ts.RandHash() addr := valKeys[0].Address() - vs := NewPrepareVoteSet(0, totalPower, valsMap) + voteSet := NewPrepareVoteSet(0, totalPower, valsMap) - correctVote := vote.NewPrepareVote(h1, 1, 0, addr) - duplicatedVote1 := vote.NewPrepareVote(h2, 1, 0, addr) - duplicatedVote2 := vote.NewPrepareVote(h3, 1, 0, addr) + correctVote := vote.NewPrepareVote(hash1, 1, 0, addr) + duplicatedVote1 := vote.NewPrepareVote(hash2, 1, 0, addr) + duplicatedVote2 := vote.NewPrepareVote(hash3, 1, 0, addr) // sign the votes ts.HelperSignVote(valKeys[0], correctVote) ts.HelperSignVote(valKeys[0], duplicatedVote1) ts.HelperSignVote(valKeys[0], duplicatedVote2) - added, err := vs.AddVote(correctVote) + added, err := voteSet.AddVote(correctVote) assert.NoError(t, err) assert.True(t, added) - added, err = vs.AddVote(duplicatedVote1) + added, err = voteSet.AddVote(duplicatedVote1) assert.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) - added, err = vs.AddVote(duplicatedVote2) + added, err = voteSet.AddVote(duplicatedVote2) assert.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) - bv1 := vs.BlockVotes(h1) - bv2 := vs.BlockVotes(h2) - bv3 := vs.BlockVotes(h3) + bv1 := voteSet.BlockVotes(hash1) + bv2 := voteSet.BlockVotes(hash2) + bv3 := voteSet.BlockVotes(hash3) assert.Equal(t, correctVote, bv1[addr]) assert.Equal(t, duplicatedVote1, bv2[addr]) assert.Equal(t, duplicatedVote2, bv3[addr]) - assert.False(t, vs.HasQuorumHash()) + assert.False(t, voteSet.HasQuorumHash()) } func TestDuplicateBinaryVote(t *testing.T) { @@ -164,34 +164,34 @@ func TestDuplicateBinaryVote(t *testing.T) { valsMap, valKeys, totalPower := setupCommittee(ts, 1, 1, 1, 1) - h1 := ts.RandHash() - h2 := ts.RandHash() - h3 := ts.RandHash() + hash1 := ts.RandHash() + hash2 := ts.RandHash() + hash3 := ts.RandHash() addr := valKeys[0].Address() - vs := NewCPPreVoteVoteSet(0, totalPower, valsMap) + voteSet := NewCPPreVoteVoteSet(0, totalPower, valsMap) - correctVote := vote.NewCPPreVote(h1, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) - duplicatedVote1 := vote.NewCPPreVote(h2, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) - duplicatedVote2 := vote.NewCPPreVote(h3, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) + correctVote := vote.NewCPPreVote(hash1, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) + duplicatedVote1 := vote.NewCPPreVote(hash2, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) + duplicatedVote2 := vote.NewCPPreVote(hash3, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) // sign the votes ts.HelperSignVote(valKeys[0], correctVote) ts.HelperSignVote(valKeys[0], duplicatedVote1) ts.HelperSignVote(valKeys[0], duplicatedVote2) - added, err := vs.AddVote(correctVote) + added, err := voteSet.AddVote(correctVote) assert.NoError(t, err) assert.True(t, added) - added, err = vs.AddVote(duplicatedVote1) + added, err = voteSet.AddVote(duplicatedVote1) assert.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) - added, err = vs.AddVote(duplicatedVote2) + added, err = voteSet.AddVote(duplicatedVote2) assert.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) - assert.False(t, vs.HasOneThirdOfTotalPower(0)) + assert.False(t, voteSet.HasOneThirdOfTotalPower(0)) } func TestQuorum(t *testing.T) { @@ -199,44 +199,44 @@ func TestQuorum(t *testing.T) { valsMap, valKeys, totalPower := setupCommittee(ts, 1000, 1500, 2500, 2000) - vs := NewPrecommitVoteSet(0, totalPower, valsMap) + voteSet := NewPrecommitVoteSet(0, totalPower, valsMap) blockHash := ts.RandHash() - v1 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[0].Address()) - v2 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[1].Address()) - v3 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[2].Address()) - v4 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[3].Address()) + vote1 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[0].Address()) + vote2 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[1].Address()) + vote3 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[2].Address()) + vote4 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[3].Address()) - ts.HelperSignVote(valKeys[0], v1) - ts.HelperSignVote(valKeys[1], v2) - ts.HelperSignVote(valKeys[2], v3) - ts.HelperSignVote(valKeys[3], v4) + ts.HelperSignVote(valKeys[0], vote1) + ts.HelperSignVote(valKeys[1], vote2) + ts.HelperSignVote(valKeys[2], vote3) + ts.HelperSignVote(valKeys[3], vote4) - _, err := vs.AddVote(v1) + _, err := voteSet.AddVote(vote1) assert.NoError(t, err) - _, err = vs.AddVote(v2) + _, err = voteSet.AddVote(vote2) assert.NoError(t, err) - assert.Nil(t, vs.QuorumHash()) - assert.False(t, vs.HasQuorumHash()) - assert.Contains(t, vs.BlockVotes(blockHash), v1.Signer()) - assert.Contains(t, vs.BlockVotes(blockHash), v2.Signer()) + assert.Nil(t, voteSet.QuorumHash()) + assert.False(t, voteSet.HasQuorumHash()) + assert.Contains(t, voteSet.BlockVotes(blockHash), vote1.Signer()) + assert.Contains(t, voteSet.BlockVotes(blockHash), vote2.Signer()) - _, err = vs.AddVote(v3) + _, err = voteSet.AddVote(vote3) assert.NoError(t, err) - assert.True(t, vs.HasQuorumHash()) - assert.Contains(t, vs.BlockVotes(blockHash), v3.Signer()) - assert.NotContains(t, vs.BlockVotes(blockHash), v4.Signer()) + assert.True(t, voteSet.HasQuorumHash()) + assert.Contains(t, voteSet.BlockVotes(blockHash), vote3.Signer()) + assert.NotContains(t, voteSet.BlockVotes(blockHash), vote4.Signer()) // Add one more vote - _, err = vs.AddVote(v4) + _, err = voteSet.AddVote(vote4) assert.NoError(t, err) - assert.NotNil(t, vs.QuorumHash()) - assert.Equal(t, &blockHash, vs.QuorumHash()) - assert.True(t, vs.HasQuorumHash()) - assert.Contains(t, vs.BlockVotes(blockHash), v4.Signer()) + assert.NotNil(t, voteSet.QuorumHash()) + assert.Equal(t, &blockHash, voteSet.QuorumHash()) + assert.True(t, voteSet.HasQuorumHash()) + assert.Contains(t, voteSet.BlockVotes(blockHash), vote4.Signer()) } func TestAllBlockVotes(t *testing.T) { @@ -244,42 +244,42 @@ func TestAllBlockVotes(t *testing.T) { valsMap, valKeys, totalPower := setupCommittee(ts, 1000, 1500, 2500, 2000) - vs := NewPrecommitVoteSet(1, totalPower, valsMap) + voteSet := NewPrecommitVoteSet(1, totalPower, valsMap) - h1 := ts.RandHash() - h2 := ts.RandHash() - v1 := vote.NewPrecommitVote(h1, 1, 1, valKeys[0].Address()) - v2 := vote.NewPrecommitVote(h1, 1, 1, valKeys[1].Address()) - v3 := vote.NewPrecommitVote(h1, 1, 1, valKeys[2].Address()) - v4 := vote.NewPrecommitVote(h2, 1, 1, valKeys[0].Address()) + hash1 := ts.RandHash() + hash2 := ts.RandHash() + vote1 := vote.NewPrecommitVote(hash1, 1, 1, valKeys[0].Address()) + vote2 := vote.NewPrecommitVote(hash1, 1, 1, valKeys[1].Address()) + vote3 := vote.NewPrecommitVote(hash1, 1, 1, valKeys[2].Address()) + vote4 := vote.NewPrecommitVote(hash2, 1, 1, valKeys[0].Address()) - ts.HelperSignVote(valKeys[0], v1) - ts.HelperSignVote(valKeys[1], v2) - ts.HelperSignVote(valKeys[2], v3) - ts.HelperSignVote(valKeys[0], v4) + ts.HelperSignVote(valKeys[0], vote1) + ts.HelperSignVote(valKeys[1], vote2) + ts.HelperSignVote(valKeys[2], vote3) + ts.HelperSignVote(valKeys[0], vote4) - _, err := vs.AddVote(v1) + _, err := voteSet.AddVote(vote1) assert.NoError(t, err) - _, err = vs.AddVote(v2) + _, err = voteSet.AddVote(vote2) assert.NoError(t, err) - _, err = vs.AddVote(v3) + _, err = voteSet.AddVote(vote3) assert.NoError(t, err) - assert.Equal(t, &h1, vs.QuorumHash()) + assert.Equal(t, &hash1, voteSet.QuorumHash()) - _, err = vs.AddVote(v4) + _, err = voteSet.AddVote(vote4) assert.ErrorIs(t, err, ErrDuplicatedVote) // duplicated // Check accumulated power - assert.Equal(t, &h1, vs.QuorumHash()) + assert.Equal(t, &hash1, voteSet.QuorumHash()) // Check previous votes - assert.Contains(t, vs.AllVotes(), v1) - assert.Contains(t, vs.AllVotes(), v2) - assert.Contains(t, vs.AllVotes(), v3) - assert.NotContains(t, vs.AllVotes(), v4) // Should add duplicated votes? + assert.Contains(t, voteSet.AllVotes(), vote1) + assert.Contains(t, voteSet.AllVotes(), vote2) + assert.Contains(t, voteSet.AllVotes(), vote3) + assert.NotContains(t, voteSet.AllVotes(), vote4) // Should add duplicated votes? } func TestAllBinaryVotes(t *testing.T) { @@ -287,36 +287,36 @@ func TestAllBinaryVotes(t *testing.T) { valsMap, valKeys, totalPower := setupCommittee(ts, 1000, 1500, 2500, 2000) - vs := NewCPMainVoteVoteSet(1, totalPower, valsMap) + voteSet := NewCPMainVoteVoteSet(1, totalPower, valsMap) - v1 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 0, vote.CPValueNo, &vote.JustInitYes{}, valKeys[0].Address()) - v2 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 1, vote.CPValueYes, &vote.JustInitYes{}, valKeys[1].Address()) - v3 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 2, vote.CPValueAbstain, &vote.JustInitYes{}, valKeys[2].Address()) + vote1 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 0, vote.CPValueNo, &vote.JustInitYes{}, valKeys[0].Address()) + vote2 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 1, vote.CPValueYes, &vote.JustInitYes{}, valKeys[1].Address()) + vote3 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 2, vote.CPValueAbstain, &vote.JustInitYes{}, valKeys[2].Address()) - ts.HelperSignVote(valKeys[0], v1) - ts.HelperSignVote(valKeys[1], v2) - ts.HelperSignVote(valKeys[2], v3) + ts.HelperSignVote(valKeys[0], vote1) + ts.HelperSignVote(valKeys[1], vote2) + ts.HelperSignVote(valKeys[2], vote3) - assert.Empty(t, vs.AllVotes()) + assert.Empty(t, voteSet.AllVotes()) - _, err := vs.AddVote(v1) + _, err := voteSet.AddVote(vote1) assert.NoError(t, err) - _, err = vs.AddVote(v2) + _, err = voteSet.AddVote(vote2) assert.NoError(t, err) - _, err = vs.AddVote(v3) + _, err = voteSet.AddVote(vote3) assert.NoError(t, err) - assert.Contains(t, vs.AllVotes(), v1) - assert.Contains(t, vs.AllVotes(), v2) - assert.Contains(t, vs.AllVotes(), v3) + assert.Contains(t, voteSet.AllVotes(), vote1) + assert.Contains(t, voteSet.AllVotes(), vote2) + assert.Contains(t, voteSet.AllVotes(), vote3) - ranVote1 := vs.GetRandomVote(1, vote.CPValueNo) + ranVote1 := voteSet.GetRandomVote(1, vote.CPValueNo) assert.Nil(t, ranVote1) - ranVote2 := vs.GetRandomVote(1, vote.CPValueYes) - assert.Equal(t, v2, ranVote2) + ranVote2 := voteSet.GetRandomVote(1, vote.CPValueYes) + assert.Equal(t, vote2, ranVote2) } func TestOneThirdPower(t *testing.T) { @@ -327,75 +327,74 @@ func TestOneThirdPower(t *testing.T) { // 2/3 of total power = 2000 valsMap, valKeys, totalPower := setupCommittee(ts, 999, 3, 999, 999) - h := ts.RandHash() + hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} - vs := NewCPPreVoteVoteSet(round, totalPower, valsMap) + voteSet := NewCPPreVoteVoteSet(round, totalPower, valsMap) - v1 := vote.NewCPPreVote(h, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) - v2 := vote.NewCPPreVote(h, height, round, 0, vote.CPValueYes, just, valKeys[1].Address()) - v3 := vote.NewCPPreVote(h, height, round, 0, vote.CPValueYes, just, valKeys[2].Address()) - v4 := vote.NewCPPreVote(h, height, round, 0, vote.CPValueNo, just, valKeys[3].Address()) + vote1 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) + vote2 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[1].Address()) + vote3 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[2].Address()) + vote4 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueNo, just, valKeys[3].Address()) - ts.HelperSignVote(valKeys[0], v1) - ts.HelperSignVote(valKeys[1], v2) - ts.HelperSignVote(valKeys[2], v3) - ts.HelperSignVote(valKeys[3], v4) + ts.HelperSignVote(valKeys[0], vote1) + ts.HelperSignVote(valKeys[1], vote2) + ts.HelperSignVote(valKeys[2], vote3) + ts.HelperSignVote(valKeys[3], vote4) - _, err := vs.AddVote(v1) + _, err := voteSet.AddVote(vote1) assert.NoError(t, err) - assert.False(t, vs.HasOneThirdOfTotalPower(0)) - assert.True(t, vs.HasAnyVoteFor(0, vote.CPValueYes)) - assert.False(t, vs.HasAnyVoteFor(0, vote.CPValueNo)) - assert.False(t, vs.HasAnyVoteFor(0, vote.CPValueAbstain)) + assert.False(t, voteSet.HasOneThirdOfTotalPower(0)) + assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueYes)) + assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) + assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueAbstain)) - _, err = vs.AddVote(v2) + _, err = voteSet.AddVote(vote2) assert.NoError(t, err) - assert.True(t, vs.HasOneThirdOfTotalPower(0)) - assert.False(t, vs.HasTwoThirdOfTotalPower(0)) + assert.True(t, voteSet.HasOneThirdOfTotalPower(0)) + assert.False(t, voteSet.HasTwoThirdOfTotalPower(0)) - _, err = vs.AddVote(v3) + _, err = voteSet.AddVote(vote3) assert.NoError(t, err) - assert.True(t, vs.HasTwoThirdOfTotalPower(0)) - assert.False(t, vs.HasAnyVoteFor(0, vote.CPValueNo)) - assert.True(t, vs.HasAnyVoteFor(0, vote.CPValueYes)) - assert.False(t, vs.HasQuorumVotesFor(0, vote.CPValueNo)) - assert.True(t, vs.HasQuorumVotesFor(0, vote.CPValueYes)) - assert.True(t, vs.HasAllVotesFor(0, vote.CPValueYes)) - - _, err = vs.AddVote(v4) + assert.True(t, voteSet.HasTwoThirdOfTotalPower(0)) + assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) + assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueYes)) + assert.False(t, voteSet.HasQuorumVotesFor(0, vote.CPValueNo)) + assert.True(t, voteSet.HasQuorumVotesFor(0, vote.CPValueYes)) + assert.True(t, voteSet.HasAllVotesFor(0, vote.CPValueYes)) + + _, err = voteSet.AddVote(vote4) assert.NoError(t, err) - assert.True(t, vs.HasAnyVoteFor(0, vote.CPValueNo)) - assert.False(t, vs.HasQuorumVotesFor(0, vote.CPValueNo)) - assert.True(t, vs.HasQuorumVotesFor(0, vote.CPValueYes)) - assert.False(t, vs.HasAllVotesFor(0, vote.CPValueYes)) - - bv1 := vs.BinaryVotes(0, vote.CPValueYes) - bv2 := vs.BinaryVotes(0, vote.CPValueNo) - - assert.Contains(t, bv1, v1.Signer()) - assert.Contains(t, bv1, v2.Signer()) - assert.Contains(t, bv1, v3.Signer()) - assert.Contains(t, bv2, v4.Signer()) + assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) + assert.False(t, voteSet.HasQuorumVotesFor(0, vote.CPValueNo)) + assert.True(t, voteSet.HasQuorumVotesFor(0, vote.CPValueYes)) + assert.False(t, voteSet.HasAllVotesFor(0, vote.CPValueYes)) + + bv1 := voteSet.BinaryVotes(0, vote.CPValueYes) + bv2 := voteSet.BinaryVotes(0, vote.CPValueNo) + + assert.Contains(t, bv1, vote1.Signer()) + assert.Contains(t, bv1, vote2.Signer()) + assert.Contains(t, bv1, vote3.Signer()) + assert.Contains(t, bv2, vote4.Signer()) } func TestDecidedVoteset(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1, 1, 1, 1) - h := ts.RandHash() + hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} - vs := NewCPDecidedVoteSet(round, totalPower, valsMap) - - v1 := vote.NewCPDecidedVote(h, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) + voteSet := NewCPDecidedVoteSet(round, totalPower, valsMap) - ts.HelperSignVote(valKeys[0], v1) + vte := vote.NewCPDecidedVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) + ts.HelperSignVote(valKeys[0], vte) - _, err := vs.AddVote(v1) + _, err := voteSet.AddVote(vte) assert.NoError(t, err) - assert.True(t, vs.HasAnyVoteFor(0, vote.CPValueYes)) - assert.False(t, vs.HasAnyVoteFor(0, vote.CPValueNo)) + assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueYes)) + assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) } diff --git a/crypto/address.go b/crypto/address.go index 09b1bb356..79af6c9bd 100644 --- a/crypto/address.go +++ b/crypto/address.go @@ -112,7 +112,7 @@ func (addr Address) Type() AddressType { } func (addr Address) Encode(w io.Writer) error { - switch t := addr.Type(); t { + switch typ := addr.Type(); typ { case AddressTypeTreasury: return encoding.WriteElement(w, uint8(0)) case AddressTypeValidator, @@ -120,7 +120,7 @@ func (addr Address) Encode(w io.Writer) error { AddressTypeEd25519Account: return encoding.WriteElement(w, addr) default: - return InvalidAddressTypeError(t) + return InvalidAddressTypeError(typ) } } @@ -129,7 +129,7 @@ func (addr *Address) Decode(r io.Reader) error { if err != nil { return err } - switch t := addr.Type(); t { + switch typ := addr.Type(); typ { case AddressTypeTreasury: return nil case AddressTypeValidator, @@ -137,13 +137,13 @@ func (addr *Address) Decode(r io.Reader) error { AddressTypeEd25519Account: return encoding.ReadElement(r, addr[1:]) default: - return InvalidAddressTypeError(t) + return InvalidAddressTypeError(typ) } } // SerializeSize returns the number of bytes it would take to serialize the address. func (addr Address) SerializeSize() int { - switch t := addr.Type(); t { + switch typ := addr.Type(); typ { case AddressTypeTreasury: return 1 case AddressTypeValidator, diff --git a/crypto/address_test.go b/crypto/address_test.go index 028255494..06e917886 100644 --- a/crypto/address_test.go +++ b/crypto/address_test.go @@ -33,11 +33,11 @@ func TestAddressType(t *testing.T) { {address: "pc1rspm7ps49gar9ft5g0tkl6lhxs8ygeakq87quh3", account: true, validator: false}, } - for _, test := range tests { - addr, _ := crypto.AddressFromString(test.address) + for _, tt := range tests { + addr, _ := crypto.AddressFromString(tt.address) - assert.Equal(t, test.account, addr.IsAccountAddress()) - assert.Equal(t, test.validator, addr.IsValidatorAddress()) + assert.Equal(t, tt.account, addr.IsAccountAddress()) + assert.Equal(t, tt.validator, addr.IsValidatorAddress()) } } @@ -152,15 +152,15 @@ func TestFromString(t *testing.T) { crypto.AddressTypeEd25519Account, }, } - for no, test := range tests { - addr, err := crypto.AddressFromString(test.encoded) - if test.err == nil { + for no, tt := range tests { + addr, err := crypto.AddressFromString(tt.encoded) + if tt.err == nil { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, test.bytes, addr.Bytes(), "test %v: invalid result", no) - assert.Equal(t, strings.ToLower(test.encoded), addr.String(), "test %v: invalid encode", no) - assert.Equal(t, test.addrType, addr.Type(), "test %v: invalid type", no) + assert.Equal(t, tt.bytes, addr.Bytes(), "test %v: invalid result", no) + assert.Equal(t, strings.ToLower(tt.encoded), addr.String(), "test %v: invalid encode", no) + assert.Equal(t, tt.addrType, addr.Type(), "test %v: invalid type", no) } else { - assert.ErrorIs(t, err, test.err, "test %v: invalid error", no) + assert.ErrorIs(t, err, tt.err, "test %v: invalid error", no) } } } @@ -212,18 +212,18 @@ func TestAddressDecoding(t *testing.T) { nil, }, } - for no, test := range tests { - data, _ := hex.DecodeString(test.hex) - r := bytes.NewBuffer(data) + for no, tt := range tests { + data, _ := hex.DecodeString(tt.hex) + buf := bytes.NewBuffer(data) addr := new(crypto.Address) - err := addr.Decode(r) - if test.err != nil { - assert.ErrorIs(t, err, test.err, "test %v: error not matched", no) - assert.Equal(t, test.size, addr.SerializeSize(), "test %v invalid size", no) + err := addr.Decode(buf) + if tt.err != nil { + assert.ErrorIs(t, err, tt.err, "test %v: error not matched", no) + assert.Equal(t, tt.size, addr.SerializeSize(), "test %v invalid size", no) } else { assert.NoError(t, err, "test %v expected no error", no) - assert.Equal(t, test.size, addr.SerializeSize(), "test %v invalid size", no) + assert.Equal(t, tt.size, addr.SerializeSize(), "test %v invalid size", no) length := addr.SerializeSize() for i := 0; i < length; i++ { diff --git a/crypto/bls/bls.go b/crypto/bls/bls.go index d37d9e86f..8e02bf0ca 100644 --- a/crypto/bls/bls.go +++ b/crypto/bls/bls.go @@ -20,14 +20,14 @@ func SignatureAggregate(sigs ...*Signature) *Signature { if len(sigs) == 0 { return nil } - g1 := new(bls12381.G1Affine) + grp1 := new(bls12381.G1Affine) aggPointG1, err := sigs[0].PointG1() if err != nil { return nil } for i := 1; i < len(sigs); i++ { pointG1, _ := sigs[i].PointG1() - aggPointG1 = g1.Add(aggPointG1, pointG1) + aggPointG1 = grp1.Add(aggPointG1, pointG1) } data := aggPointG1.Bytes() @@ -42,14 +42,14 @@ func PublicKeyAggregate(pubs ...*PublicKey) *PublicKey { if len(pubs) == 0 { return nil } - g2 := new(bls12381.G2Affine) + grp2 := new(bls12381.G2Affine) aggPointG2, err := pubs[0].PointG2() if err != nil { return nil } for i := 1; i < len(pubs); i++ { pointG2, _ := pubs[i].PointG2() - aggPointG2 = g2.Add(aggPointG2, pointG2) + aggPointG2 = grp2.Add(aggPointG2, pointG2) } data := aggPointG2.Bytes() diff --git a/crypto/bls/bls_test.go b/crypto/bls/bls_test.go index 93542917d..4fa23a66f 100644 --- a/crypto/bls/bls_test.go +++ b/crypto/bls/bls_test.go @@ -186,9 +186,9 @@ func TestHashToCurve(t *testing.T) { }, } - for no, test := range tests { - mappedPoint, _ := bls12381.HashToG1([]byte(test.msg), domain) - d, _ := hex.DecodeString(test.expected) + for no, tt := range tests { + mappedPoint, _ := bls12381.HashToG1([]byte(tt.msg), domain) + d, _ := hex.DecodeString(tt.expected) expectedPoint := bls12381.G1Affine{} err := expectedPoint.Unmarshal(d) diff --git a/crypto/bls/hdkeychain/extendedkey.go b/crypto/bls/hdkeychain/extendedkey.go index 087c272a0..a6fb64ea0 100644 --- a/crypto/bls/hdkeychain/extendedkey.go +++ b/crypto/bls/hdkeychain/extendedkey.go @@ -70,23 +70,23 @@ func (k *ExtendedKey) pubKeyBytes() []byte { if !k.isPrivate { return k.key } - g1 := bls12381.NewG1() + grp1 := bls12381.NewG1() privKey := bls12381.NewFr() privKey.FromBytes(k.key) if k.pubOnG1 { pub := new(bls12381.PointG1) - g1.MulScalar(pub, g1.One(), privKey) + grp1.MulScalar(pub, grp1.One(), privKey) - return g1.ToCompressed(pub) + return grp1.ToCompressed(pub) } - g2 := bls12381.NewG2() + grp2 := bls12381.NewG2() pub := new(bls12381.PointG2) - g2.MulScalar(pub, g2.One(), privKey) + grp2.MulScalar(pub, grp2.One(), privKey) - return g2.ToCompressed(pub) + return grp2.ToCompressed(pub) } // IsPrivate returns whether or not the extended key is a private extended key. @@ -255,36 +255,36 @@ func (k *ExtendedKey) Derive(index uint32) (*ExtendedKey, error) { // Public key is in G1 subgroup // // childKey = pointG1(parse256(Il)) + parentKey - g1 := bls12381.NewG1() + grp1 := bls12381.NewG1() ilPoint := new(bls12381.PointG1) - g1.MulScalar(ilPoint, g1.One(), ilFr) + grp1.MulScalar(ilPoint, grp1.One(), ilFr) - pubKey, err := g1.FromCompressed(k.key) + pubKey, err := grp1.FromCompressed(k.key) if err != nil { return nil, err } childPubKey := new(bls12381.PointG1) - g1.Add(childPubKey, pubKey, ilPoint) + grp1.Add(childPubKey, pubKey, ilPoint) - childKey = g1.ToCompressed(childPubKey) + childKey = grp1.ToCompressed(childPubKey) } else { // Public key is in G2 subgroup // // childKey = pointG2(parse256(Il)) + parentKey - g2 := bls12381.NewG2() + grp2 := bls12381.NewG2() ilPoint := new(bls12381.PointG2) - g2.MulScalar(ilPoint, g2.One(), ilFr) + grp2.MulScalar(ilPoint, grp2.One(), ilFr) - pubKey, err := g2.FromCompressed(k.key) + pubKey, err := grp2.FromCompressed(k.key) if err != nil { return nil, err } childPubKey := new(bls12381.PointG2) - g2.Add(childPubKey, pubKey, ilPoint) + grp2.Add(childPubKey, pubKey, ilPoint) - childKey = g2.ToCompressed(childPubKey) + childKey = grp2.ToCompressed(childPubKey) } } @@ -362,29 +362,29 @@ func (k *ExtendedKey) String() string { // - Key data: Can be 32, 48, or 96 bytes. // - w := bytes.NewBuffer(make([]byte, 0)) - err := encoding.WriteElement(w, byte(len(k.path))) + buf := bytes.NewBuffer(make([]byte, 0)) + err := encoding.WriteElement(buf, byte(len(k.path))) if err != nil { return err.Error() } for _, p := range k.path { - err := encoding.WriteElement(w, p) + err := encoding.WriteElement(buf, p) if err != nil { return err.Error() } } - err = encoding.WriteVarBytes(w, k.chainCode) + err = encoding.WriteVarBytes(buf, k.chainCode) if err != nil { return err.Error() } - err = encoding.WriteElement(w, k.pubOnG1) + err = encoding.WriteElement(buf, k.pubOnG1) if err != nil { return err.Error() } - err = encoding.WriteVarBytes(w, k.key) + err = encoding.WriteVarBytes(buf, k.key) if err != nil { return err.Error() } @@ -394,7 +394,7 @@ func (k *ExtendedKey) String() string { hrp = crypto.XPrivateKeyHRP } - str, err := bech32m.EncodeFromBase256WithType(hrp, crypto.SignatureTypeBLS, w.Bytes()) + str, err := bech32m.EncodeFromBase256WithType(hrp, crypto.SignatureTypeBLS, buf.Bytes()) if err != nil { return err.Error() } @@ -417,33 +417,33 @@ func NewKeyFromString(str string) (*ExtendedKey, error) { return nil, ErrInvalidKeyData } - r := bytes.NewReader(data) + reader := bytes.NewReader(data) depth := uint8(0) - err = encoding.ReadElement(r, &depth) + err = encoding.ReadElement(reader, &depth) if err != nil { return nil, err } path := make([]uint32, depth) for i := byte(0); i < depth; i++ { - err := encoding.ReadElement(r, &path[i]) + err := encoding.ReadElement(reader, &path[i]) if err != nil { return nil, err } } - chainCode, err := encoding.ReadVarBytes(r) + chainCode, err := encoding.ReadVarBytes(reader) if err != nil { return nil, err } var pubOnG1 bool - err = encoding.ReadElement(r, &pubOnG1) + err = encoding.ReadElement(reader, &pubOnG1) if err != nil { return nil, err } - key, err := encoding.ReadVarBytes(r) + key, err := encoding.ReadVarBytes(reader) if err != nil { return nil, err } @@ -477,13 +477,13 @@ func NewMaster(seed []byte, pubOnG1 bool) (*ExtendedKey, error) { // I = HMAC-SHA512(Key = "BLS12381-HD seed", Data = S) hmac512 := hmac.New(sha512.New, masterKey) _, _ = hmac512.Write(seed) - lr := hmac512.Sum(nil) + ilr := hmac512.Sum(nil) // Split "I" into two 32-byte sequences Il and Ir where: // Il = master IKM // Ir = master chain code - ikm := lr[:len(lr)/2] - chainCode := lr[len(lr)/2:] + ikm := ilr[:len(ilr)/2] + chainCode := ilr[len(ilr)/2:] // Using BLS KeyGen to generate the master private key from the IKM. privKey, err := bls.KeyGen(ikm, nil) diff --git a/crypto/bls/hdkeychain/extendedkey_test.go b/crypto/bls/hdkeychain/extendedkey_test.go index 478fc1690..9ad7f170c 100644 --- a/crypto/bls/hdkeychain/extendedkey_test.go +++ b/crypto/bls/hdkeychain/extendedkey_test.go @@ -137,30 +137,30 @@ func TestDerivation(t *testing.T) { masterKeyG1, _ := NewMaster(testSeed, true) masterKeyG2, _ := NewMaster(testSeed, false) - for i, test := range tests { - extKeyG1, err := masterKeyG1.DerivePath(test.path) + for no, tt := range tests { + extKeyG1, err := masterKeyG1.DerivePath(tt.path) require.NoError(t, err) - extKeyG2, err := masterKeyG2.DerivePath(test.path) + extKeyG2, err := masterKeyG2.DerivePath(tt.path) require.NoError(t, err) privKeyG1, err := extKeyG1.RawPrivateKey() require.NoError(t, err) - require.Equal(t, test.wantPrivG1, hex.EncodeToString(privKeyG1), - "mismatched serialized private key for test #%v", i+1) + require.Equal(t, tt.wantPrivG1, hex.EncodeToString(privKeyG1), + "mismatched serialized private key for test #%v", no+1) privKeyG2, err := extKeyG2.RawPrivateKey() require.NoError(t, err) - require.Equal(t, test.wantPrivG2, hex.EncodeToString(privKeyG2), - "mismatched serialized private key for test #%v", i+1) + require.Equal(t, tt.wantPrivG2, hex.EncodeToString(privKeyG2), + "mismatched serialized private key for test #%v", no+1) pubKeyG1 := extKeyG1.RawPublicKey() - require.Equal(t, test.wantPubG1, hex.EncodeToString(pubKeyG1), - "mismatched serialized public key for test #%v", i+1) + require.Equal(t, tt.wantPubG1, hex.EncodeToString(pubKeyG1), + "mismatched serialized public key for test #%v", no+1) pubKeyG2 := extKeyG2.RawPublicKey() - require.Equal(t, test.wantPubG2, hex.EncodeToString(pubKeyG2), - "mismatched serialized public key for test #%v", i+1) + require.Equal(t, tt.wantPubG2, hex.EncodeToString(pubKeyG2), + "mismatched serialized public key for test #%v", no+1) neuterKeyG1 := extKeyG1.Neuter() neuterKeyG2 := extKeyG2.Neuter() @@ -173,10 +173,10 @@ func TestDerivation(t *testing.T) { require.False(t, neuterKeyG2.IsPrivate()) require.Equal(t, pubKeyG1, neuterPubKeyG1) require.Equal(t, pubKeyG2, neuterPubKeyG2) - require.Equal(t, test.path, extKeyG1.Path()) - require.Equal(t, test.path, extKeyG2.Path()) - require.Equal(t, test.path, neuterKeyG1.Path()) - require.Equal(t, test.path, neuterKeyG2.Path()) + require.Equal(t, tt.path, extKeyG1.Path()) + require.Equal(t, tt.path, extKeyG2.Path()) + require.Equal(t, tt.path, neuterKeyG1.Path()) + require.Equal(t, tt.path, neuterKeyG2.Path()) _, err = neuterKeyG1.RawPrivateKey() assert.ErrorIs(t, err, ErrNotPrivExtKey) @@ -251,14 +251,14 @@ func TestGenerateSeed(t *testing.T) { {name: "65 bytes", length: 65, err: ErrInvalidSeedLen}, } - for i, test := range tests { - seed, err := GenerateSeed(test.length) - assert.ErrorIs(t, err, test.err) + for no, tt := range tests { + seed, err := GenerateSeed(tt.length) + assert.ErrorIs(t, err, tt.err) - if test.err == nil { - assert.Len(t, seed, int(test.length), + if tt.err == nil { + assert.Len(t, seed, int(tt.length), "GenerateSeed #%d (%s): length mismatch -- got %d, want %d", - i, test.name, len(seed), test.length) + no, tt.name, len(seed), tt.length) } } } @@ -308,24 +308,24 @@ func TestNewMaster(t *testing.T) { }, } - for i, test := range tests { - seed, _ := hex.DecodeString(test.seed) + for no, tt := range tests { + seed, _ := hex.DecodeString(tt.seed) extKeyG1, err := NewMaster(seed, true) - assert.ErrorIs(t, err, test.err) + assert.ErrorIs(t, err, tt.err) extKeyG2, err := NewMaster(seed, true) - assert.ErrorIs(t, err, test.err) + assert.ErrorIs(t, err, tt.err) - if test.err == nil { + if tt.err == nil { privKeyG1, _ := extKeyG1.RawPrivateKey() - assert.Equal(t, test.privKey, hex.EncodeToString(privKeyG1), + assert.Equal(t, tt.privKey, hex.EncodeToString(privKeyG1), "NewMaster #%d (%s): privKeyG1 mismatch -- got %x, want %s", - i+1, test.name, privKeyG1, test.privKey) + no+1, tt.name, privKeyG1, tt.privKey) privKeyG2, _ := extKeyG2.RawPrivateKey() - assert.Equal(t, test.privKey, hex.EncodeToString(privKeyG2), + assert.Equal(t, tt.privKey, hex.EncodeToString(privKeyG2), "NewMaster #%d (%s): privKeyG2 mismatch -- got %x, want %s", - i+1, test.name, privKeyG2, test.privKey) + no+1, tt.name, privKeyG2, tt.privKey) } } } @@ -396,38 +396,38 @@ func TestKeyToString(t *testing.T) { masterKeyG1, _ := NewMaster(testSeed, true) masterKeyG2, _ := NewMaster(testSeed, false) - for i, test := range tests { - extKeyG1, _ := masterKeyG1.DerivePath(test.path) + for no, tt := range tests { + extKeyG1, _ := masterKeyG1.DerivePath(tt.path) neuterKeyG1 := extKeyG1.Neuter() - extKeyG2, _ := masterKeyG2.DerivePath(test.path) + extKeyG2, _ := masterKeyG2.DerivePath(tt.path) neuterKeyG2 := extKeyG2.Neuter() - require.Equal(t, test.wantXPrivG1, extKeyG1.String(), "test %d failed", i) - require.Equal(t, test.wantXPubG1, neuterKeyG1.String(), "test %d failed", i) - require.Equal(t, test.wantXPrivG2, extKeyG2.String(), "test %d failed", i) - require.Equal(t, test.wantXPubG2, neuterKeyG2.String(), "test %d failed", i) + require.Equal(t, tt.wantXPrivG1, extKeyG1.String(), "test %d failed", no) + require.Equal(t, tt.wantXPubG1, neuterKeyG1.String(), "test %d failed", no) + require.Equal(t, tt.wantXPrivG2, extKeyG2.String(), "test %d failed", no) + require.Equal(t, tt.wantXPubG2, neuterKeyG2.String(), "test %d failed", no) - recoveredExtKeyG1, err := NewKeyFromString(test.wantXPrivG1) + recoveredExtKeyG1, err := NewKeyFromString(tt.wantXPrivG1) require.NoError(t, err) - recoveredExtKeyG2, err := NewKeyFromString(test.wantXPrivG2) + recoveredExtKeyG2, err := NewKeyFromString(tt.wantXPrivG2) require.NoError(t, err) - recoveredNeuterKeyG1, err := NewKeyFromString(test.wantXPubG1) + recoveredNeuterKeyG1, err := NewKeyFromString(tt.wantXPubG1) require.NoError(t, err) - recoveredNeuterKeyG2, err := NewKeyFromString(test.wantXPubG2) + recoveredNeuterKeyG2, err := NewKeyFromString(tt.wantXPubG2) require.NoError(t, err) require.Equal(t, extKeyG1, recoveredExtKeyG1) require.Equal(t, extKeyG2, recoveredExtKeyG2) require.Equal(t, neuterKeyG1, recoveredNeuterKeyG1) require.Equal(t, neuterKeyG2, recoveredNeuterKeyG2) - require.Equal(t, test.path, recoveredExtKeyG1.path) - require.Equal(t, test.path, recoveredExtKeyG2.path) - require.Equal(t, test.path, recoveredNeuterKeyG1.path) - require.Equal(t, test.path, recoveredNeuterKeyG2.path) + require.Equal(t, tt.path, recoveredExtKeyG1.path) + require.Equal(t, tt.path, recoveredExtKeyG2.path) + require.Equal(t, tt.path, recoveredNeuterKeyG1.path) + require.Equal(t, tt.path, recoveredNeuterKeyG2.path) } } @@ -492,9 +492,9 @@ func TestInvalidString(t *testing.T) { }, } - for i, test := range tests { - _, err := NewKeyFromString(test.str) - assert.ErrorIs(t, err, test.expectedError, "test %d error is not matched", i) + for no, tt := range tests { + _, err := NewKeyFromString(tt.str) + assert.ErrorIs(t, err, tt.expectedError, "test %d error is not matched", no) } } diff --git a/crypto/bls/private_key.go b/crypto/bls/private_key.go index 284d9b4f4..334f70ee9 100644 --- a/crypto/bls/private_key.go +++ b/crypto/bls/private_key.go @@ -67,22 +67,22 @@ func KeyGen(ikm, keyInfo []byte) (*PrivateKey, error) { pseudoRandomKey = append(pseudoRandomKey, util.I2OSP(big.NewInt(l), 2)...) salt := []byte("BLS-SIG-KEYGEN-SALT-") - x := big.NewInt(0) - for x.Sign() == 0 { - h := sha256.Sum256(salt) - salt = h[:] + num := big.NewInt(0) + for num.Sign() == 0 { + hash := sha256.Sum256(salt) + salt = hash[:] okm := make([]byte, l) prk := hkdf.Extract(sha256.New, secret, salt) reader := hkdf.Expand(sha256.New, prk, pseudoRandomKey) _, _ = reader.Read(okm) - r := fr.Modulus() - x = new(big.Int).Mod(util.OS2IP(okm), r) + order := fr.Modulus() + num = new(big.Int).Mod(util.OS2IP(okm), order) } sk := make([]byte, 32) - x.FillBytes(sk) + num.FillBytes(sk) return PrivateKeyFromBytes(sk) } diff --git a/crypto/bls/private_key_test.go b/crypto/bls/private_key_test.go index 6e2e756e5..cfc1e3393 100644 --- a/crypto/bls/private_key_test.go +++ b/crypto/bls/private_key_test.go @@ -88,14 +88,14 @@ func TestPrivateKeyFromString(t *testing.T) { }, }, } - for no, test := range tests { - prv, err := bls.PrivateKeyFromString(test.encoded) - if test.valid { + for no, tt := range tests { + prv, err := bls.PrivateKeyFromString(tt.encoded) + if tt.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, test.result, prv.Bytes(), "test %v: invalid bytes", no) - assert.Equal(t, strings.ToUpper(test.encoded), prv.String(), "test %v: invalid encoded", no) + assert.Equal(t, tt.result, prv.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, strings.ToUpper(tt.encoded), prv.String(), "test %v: invalid encoded", no) } else { - assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) + assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } @@ -143,17 +143,17 @@ func TestKeyGen(t *testing.T) { }, } - for i, test := range tests { - ikm, _ := hex.DecodeString(test.ikm) + for no, tt := range tests { + ikm, _ := hex.DecodeString(tt.ikm) prv, err := bls.KeyGen(ikm, nil) - if test.sk == "Err" { + if tt.sk == "Err" { assert.Error(t, err, - "test '%v' failed. no error", i) + "test '%v' failed. no error", no) } else { assert.NoError(t, err, - "test'%v' failed. has error", i) - assert.Equal(t, test.sk, hex.EncodeToString(prv.Bytes()), - "test '%v' failed. not equal", i) + "test'%v' failed. has error", no) + assert.Equal(t, tt.sk, hex.EncodeToString(prv.Bytes()), + "test '%v' failed. not equal", no) } } } diff --git a/crypto/bls/public_key_test.go b/crypto/bls/public_key_test.go index 321c633d0..d7c31946f 100644 --- a/crypto/bls/public_key_test.go +++ b/crypto/bls/public_key_test.go @@ -51,17 +51,17 @@ func TestPublicKeyEncoding(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, _ := ts.RandBLSKeyPair() - w1 := util.NewFixedWriter(20) - assert.Error(t, pub.Encode(w1)) + fw1 := util.NewFixedWriter(20) + assert.Error(t, pub.Encode(fw1)) - w2 := util.NewFixedWriter(bls.PublicKeySize) - assert.NoError(t, pub.Encode(w2)) + fw2 := util.NewFixedWriter(bls.PublicKeySize) + assert.NoError(t, pub.Encode(fw2)) - r1 := util.NewFixedReader(20, w2.Bytes()) - assert.Error(t, pub.Decode(r1)) + fr1 := util.NewFixedReader(20, fw2.Bytes()) + assert.Error(t, pub.Decode(fr1)) - r2 := util.NewFixedReader(bls.PublicKeySize, w2.Bytes()) - assert.NoError(t, pub.Decode(r2)) + fr2 := util.NewFixedReader(bls.PublicKeySize, fw2.Bytes()) + assert.NoError(t, pub.Decode(fr2)) assert.Equal(t, bls.PublicKeySize, pub.SerializeSize()) } @@ -176,14 +176,14 @@ func TestPublicKeyFromString(t *testing.T) { }, } - for no, test := range tests { - pub, err := bls.PublicKeyFromString(test.encoded) - if test.valid { + for no, tt := range tests { + pub, err := bls.PublicKeyFromString(tt.encoded) + if tt.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, test.result, pub.Bytes(), "test %v: invalid bytes", no) - assert.Equal(t, test.encoded, pub.String(), "test %v: invalid encoded", no) + assert.Equal(t, tt.result, pub.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, tt.encoded, pub.String(), "test %v: invalid encoded", no) } else { - assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) + assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } @@ -220,15 +220,15 @@ func TestPointG2(t *testing.T) { }, } - for no, test := range tests { - pub, err := bls.PublicKeyFromString(test.encoded) + for no, tt := range tests { + pub, err := bls.PublicKeyFromString(tt.encoded) require.NoError(t, err) _, err = pub.PointG2() - if test.valid { + if tt.valid { assert.NoError(t, err, "test %v: unexpected error", no) } else { - assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) + assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } diff --git a/crypto/bls/signature_test.go b/crypto/bls/signature_test.go index 7b9055182..6ea58a782 100644 --- a/crypto/bls/signature_test.go +++ b/crypto/bls/signature_test.go @@ -57,17 +57,17 @@ func TestSignatureEncoding(t *testing.T) { _, prv := ts.RandBLSKeyPair() sig := prv.Sign(ts.RandBytes(16)) - w1 := util.NewFixedWriter(20) - assert.Error(t, sig.Encode(w1)) + fw1 := util.NewFixedWriter(20) + assert.Error(t, sig.Encode(fw1)) - w2 := util.NewFixedWriter(bls.SignatureSize) - assert.NoError(t, sig.Encode(w2)) + fw2 := util.NewFixedWriter(bls.SignatureSize) + assert.NoError(t, sig.Encode(fw2)) - r1 := util.NewFixedReader(20, w2.Bytes()) - assert.Error(t, sig.Decode(r1)) + fr1 := util.NewFixedReader(20, fw2.Bytes()) + assert.Error(t, sig.Decode(fr1)) - r2 := util.NewFixedReader(bls.SignatureSize, w2.Bytes()) - assert.NoError(t, sig.Decode(r2)) + fr2 := util.NewFixedReader(bls.SignatureSize, fw2.Bytes()) + assert.NoError(t, sig.Decode(fr2)) assert.Equal(t, bls.SignatureSize, sig.SerializeSize()) } @@ -128,14 +128,14 @@ func TestSignatureFromString(t *testing.T) { }, } - for no, test := range tests { - sig, err := bls.SignatureFromString(test.encoded) - if test.valid { + for no, tt := range tests { + sig, err := bls.SignatureFromString(tt.encoded) + if tt.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, test.bytes, sig.Bytes(), "test %v: invalid bytes", no) - assert.Equal(t, test.encoded, sig.String(), "test %v: invalid encode", no) + assert.Equal(t, tt.bytes, sig.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, tt.encoded, sig.String(), "test %v: invalid encode", no) } else { - assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) + assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } @@ -168,15 +168,15 @@ func TestPointG1(t *testing.T) { }, } - for no, test := range tests { - sig, err := bls.SignatureFromString(test.encoded) + for no, tt := range tests { + sig, err := bls.SignatureFromString(tt.encoded) require.NoError(t, err) _, err = sig.PointG1() - if test.valid { + if tt.valid { assert.NoError(t, err, "test %v: unexpected error", no) } else { - assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) + assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } diff --git a/crypto/ed25519/ed25519_test.go b/crypto/ed25519/ed25519_test.go index 2ba4a71a0..8184985bf 100644 --- a/crypto/ed25519/ed25519_test.go +++ b/crypto/ed25519/ed25519_test.go @@ -105,11 +105,11 @@ func TestEd25519S(t *testing.T) { }, } - for _, test := range tests { - privateKey, _ := ed25519.PrivateKeyFromBytes(ts.DecodingHex(test.sk)) - expectedPublicKey, _ := ed25519.PublicKeyFromBytes(ts.DecodingHex(test.pk)) - msg := ts.DecodingHex(test.msg) - expectedSig, _ := ed25519.SignatureFromString(test.sig) + for _, tt := range tests { + privateKey, _ := ed25519.PrivateKeyFromBytes(ts.DecodingHex(tt.sk)) + expectedPublicKey, _ := ed25519.PublicKeyFromBytes(ts.DecodingHex(tt.pk)) + msg := ts.DecodingHex(tt.msg) + expectedSig, _ := ed25519.SignatureFromString(tt.sig) sig := privateKey.Sign(msg) assert.Equal(t, expectedSig, sig) diff --git a/crypto/ed25519/hdkeychain/extendedkey.go b/crypto/ed25519/hdkeychain/extendedkey.go index 02846dbe3..0f304d721 100644 --- a/crypto/ed25519/hdkeychain/extendedkey.go +++ b/crypto/ed25519/hdkeychain/extendedkey.go @@ -146,34 +146,34 @@ func (k *ExtendedKey) String() string { // - Key data: The key data that is 32 bytes. // - w := bytes.NewBuffer(make([]byte, 0)) - err := encoding.WriteElement(w, byte(len(k.path))) + buf := bytes.NewBuffer(make([]byte, 0)) + err := encoding.WriteElement(buf, byte(len(k.path))) if err != nil { return err.Error() } for _, p := range k.path { - err := encoding.WriteElement(w, p) + err := encoding.WriteElement(buf, p) if err != nil { return err.Error() } } - err = encoding.WriteVarBytes(w, k.chainCode) + err = encoding.WriteVarBytes(buf, k.chainCode) if err != nil { return err.Error() } - err = encoding.WriteElement(w, uint8(0)) + err = encoding.WriteElement(buf, uint8(0)) if err != nil { return err.Error() } - err = encoding.WriteVarBytes(w, k.key) + err = encoding.WriteVarBytes(buf, k.key) if err != nil { return err.Error() } - str, err := bech32m.EncodeFromBase256WithType(crypto.XPrivateKeyHRP, crypto.SignatureTypeEd25519, w.Bytes()) + str, err := bech32m.EncodeFromBase256WithType(crypto.XPrivateKeyHRP, crypto.SignatureTypeEd25519, buf.Bytes()) if err != nil { return err.Error() } @@ -198,33 +198,33 @@ func NewKeyFromString(str string) (*ExtendedKey, error) { return nil, ErrInvalidHRP } - r := bytes.NewReader(data) + reader := bytes.NewReader(data) depth := uint8(0) - err = encoding.ReadElement(r, &depth) + err = encoding.ReadElement(reader, &depth) if err != nil { return nil, err } path := make([]uint32, depth) for i := byte(0); i < depth; i++ { - err := encoding.ReadElement(r, &path[i]) + err := encoding.ReadElement(reader, &path[i]) if err != nil { return nil, err } } - chainCode, err := encoding.ReadVarBytes(r) + chainCode, err := encoding.ReadVarBytes(reader) if err != nil { return nil, err } var res uint8 - err = encoding.ReadElement(r, &res) + err = encoding.ReadElement(reader, &res) if err != nil { return nil, err } - key, err := encoding.ReadVarBytes(r) + key, err := encoding.ReadVarBytes(reader) if err != nil { return nil, err } @@ -246,13 +246,13 @@ func NewMaster(seed []byte) (*ExtendedKey, error) { curve := []byte("ed25519 seed") hmac512 := hmac.New(sha512.New, curve) _, _ = hmac512.Write(seed) - lr := hmac512.Sum(nil) + ilr := hmac512.Sum(nil) // Split "I" into two 32-byte sequences Il and Ir where: // Il = master key // Ir = master chain code - masterChainCode := lr[32:] - masterKey := lr[:32] + masterChainCode := ilr[32:] + masterKey := ilr[:32] return newExtendedKey(masterKey, masterChainCode, []uint32{}), nil } diff --git a/crypto/ed25519/hdkeychain/extendedkey_test.go b/crypto/ed25519/hdkeychain/extendedkey_test.go index bb7e87073..ec61cd166 100644 --- a/crypto/ed25519/hdkeychain/extendedkey_test.go +++ b/crypto/ed25519/hdkeychain/extendedkey_test.go @@ -94,19 +94,19 @@ func TestDerivation(t *testing.T) { } masterKey, _ := NewMaster(testSeed) - for i, test := range tests { - extKey, err := masterKey.DerivePath(test.path) + for no, tt := range tests { + extKey, err := masterKey.DerivePath(tt.path) require.NoError(t, err) privKey := extKey.RawPrivateKey() - require.Equal(t, test.wantPrv, hex.EncodeToString(privKey), - "mismatched serialized private key for test #%v", i+1) + require.Equal(t, tt.wantPrv, hex.EncodeToString(privKey), + "mismatched serialized private key for test #%v", no+1) pubKey := extKey.RawPublicKey() - require.Equal(t, test.wantPub, hex.EncodeToString(pubKey), - "mismatched serialized public key for test #%v", i+1) + require.Equal(t, tt.wantPub, hex.EncodeToString(pubKey), + "mismatched serialized public key for test #%v", no+1) - require.Equal(t, test.path, extKey.Path()) + require.Equal(t, tt.path, extKey.Path()) } } @@ -129,14 +129,14 @@ func TestGenerateSeed(t *testing.T) { {name: "65 bytes", length: 65, err: ErrInvalidSeedLen}, } - for i, test := range tests { - seed, err := GenerateSeed(test.length) - assert.ErrorIs(t, err, test.err) + for no, tt := range tests { + seed, err := GenerateSeed(tt.length) + assert.ErrorIs(t, err, tt.err) - if test.err == nil { - assert.Len(t, seed, int(test.length), + if tt.err == nil { + assert.Len(t, seed, int(tt.length), "GenerateSeed #%d (%s): length mismatch -- got %d, want %d", - i+1, test.name, len(seed), test.length) + no+1, tt.name, len(seed), tt.length) } } } @@ -186,16 +186,16 @@ func TestNewMaster(t *testing.T) { }, } - for i, test := range tests { - seed, _ := hex.DecodeString(test.seed) + for no, tt := range tests { + seed, _ := hex.DecodeString(tt.seed) extKey, err := NewMaster(seed) - assert.ErrorIs(t, err, test.err) + assert.ErrorIs(t, err, tt.err) - if test.err == nil { + if tt.err == nil { privKey := extKey.RawPrivateKey() - assert.Equal(t, test.key, hex.EncodeToString(privKey), + assert.Equal(t, tt.key, hex.EncodeToString(privKey), "NewMaster #%d (%s): key mismatch -- got %x, want %s", - i+1, test.name, privKey, test.key) + no+1, tt.name, privKey, tt.key) } } } @@ -244,15 +244,15 @@ func TestKeyToString(t *testing.T) { } masterKey, _ := NewMaster(testSeed) - for i, test := range tests { - extKey, _ := masterKey.DerivePath(test.path) - require.Equal(t, test.wantXPriv, extKey.String(), "test %d failed", i) + for no, tt := range tests { + extKey, _ := masterKey.DerivePath(tt.path) + require.Equal(t, tt.wantXPriv, extKey.String(), "test %d failed", no) - recoveredExtKey, err := NewKeyFromString(test.wantXPriv) + recoveredExtKey, err := NewKeyFromString(tt.wantXPriv) require.NoError(t, err) require.Equal(t, extKey, recoveredExtKey) - require.Equal(t, test.path, recoveredExtKey.path) + require.Equal(t, tt.path, recoveredExtKey.path) } } @@ -307,8 +307,8 @@ func TestInvalidString(t *testing.T) { }, } - for i, test := range tests { - _, err := NewKeyFromString(test.str) - assert.ErrorIs(t, err, test.expectedError, "test %d error is not matched", i) + for no, tt := range tests { + _, err := NewKeyFromString(tt.str) + assert.ErrorIs(t, err, tt.expectedError, "test %d error is not matched", no) } } diff --git a/crypto/ed25519/private_key_test.go b/crypto/ed25519/private_key_test.go index 05bf9699a..2be4ab3f5 100644 --- a/crypto/ed25519/private_key_test.go +++ b/crypto/ed25519/private_key_test.go @@ -64,14 +64,14 @@ func TestPrivateKeyFromString(t *testing.T) { }, } - for no, test := range tests { - prv, err := ed25519.PrivateKeyFromString(test.encoded) - if test.valid { + for no, tt := range tests { + prv, err := ed25519.PrivateKeyFromString(tt.encoded) + if tt.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, test.result, prv.Bytes(), "test %v: invalid bytes", no) - assert.Equal(t, strings.ToUpper(test.encoded), prv.String(), "test %v: invalid encoded", no) + assert.Equal(t, tt.result, prv.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, strings.ToUpper(tt.encoded), prv.String(), "test %v: invalid encoded", no) } else { - assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) + assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } diff --git a/crypto/ed25519/public_key_test.go b/crypto/ed25519/public_key_test.go index 443e9e709..8aaa52a22 100644 --- a/crypto/ed25519/public_key_test.go +++ b/crypto/ed25519/public_key_test.go @@ -47,17 +47,17 @@ func TestPublicKeyEncoding(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, _ := ts.RandEd25519KeyPair() - w1 := util.NewFixedWriter(20) - assert.Error(t, pub.Encode(w1)) + fw1 := util.NewFixedWriter(20) + assert.Error(t, pub.Encode(fw1)) - w2 := util.NewFixedWriter(ed25519.PublicKeySize) - assert.NoError(t, pub.Encode(w2)) + fw2 := util.NewFixedWriter(ed25519.PublicKeySize) + assert.NoError(t, pub.Encode(fw2)) - r1 := util.NewFixedReader(20, w2.Bytes()) - assert.Error(t, pub.Decode(r1)) + fr1 := util.NewFixedReader(20, fw2.Bytes()) + assert.Error(t, pub.Decode(fr1)) - r2 := util.NewFixedReader(ed25519.PublicKeySize, w2.Bytes()) - assert.NoError(t, pub.Decode(r2)) + fr2 := util.NewFixedReader(ed25519.PublicKeySize, fw2.Bytes()) + assert.NoError(t, pub.Decode(fr2)) assert.Equal(t, ed25519.PublicKeySize, pub.SerializeSize()) } @@ -140,14 +140,14 @@ func TestPublicKeyFromString(t *testing.T) { }, } - for no, test := range tests { - pub, err := ed25519.PublicKeyFromString(test.encoded) - if test.valid { + for no, tt := range tests { + pub, err := ed25519.PublicKeyFromString(tt.encoded) + if tt.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, test.result, pub.Bytes(), "test %v: invalid bytes", no) - assert.Equal(t, test.encoded, pub.String(), "test %v: invalid encoded", no) + assert.Equal(t, tt.result, pub.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, tt.encoded, pub.String(), "test %v: invalid encoded", no) } else { - assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) + assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } diff --git a/crypto/ed25519/signature_test.go b/crypto/ed25519/signature_test.go index c8edd7442..7def32b6c 100644 --- a/crypto/ed25519/signature_test.go +++ b/crypto/ed25519/signature_test.go @@ -53,17 +53,17 @@ func TestSignatureEncoding(t *testing.T) { _, prv := ts.RandEd25519KeyPair() sig := prv.Sign(ts.RandBytes(16)) - w1 := util.NewFixedWriter(20) - assert.Error(t, sig.Encode(w1)) + fw1 := util.NewFixedWriter(20) + assert.Error(t, sig.Encode(fw1)) - w2 := util.NewFixedWriter(ed25519.SignatureSize) - assert.NoError(t, sig.Encode(w2)) + fw2 := util.NewFixedWriter(ed25519.SignatureSize) + assert.NoError(t, sig.Encode(fw2)) - r1 := util.NewFixedReader(20, w2.Bytes()) - assert.Error(t, sig.Decode(r1)) + fr1 := util.NewFixedReader(20, fw2.Bytes()) + assert.Error(t, sig.Decode(fr1)) - r2 := util.NewFixedReader(ed25519.SignatureSize, w2.Bytes()) - assert.NoError(t, sig.Decode(r2)) + fr2 := util.NewFixedReader(ed25519.SignatureSize, fw2.Bytes()) + assert.NoError(t, sig.Decode(fr2)) assert.Equal(t, ed25519.SignatureSize, sig.SerializeSize()) } @@ -116,14 +116,14 @@ func TestSignatureFromString(t *testing.T) { }, } - for no, test := range tests { - sig, err := ed25519.SignatureFromString(test.encoded) - if test.valid { + for no, tt := range tests { + sig, err := ed25519.SignatureFromString(tt.encoded) + if tt.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, test.bytes, sig.Bytes(), "test %v: invalid bytes", no) - assert.Equal(t, test.encoded, sig.String(), "test %v: invalid encode", no) + assert.Equal(t, tt.bytes, sig.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, tt.encoded, sig.String(), "test %v: invalid encode", no) } else { - assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) + assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } diff --git a/execution/execution.go b/execution/execution.go index 9e0955944..312a87f3f 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -6,37 +6,37 @@ import ( "github.com/pactus-project/pactus/types/tx" ) -func Execute(trx *tx.Tx, sb sandbox.Sandbox) error { - exe, err := executor.MakeExecutor(trx, sb) +func Execute(trx *tx.Tx, sbx sandbox.Sandbox) error { + exe, err := executor.MakeExecutor(trx, sbx) if err != nil { return err } exe.Execute() - sb.CommitTransaction(trx) + sbx.CommitTransaction(trx) return nil } -func CheckAndExecute(trx *tx.Tx, sb sandbox.Sandbox, strict bool) error { - exe, err := executor.MakeExecutor(trx, sb) +func CheckAndExecute(trx *tx.Tx, sbx sandbox.Sandbox, strict bool) error { + exe, err := executor.MakeExecutor(trx, sbx) if err != nil { return err } - if sb.IsBanned(trx.Payload().Signer()) { + if sbx.IsBanned(trx.Payload().Signer()) { return SignerBannedError{ addr: trx.Payload().Signer(), } } - if exists := sb.RecentTransaction(trx.ID()); exists { + if exists := sbx.RecentTransaction(trx.ID()); exists { return TransactionCommittedError{ ID: trx.ID(), } } - if err := CheckLockTime(trx, sb, strict); err != nil { + if err := CheckLockTime(trx, sbx, strict); err != nil { return err } @@ -49,22 +49,22 @@ func CheckAndExecute(trx *tx.Tx, sb sandbox.Sandbox, strict bool) error { } exe.Execute() - sb.CommitTransaction(trx) + sbx.CommitTransaction(trx) return nil } -func CheckLockTime(trx *tx.Tx, sb sandbox.Sandbox, strict bool) error { - interval := sb.Params().TransactionToLiveInterval +func CheckLockTime(trx *tx.Tx, sbx sandbox.Sandbox, strict bool) error { + interval := sbx.Params().TransactionToLiveInterval if trx.IsSubsidyTx() { interval = 0 } else if trx.IsSortitionTx() { - interval = sb.Params().SortitionInterval + interval = sbx.Params().SortitionInterval } - if sb.CurrentHeight() > interval { - if trx.LockTime() < sb.CurrentHeight()-interval { + if sbx.CurrentHeight() > interval { + if trx.LockTime() < sbx.CurrentHeight()-interval { return LockTimeExpiredError{ LockTime: trx.LockTime(), } @@ -75,7 +75,7 @@ func CheckLockTime(trx *tx.Tx, sb sandbox.Sandbox, strict bool) error { // In strict mode, transactions with future lock times are rejected. // In non-strict mode, they are added to the transaction pool and // processed once eligible. - if trx.LockTime() > sb.CurrentHeight() { + if trx.LockTime() > sbx.CurrentHeight() { return LockTimeInFutureError{ LockTime: trx.LockTime(), } diff --git a/execution/execution_test.go b/execution/execution_test.go index 74884f8f2..33a19d11e 100644 --- a/execution/execution_test.go +++ b/execution/execution_test.go @@ -15,13 +15,13 @@ import ( func TestTransferLockTime(t *testing.T) { ts := testsuite.NewTestSuite(t) - sb := sandbox.MockingSandbox(ts) + sbx := sandbox.MockingSandbox(ts) rndPubKey, rndPrvKey := ts.RandEd25519KeyPair() rndAccAddr := rndPubKey.AccountAddress() - rndAcc := sb.MakeNewAccount(rndAccAddr) + rndAcc := sbx.MakeNewAccount(rndAccAddr) rndAcc.AddToBalance(1000 * 1e9) - sb.UpdateAccount(rndAccAddr, rndAcc) - _ = sb.TestStore.AddTestBlock(8642) + sbx.UpdateAccount(rndAccAddr, rndAcc) + _ = sbx.TestStore.AddTestBlock(8642) tests := []struct { name string @@ -31,46 +31,46 @@ func TestTransferLockTime(t *testing.T) { }{ { name: "Transaction has expired LockTime (-8641)", - lockTime: sb.CurrentHeight() - sb.TestParams.TransactionToLiveInterval - 1, - strictErr: LockTimeExpiredError{sb.CurrentHeight() - sb.TestParams.TransactionToLiveInterval - 1}, - nonStrictErr: LockTimeExpiredError{sb.CurrentHeight() - sb.TestParams.TransactionToLiveInterval - 1}, + lockTime: sbx.CurrentHeight() - sbx.TestParams.TransactionToLiveInterval - 1, + strictErr: LockTimeExpiredError{sbx.CurrentHeight() - sbx.TestParams.TransactionToLiveInterval - 1}, + nonStrictErr: LockTimeExpiredError{sbx.CurrentHeight() - sbx.TestParams.TransactionToLiveInterval - 1}, }, { name: "Transaction has valid LockTime (-8640)", - lockTime: sb.CurrentHeight() - sb.TestParams.TransactionToLiveInterval, + lockTime: sbx.CurrentHeight() - sbx.TestParams.TransactionToLiveInterval, strictErr: nil, nonStrictErr: nil, }, { name: "Transaction has valid LockTime (-88)", - lockTime: sb.CurrentHeight() - 88, + lockTime: sbx.CurrentHeight() - 88, strictErr: nil, nonStrictErr: nil, }, { name: "Transaction has valid LockTime (0)", - lockTime: sb.CurrentHeight(), + lockTime: sbx.CurrentHeight(), strictErr: nil, nonStrictErr: nil, }, { name: "Transaction has future LockTime (+1)", - lockTime: sb.CurrentHeight() + 1, - strictErr: LockTimeInFutureError{sb.CurrentHeight() + 1}, + lockTime: sbx.CurrentHeight() + 1, + strictErr: LockTimeInFutureError{sbx.CurrentHeight() + 1}, nonStrictErr: nil, }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - trx := tx.NewTransferTx(tc.lockTime, rndAccAddr, ts.RandAccAddress(), 1000, 1000) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + trx := tx.NewTransferTx(tt.lockTime, rndAccAddr, ts.RandAccAddress(), 1000, 1000) ts.HelperSignTransaction(rndPrvKey, trx) - strictErr := CheckLockTime(trx, sb, true) - assert.ErrorIs(t, strictErr, tc.strictErr) + strictErr := CheckLockTime(trx, sbx, true) + assert.ErrorIs(t, strictErr, tt.strictErr) - nonStrictErr := CheckLockTime(trx, sb, false) - assert.ErrorIs(t, nonStrictErr, tc.nonStrictErr) + nonStrictErr := CheckLockTime(trx, sbx, false) + assert.ErrorIs(t, nonStrictErr, tt.nonStrictErr) }) } } @@ -78,14 +78,14 @@ func TestTransferLockTime(t *testing.T) { func TestSortitionLockTime(t *testing.T) { ts := testsuite.NewTestSuite(t) - sb := sandbox.MockingSandbox(ts) - sb.TestAcceptSortition = true + sbx := sandbox.MockingSandbox(ts) + sbx.TestAcceptSortition = true rndPubKey, rndPrvKey := ts.RandBLSKeyPair() rndValAddr := rndPubKey.ValidatorAddress() - rndVal := sb.MakeNewValidator(rndPubKey) + rndVal := sbx.MakeNewValidator(rndPubKey) rndVal.AddToStake(1000 * 1e9) - sb.UpdateValidator(rndVal) - _ = sb.TestStore.AddTestBlock(8642) + sbx.UpdateValidator(rndVal) + _ = sbx.TestStore.AddTestBlock(8642) tests := []struct { name string @@ -95,46 +95,46 @@ func TestSortitionLockTime(t *testing.T) { }{ { name: "Sortition transaction has expired LockTime (-8)", - lockTime: sb.CurrentHeight() - sb.TestParams.SortitionInterval - 1, - strictErr: LockTimeExpiredError{sb.CurrentHeight() - sb.TestParams.SortitionInterval - 1}, - nonStrictErr: LockTimeExpiredError{sb.CurrentHeight() - sb.TestParams.SortitionInterval - 1}, + lockTime: sbx.CurrentHeight() - sbx.TestParams.SortitionInterval - 1, + strictErr: LockTimeExpiredError{sbx.CurrentHeight() - sbx.TestParams.SortitionInterval - 1}, + nonStrictErr: LockTimeExpiredError{sbx.CurrentHeight() - sbx.TestParams.SortitionInterval - 1}, }, { name: "Sortition transaction has valid LockTime (-7)", - lockTime: sb.CurrentHeight() - sb.TestParams.SortitionInterval, + lockTime: sbx.CurrentHeight() - sbx.TestParams.SortitionInterval, strictErr: nil, nonStrictErr: nil, }, { name: "Sortition transaction has valid LockTime (-1)", - lockTime: sb.CurrentHeight() - 1, + lockTime: sbx.CurrentHeight() - 1, strictErr: nil, nonStrictErr: nil, }, { name: "Sortition transaction has valid LockTime (0)", - lockTime: sb.CurrentHeight(), + lockTime: sbx.CurrentHeight(), strictErr: nil, nonStrictErr: nil, }, { name: "Sortition transaction has future LockTime (+1)", - lockTime: sb.CurrentHeight() + 1, - strictErr: LockTimeInFutureError{sb.CurrentHeight() + 1}, + lockTime: sbx.CurrentHeight() + 1, + strictErr: LockTimeInFutureError{sbx.CurrentHeight() + 1}, nonStrictErr: nil, }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - trx := tx.NewSortitionTx(tc.lockTime, rndValAddr, ts.RandProof()) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + trx := tx.NewSortitionTx(tt.lockTime, rndValAddr, ts.RandProof()) ts.HelperSignTransaction(rndPrvKey, trx) - strictErr := CheckLockTime(trx, sb, true) - assert.ErrorIs(t, strictErr, tc.strictErr) + strictErr := CheckLockTime(trx, sbx, true) + assert.ErrorIs(t, strictErr, tt.strictErr) - nonStrictErr := CheckLockTime(trx, sb, false) - assert.ErrorIs(t, nonStrictErr, tc.nonStrictErr) + nonStrictErr := CheckLockTime(trx, sbx, false) + assert.ErrorIs(t, nonStrictErr, tt.nonStrictErr) }) } } @@ -142,8 +142,8 @@ func TestSortitionLockTime(t *testing.T) { func TestSubsidyLockTime(t *testing.T) { ts := testsuite.NewTestSuite(t) - sb := sandbox.MockingSandbox(ts) - _ = sb.TestStore.AddTestBlock(8642) + sbx := sandbox.MockingSandbox(ts) + _ = sbx.TestStore.AddTestBlock(8642) tests := []struct { name string @@ -153,33 +153,33 @@ func TestSubsidyLockTime(t *testing.T) { }{ { name: "Subsidy transaction has expired LockTime (-1)", - lockTime: sb.CurrentHeight() - 1, - strictErr: LockTimeExpiredError{sb.CurrentHeight() - 1}, - nonStrictErr: LockTimeExpiredError{sb.CurrentHeight() - 1}, + lockTime: sbx.CurrentHeight() - 1, + strictErr: LockTimeExpiredError{sbx.CurrentHeight() - 1}, + nonStrictErr: LockTimeExpiredError{sbx.CurrentHeight() - 1}, }, { name: "Subsidy transaction has valid LockTime (0)", - lockTime: sb.CurrentHeight(), + lockTime: sbx.CurrentHeight(), strictErr: nil, nonStrictErr: nil, }, { name: "Subsidy transaction has future LockTime (+1)", - lockTime: sb.CurrentHeight() + 1, - strictErr: LockTimeInFutureError{sb.CurrentHeight() + 1}, + lockTime: sbx.CurrentHeight() + 1, + strictErr: LockTimeInFutureError{sbx.CurrentHeight() + 1}, nonStrictErr: nil, }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - trx := tx.NewSubsidyTx(tc.lockTime, ts.RandAccAddress(), 1000) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + trx := tx.NewSubsidyTx(tt.lockTime, ts.RandAccAddress(), 1000) - strictErr := CheckLockTime(trx, sb, true) - assert.ErrorIs(t, strictErr, tc.strictErr) + strictErr := CheckLockTime(trx, sbx, true) + assert.ErrorIs(t, strictErr, tt.strictErr) - nonStrictErr := CheckLockTime(trx, sb, false) - assert.ErrorIs(t, nonStrictErr, tc.nonStrictErr) + nonStrictErr := CheckLockTime(trx, sbx, false) + assert.ErrorIs(t, nonStrictErr, tt.nonStrictErr) }) } } @@ -218,10 +218,10 @@ func TestCheckFee(t *testing.T) { }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - err := CheckFee(tc.trx) - assert.ErrorIs(t, err, tc.expectedErr) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := CheckFee(tt.trx) + assert.ErrorIs(t, err, tt.expectedErr) }) } } @@ -229,40 +229,40 @@ func TestCheckFee(t *testing.T) { func TestExecute(t *testing.T) { ts := testsuite.NewTestSuite(t) - sb := sandbox.MockingSandbox(ts) - _ = sb.TestStore.AddTestBlock(8642) - lockTime := sb.CurrentHeight() + sbx := sandbox.MockingSandbox(ts) + _ = sbx.TestStore.AddTestBlock(8642) + lockTime := sbx.CurrentHeight() t.Run("Invalid transaction, Should return error", func(t *testing.T) { randAddr := ts.RandAccAddress() trx := tx.NewTransferTx(lockTime, randAddr, ts.RandAccAddress(), ts.RandAmount(), ts.RandFee()) - err := Execute(trx, sb) + err := Execute(trx, sbx) assert.ErrorIs(t, err, executor.AccountNotFoundError{Address: randAddr}) }) t.Run("Ok", func(t *testing.T) { trx := tx.NewSubsidyTx(lockTime, ts.RandAccAddress(), 1000) - err := Execute(trx, sb) + err := Execute(trx, sbx) assert.NoError(t, err) - assert.True(t, sb.RecentTransaction(trx.ID())) + assert.True(t, sbx.RecentTransaction(trx.ID())) }) } func TestCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) - sb := sandbox.MockingSandbox(ts) - _ = sb.TestStore.AddTestBlock(8642) - lockTime := sb.CurrentHeight() + sbx := sandbox.MockingSandbox(ts) + _ = sbx.TestStore.AddTestBlock(8642) + lockTime := sbx.CurrentHeight() t.Run("Invalid lock-time, Should return error", func(t *testing.T) { invalidLocoTme := lockTime + 1 trx := tx.NewTransferTx(invalidLocoTme, crypto.TreasuryAddress, ts.RandAccAddress(), ts.RandAmount(), 0) - err := CheckAndExecute(trx, sb, true) + err := CheckAndExecute(trx, sbx, true) assert.ErrorIs(t, err, LockTimeInFutureError{LockTime: invalidLocoTme}) }) @@ -270,7 +270,7 @@ func TestCheck(t *testing.T) { invalidFee := amount.Amount(1) trx := tx.NewTransferTx(lockTime, crypto.TreasuryAddress, ts.RandAccAddress(), ts.RandAmount(), invalidFee) - err := CheckAndExecute(trx, sb, true) + err := CheckAndExecute(trx, sbx, true) assert.ErrorIs(t, err, InvalidFeeError{Fee: invalidFee, Expected: 0}) }) @@ -278,47 +278,47 @@ func TestCheck(t *testing.T) { randAddr := ts.RandAccAddress() trx := tx.NewTransferTx(lockTime, randAddr, ts.RandAccAddress(), ts.RandAmount(), ts.RandFee()) - err := CheckAndExecute(trx, sb, true) + err := CheckAndExecute(trx, sbx, true) assert.ErrorIs(t, err, executor.AccountNotFoundError{Address: randAddr}) }) t.Run("Invalid transaction, Should return error", func(t *testing.T) { - valAddr := sb.TestCommittee.Validators()[0].Address() - sb.TestAcceptSortition = false + valAddr := sbx.TestCommittee.Validators()[0].Address() + sbx.TestAcceptSortition = false trx := tx.NewSortitionTx(lockTime, valAddr, ts.RandProof()) - err := CheckAndExecute(trx, sb, true) + err := CheckAndExecute(trx, sbx, true) assert.ErrorIs(t, err, executor.ErrInvalidSortitionProof) }) t.Run("Ok", func(t *testing.T) { trx := tx.NewSubsidyTx(lockTime, ts.RandAccAddress(), 1000) - err := CheckAndExecute(trx, sb, true) + err := CheckAndExecute(trx, sbx, true) assert.NoError(t, err) - assert.True(t, sb.RecentTransaction(trx.ID())) + assert.True(t, sbx.RecentTransaction(trx.ID())) }) } func TestReplay(t *testing.T) { ts := testsuite.NewTestSuite(t) - sb := sandbox.MockingSandbox(ts) + sbx := sandbox.MockingSandbox(ts) rndPubKey, rndPrvKey := ts.RandEd25519KeyPair() rndAccAddr := rndPubKey.AccountAddress() - rndAcc := sb.MakeNewAccount(rndAccAddr) + rndAcc := sbx.MakeNewAccount(rndAccAddr) rndAcc.AddToBalance(1e9) - sb.UpdateAccount(rndAccAddr, rndAcc) - lockTime := sb.CurrentHeight() + sbx.UpdateAccount(rndAccAddr, rndAcc) + lockTime := sbx.CurrentHeight() trx := tx.NewTransferTx(lockTime, rndAccAddr, ts.RandAccAddress(), 10000, 1000) ts.HelperSignTransaction(rndPrvKey, trx) - err := Execute(trx, sb) + err := Execute(trx, sbx) assert.NoError(t, err) - err = CheckAndExecute(trx, sb, false) + err = CheckAndExecute(trx, sbx, false) assert.ErrorIs(t, err, TransactionCommittedError{ ID: trx.ID(), }) diff --git a/execution/executor/bond.go b/execution/executor/bond.go index 01449aa85..2a9b96beb 100644 --- a/execution/executor/bond.go +++ b/execution/executor/bond.go @@ -10,33 +10,33 @@ import ( ) type BondExecutor struct { - sb sandbox.Sandbox + sbx sandbox.Sandbox pld *payload.BondPayload fee amount.Amount sender *account.Account receiver *validator.Validator } -func newBondExecutor(trx *tx.Tx, sb sandbox.Sandbox) (*BondExecutor, error) { +func newBondExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*BondExecutor, error) { pld := trx.Payload().(*payload.BondPayload) - sender := sb.Account(pld.From) + sender := sbx.Account(pld.From) if sender == nil { return nil, AccountNotFoundError{Address: pld.From} } - receiver := sb.Validator(pld.To) + receiver := sbx.Validator(pld.To) if receiver == nil { if pld.PublicKey == nil { return nil, ErrPublicKeyNotSet } - receiver = sb.MakeNewValidator(pld.PublicKey) + receiver = sbx.MakeNewValidator(pld.PublicKey) } else if pld.PublicKey != nil { return nil, ErrPublicKeyAlreadySet } return &BondExecutor{ - sb: sb, + sbx: sbx, pld: pld, fee: trx.Fee(), sender: sender, @@ -53,20 +53,20 @@ func (e *BondExecutor) Check(strict bool) error { return ErrInsufficientFunds } - if e.pld.Stake < e.sb.Params().MinimumStake { + if e.pld.Stake < e.sbx.Params().MinimumStake { // This check prevents a potential attack where an attacker could send zero // or a small amount of stake to a full validator, effectively parking the // validator for the bonding period. - if e.pld.Stake == 0 || e.pld.Stake+e.receiver.Stake() != e.sb.Params().MaximumStake { + if e.pld.Stake == 0 || e.pld.Stake+e.receiver.Stake() != e.sbx.Params().MaximumStake { return SmallStakeError{ - Minimum: e.sb.Params().MinimumStake, + Minimum: e.sbx.Params().MinimumStake, } } } - if e.receiver.Stake()+e.pld.Stake > e.sb.Params().MaximumStake { + if e.receiver.Stake()+e.pld.Stake > e.sbx.Params().MaximumStake { return MaximumStakeError{ - Maximum: e.sb.Params().MaximumStake, + Maximum: e.sbx.Params().MaximumStake, } } @@ -75,7 +75,7 @@ func (e *BondExecutor) Check(strict bool) error { // already in the committee. // In non-strict mode, they are added to the transaction pool and // processed once eligible. - if e.sb.Committee().Contains(e.pld.To) { + if e.sbx.Committee().Contains(e.pld.To) { return ErrValidatorInCommittee } @@ -83,7 +83,7 @@ func (e *BondExecutor) Check(strict bool) error { // going to join the committee in the next height. // In non-strict mode, they are added to the transaction pool and // processed once eligible. - if e.sb.IsJoinedCommittee(e.pld.To) { + if e.sbx.IsJoinedCommittee(e.pld.To) { return ErrValidatorInCommittee } } @@ -94,9 +94,9 @@ func (e *BondExecutor) Check(strict bool) error { func (e *BondExecutor) Execute() { e.sender.SubtractFromBalance(e.pld.Stake + e.fee) e.receiver.AddToStake(e.pld.Stake) - e.receiver.UpdateLastBondingHeight(e.sb.CurrentHeight()) + e.receiver.UpdateLastBondingHeight(e.sbx.CurrentHeight()) - e.sb.UpdatePowerDelta(int64(e.pld.Stake)) - e.sb.UpdateAccount(e.pld.From, e.sender) - e.sb.UpdateValidator(e.receiver) + e.sbx.UpdatePowerDelta(int64(e.pld.Stake)) + e.sbx.UpdateAccount(e.pld.From, e.sender) + e.sbx.UpdateValidator(e.receiver) } diff --git a/execution/executor/bond_test.go b/execution/executor/bond_test.go index 6ae24e6b9..a68919e5f 100644 --- a/execution/executor/bond_test.go +++ b/execution/executor/bond_test.go @@ -10,16 +10,16 @@ import ( func TestExecuteBondTx(t *testing.T) { td := setup(t) - senderAddr, senderAcc := td.sandbox.TestStore.RandomTestAcc() + senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() senderBalance := senderAcc.Balance() valPub, _ := td.RandBLSKeyPair() receiverAddr := valPub.ValidatorAddress() amt := td.RandAmountRange( - td.sandbox.TestParams.MinimumStake, - td.sandbox.TestParams.MaximumStake) + td.sbx.TestParams.MinimumStake, + td.sbx.TestParams.MaximumStake) fee := td.RandFee() - lockTime := td.sandbox.CurrentHeight() + lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandAccAddress() @@ -38,8 +38,8 @@ func TestExecuteBondTx(t *testing.T) { t.Run("Should fail, public key should not set for existing validators", func(t *testing.T) { randPub, _ := td.RandBLSKeyPair() - val := td.sandbox.MakeNewValidator(randPub) - td.sandbox.UpdateValidator(val) + val := td.sbx.MakeNewValidator(randPub) + td.sbx.UpdateValidator(val) trx := tx.NewBondTx(lockTime, senderAddr, randPub.ValidatorAddress(), randPub, amt, fee) @@ -56,9 +56,9 @@ func TestExecuteBondTx(t *testing.T) { t.Run("Should fail, unbonded before", func(t *testing.T) { randPub, _ := td.RandBLSKeyPair() - val := td.sandbox.MakeNewValidator(randPub) + val := td.sbx.MakeNewValidator(randPub) val.UpdateUnbondingHeight(td.RandHeight()) - td.sandbox.UpdateValidator(val) + td.sbx.UpdateValidator(val) trx := tx.NewBondTx(lockTime, senderAddr, randPub.ValidatorAddress(), nil, amt, fee) td.check(t, trx, true, ErrValidatorUnbonded) @@ -66,21 +66,21 @@ func TestExecuteBondTx(t *testing.T) { }) t.Run("Should fail, amount less than MinimumStake", func(t *testing.T) { - trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, td.sandbox.TestParams.MinimumStake-1, fee) + trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, td.sbx.TestParams.MinimumStake-1, fee) - td.check(t, trx, true, SmallStakeError{td.sandbox.TestParams.MinimumStake}) - td.check(t, trx, false, SmallStakeError{td.sandbox.TestParams.MinimumStake}) + td.check(t, trx, true, SmallStakeError{td.sbx.TestParams.MinimumStake}) + td.check(t, trx, false, SmallStakeError{td.sbx.TestParams.MinimumStake}) }) t.Run("Should fail, validator's stake exceeds the MaximumStake", func(t *testing.T) { - trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, td.sandbox.TestParams.MaximumStake+1, fee) + trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, td.sbx.TestParams.MaximumStake+1, fee) - td.check(t, trx, true, MaximumStakeError{td.sandbox.TestParams.MaximumStake}) - td.check(t, trx, false, MaximumStakeError{td.sandbox.TestParams.MaximumStake}) + td.check(t, trx, true, MaximumStakeError{td.sbx.TestParams.MaximumStake}) + td.check(t, trx, false, MaximumStakeError{td.sbx.TestParams.MaximumStake}) }) t.Run("Should fail, inside committee", func(t *testing.T) { - pub0 := td.sandbox.Committee().Proposer(0).PublicKey() + pub0 := td.sbx.Committee().Proposer(0).PublicKey() trx := tx.NewBondTx(lockTime, senderAddr, pub0.ValidatorAddress(), nil, 1e9, fee) td.check(t, trx, true, ErrValidatorInCommittee) @@ -89,9 +89,9 @@ func TestExecuteBondTx(t *testing.T) { t.Run("Should fail, joining committee", func(t *testing.T) { randPub, _ := td.RandBLSKeyPair() - val := td.sandbox.MakeNewValidator(randPub) - td.sandbox.UpdateValidator(val) - td.sandbox.JoinedToCommittee(val.Address()) + val := td.sbx.MakeNewValidator(randPub) + td.sbx.UpdateValidator(val) + td.sbx.JoinedToCommittee(val.Address()) trx := tx.NewBondTx(lockTime, senderAddr, randPub.ValidatorAddress(), nil, amt, fee) td.check(t, trx, true, ErrValidatorInCommittee) @@ -106,8 +106,8 @@ func TestExecuteBondTx(t *testing.T) { td.execute(t, trx) }) - updatedSenderAcc := td.sandbox.Account(senderAddr) - updatedReceiverVal := td.sandbox.Validator(receiverAddr) + updatedSenderAcc := td.sbx.Account(senderAddr) + updatedReceiverVal := td.sbx.Validator(receiverAddr) assert.Equal(t, senderBalance-(amt+fee), updatedSenderAcc.Balance()) assert.Equal(t, amt, updatedReceiverVal.Stake()) assert.Equal(t, lockTime, updatedReceiverVal.LastBondingHeight()) @@ -118,19 +118,19 @@ func TestExecuteBondTx(t *testing.T) { func TestPowerDeltaBond(t *testing.T) { td := setup(t) - senderAddr, _ := td.sandbox.TestStore.RandomTestAcc() + senderAddr, _ := td.sbx.TestStore.RandomTestAcc() pub, _ := td.RandBLSKeyPair() receiverAddr := pub.ValidatorAddress() amt := td.RandAmountRange( - td.sandbox.TestParams.MinimumStake, - td.sandbox.TestParams.MaximumStake) + td.sbx.TestParams.MinimumStake, + td.sbx.TestParams.MaximumStake) fee := td.RandFee() - lockTime := td.sandbox.CurrentHeight() + lockTime := td.sbx.CurrentHeight() trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, pub, amt, fee) td.execute(t, trx) - assert.Equal(t, int64(amt), td.sandbox.PowerDelta()) + assert.Equal(t, int64(amt), td.sbx.PowerDelta()) } // TestSmallBond tests scenarios involving small and zero stake amounts in bond transactions. @@ -139,27 +139,27 @@ func TestPowerDeltaBond(t *testing.T) { func TestSmallBond(t *testing.T) { td := setup(t) - senderAddr, _ := td.sandbox.TestStore.RandomTestAcc() + senderAddr, _ := td.sbx.TestStore.RandomTestAcc() receiverPub, _ := td.RandBLSKeyPair() receiverAddr := receiverPub.ValidatorAddress() - receiverVal := td.sandbox.MakeNewValidator(receiverPub) - receiverVal.AddToStake(td.sandbox.TestParams.MaximumStake - 2) - td.sandbox.UpdateValidator(receiverVal) - lockTime := td.sandbox.CurrentHeight() + receiverVal := td.sbx.MakeNewValidator(receiverPub) + receiverVal.AddToStake(td.sbx.TestParams.MaximumStake - 2) + td.sbx.UpdateValidator(receiverVal) + lockTime := td.sbx.CurrentHeight() fee := td.RandFee() t.Run("Rejects bond transaction with zero amount", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, nil, 0, fee) - td.check(t, trx, true, SmallStakeError{td.sandbox.TestParams.MinimumStake}) - td.check(t, trx, false, SmallStakeError{td.sandbox.TestParams.MinimumStake}) + td.check(t, trx, true, SmallStakeError{td.sbx.TestParams.MinimumStake}) + td.check(t, trx, false, SmallStakeError{td.sbx.TestParams.MinimumStake}) }) t.Run("Rejects bond transaction below full validator stake", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, nil, 1, fee) - td.check(t, trx, true, SmallStakeError{td.sandbox.TestParams.MinimumStake}) - td.check(t, trx, false, SmallStakeError{td.sandbox.TestParams.MinimumStake}) + td.check(t, trx, true, SmallStakeError{td.sbx.TestParams.MinimumStake}) + td.check(t, trx, false, SmallStakeError{td.sbx.TestParams.MinimumStake}) }) t.Run("Accepts bond transaction reaching full validator stake", func(t *testing.T) { @@ -173,10 +173,10 @@ func TestSmallBond(t *testing.T) { t.Run("Rejects bond transaction with zero amount on full validator", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, nil, 0, fee) - td.check(t, trx, true, SmallStakeError{td.sandbox.TestParams.MinimumStake}) - td.check(t, trx, false, SmallStakeError{td.sandbox.TestParams.MinimumStake}) + td.check(t, trx, true, SmallStakeError{td.sbx.TestParams.MinimumStake}) + td.check(t, trx, false, SmallStakeError{td.sbx.TestParams.MinimumStake}) }) - receiverValAfterExecution, _ := td.sandbox.TestStore.Validator(receiverVal.Address()) - assert.Equal(t, td.sandbox.Params().MaximumStake, receiverValAfterExecution.Stake()) + receiverValAfterExecution, _ := td.sbx.TestStore.Validator(receiverVal.Address()) + assert.Equal(t, td.sbx.Params().MaximumStake, receiverValAfterExecution.Stake()) } diff --git a/execution/executor/executor.go b/execution/executor/executor.go index a608557bb..89a8e6fac 100644 --- a/execution/executor/executor.go +++ b/execution/executor/executor.go @@ -11,23 +11,23 @@ type Executor interface { Execute() } -func MakeExecutor(trx *tx.Tx, sb sandbox.Sandbox) (Executor, error) { +func MakeExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (Executor, error) { var exe Executor var err error - switch t := trx.Payload().Type(); t { + switch typ := trx.Payload().Type(); typ { case payload.TypeTransfer: - exe, err = newTransferExecutor(trx, sb) + exe, err = newTransferExecutor(trx, sbx) case payload.TypeBond: - exe, err = newBondExecutor(trx, sb) + exe, err = newBondExecutor(trx, sbx) case payload.TypeUnbond: - exe, err = newUnbondExecutor(trx, sb) + exe, err = newUnbondExecutor(trx, sbx) case payload.TypeWithdraw: - exe, err = newWithdrawExecutor(trx, sb) + exe, err = newWithdrawExecutor(trx, sbx) case payload.TypeSortition: - exe, err = newSortitionExecutor(trx, sb) + exe, err = newSortitionExecutor(trx, sbx) default: return nil, InvalidPayloadTypeError{ - PayloadType: t, + PayloadType: typ, } } diff --git a/execution/executor/executor_test.go b/execution/executor/executor_test.go index 82386d9ca..5802c8a0c 100644 --- a/execution/executor/executor_test.go +++ b/execution/executor/executor_test.go @@ -14,7 +14,7 @@ import ( type testData struct { *testsuite.TestSuite - sandbox *sandbox.MockSandbox + sbx *sandbox.MockSandbox } func setup(t *testing.T) *testData { @@ -22,13 +22,13 @@ func setup(t *testing.T) *testData { ts := testsuite.NewTestSuite(t) - sb := sandbox.MockingSandbox(ts) + sbx := sandbox.MockingSandbox(ts) randHeight := ts.RandHeight() - _ = sb.TestStore.AddTestBlock(randHeight) + _ = sbx.TestStore.AddTestBlock(randHeight) return &testData{ TestSuite: ts, - sandbox: sb, + sbx: sbx, } } @@ -36,11 +36,11 @@ func (td *testData) checkTotalCoin(t *testing.T, fee amount.Amount) { t.Helper() total := amount.Amount(0) - for _, acc := range td.sandbox.TestStore.Accounts { + for _, acc := range td.sbx.TestStore.Accounts { total += acc.Balance() } - for _, val := range td.sandbox.TestStore.Validators { + for _, val := range td.sbx.TestStore.Validators { total += val.Stake() } assert.Equal(t, total+fee, amount.Amount(21_000_000*1e9)) @@ -49,7 +49,7 @@ func (td *testData) checkTotalCoin(t *testing.T, fee amount.Amount) { func (td *testData) check(t *testing.T, trx *tx.Tx, strict bool, expectedErr error) { t.Helper() - exe, err := MakeExecutor(trx, td.sandbox) + exe, err := MakeExecutor(trx, td.sbx) if err != nil { assert.ErrorIs(t, err, expectedErr) @@ -63,7 +63,7 @@ func (td *testData) check(t *testing.T, trx *tx.Tx, strict bool, expectedErr err func (td *testData) execute(t *testing.T, trx *tx.Tx) { t.Helper() - exe, err := MakeExecutor(trx, td.sandbox) + exe, err := MakeExecutor(trx, td.sbx) require.NoError(t, err) exe.Execute() diff --git a/execution/executor/sortition.go b/execution/executor/sortition.go index dedf6a7b1..13e4927a0 100644 --- a/execution/executor/sortition.go +++ b/execution/executor/sortition.go @@ -10,16 +10,16 @@ import ( ) type SortitionExecutor struct { - sb sandbox.Sandbox + sbx sandbox.Sandbox pld *payload.SortitionPayload validator *validator.Validator sortitionHeight uint32 } -func newSortitionExecutor(trx *tx.Tx, sb sandbox.Sandbox) (*SortitionExecutor, error) { +func newSortitionExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*SortitionExecutor, error) { pld := trx.Payload().(*payload.SortitionPayload) - val := sb.Validator(pld.Validator) + val := sbx.Validator(pld.Validator) if val == nil { return nil, ValidatorNotFoundError{ Address: pld.Validator, @@ -28,18 +28,18 @@ func newSortitionExecutor(trx *tx.Tx, sb sandbox.Sandbox) (*SortitionExecutor, e return &SortitionExecutor{ pld: pld, - sb: sb, + sbx: sbx, validator: val, sortitionHeight: trx.LockTime(), }, nil } func (e *SortitionExecutor) Check(strict bool) error { - if e.sb.CurrentHeight()-e.validator.LastBondingHeight() < e.sb.Params().BondInterval { + if e.sbx.CurrentHeight()-e.validator.LastBondingHeight() < e.sbx.Params().BondInterval { return ErrBondingPeriod } - ok := e.sb.VerifyProof(e.sortitionHeight, e.pld.Proof, e.validator) + ok := e.sbx.VerifyProof(e.sortitionHeight, e.pld.Proof, e.validator) if !ok { return ErrInvalidSortitionProof } @@ -59,9 +59,9 @@ func (e *SortitionExecutor) Check(strict bool) error { } func (e *SortitionExecutor) canJoinCommittee() error { - if e.sb.Committee().Size() < e.sb.Params().CommitteeSize { + if e.sbx.Committee().Size() < e.sbx.Params().CommitteeSize { // There are available seats in the committee. - if e.sb.Committee().Contains(e.pld.Validator) { + if e.sbx.Committee().Contains(e.pld.Validator) { return ErrValidatorInCommittee } @@ -71,8 +71,8 @@ func (e *SortitionExecutor) canJoinCommittee() error { // The committee is full, check if the validator can join the committee. joiningNum := 0 joiningPower := int64(0) - committee := e.sb.Committee() - e.sb.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { + committee := e.sbx.Committee() + e.sbx.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { if joined { if !committee.Contains(val.Address()) { joiningPower += val.Power() @@ -100,7 +100,7 @@ func (e *SortitionExecutor) canJoinCommittee() error { return ErrCommitteeLeaveLimitExceeded } - oldestSortitionHeight := e.sb.CurrentHeight() + oldestSortitionHeight := e.sbx.CurrentHeight() for _, v := range committee.Validators() { if v.LastSortitionHeight() < oldestSortitionHeight { oldestSortitionHeight = v.LastSortitionHeight() @@ -109,7 +109,7 @@ func (e *SortitionExecutor) canJoinCommittee() error { // If the oldest validator in the committee still hasn't propose a block yet, // it stays in the committee. - proposerHeight := e.sb.Committee().Proposer(0).LastSortitionHeight() + proposerHeight := e.sbx.Committee().Proposer(0).LastSortitionHeight() if oldestSortitionHeight >= proposerHeight { return ErrOldestValidatorNotProposed } @@ -120,6 +120,6 @@ func (e *SortitionExecutor) canJoinCommittee() error { func (e *SortitionExecutor) Execute() { e.validator.UpdateLastSortitionHeight(e.sortitionHeight) - e.sb.JoinedToCommittee(e.pld.Validator) - e.sb.UpdateValidator(e.validator) + e.sbx.JoinedToCommittee(e.pld.Validator) + e.sbx.UpdateValidator(e.validator) } diff --git a/execution/executor/sortition_test.go b/execution/executor/sortition_test.go index d0f0ab836..ca12c4989 100644 --- a/execution/executor/sortition_test.go +++ b/execution/executor/sortition_test.go @@ -12,42 +12,42 @@ import ( func updateCommittee(td *testData) { joiningCommittee := make([]*validator.Validator, 0) - td.sandbox.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { + td.sbx.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { if joined { joiningCommittee = append(joiningCommittee, val) } }) - td.sandbox.TestCommittee.Update(0, joiningCommittee) - td.sandbox.TestJoinedValidators = make(map[crypto.Address]bool) + td.sbx.TestCommittee.Update(0, joiningCommittee) + td.sbx.TestJoinedValidators = make(map[crypto.Address]bool) } func TestExecuteSortitionTx(t *testing.T) { td := setup(t) - bonderAddr, bonderAcc := td.sandbox.TestStore.RandomTestAcc() + bonderAddr, bonderAcc := td.sbx.TestStore.RandomTestAcc() bonderBalance := bonderAcc.Balance() stake := td.RandAmountRange( - td.sandbox.TestParams.MinimumStake, + td.sbx.TestParams.MinimumStake, bonderBalance) bonderAcc.SubtractFromBalance(stake) - td.sandbox.UpdateAccount(bonderAddr, bonderAcc) + td.sbx.UpdateAccount(bonderAddr, bonderAcc) valPub, _ := td.RandBLSKeyPair() valAddr := valPub.ValidatorAddress() - val := td.sandbox.MakeNewValidator(valPub) + val := td.sbx.MakeNewValidator(valPub) val.AddToStake(stake) - td.sandbox.UpdateValidator(val) + td.sbx.UpdateValidator(val) - curHeight := td.sandbox.CurrentHeight() - lockTime := td.sandbox.CurrentHeight() + curHeight := td.sbx.CurrentHeight() + lockTime := td.sbx.CurrentHeight() proof := td.RandProof() - val.UpdateLastBondingHeight(curHeight - td.sandbox.Params().BondInterval) - td.sandbox.UpdateValidator(val) + val.UpdateLastBondingHeight(curHeight - td.sbx.Params().BondInterval) + td.sbx.UpdateValidator(val) assert.Zero(t, val.LastSortitionHeight()) - assert.False(t, td.sandbox.IsJoinedCommittee(val.Address())) + assert.False(t, td.sbx.IsJoinedCommittee(val.Address())) t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandAccAddress() @@ -57,8 +57,8 @@ func TestExecuteSortitionTx(t *testing.T) { td.check(t, trx, false, ValidatorNotFoundError{Address: randomAddr}) }) - val.UpdateLastBondingHeight(curHeight - td.sandbox.Params().BondInterval + 1) - td.sandbox.UpdateValidator(val) + val.UpdateLastBondingHeight(curHeight - td.sbx.Params().BondInterval + 1) + td.sbx.UpdateValidator(val) t.Run("Should fail, Bonding period", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime, val.Address(), proof) @@ -68,19 +68,19 @@ func TestExecuteSortitionTx(t *testing.T) { }) // Let's add one more block - td.sandbox.TestStore.AddTestBlock(curHeight + 1) + td.sbx.TestStore.AddTestBlock(curHeight + 1) t.Run("Should fail, invalid proof", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime, val.Address(), proof) - td.sandbox.TestAcceptSortition = false + td.sbx.TestAcceptSortition = false td.check(t, trx, true, ErrInvalidSortitionProof) td.check(t, trx, false, ErrInvalidSortitionProof) }) t.Run("Should fail, committee has free seats and validator is in the committee", func(t *testing.T) { - val0 := td.sandbox.Committee().Proposer(0) + val0 := td.sbx.Committee().Proposer(0) trx := tx.NewSortitionTx(lockTime, val0.Address(), proof) - td.sandbox.TestAcceptSortition = true + td.sbx.TestAcceptSortition = true td.check(t, trx, true, ErrValidatorInCommittee) td.check(t, trx, false, nil) @@ -88,7 +88,7 @@ func TestExecuteSortitionTx(t *testing.T) { t.Run("Should be ok", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime, val.Address(), proof) - td.sandbox.TestAcceptSortition = true + td.sbx.TestAcceptSortition = true td.check(t, trx, true, nil) td.check(t, trx, false, nil) @@ -97,7 +97,7 @@ func TestExecuteSortitionTx(t *testing.T) { t.Run("Should fail, expired sortition", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime-1, val.Address(), proof) - td.sandbox.TestAcceptSortition = true + td.sbx.TestAcceptSortition = true td.check(t, trx, true, ErrExpiredSortition) td.check(t, trx, false, ErrExpiredSortition) }) @@ -109,10 +109,10 @@ func TestExecuteSortitionTx(t *testing.T) { td.check(t, trx, false, ErrExpiredSortition) }) - updatedVal := td.sandbox.Validator(valAddr) + updatedVal := td.sbx.Validator(valAddr) assert.Equal(t, lockTime, updatedVal.LastSortitionHeight()) - assert.True(t, td.sandbox.IsJoinedCommittee(val.Address())) + assert.True(t, td.sbx.IsJoinedCommittee(val.Address())) td.checkTotalCoin(t, 0) } @@ -125,26 +125,26 @@ func TestChangePower1(t *testing.T) { // Let's create validators first pub1, _ := td.RandBLSKeyPair() - amt1 := td.sandbox.Committee().TotalPower() / 3 - val1 := td.sandbox.MakeNewValidator(pub1) + amt1 := td.sbx.Committee().TotalPower() / 3 + val1 := td.sbx.MakeNewValidator(pub1) val1.AddToStake(amount.Amount(amt1 - 1)) - val1.UpdateLastBondingHeight(td.sandbox.CurrentHeight() - td.sandbox.Params().BondInterval) - td.sandbox.UpdateValidator(val1) + val1.UpdateLastBondingHeight(td.sbx.CurrentHeight() - td.sbx.Params().BondInterval) + td.sbx.UpdateValidator(val1) proof1 := td.RandProof() pub2, _ := td.RandBLSKeyPair() - val2 := td.sandbox.MakeNewValidator(pub2) + val2 := td.sbx.MakeNewValidator(pub2) val2.AddToStake(2) - val2.UpdateLastBondingHeight(td.sandbox.CurrentHeight() - td.sandbox.Params().BondInterval) - td.sandbox.UpdateValidator(val2) - lockTime := td.sandbox.CurrentHeight() + val2.UpdateLastBondingHeight(td.sbx.CurrentHeight() - td.sbx.Params().BondInterval) + td.sbx.UpdateValidator(val2) + lockTime := td.sbx.CurrentHeight() proof2 := td.RandProof() - val3 := td.sandbox.Committee().Proposer(0) + val3 := td.sbx.Committee().Proposer(0) proof3 := td.RandProof() - td.sandbox.TestParams.CommitteeSize = 4 - td.sandbox.TestAcceptSortition = true + td.sbx.TestParams.CommitteeSize = 4 + td.sbx.TestAcceptSortition = true trx1 := tx.NewSortitionTx(lockTime, val1.Address(), proof1) td.check(t, trx1, true, nil) td.check(t, trx1, false, nil) @@ -168,32 +168,32 @@ func TestChangePower2(t *testing.T) { // Let's create validators first pub1, _ := td.RandBLSKeyPair() - val1 := td.sandbox.MakeNewValidator(pub1) + val1 := td.sbx.MakeNewValidator(pub1) val1.AddToStake(1) - val1.UpdateLastBondingHeight(td.sandbox.CurrentHeight() - td.sandbox.Params().BondInterval) - td.sandbox.UpdateValidator(val1) + val1.UpdateLastBondingHeight(td.sbx.CurrentHeight() - td.sbx.Params().BondInterval) + td.sbx.UpdateValidator(val1) proof1 := td.RandProof() pub2, _ := td.RandBLSKeyPair() - val2 := td.sandbox.MakeNewValidator(pub2) + val2 := td.sbx.MakeNewValidator(pub2) val2.AddToStake(1) - val2.UpdateLastBondingHeight(td.sandbox.CurrentHeight() - td.sandbox.Params().BondInterval) - td.sandbox.UpdateValidator(val2) + val2.UpdateLastBondingHeight(td.sbx.CurrentHeight() - td.sbx.Params().BondInterval) + td.sbx.UpdateValidator(val2) proof2 := td.RandProof() pub3, _ := td.RandBLSKeyPair() - val3 := td.sandbox.MakeNewValidator(pub3) + val3 := td.sbx.MakeNewValidator(pub3) val3.AddToStake(1) - val3.UpdateLastBondingHeight(td.sandbox.CurrentHeight() - td.sandbox.Params().BondInterval) - td.sandbox.UpdateValidator(val3) - lockTime := td.sandbox.CurrentHeight() + val3.UpdateLastBondingHeight(td.sbx.CurrentHeight() - td.sbx.Params().BondInterval) + td.sbx.UpdateValidator(val3) + lockTime := td.sbx.CurrentHeight() proof3 := td.RandProof() - val4 := td.sandbox.Committee().Proposer(0) + val4 := td.sbx.Committee().Proposer(0) proof4 := td.RandProof() - td.sandbox.TestParams.CommitteeSize = 7 - td.sandbox.TestAcceptSortition = true + td.sbx.TestParams.CommitteeSize = 7 + td.sbx.TestAcceptSortition = true trx1 := tx.NewSortitionTx(lockTime, val1.Address(), proof1) td.check(t, trx1, true, nil) td.check(t, trx1, false, nil) @@ -222,27 +222,27 @@ func TestOldestDidNotPropose(t *testing.T) { // Let's create validators first vals := make([]*validator.Validator, 9) - for i := 0; i < 9; i++ { + for index := 0; index < 9; index++ { pub, _ := td.RandBLSKeyPair() - val := td.sandbox.MakeNewValidator(pub) + val := td.sbx.MakeNewValidator(pub) val.AddToStake(10 * 1e9) val.UpdateLastBondingHeight( - td.sandbox.CurrentHeight() - td.sandbox.Params().BondInterval) - td.sandbox.UpdateValidator(val) - vals[i] = val + td.sbx.CurrentHeight() - td.sbx.Params().BondInterval) + td.sbx.UpdateValidator(val) + vals[index] = val } - td.sandbox.TestParams.CommitteeSize = 7 - td.sandbox.TestAcceptSortition = true + td.sbx.TestParams.CommitteeSize = 7 + td.sbx.TestAcceptSortition = true // This moves proposer to the next validator updateCommittee(td) // Let's update committee - height := td.sandbox.CurrentHeight() + height := td.sbx.CurrentHeight() for i := uint32(0); i < 7; i++ { height++ - _ = td.sandbox.TestStore.AddTestBlock(height) + _ = td.sbx.TestStore.AddTestBlock(height) lockTime := height trx := tx.NewSortitionTx(lockTime, vals[i].Address(), td.RandProof()) @@ -255,8 +255,8 @@ func TestOldestDidNotPropose(t *testing.T) { } height++ - _ = td.sandbox.TestStore.AddTestBlock(height) - lockTime := td.sandbox.CurrentHeight() + _ = td.sbx.TestStore.AddTestBlock(height) + lockTime := td.sbx.CurrentHeight() trx1 := tx.NewSortitionTx(lockTime, vals[7].Address(), td.RandProof()) td.check(t, trx1, true, nil) @@ -271,7 +271,7 @@ func TestOldestDidNotPropose(t *testing.T) { updateCommittee(td) height++ - _ = td.sandbox.TestStore.AddTestBlock(height) + _ = td.sbx.TestStore.AddTestBlock(height) // Entering validator 16 trx3 := tx.NewSortitionTx(lockTime+1, vals[8].Address(), td.RandProof()) td.check(t, trx3, true, ErrOldestValidatorNotProposed) diff --git a/execution/executor/transfer.go b/execution/executor/transfer.go index fc733f7f1..aaba2d966 100644 --- a/execution/executor/transfer.go +++ b/execution/executor/transfer.go @@ -9,17 +9,17 @@ import ( ) type TransferExecutor struct { - sb sandbox.Sandbox + sbx sandbox.Sandbox pld *payload.TransferPayload fee amount.Amount sender *account.Account receiver *account.Account } -func newTransferExecutor(trx *tx.Tx, sb sandbox.Sandbox) (*TransferExecutor, error) { +func newTransferExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*TransferExecutor, error) { pld := trx.Payload().(*payload.TransferPayload) - sender := sb.Account(pld.From) + sender := sbx.Account(pld.From) if sender == nil { return nil, AccountNotFoundError{Address: pld.From} } @@ -28,14 +28,14 @@ func newTransferExecutor(trx *tx.Tx, sb sandbox.Sandbox) (*TransferExecutor, err if pld.To == pld.From { receiver = sender } else { - receiver = sb.Account(pld.To) + receiver = sbx.Account(pld.To) if receiver == nil { - receiver = sb.MakeNewAccount(pld.To) + receiver = sbx.MakeNewAccount(pld.To) } } return &TransferExecutor{ - sb: sb, + sbx: sbx, pld: pld, fee: trx.Fee(), sender: sender, @@ -55,6 +55,6 @@ func (e *TransferExecutor) Execute() { e.sender.SubtractFromBalance(e.pld.Amount + e.fee) e.receiver.AddToBalance(e.pld.Amount) - e.sb.UpdateAccount(e.pld.From, e.sender) - e.sb.UpdateAccount(e.pld.To, e.receiver) + e.sbx.UpdateAccount(e.pld.From, e.sender) + e.sbx.UpdateAccount(e.pld.To, e.receiver) } diff --git a/execution/executor/transfer_test.go b/execution/executor/transfer_test.go index 255c319ef..4ec61c406 100644 --- a/execution/executor/transfer_test.go +++ b/execution/executor/transfer_test.go @@ -10,13 +10,13 @@ import ( func TestExecuteTransferTx(t *testing.T) { td := setup(t) - senderAddr, senderAcc := td.sandbox.TestStore.RandomTestAcc() + senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() senderBalance := senderAcc.Balance() receiverAddr := td.RandAccAddress() amt := td.RandAmountRange(0, senderBalance) fee := td.RandFee() - lockTime := td.sandbox.CurrentHeight() + lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandAccAddress() @@ -41,8 +41,8 @@ func TestExecuteTransferTx(t *testing.T) { td.execute(t, trx) }) - updatedSenderAcc := td.sandbox.Account(senderAddr) - updatedReceiverAcc := td.sandbox.Account(receiverAddr) + updatedSenderAcc := td.sbx.Account(senderAddr) + updatedReceiverAcc := td.sbx.Account(receiverAddr) assert.Equal(t, senderBalance-(amt+fee), updatedSenderAcc.Balance()) assert.Equal(t, amt, updatedReceiverAcc.Balance()) @@ -53,10 +53,10 @@ func TestExecuteTransferTx(t *testing.T) { func TestTransferToSelf(t *testing.T) { td := setup(t) - senderAddr, senderAcc := td.sandbox.TestStore.RandomTestAcc() + senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() amt := td.RandAmountRange(0, senderAcc.Balance()) fee := td.RandFee() - lockTime := td.sandbox.CurrentHeight() + lockTime := td.sbx.CurrentHeight() trx := tx.NewTransferTx(lockTime, senderAddr, senderAddr, amt, fee) td.check(t, trx, true, nil) @@ -64,7 +64,7 @@ func TestTransferToSelf(t *testing.T) { td.execute(t, trx) expectedBalance := senderAcc.Balance() - fee // Fee should be deducted - updatedAcc := td.sandbox.Account(senderAddr) + updatedAcc := td.sbx.Account(senderAddr) assert.Equal(t, expectedBalance, updatedAcc.Balance()) td.checkTotalCoin(t, fee) diff --git a/execution/executor/unbond.go b/execution/executor/unbond.go index ed6f6b8cb..fd511c545 100644 --- a/execution/executor/unbond.go +++ b/execution/executor/unbond.go @@ -8,21 +8,21 @@ import ( ) type UnbondExecutor struct { - sb sandbox.Sandbox + sbx sandbox.Sandbox pld *payload.UnbondPayload validator *validator.Validator } -func newUnbondExecutor(trx *tx.Tx, sb sandbox.Sandbox) (*UnbondExecutor, error) { +func newUnbondExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*UnbondExecutor, error) { pld := trx.Payload().(*payload.UnbondPayload) - val := sb.Validator(pld.Signer()) + val := sbx.Validator(pld.Signer()) if val == nil { return nil, ValidatorNotFoundError{Address: pld.Validator} } return &UnbondExecutor{ - sb: sb, + sbx: sbx, pld: pld, validator: val, }, nil @@ -38,7 +38,7 @@ func (e *UnbondExecutor) Check(strict bool) error { // validator is in the committee. // In non-strict mode, they are added to the transaction pool and // processed once eligible. - if e.sb.Committee().Contains(e.pld.Validator) { + if e.sbx.Committee().Contains(e.pld.Validator) { return ErrValidatorInCommittee } @@ -46,7 +46,7 @@ func (e *UnbondExecutor) Check(strict bool) error { // going to be in the committee for the next height. // In non-strict mode, they are added to the transaction pool and // processed once eligible. - if e.sb.IsJoinedCommittee(e.pld.Validator) { + if e.sbx.IsJoinedCommittee(e.pld.Validator) { return ErrValidatorInCommittee } } @@ -56,10 +56,10 @@ func (e *UnbondExecutor) Check(strict bool) error { func (e *UnbondExecutor) Execute() { unbondedPower := e.validator.Power() - e.validator.UpdateUnbondingHeight(e.sb.CurrentHeight()) + e.validator.UpdateUnbondingHeight(e.sbx.CurrentHeight()) // The validator's power is reduced to zero, // so we update the power delta with the negative value of the validator's power. - e.sb.UpdatePowerDelta(-1 * unbondedPower) - e.sb.UpdateValidator(e.validator) + e.sbx.UpdatePowerDelta(-1 * unbondedPower) + e.sbx.UpdateValidator(e.validator) } diff --git a/execution/executor/unbond_test.go b/execution/executor/unbond_test.go index 94b742685..58db1893e 100644 --- a/execution/executor/unbond_test.go +++ b/execution/executor/unbond_test.go @@ -10,20 +10,20 @@ import ( func TestExecuteUnbondTx(t *testing.T) { td := setup(t) - bonderAddr, bonderAcc := td.sandbox.TestStore.RandomTestAcc() + bonderAddr, bonderAcc := td.sbx.TestStore.RandomTestAcc() bonderBalance := bonderAcc.Balance() stake := td.RandAmountRange( - td.sandbox.TestParams.MinimumStake, + td.sbx.TestParams.MinimumStake, bonderBalance) bonderAcc.SubtractFromBalance(stake) - td.sandbox.UpdateAccount(bonderAddr, bonderAcc) + td.sbx.UpdateAccount(bonderAddr, bonderAcc) valPub, _ := td.RandBLSKeyPair() valAddr := valPub.ValidatorAddress() - val := td.sandbox.MakeNewValidator(valPub) + val := td.sbx.MakeNewValidator(valPub) val.AddToStake(stake) - td.sandbox.UpdateValidator(val) - lockTime := td.sandbox.CurrentHeight() + td.sbx.UpdateValidator(val) + lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandValAddress() @@ -34,7 +34,7 @@ func TestExecuteUnbondTx(t *testing.T) { }) t.Run("Should fail, inside committee", func(t *testing.T) { - val0 := td.sandbox.Committee().Proposer(0) + val0 := td.sbx.Committee().Proposer(0) trx := tx.NewUnbondTx(lockTime, val0.Address()) td.check(t, trx, true, ErrValidatorInCommittee) @@ -43,9 +43,9 @@ func TestExecuteUnbondTx(t *testing.T) { t.Run("Should fail, joining committee", func(t *testing.T) { randPub, _ := td.RandBLSKeyPair() - randVal := td.sandbox.MakeNewValidator(randPub) - td.sandbox.UpdateValidator(randVal) - td.sandbox.JoinedToCommittee(randVal.Address()) + randVal := td.sbx.MakeNewValidator(randPub) + td.sbx.UpdateValidator(randVal) + td.sbx.JoinedToCommittee(randVal.Address()) trx := tx.NewUnbondTx(lockTime, randPub.ValidatorAddress()) td.check(t, trx, true, ErrValidatorInCommittee) @@ -67,12 +67,12 @@ func TestExecuteUnbondTx(t *testing.T) { td.check(t, trx, false, ErrValidatorUnbonded) }) - updatedVal := td.sandbox.Validator(valAddr) + updatedVal := td.sbx.Validator(valAddr) assert.Equal(t, stake, updatedVal.Stake()) assert.Zero(t, updatedVal.Power()) assert.Equal(t, lockTime, updatedVal.UnbondingHeight()) - assert.Equal(t, int64(-stake), td.sandbox.PowerDelta()) + assert.Equal(t, int64(-stake), td.sbx.PowerDelta()) td.checkTotalCoin(t, 0) } @@ -82,14 +82,14 @@ func TestPowerDeltaUnbond(t *testing.T) { pub, _ := td.RandBLSKeyPair() valAddr := pub.ValidatorAddress() - val := td.sandbox.MakeNewValidator(pub) + val := td.sbx.MakeNewValidator(pub) amt := td.RandAmount() val.AddToStake(amt) - td.sandbox.UpdateValidator(val) - lockTime := td.sandbox.CurrentHeight() + td.sbx.UpdateValidator(val) + lockTime := td.sbx.CurrentHeight() trx := tx.NewUnbondTx(lockTime, valAddr) td.execute(t, trx) - assert.Equal(t, int64(-amt), td.sandbox.PowerDelta()) + assert.Equal(t, int64(-amt), td.sbx.PowerDelta()) } diff --git a/execution/executor/withdraw.go b/execution/executor/withdraw.go index eb3397d2d..3dffb8a3b 100644 --- a/execution/executor/withdraw.go +++ b/execution/executor/withdraw.go @@ -10,28 +10,28 @@ import ( ) type WithdrawExecutor struct { - sb sandbox.Sandbox + sbx sandbox.Sandbox pld *payload.WithdrawPayload fee amount.Amount sender *validator.Validator receiver *account.Account } -func newWithdrawExecutor(trx *tx.Tx, sb sandbox.Sandbox) (*WithdrawExecutor, error) { +func newWithdrawExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*WithdrawExecutor, error) { pld := trx.Payload().(*payload.WithdrawPayload) - sender := sb.Validator(pld.From) + sender := sbx.Validator(pld.From) if sender == nil { return nil, ValidatorNotFoundError{Address: pld.From} } - receiver := sb.Account(pld.To) + receiver := sbx.Account(pld.To) if receiver == nil { - receiver = sb.MakeNewAccount(pld.To) + receiver = sbx.MakeNewAccount(pld.To) } return &WithdrawExecutor{ - sb: sb, + sbx: sbx, pld: pld, fee: trx.Fee(), sender: sender, @@ -48,7 +48,7 @@ func (e *WithdrawExecutor) Check(_ bool) error { return ErrValidatorBonded } - if e.sb.CurrentHeight() < e.sender.UnbondingHeight()+e.sb.Params().UnbondInterval { + if e.sbx.CurrentHeight() < e.sender.UnbondingHeight()+e.sbx.Params().UnbondInterval { return ErrUnbondingPeriod } @@ -59,6 +59,6 @@ func (e *WithdrawExecutor) Execute() { e.sender.SubtractFromStake(e.pld.Amount + e.fee) e.receiver.AddToBalance(e.pld.Amount) - e.sb.UpdateValidator(e.sender) - e.sb.UpdateAccount(e.pld.To, e.receiver) + e.sbx.UpdateValidator(e.sender) + e.sbx.UpdateAccount(e.pld.To, e.receiver) } diff --git a/execution/executor/withdraw_test.go b/execution/executor/withdraw_test.go index d18f6d32c..2bcc83869 100644 --- a/execution/executor/withdraw_test.go +++ b/execution/executor/withdraw_test.go @@ -10,25 +10,25 @@ import ( func TestExecuteWithdrawTx(t *testing.T) { td := setup(t) - bonderAddr, bonderAcc := td.sandbox.TestStore.RandomTestAcc() + bonderAddr, bonderAcc := td.sbx.TestStore.RandomTestAcc() bonderBalance := bonderAcc.Balance() stake := td.RandAmountRange( - td.sandbox.TestParams.MinimumStake, + td.sbx.TestParams.MinimumStake, bonderBalance) bonderAcc.SubtractFromBalance(stake) - td.sandbox.UpdateAccount(bonderAddr, bonderAcc) + td.sbx.UpdateAccount(bonderAddr, bonderAcc) valPub, _ := td.RandBLSKeyPair() - val := td.sandbox.MakeNewValidator(valPub) + val := td.sbx.MakeNewValidator(valPub) val.AddToStake(stake) - td.sandbox.UpdateValidator(val) + td.sbx.UpdateValidator(val) totalStake := val.Stake() fee := td.RandFee() amt := td.RandAmountRange(0, totalStake-fee) senderAddr := val.Address() receiverAddr := td.RandAccAddress() - lockTime := td.sandbox.CurrentHeight() + lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandValAddress() @@ -45,8 +45,8 @@ func TestExecuteWithdrawTx(t *testing.T) { td.check(t, trx, false, ErrValidatorBonded) }) - val.UpdateUnbondingHeight(td.sandbox.CurrentHeight() - td.sandbox.Params().UnbondInterval + 1) - td.sandbox.UpdateValidator(val) + val.UpdateUnbondingHeight(td.sbx.CurrentHeight() - td.sbx.Params().UnbondInterval + 1) + td.sbx.UpdateValidator(val) t.Run("Should fail, insufficient balance", func(t *testing.T) { trx := tx.NewWithdrawTx(lockTime, senderAddr, receiverAddr, totalStake, 1) @@ -62,8 +62,8 @@ func TestExecuteWithdrawTx(t *testing.T) { td.check(t, trx, false, ErrUnbondingPeriod) }) - curHeight := td.sandbox.CurrentHeight() - td.sandbox.TestStore.AddTestBlock(curHeight + 1) + curHeight := td.sbx.CurrentHeight() + td.sbx.TestStore.AddTestBlock(curHeight + 1) t.Run("Should pass, Everything is Ok!", func(t *testing.T) { trx := tx.NewWithdrawTx(lockTime, senderAddr, receiverAddr, amt, fee) @@ -73,8 +73,8 @@ func TestExecuteWithdrawTx(t *testing.T) { td.execute(t, trx) }) - updatedSenderVal := td.sandbox.Validator(senderAddr) - updatedReceiverAcc := td.sandbox.Account(receiverAddr) + updatedSenderVal := td.sbx.Validator(senderAddr) + updatedReceiverAcc := td.sbx.Account(receiverAddr) assert.Equal(t, totalStake-amt-fee, updatedSenderVal.Stake()) assert.Equal(t, amt, updatedReceiverAcc.Balance()) diff --git a/genesis/genesis.go b/genesis/genesis.go index 8e5c55fce..b58fe1748 100644 --- a/genesis/genesis.go +++ b/genesis/genesis.go @@ -167,13 +167,13 @@ func LoadFromFile(file string) (*Genesis, error) { // SaveToFile saves the genesis into a JSON file. func (gen *Genesis) SaveToFile(file string) error { - j, err := gen.MarshalJSON() + data, err := gen.MarshalJSON() if err != nil { return err } // write dataContent to file - return util.WriteFile(file, j) + return util.WriteFile(file, data) } func (gen *Genesis) TotalSupply() amount.Amount { diff --git a/network/config_test.go b/network/config_test.go index 7e16ffa85..e3318e66f 100644 --- a/network/config_test.go +++ b/network/config_test.go @@ -8,7 +8,7 @@ import ( ) func TestConfigBasicCheck(t *testing.T) { - testCases := []struct { + tests := []struct { name string expectedErr error updateFn func(c *Config) @@ -101,7 +101,9 @@ func TestConfigBasicCheck(t *testing.T) { { name: "Valid BootstrapAddrStrings", updateFn: func(c *Config) { - c.BootstrapAddrStrings = []string{"/ip4/127.0.0.1/p2p/12D3KooWQBpPV6NtZy1dvN2oF7dJdLoooRZfEmwtHiDUf42ArDjT"} + c.BootstrapAddrStrings = []string{ + "/ip4/127.0.0.1/p2p/12D3KooWQBpPV6NtZy1dvN2oF7dJdLoooRZfEmwtHiDUf42ArDjT", + } }, }, { @@ -110,17 +112,20 @@ func TestConfigBasicCheck(t *testing.T) { }, } - for i, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { + for no, tt := range tests { + t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() - tc.updateFn(conf) - if tc.expectedErr != nil { + tt.updateFn(conf) + if tt.expectedErr != nil { err := conf.BasicCheck() - assert.ErrorIs(t, err, tc.expectedErr, - "Expected error not matched for test %d-%s, expected: %s, got: %s", i, tc.name, tc.expectedErr, err) + assert.ErrorIs(t, err, tt.expectedErr, + "Expected error not matched for test %d-%s, expected: %s, got: %s", + no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() - assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", i, tc.name, err) + assert.NoError(t, err, + "Expected no error for test %d-%s, get: %s", + no, tt.name, err) } }) } @@ -155,13 +160,13 @@ func TestMinConns(t *testing.T) { {Config{MaxConns: 128}, 30}, } - for _, test := range tests { - resultMin := test.config.MinConns() - if resultMin != test.expectedMin { + for _, tt := range tests { + resultMin := tt.config.MinConns() + if resultMin != tt.expectedMin { t.Errorf("For MaxConns %d, "+ "MinConns() returned %d (expected %d)", - test.config.MaxConns, - resultMin, test.expectedMin) + tt.config.MaxConns, + resultMin, tt.expectedMin) } } } diff --git a/network/gossip.go b/network/gossip.go index d8cf71145..48a3f5623 100644 --- a/network/gossip.go +++ b/network/gossip.go @@ -115,7 +115,7 @@ func (g *gossipService) publish(msg []byte, topic *lp2pps.Topic) error { } // JoinTopic joins to the topic with the given name and subscribes to receive topic messages. -func (g *gossipService) JoinTopic(topicID TopicID, sp ShouldPropagate) error { +func (g *gossipService) JoinTopic(topicID TopicID, shouldPropagate ShouldPropagate) error { switch topicID { case TopicIDUnspecified: return InvalidTopicError{TopicID: topicID} @@ -127,7 +127,7 @@ func (g *gossipService) JoinTopic(topicID TopicID, sp ShouldPropagate) error { return nil } - topic, err := g.joinTopic(topicID, sp) + topic, err := g.joinTopic(topicID, shouldPropagate) if err != nil { return err } @@ -142,7 +142,7 @@ func (g *gossipService) JoinTopic(topicID TopicID, sp ShouldPropagate) error { return nil } - topic, err := g.joinTopic(topicID, sp) + topic, err := g.joinTopic(topicID, shouldPropagate) if err != nil { return err } @@ -157,7 +157,7 @@ func (g *gossipService) JoinTopic(topicID TopicID, sp ShouldPropagate) error { return nil } - topic, err := g.joinTopic(topicID, sp) + topic, err := g.joinTopic(topicID, shouldPropagate) if err != nil { return err } @@ -176,7 +176,7 @@ func (g *gossipService) TopicName(topicID TopicID) string { // joinTopic joins a given topic and registers a validator for it. // If successful, it returns the topic and subscribes to it. -func (g *gossipService) joinTopic(topicID TopicID, sp ShouldPropagate) (*lp2pps.Topic, error) { +func (g *gossipService) joinTopic(topicID TopicID, shouldPropagate ShouldPropagate) (*lp2pps.Topic, error) { topicName := g.TopicName(topicID) topic, err := g.pubsub.Join(topicName) if err != nil { @@ -189,7 +189,7 @@ func (g *gossipService) joinTopic(topicID TopicID, sp ShouldPropagate) (*lp2pps. } err = g.pubsub.RegisterTopicValidator( - topicName, g.createValidator(topicID, sp)) + topicName, g.createValidator(topicID, shouldPropagate)) if err != nil { return nil, LibP2PError{Err: err} } @@ -202,26 +202,32 @@ func (g *gossipService) joinTopic(topicID TopicID, sp ShouldPropagate) (*lp2pps. defer g.wg.Done() for { - m, err := sub.Next(g.ctx) + lp2pMsg, err := sub.Next(g.ctx) if err != nil { g.logger.Debug("readLoop error", "error", err) return } - g.onReceiveMessage(m) + msg := &GossipMessage{ + From: lp2pMsg.ReceivedFrom, + Data: lp2pMsg.Data, + TopicID: topicID, + } + + g.onReceiveMessage(msg) } }() return topic, nil } -func (g *gossipService) createValidator(topicID TopicID, sp ShouldPropagate, +func (g *gossipService) createValidator(topicID TopicID, shouldPropagate ShouldPropagate, ) func(context.Context, lp2pcore.PeerID, *lp2pps.Message) lp2pps.ValidationResult { - return func(_ context.Context, peerId lp2pcore.PeerID, m *lp2pps.Message) lp2pps.ValidationResult { + return func(_ context.Context, peerId lp2pcore.PeerID, lp2pMsg *lp2pps.Message) lp2pps.ValidationResult { msg := &GossipMessage{ From: peerId, - Data: m.Data, + Data: lp2pMsg.Data, TopicID: topicID, } @@ -230,11 +236,11 @@ func (g *gossipService) createValidator(topicID TopicID, sp ShouldPropagate, return lp2pps.ValidationAccept } - if !sp(msg) { + if !shouldPropagate(msg) { g.logger.Debug("message ignored", "from", peerId, "topic", topicID) // Consume the message first - g.onReceiveMessage(m) + g.onReceiveMessage(msg) return lp2pps.ValidationIgnore } @@ -260,17 +266,12 @@ func (g *gossipService) Stop() { g.wg.Wait() } -func (g *gossipService) onReceiveMessage(m *lp2pps.Message) { +func (g *gossipService) onReceiveMessage(msg *GossipMessage) { // only forward messages delivered by others - if m.ReceivedFrom == g.host.ID() { + if msg.From == g.host.ID() { return } - g.logger.Debug("receiving new gossip message", "from", m.ReceivedFrom) - event := &GossipMessage{ - From: m.ReceivedFrom, - Data: m.Data, - } - - g.eventCh <- event + g.logger.Debug("receiving new gossip message", "from", msg.From) + g.eventCh <- msg } diff --git a/network/mdns.go b/network/mdns.go index 27df86137..2c68091a8 100644 --- a/network/mdns.go +++ b/network/mdns.go @@ -34,14 +34,14 @@ func newMdnsService(ctx context.Context, host lp2phost.Host, log *logger.SubLogg // HandlePeerFound connects to peers discovered via mDNS. Once they're connected, // the PubSub system will automatically start interacting with them if they also // support PubSub. -func (s *mdnsService) HandlePeerFound(pi lp2ppeer.AddrInfo) { +func (s *mdnsService) HandlePeerFound(addrInfo lp2ppeer.AddrInfo) { ctx, cancel := context.WithTimeout(s.ctx, time.Second*10) defer cancel() - if pi.ID != s.host.ID() { - s.logger.Debug("connecting to new peer", "addr", pi.Addrs, "id", pi.ID) - if err := s.host.Connect(ctx, pi); err != nil { - s.logger.Error("error on connecting to peer", "id", pi.ID, "error", err) + if addrInfo.ID != s.host.ID() { + s.logger.Debug("connecting to new peer", "addr", addrInfo.Addrs, "id", addrInfo.ID) + if err := s.host.Connect(ctx, addrInfo); err != nil { + s.logger.Error("error on connecting to peer", "id", addrInfo.ID, "error", err) } } } diff --git a/network/mock.go b/network/mock.go index 09679ca9d..41d3e606d 100644 --- a/network/mock.go +++ b/network/mock.go @@ -25,13 +25,13 @@ type MockNetwork struct { OtherNets []*MockNetwork } -func MockingNetwork(ts *testsuite.TestSuite, id lp2ppeer.ID) *MockNetwork { +func MockingNetwork(ts *testsuite.TestSuite, pid lp2ppeer.ID) *MockNetwork { return &MockNetwork{ TestSuite: ts, PublishCh: make(chan PublishData, 100), EventCh: make(chan Event, 100), OtherNets: make([]*MockNetwork, 0), - ID: id, + ID: pid, } } diff --git a/network/network.go b/network/network.go index a84264137..a72e8116d 100644 --- a/network/network.go +++ b/network/network.go @@ -279,16 +279,16 @@ func findRelayPeers(networkGetter func() *network) func(ctx context.Context, // Because the network is initialized after relay, we need to // obtain them indirectly this way. - n := networkGetter() - if n == nil { // context canceled etc. + net := networkGetter() + if net == nil { // context canceled etc. return r } - n.logger.Debug("try to find relay peers", "num", num) + net.logger.Debug("try to find relay peers", "num", num) - peerStore := n.host.Peerstore() - for _, id := range peerStore.Peers() { - protos, err := peerStore.GetProtocols(id) + peerStore := net.host.Peerstore() + for _, pid := range peerStore.Peers() { + protos, err := peerStore.GetProtocols(pid) if err != nil { continue } @@ -297,9 +297,9 @@ func findRelayPeers(networkGetter func() *network) func(ctx context.Context, continue } - addr := peerStore.Addrs(id) - n.logger.Debug("found relay peer", "addr", addr) - dhtPeer := lp2ppeer.AddrInfo{ID: id, Addrs: addr} + addr := peerStore.Addrs(pid) + net.logger.Debug("found relay peer", "addr", addr) + dhtPeer := lp2ppeer.AddrInfo{ID: pid, Addrs: addr} // Attempt to put peers on r if we have space, // otherwise return (we reached numPeers) select { diff --git a/network/network_test.go b/network/network_test.go index 085cc8525..27322aa46 100644 --- a/network/network_test.go +++ b/network/network_test.go @@ -429,10 +429,10 @@ func TestConnections(t *testing.T) { {"/ip6/::1/udp/%d/quic-v1", "/ip6/::1/udp/0/quic-v1"}, } - for i, test := range tests { + for no, tt := range tests { // Bootstrap node confB := testConfig() - bootstrapAddr := fmt.Sprintf(test.bootstrapAddr, confB.DefaultPort) + bootstrapAddr := fmt.Sprintf(tt.bootstrapAddr, confB.DefaultPort) confB.ListenAddrStrings = []string{bootstrapAddr} fmt.Println("Starting Bootstrap node") networkB := makeTestNetwork(t, confB, []lp2p.Option{ @@ -444,14 +444,14 @@ func TestConnections(t *testing.T) { confP.BootstrapAddrStrings = []string{ fmt.Sprintf("%s/p2p/%v", bootstrapAddr, networkB.SelfID().String()), } - confP.ListenAddrStrings = []string{test.peerAddr} + confP.ListenAddrStrings = []string{tt.peerAddr} fmt.Println("Starting Public node") networkP := makeTestNetwork(t, confP, []lp2p.Option{ lp2p.ForceReachabilityPublic(), }) t.Run(fmt.Sprintf("Running test %d: %s <-> %s ... ", - i, bootstrapAddr, test.peerAddr), func(t *testing.T) { + no, bootstrapAddr, tt.peerAddr), func(t *testing.T) { t.Parallel() // run the tests in parallel testConnection(t, networkP, networkB) diff --git a/network/notifee.go b/network/notifee.go index 883547b04..3b4e0e67c 100644 --- a/network/notifee.go +++ b/network/notifee.go @@ -60,21 +60,21 @@ func (s *NotifeeService) Start() { for { select { case evt := <-s.lp2pEventSub.Out(): - switch e := evt.(type) { + switch evt := evt.(type) { case lp2pevent.EvtLocalReachabilityChanged: - s.logger.Info("reachability changed", "reachability", e.Reachability) - s.reachability = e.Reachability + s.logger.Info("reachability changed", "reachability", evt.Reachability) + s.reachability = evt.Reachability case lp2pevent.EvtPeerIdentificationCompleted: - s.logger.Debug("identification completed", "pid", e.Peer) - s.sendProtocolsEvent(e.Peer) + s.logger.Debug("identification completed", "pid", evt.Peer) + s.sendProtocolsEvent(evt.Peer) case lp2pevent.EvtPeerIdentificationFailed: - s.logger.Warn("identification failed", "pid", e.Peer) + s.logger.Warn("identification failed", "pid", evt.Peer) case lp2pevent.EvtPeerProtocolsUpdated: - s.logger.Debug("protocols updated", "pid", e.Peer, "protocols", e.Added) - s.sendProtocolsEvent(e.Peer) + s.logger.Debug("protocols updated", "pid", evt.Peer, "protocols", evt.Added) + s.sendProtocolsEvent(evt.Peer) default: s.logger.Debug("unhandled libp2p event", "event", evt) diff --git a/network/peermgr.go b/network/peermgr.go index 9c6334f55..f7d774c7e 100644 --- a/network/peermgr.go +++ b/network/peermgr.go @@ -37,7 +37,7 @@ type peerMgr struct { } // newPeerMgr creates a new Peer Manager instance. -func newPeerMgr(ctx context.Context, h lp2phost.Host, +func newPeerMgr(ctx context.Context, host lp2phost.Host, conf *Config, log *logger.SubLogger, ) *peerMgr { peerStore, err := loadPeerStore(conf.PeerStorePath) @@ -57,18 +57,18 @@ func newPeerMgr(ctx context.Context, h lp2phost.Host, } } - pm := &peerMgr{ + mgr := &peerMgr{ ctx: ctx, minConns: conf.MinConns(), peers: peers, peerStorePath: conf.PeerStorePath, - host: h, + host: host, logger: log, } - log.Info("peer manager created", "minConns", pm.minConns) + log.Info("peer manager created", "minConns", mgr.minConns) - return pm + return mgr } // Start starts the Peer Manager. @@ -139,16 +139,16 @@ func (mgr *peerMgr) SetPeerDisconnected(pid lp2ppeer.ID) { } func (mgr *peerMgr) setPeerDisconnected(pid lp2ppeer.ID) { - pi, exists := mgr.peers[pid] + peerInfo, exists := mgr.peers[pid] if !exists { return } - if !pi.Connected { + if !peerInfo.Connected { return } - switch pi.Direction { + switch peerInfo.Direction { case lp2pnet.DirInbound: mgr.numInbound-- @@ -159,8 +159,8 @@ func (mgr *peerMgr) setPeerDisconnected(pid lp2ppeer.ID) { // } - pi.Connected = false - pi.Direction = lp2pnet.DirUnknown + peerInfo.Connected = false + peerInfo.Direction = lp2pnet.DirUnknown } // CheckConnectivity performs the actual work of maintaining connections. @@ -190,22 +190,22 @@ func (mgr *peerMgr) CheckConnectivity() { "numConnected", numConnected, "min", mgr.minConns) - for id, pi := range mgr.peers { + for pid, info := range mgr.peers { // preventing self dialing. - if id == mgr.host.ID() { + if pid == mgr.host.ID() { continue } - mgr.logger.Debug("try connecting to a bootstrap peer", "peer", id.String()) + mgr.logger.Debug("try connecting to a bootstrap peer", "peer", pid.String()) // Don't try to connect to an already connected peer. - if pi.Connected { + if info.Connected { continue } ai := lp2ppeer.AddrInfo{ - ID: id, - Addrs: []multiaddr.Multiaddr{pi.MultiAddress}, + ID: pid, + Addrs: []multiaddr.Multiaddr{info.MultiAddress}, } ConnectAsync(mgr.ctx, mgr.host, ai, mgr.logger) } @@ -251,13 +251,13 @@ func loadPeerStore(path string) ([]lp2ppeer.AddrInfo, error) { return peerStore, err } - ps := make([]string, 0) - err = json.Unmarshal(data, &ps) + addrs := make([]string, 0) + err = json.Unmarshal(data, &addrs) if err != nil { return peerStore, err } - peerStore, err = MakeAddrInfos(ps) + peerStore, err = MakeAddrInfos(addrs) if err != nil { return []lp2ppeer.AddrInfo{}, err } diff --git a/network/stream.go b/network/stream.go index 883fe6ad4..ef4bbea91 100644 --- a/network/stream.go +++ b/network/stream.go @@ -23,7 +23,7 @@ type streamService struct { func newStreamService(ctx context.Context, host lp2phost.Host, conf *Config, protocolID lp2pcore.ProtocolID, eventCh chan Event, log *logger.SubLogger, ) *streamService { - s := &streamService{ + service := &streamService{ ctx: ctx, host: host, protocolID: protocolID, @@ -32,9 +32,9 @@ func newStreamService(ctx context.Context, host lp2phost.Host, conf *Config, logger: log, } - s.host.SetStreamHandler(protocolID, s.handleStream) + service.host.SetStreamHandler(protocolID, service.handleStream) - return s + return service } func (*streamService) Start() {} diff --git a/network/utils_test.go b/network/utils_test.go index 6f03b8909..7e3e8f67a 100644 --- a/network/utils_test.go +++ b/network/utils_test.go @@ -10,7 +10,7 @@ import ( ) func TestMakeMultiAddrs(t *testing.T) { - testCases := []struct { + tests := []struct { name string inputAddrs []string expected []multiaddr.Multiaddr @@ -38,12 +38,12 @@ func TestMakeMultiAddrs(t *testing.T) { }, } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - actualPis, actualError := MakeMultiAddrs(tc.inputAddrs) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actualPis, actualError := MakeMultiAddrs(tt.inputAddrs) - if tc.expected != nil { - assert.Equal(t, tc.expected, actualPis) + if tt.expected != nil { + assert.Equal(t, tt.expected, actualPis) assert.NoError(t, actualError) } else { assert.Error(t, actualError) @@ -55,7 +55,7 @@ func TestMakeMultiAddrs(t *testing.T) { func TestMakeAddrInfos(t *testing.T) { pid, _ := lp2ppeer.Decode("12D3KooWCwQZt8UriVXobQHPXPR8m83eceXVoeT6brPNiBHomebc") - testCases := []struct { + tests := []struct { name string inputAddrs []string expectedPis []lp2ppeer.AddrInfo @@ -95,12 +95,12 @@ func TestMakeAddrInfos(t *testing.T) { }, } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - actualPis, actualError := MakeAddrInfos(tc.inputAddrs) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actualPis, actualError := MakeAddrInfos(tt.inputAddrs) - if tc.expectedPis != nil { - assert.Equal(t, tc.expectedPis, actualPis) + if tt.expectedPis != nil { + assert.Equal(t, tt.expectedPis, actualPis) assert.NoError(t, actualError) } else { assert.Error(t, actualError) @@ -111,7 +111,7 @@ func TestMakeAddrInfos(t *testing.T) { } func TestIPToMultiAddr(t *testing.T) { - testCases := []struct { + tests := []struct { ip string port int expected string @@ -122,12 +122,12 @@ func TestIPToMultiAddr(t *testing.T) { {"invalid_ip", 80, ""}, } - for _, testCase := range testCases { - t.Run(testCase.expected, func(t *testing.T) { - ma, err := IPToMultiAddr(testCase.ip, testCase.port) - if testCase.expected != "" { + for _, tt := range tests { + t.Run(tt.expected, func(t *testing.T) { + ma, err := IPToMultiAddr(tt.ip, tt.port) + if tt.expected != "" { assert.NoError(t, err) - assert.Equal(t, testCase.expected, ma.String()) + assert.Equal(t, tt.expected, ma.String()) } else { assert.Error(t, err) } @@ -144,15 +144,15 @@ func TestHasPID(t *testing.T) { func TestSubnetsToFilters(t *testing.T) { sns := PrivateSubnets() - f := SubnetsToFilters(sns, multiaddr.ActionDeny) + filter := SubnetsToFilters(sns, multiaddr.ActionDeny) ma1, _ := multiaddr.NewMultiaddr("/ip4/0.0.0.0") ma2, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1") ma3, _ := multiaddr.NewMultiaddr("/ip4/8.8.8.8") - assert.False(t, f.AddrBlocked(ma1)) - assert.True(t, f.AddrBlocked(ma2)) - assert.False(t, f.AddrBlocked(ma3)) + assert.False(t, filter.AddrBlocked(ma1)) + assert.True(t, filter.AddrBlocked(ma2)) + assert.False(t, filter.AddrBlocked(ma3)) } func TestMessageIdFunc(t *testing.T) { diff --git a/node/node.go b/node/node.go index 86eac2c35..4c54525cc 100644 --- a/node/node.go +++ b/node/node.go @@ -59,14 +59,14 @@ func NewNode(genDoc *genesis.Genesis, conf *config.Config, eventCh = nil } - str, err := store.NewStore(conf.Store) + store, err := store.NewStore(conf.Store) if err != nil { return nil, err } - txPool := txpool.NewTxPool(conf.TxPool, str, messageCh) + txPool := txpool.NewTxPool(conf.TxPool, store, messageCh) - st, err := state.LoadOrNewState(genDoc, valKeys, str, txPool, eventCh) + state, err := state.LoadOrNewState(genDoc, valKeys, store, txPool, eventCh) if err != nil { return nil, err } @@ -76,13 +76,13 @@ func NewNode(genDoc *genesis.Genesis, conf *config.Config, return nil, err } - consMgr := consensus.NewManager(conf.Consensus, st, valKeys, rewardAddrs, messageCh) + consMgr := consensus.NewManager(conf.Consensus, state, valKeys, rewardAddrs, messageCh) walletMgr := wallet.NewWalletManager(conf.WalletManager) - if !str.IsPruned() { + if !store.IsPruned() { conf.Sync.Services.Append(service.FullNode) } - syn, err := sync.NewSynchronizer(conf.Sync, valKeys, st, consMgr, net, messageCh) + syn, err := sync.NewSynchronizer(conf.Sync, valKeys, state, consMgr, net, messageCh) if err != nil { return nil, err } @@ -91,7 +91,7 @@ func NewNode(genDoc *genesis.Genesis, conf *config.Config, if conf.GRPC.BasicAuth != "" { enableHTTPAuth = true } - grpcServer := grpc.NewServer(conf.GRPC, st, syn, net, consMgr, walletMgr) + grpcServer := grpc.NewServer(conf.GRPC, state, syn, net, consMgr, walletMgr) httpServer := http.NewServer(conf.HTTP, enableHTTPAuth) jsonrpcServer := jsonrpc.NewServer(conf.JSONRPC) nanomsgServer := nanomsg.NewServer(conf.Nanomsg, eventCh) @@ -100,11 +100,11 @@ func NewNode(genDoc *genesis.Genesis, conf *config.Config, config: conf, genesisDoc: genDoc, network: net, - state: st, + state: state, txPool: txPool, consMgr: consMgr, sync: syn, - store: str, + store: store, http: httpServer, grpc: grpcServer, jsonrpc: jsonrpcServer, diff --git a/node/node_test.go b/node/node_test.go index 04c4520ab..40343064a 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -48,27 +48,27 @@ func TestRunningNode(t *testing.T) { valKeys := []*bls.ValidatorKey{ts.RandValKey(), ts.RandValKey()} rewardAddrs := []crypto.Address{ts.RandAccAddress(), ts.RandAccAddress()} - nd, err := NewNode(gen, conf, valKeys, rewardAddrs) + node, err := NewNode(gen, conf, valKeys, rewardAddrs) assert.True(t, conf.Sync.Services.IsFullNode()) assert.True(t, conf.Sync.Services.IsPrunedNode()) require.NoError(t, err) - assert.Equal(t, hash.UndefHash, nd.state.LastBlockHash()) + assert.Equal(t, hash.UndefHash, node.state.LastBlockHash()) - err = nd.Start() + err = node.Start() require.NoError(t, err) - consHeight, _ := nd.ConsManager().HeightRound() + consHeight, _ := node.ConsManager().HeightRound() assert.Equal(t, uint32(1), consHeight) - lastBlockTime := nd.State().LastBlockTime() + lastBlockTime := node.State().LastBlockTime() assert.Equal(t, gen.GenesisTime(), lastBlockTime) - syncSelfID := nd.Sync().SelfID() - netSelfID := nd.Network().SelfID() + syncSelfID := node.Sync().SelfID() + netSelfID := node.Network().SelfID() assert.Equal(t, syncSelfID, netSelfID) - assert.NotEmpty(t, nd.GRPC().Address()) + assert.NotEmpty(t, node.GRPC().Address()) - nd.Stop() + node.Stop() } diff --git a/sandbox/mock.go b/sandbox/mock.go index ae60daf25..f585637a5 100644 --- a/sandbox/mock.go +++ b/sandbox/mock.go @@ -33,7 +33,7 @@ type MockSandbox struct { func MockingSandbox(ts *testsuite.TestSuite) *MockSandbox { cmt, _ := ts.GenerateTestCommittee(7) - sb := &MockSandbox{ + sbx := &MockSandbox{ ts: ts, TestParams: param.FromGenesis(genesis.DefaultGenesisParams()), TestStore: store.MockingStore(ts), @@ -47,17 +47,17 @@ func MockingSandbox(ts *testsuite.TestSuite) *MockSandbox { for i, val := range cmt.Validators() { acc := account.NewAccount(int32(i + 1)) acc.AddToBalance(10000 * 1e9) - sb.UpdateAccount(val.Address(), acc) - sb.UpdateValidator(val) + sbx.UpdateAccount(val.Address(), acc) + sbx.UpdateValidator(val) treasuryAmt -= val.Stake() treasuryAmt -= acc.Balance() } acc0 := account.NewAccount(0) acc0.AddToBalance(treasuryAmt) - sb.UpdateAccount(crypto.TreasuryAddress, acc0) + sbx.UpdateAccount(crypto.TreasuryAddress, acc0) - return sb + return sbx } func (m *MockSandbox) Account(addr crypto.Address) *account.Account { diff --git a/sandbox/sandbox.go b/sandbox/sandbox.go index 7bebffce5..e8e6bb935 100644 --- a/sandbox/sandbox.go +++ b/sandbox/sandbox.go @@ -46,24 +46,24 @@ type sandboxAccount struct { updated bool } -func NewSandbox(height uint32, str store.Reader, params *param.Params, - cmt committee.Reader, totalPower int64, +func NewSandbox(height uint32, store store.Reader, params *param.Params, + committee committee.Reader, totalPower int64, ) Sandbox { - sb := &sandbox{ + sbx := &sandbox{ height: height, - store: str, - committee: cmt, + store: store, + committee: committee, totalPower: totalPower, params: params, } - sb.accounts = make(map[crypto.Address]*sandboxAccount) - sb.validators = make(map[crypto.Address]*sandboxValidator) - sb.committedTrxs = make(map[tx.ID]*tx.Tx) - sb.totalAccounts = sb.store.TotalAccounts() - sb.totalValidators = sb.store.TotalValidators() + sbx.accounts = make(map[crypto.Address]*sandboxAccount) + sbx.validators = make(map[crypto.Address]*sandboxValidator) + sbx.committedTrxs = make(map[tx.ID]*tx.Tx) + sbx.totalAccounts = sbx.store.TotalAccounts() + sbx.totalValidators = sbx.store.TotalValidators() - return sb + return sbx } func (*sandbox) shouldPanicForDuplicatedAddress() { @@ -218,13 +218,13 @@ func (sb *sandbox) UpdateValidator(val *validator.Validator) { defer sb.lk.Unlock() addr := val.Address() - s, ok := sb.validators[addr] + sbVal, ok := sb.validators[addr] if !ok { sb.shouldPanicForUnknownAddress() } - s.validator = val - s.updated = true + sbVal.validator = val + sbVal.updated = true } func (sb *sandbox) Params() *param.Params { diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go index 26b36ab8c..8f979175f 100644 --- a/sandbox/sandbox_test.go +++ b/sandbox/sandbox_test.go @@ -21,7 +21,7 @@ type testData struct { valKeys []*bls.ValidatorKey store *store.MockStore - sandbox *sandbox + sbx *sandbox } func setup(t *testing.T) *testData { @@ -54,16 +54,16 @@ func setup(t *testing.T) *testData { blk, cert := ts.GenerateTestBlock(height) mockStore.SaveBlock(blk, cert) } - sandbox := NewSandbox(mockStore.LastHeight, + sbx := NewSandbox(mockStore.LastHeight, mockStore, param.FromGenesis(params), cmt, totalPower).(*sandbox) - assert.Equal(t, lastHeight, sandbox.CurrentHeight()) - assert.Equal(t, param.FromGenesis(params), sandbox.Params()) + assert.Equal(t, lastHeight, sbx.CurrentHeight()) + assert.Equal(t, param.FromGenesis(params), sbx.Params()) return &testData{ TestSuite: ts, valKeys: valKeys, store: mockStore, - sandbox: sandbox, + sbx: sbx, } } @@ -72,9 +72,9 @@ func TestAccountChange(t *testing.T) { t.Run("Should returns nil for invalid address", func(t *testing.T) { invAddr := td.RandAccAddress() - assert.Nil(t, td.sandbox.Account(invAddr)) + assert.Nil(t, td.sbx.Account(invAddr)) - td.sandbox.IterateAccounts(func(_ crypto.Address, _ *account.Account, _ bool) { + td.sbx.IterateAccounts(func(_ crypto.Address, _ *account.Account, _ bool) { panic("should be empty") }) }) @@ -84,30 +84,30 @@ func TestAccountChange(t *testing.T) { bal := acc.Balance() td.store.UpdateAccount(addr, acc) - sbAcc1 := td.sandbox.Account(addr) + sbAcc1 := td.sbx.Account(addr) assert.Equal(t, acc, sbAcc1) sbAcc1.AddToBalance(1) - assert.False(t, td.sandbox.accounts[addr].updated) - assert.Equal(t, bal, td.sandbox.Account(addr).Balance()) - td.sandbox.UpdateAccount(addr, sbAcc1) - assert.True(t, td.sandbox.accounts[addr].updated) - assert.Equal(t, bal+1, td.sandbox.Account(addr).Balance()) + assert.False(t, td.sbx.accounts[addr].updated) + assert.Equal(t, bal, td.sbx.Account(addr).Balance()) + td.sbx.UpdateAccount(addr, sbAcc1) + assert.True(t, td.sbx.accounts[addr].updated) + assert.Equal(t, bal+1, td.sbx.Account(addr).Balance()) t.Run("Update the same account again", func(t *testing.T) { - sbAcc2 := td.sandbox.Account(addr) + sbAcc2 := td.sbx.Account(addr) sbAcc2.AddToBalance(1) - assert.True(t, td.sandbox.accounts[addr].updated, "it is updated before") - assert.Equal(t, bal+1, td.sandbox.Account(addr).Balance()) - td.sandbox.UpdateAccount(addr, sbAcc2) - assert.True(t, td.sandbox.accounts[addr].updated) - assert.Equal(t, bal+2, td.sandbox.Account(addr).Balance()) + assert.True(t, td.sbx.accounts[addr].updated, "it is updated before") + assert.Equal(t, bal+1, td.sbx.Account(addr).Balance()) + td.sbx.UpdateAccount(addr, sbAcc2) + assert.True(t, td.sbx.accounts[addr].updated) + assert.Equal(t, bal+2, td.sbx.Account(addr).Balance()) }) t.Run("Should be iterated", func(t *testing.T) { - td.sandbox.IterateAccounts(func(a crypto.Address, acc *account.Account, updated bool) { + td.sbx.IterateAccounts(func(a crypto.Address, acc *account.Account, updated bool) { assert.Equal(t, addr, a) assert.True(t, updated) assert.Equal(t, bal+2, acc.Balance()) @@ -117,16 +117,16 @@ func TestAccountChange(t *testing.T) { t.Run("Make new account", func(t *testing.T) { addr := td.RandAccAddress() - acc := td.sandbox.MakeNewAccount(addr) + acc := td.sbx.MakeNewAccount(addr) acc.AddToBalance(1) - td.sandbox.UpdateAccount(addr, acc) - sbAcc := td.sandbox.Account(addr) + td.sbx.UpdateAccount(addr, acc) + sbAcc := td.sbx.Account(addr) assert.Equal(t, acc, sbAcc) t.Run("Should be iterated", func(t *testing.T) { - td.sandbox.IterateAccounts(func(a crypto.Address, acc *account.Account, updated bool) { + td.sbx.IterateAccounts(func(a crypto.Address, acc *account.Account, updated bool) { if a == addr { assert.True(t, updated) assert.Equal(t, amount.Amount(1), acc.Balance()) @@ -141,14 +141,14 @@ func TestRecentTransaction(t *testing.T) { randTx1 := td.GenerateTestTransferTx() randTx2 := td.GenerateTestTransferTx() - td.sandbox.CommitTransaction(randTx1) - td.sandbox.CommitTransaction(randTx2) + td.sbx.CommitTransaction(randTx1) + td.sbx.CommitTransaction(randTx2) - assert.True(t, td.sandbox.RecentTransaction(randTx1.ID())) - assert.True(t, td.sandbox.RecentTransaction(randTx2.ID())) + assert.True(t, td.sbx.RecentTransaction(randTx1.ID())) + assert.True(t, td.sbx.RecentTransaction(randTx2.ID())) totalTxFees := randTx1.Fee() + randTx2.Fee() - assert.Equal(t, totalTxFees, td.sandbox.AccumulatedFee()) + assert.Equal(t, totalTxFees, td.sbx.AccumulatedFee()) } func TestValidatorChange(t *testing.T) { @@ -156,9 +156,9 @@ func TestValidatorChange(t *testing.T) { t.Run("Should returns nil for invalid address", func(t *testing.T) { invAddr := td.RandAccAddress() - assert.Nil(t, td.sandbox.Validator(invAddr)) + assert.Nil(t, td.sbx.Validator(invAddr)) - td.sandbox.IterateValidators(func(_ *validator.Validator, _ bool, _ bool) { + td.sbx.IterateValidators(func(_ *validator.Validator, _ bool, _ bool) { panic("should be empty") }) }) @@ -169,30 +169,30 @@ func TestValidatorChange(t *testing.T) { stk := val.Stake() td.store.UpdateValidator(val) - sbVal1 := td.sandbox.Validator(addr) + sbVal1 := td.sbx.Validator(addr) assert.Equal(t, val.Hash(), sbVal1.Hash()) sbVal1.AddToStake(1) - assert.False(t, td.sandbox.validators[addr].updated) - assert.Equal(t, stk, td.sandbox.Validator(addr).Stake()) - td.sandbox.UpdateValidator(sbVal1) - assert.True(t, td.sandbox.validators[sbVal1.Address()].updated) - assert.Equal(t, stk+1, td.sandbox.Validator(addr).Stake()) + assert.False(t, td.sbx.validators[addr].updated) + assert.Equal(t, stk, td.sbx.Validator(addr).Stake()) + td.sbx.UpdateValidator(sbVal1) + assert.True(t, td.sbx.validators[sbVal1.Address()].updated) + assert.Equal(t, stk+1, td.sbx.Validator(addr).Stake()) t.Run("Update the same validator again", func(t *testing.T) { - sbVal2 := td.sandbox.Validator(addr) + sbVal2 := td.sbx.Validator(addr) sbVal2.AddToStake(1) - assert.True(t, td.sandbox.validators[addr].updated, "it is updated before") - assert.Equal(t, stk+1, td.sandbox.Validator(addr).Stake()) - td.sandbox.UpdateValidator(sbVal2) - assert.True(t, td.sandbox.validators[sbVal1.Address()].updated) - assert.Equal(t, stk+2, td.sandbox.Validator(addr).Stake()) + assert.True(t, td.sbx.validators[addr].updated, "it is updated before") + assert.Equal(t, stk+1, td.sbx.Validator(addr).Stake()) + td.sbx.UpdateValidator(sbVal2) + assert.True(t, td.sbx.validators[sbVal1.Address()].updated) + assert.Equal(t, stk+2, td.sbx.Validator(addr).Stake()) }) t.Run("Should be iterated", func(t *testing.T) { - td.sandbox.IterateValidators(func(val *validator.Validator, updated bool, joined bool) { + td.sbx.IterateValidators(func(val *validator.Validator, updated bool, joined bool) { assert.True(t, updated) assert.False(t, joined) assert.Equal(t, stk+2, val.Stake()) @@ -202,16 +202,16 @@ func TestValidatorChange(t *testing.T) { t.Run("Make new validator", func(t *testing.T) { pub, _ := td.RandBLSKeyPair() - val := td.sandbox.MakeNewValidator(pub) + val := td.sbx.MakeNewValidator(pub) val.AddToStake(1) - td.sandbox.UpdateValidator(val) - sbVal := td.sandbox.Validator(val.Address()) + td.sbx.UpdateValidator(val) + sbVal := td.sbx.Validator(val.Address()) assert.Equal(t, val, sbVal) t.Run("Should be iterated", func(t *testing.T) { - td.sandbox.IterateValidators(func(val *validator.Validator, updated bool, joined bool) { + td.sbx.IterateValidators(func(val *validator.Validator, updated bool, joined bool) { if val.PublicKey() == pub { assert.True(t, updated) assert.False(t, joined) @@ -228,10 +228,10 @@ func TestTotalAccountCounter(t *testing.T) { t.Run("Should update total account counter", func(t *testing.T) { totalAccs := td.store.TotalAccounts() - acc1 := td.sandbox.MakeNewAccount(td.RandAccAddress()) + acc1 := td.sbx.MakeNewAccount(td.RandAccAddress()) assert.Equal(t, totalAccs, acc1.Number()) - acc2 := td.sandbox.MakeNewAccount(td.RandAccAddress()) + acc2 := td.sbx.MakeNewAccount(td.RandAccAddress()) assert.Equal(t, totalAccs+1, acc2.Number()) }) } @@ -244,10 +244,10 @@ func TestTotalValidatorCounter(t *testing.T) { pub, _ := td.RandBLSKeyPair() pub2, _ := td.RandBLSKeyPair() - val1 := td.sandbox.MakeNewValidator(pub) + val1 := td.sbx.MakeNewValidator(pub) assert.Equal(t, totalVals, val1.Number()) - val2 := td.sandbox.MakeNewValidator(pub2) + val2 := td.sbx.MakeNewValidator(pub2) assert.Equal(t, totalVals+1, val2.Number()) }) } @@ -262,13 +262,13 @@ func TestCreateDuplicated(t *testing.T) { } }() addr := crypto.TreasuryAddress - td.sandbox.MakeNewAccount(addr) + td.sbx.MakeNewAccount(addr) }) t.Run("Try creating duplicated validator, Should panic", func(t *testing.T) { assert.Panics(t, func() { pub := td.valKeys[3].PublicKey() - td.sandbox.MakeNewValidator(pub) + td.sbx.MakeNewValidator(pub) }) }) } @@ -279,14 +279,14 @@ func TestUpdateFromOutsideTheSandbox(t *testing.T) { t.Run("Try update an account from outside the sandbox, Should panic", func(t *testing.T) { assert.Panics(t, func() { acc, addr := td.GenerateTestAccount(td.RandInt32(0)) - td.sandbox.UpdateAccount(addr, acc) + td.sbx.UpdateAccount(addr, acc) }) }) t.Run("Try update a validator from outside the sandbox, Should panic", func(t *testing.T) { assert.Panics(t, func() { val, _ := td.GenerateTestValidator(td.RandInt32(0)) - td.sandbox.UpdateValidator(val) + td.sbx.UpdateValidator(val) }) }) } @@ -296,26 +296,26 @@ func TestAccountDeepCopy(t *testing.T) { t.Run("non existing account", func(t *testing.T) { addr := td.RandAccAddress() - acc := td.sandbox.MakeNewAccount(addr) + acc := td.sbx.MakeNewAccount(addr) acc.AddToBalance(1) - assert.NotEqual(t, acc, td.sandbox.Account(addr)) + assert.NotEqual(t, acc, td.sbx.Account(addr)) }) t.Run("existing account", func(t *testing.T) { addr := crypto.TreasuryAddress - acc := td.sandbox.Account(addr) + acc := td.sbx.Account(addr) acc.AddToBalance(1) - assert.NotEqual(t, acc, td.sandbox.Account(addr)) + assert.NotEqual(t, acc, td.sbx.Account(addr)) }) t.Run("sandbox account", func(t *testing.T) { addr := crypto.TreasuryAddress - acc := td.sandbox.Account(addr) + acc := td.sbx.Account(addr) acc.AddToBalance(1) - assert.NotEqual(t, acc, td.sandbox.Account(addr)) + assert.NotEqual(t, acc, td.sbx.Account(addr)) }) } @@ -324,37 +324,37 @@ func TestValidatorDeepCopy(t *testing.T) { t.Run("non existing validator", func(t *testing.T) { pub, _ := td.RandBLSKeyPair() - val := td.sandbox.MakeNewValidator(pub) + val := td.sbx.MakeNewValidator(pub) val.AddToStake(1) - assert.NotEqual(t, val, td.sandbox.Validator(pub.ValidatorAddress())) + assert.NotEqual(t, val, td.sbx.Validator(pub.ValidatorAddress())) }) val0, _ := td.store.ValidatorByNumber(0) addr := val0.Address() t.Run("existing validator", func(t *testing.T) { - val := td.sandbox.Validator(addr) + val := td.sbx.Validator(addr) val.AddToStake(1) - assert.NotEqual(t, val, td.sandbox.Validator(addr)) + assert.NotEqual(t, val, td.sbx.Validator(addr)) }) t.Run("sandbox validator", func(t *testing.T) { - val := td.sandbox.Validator(addr) + val := td.sbx.Validator(addr) val.AddToStake(1) - assert.NotEqual(t, val, td.sandbox.Validator(addr)) + assert.NotEqual(t, val, td.sbx.Validator(addr)) }) } func TestPowerDelta(t *testing.T) { td := setup(t) - assert.Zero(t, td.sandbox.PowerDelta()) - td.sandbox.UpdatePowerDelta(1) - assert.Equal(t, int64(1), td.sandbox.PowerDelta()) - td.sandbox.UpdatePowerDelta(-1) - assert.Zero(t, td.sandbox.PowerDelta()) + assert.Zero(t, td.sbx.PowerDelta()) + td.sbx.UpdatePowerDelta(1) + assert.Equal(t, int64(1), td.sbx.PowerDelta()) + td.sbx.UpdatePowerDelta(-1) + assert.Zero(t, td.sbx.PowerDelta()) } func TestVerifyProof(t *testing.T) { @@ -362,7 +362,7 @@ func TestVerifyProof(t *testing.T) { lastCert := td.store.LastCertificate() lastHeight := lastCert.Height() - vals := td.sandbox.committee.Validators() + vals := td.sbx.committee.Validators() // Try to evaluate a valid sortition var validProof sortition.Proof @@ -370,32 +370,32 @@ func TestVerifyProof(t *testing.T) { var validVal *validator.Validator for height := lastHeight; height > 0; height-- { block := td.store.Blocks[height] - for i, valKey := range td.valKeys { + for index, valKey := range td.valKeys { ok, proof := sortition.EvaluateSortition( block.Header().SortitionSeed(), valKey.PrivateKey(), - td.sandbox.totalPower, vals[i].Power()) + td.sbx.totalPower, vals[index].Power()) if ok { validProof = proof validLockTime = height - validVal = vals[i] + validVal = vals[index] } } } t.Run("invalid proof", func(t *testing.T) { invalidProof := td.RandProof() - assert.False(t, td.sandbox.VerifyProof(validLockTime, invalidProof, validVal)) + assert.False(t, td.sbx.VerifyProof(validLockTime, invalidProof, validVal)) }) t.Run("invalid height", func(t *testing.T) { - assert.False(t, td.sandbox.VerifyProof(td.RandHeight(), validProof, validVal)) + assert.False(t, td.sbx.VerifyProof(td.RandHeight(), validProof, validVal)) }) t.Run("genesis block height", func(t *testing.T) { - assert.False(t, td.sandbox.VerifyProof(0, validProof, validVal)) + assert.False(t, td.sbx.VerifyProof(0, validProof, validVal)) }) t.Run("Ok", func(t *testing.T) { - assert.True(t, td.sandbox.VerifyProof(validLockTime, validProof, validVal)) + assert.True(t, td.sbx.VerifyProof(validLockTime, validProof, validVal)) }) } diff --git a/sortition/vrf.go b/sortition/vrf.go index fb3ad434a..9bab48e14 100644 --- a/sortition/vrf.go +++ b/sortition/vrf.go @@ -53,14 +53,14 @@ func Verify(seed VerifiableSeed, pub *bls.PublicKey, proof Proof, max uint64) (u } func GetIndex(proof Proof, max uint64) uint64 { - h := hash.CalcHash(proof[:]) + hash := hash.CalcHash(proof[:]) // construct the numerator and denominator for normalizing the proof uint bigRnd := &big.Int{} bigMax := &big.Int{} numerator := &big.Int{} - bigRnd.SetBytes(h.Bytes()) + bigRnd.SetBytes(hash.Bytes()) bigMax.SetUint64(max) numerator = numerator.Mul(bigRnd, bigMax) diff --git a/sortition/vrf_test.go b/sortition/vrf_test.go index 0967c0162..0cab5ea68 100644 --- a/sortition/vrf_test.go +++ b/sortition/vrf_test.go @@ -14,8 +14,8 @@ import ( func TestVRF(t *testing.T) { ts := testsuite.NewTestSuite(t) - pk, pv := ts.RandBLSKeyPair() - valKey := bls.NewValidatorKey(pv) + pub, prv := ts.RandBLSKeyPair() + valKey := bls.NewValidatorKey(prv) for i := 0; i < 100; i++ { seed := ts.RandSeed() t.Logf("seed is: %x \n", seed) @@ -25,7 +25,7 @@ func TestVRF(t *testing.T) { assert.LessOrEqual(t, index, maxSize) - index2, result := sortition.Verify(seed, pk, proof, maxSize) + index2, result := sortition.Verify(seed, pub, proof, maxSize) assert.True(t, result) assert.Equal(t, index, index2) diff --git a/state/execution.go b/state/execution.go index 1ae82c5f6..138f90fbb 100644 --- a/state/execution.go +++ b/state/execution.go @@ -10,9 +10,9 @@ import ( "github.com/pactus-project/pactus/types/tx" ) -func (st *state) executeBlock(b *block.Block, sb sandbox.Sandbox, check bool) error { +func (st *state) executeBlock(blk *block.Block, sbx sandbox.Sandbox, check bool) error { var subsidyTrx *tx.Tx - for i, trx := range b.Transactions() { + for i, trx := range blk.Transactions() { // The first transaction should be subsidy transaction isSubsidyTx := (i == 0) if isSubsidyTx { @@ -29,20 +29,20 @@ func (st *state) executeBlock(b *block.Block, sb sandbox.Sandbox, check bool) er return err } - err := execution.CheckAndExecute(trx, sb, true) + err := execution.CheckAndExecute(trx, sbx, true) if err != nil { return err } } else { - err := execution.Execute(trx, sb) + err := execution.Execute(trx, sbx) if err != nil { return err } } } - accumulatedFee := sb.AccumulatedFee() - subsidyAmt := st.params.BlockReward + sb.AccumulatedFee() + accumulatedFee := sbx.AccumulatedFee() + subsidyAmt := st.params.BlockReward + sbx.AccumulatedFee() if subsidyTrx.Payload().Value() != subsidyAmt { return InvalidSubsidyAmountError{ Expected: subsidyAmt, @@ -51,9 +51,9 @@ func (st *state) executeBlock(b *block.Block, sb sandbox.Sandbox, check bool) er } // Claim accumulated fees - acc := sb.Account(crypto.TreasuryAddress) + acc := sbx.Account(crypto.TreasuryAddress) acc.AddToBalance(accumulatedFee) - sb.UpdateAccount(crypto.TreasuryAddress, acc) + sbx.UpdateAccount(crypto.TreasuryAddress, acc) return nil } diff --git a/state/facade.go b/state/facade.go index 6b3bfb633..590ee0f92 100644 --- a/state/facade.go +++ b/state/facade.go @@ -38,11 +38,11 @@ type Facade interface { TotalAccounts() int32 TotalValidators() int32 CommitteePower() int64 - PendingTx(id tx.ID) *tx.Tx + PendingTx(txID tx.ID) *tx.Tx AddPendingTx(trx *tx.Tx) error AddPendingTxAndBroadcast(trx *tx.Tx) error CommittedBlock(height uint32) *store.CommittedBlock - CommittedTx(id tx.ID) *store.CommittedTx + CommittedTx(txID tx.ID) *store.CommittedTx BlockHash(height uint32) hash.Hash BlockHeight(h hash.Hash) uint32 AccountByAddress(addr crypto.Address) *account.Account diff --git a/state/lastinfo/last_info.go b/state/lastinfo/last_info.go index dfb52e4ef..40398f3e7 100644 --- a/state/lastinfo/last_info.go +++ b/state/lastinfo/last_info.go @@ -111,11 +111,11 @@ func (li *LastInfo) UpdateValidators(vals []*validator.Validator) { li.lastValidators = vals } -func (li *LastInfo) RestoreLastInfo(str store.Store, committeeSize int) (committee.Committee, error) { - lastCert := str.LastCertificate() +func (li *LastInfo) RestoreLastInfo(store store.Store, committeeSize int) (committee.Committee, error) { + lastCert := store.LastCertificate() lastHeight := lastCert.Height() logger.Debug("try to restore last state info", "height", lastHeight) - sb, err := str.Block(lastHeight) + sb, err := store.Block(lastHeight) if err != nil { return nil, fmt.Errorf("unable to retrieve block %v: %w", lastHeight, err) } @@ -130,7 +130,7 @@ func (li *LastInfo) RestoreLastInfo(str store.Store, committeeSize int) (committ li.lastBlockHash = lastBlock.Hash() li.lastBlockTime = lastBlock.Header().Time() - cmt, err := li.restoreCommittee(str, lastBlock, committeeSize) + cmt, err := li.restoreCommittee(store, lastBlock, committeeSize) if err != nil { return nil, err } @@ -138,7 +138,7 @@ func (li *LastInfo) RestoreLastInfo(str store.Store, committeeSize int) (committ return cmt, nil } -func (li *LastInfo) restoreCommittee(str store.Store, lastBlock *block.Block, +func (li *LastInfo) restoreCommittee(store store.Store, lastBlock *block.Block, committeeSize int, ) (committee.Committee, error) { joinedVals := make([]*validator.Validator, 0) @@ -147,7 +147,7 @@ func (li *LastInfo) restoreCommittee(str store.Store, lastBlock *block.Block, // we should update the last committee. if trx.IsSortitionTx() { pld := trx.Payload().(*payload.SortitionPayload) - val, err := str.Validator(pld.Validator) + val, err := store.Validator(pld.Validator) if err != nil { return nil, fmt.Errorf("unable to retrieve validator %s: %w", pld.Validator, err) } @@ -159,7 +159,7 @@ func (li *LastInfo) restoreCommittee(str store.Store, lastBlock *block.Block, curCommitteeSize := len(li.lastCert.Committers()) vals := make([]*validator.Validator, len(li.lastCert.Committers())) for i, num := range li.lastCert.Committers() { - val, err := str.ValidatorByNumber(num) + val, err := store.ValidatorByNumber(num) if err != nil { return nil, fmt.Errorf("unable to retrieve committee member %v: %w", num, err) } diff --git a/state/lastinfo/last_info_test.go b/state/lastinfo/last_info_test.go index 3a901f52e..bd193a55e 100644 --- a/state/lastinfo/last_info_test.go +++ b/state/lastinfo/last_info_test.go @@ -102,9 +102,9 @@ func setup(t *testing.T) *testData { func TestRestoreCommittee(t *testing.T) { td := setup(t) - li := NewLastInfo() + lastInfo := NewLastInfo() - cmt, err := li.RestoreLastInfo(td.store, 4) + cmt, err := lastInfo.RestoreLastInfo(td.store, 4) assert.NoError(t, err) val0, _ := td.store.ValidatorByNumber(0) @@ -112,11 +112,11 @@ func TestRestoreCommittee(t *testing.T) { val2, _ := td.store.ValidatorByNumber(2) val3, _ := td.store.ValidatorByNumber(3) - assert.Equal(t, td.lastInfo.SortitionSeed(), li.SortitionSeed()) - assert.Equal(t, td.lastInfo.BlockHeight(), li.BlockHeight()) - assert.Equal(t, td.lastInfo.BlockHash(), li.BlockHash()) - assert.Equal(t, td.lastInfo.Certificate().Hash(), li.Certificate().Hash()) - assert.Equal(t, td.lastInfo.BlockTime(), li.BlockTime()) + assert.Equal(t, td.lastInfo.SortitionSeed(), lastInfo.SortitionSeed()) + assert.Equal(t, td.lastInfo.BlockHeight(), lastInfo.BlockHeight()) + assert.Equal(t, td.lastInfo.BlockHash(), lastInfo.BlockHash()) + assert.Equal(t, td.lastInfo.Certificate().Hash(), lastInfo.Certificate().Hash()) + assert.Equal(t, td.lastInfo.BlockTime(), lastInfo.BlockTime()) assert.Equal(t, td.lastInfo.Validators(), []*validator.Validator{val0, val1, val2, val3}) assert.Equal(t, []int32{1, 4, 2, 3}, cmt.Committers()) } diff --git a/state/mock.go b/state/mock.go index 49bf929be..197fbc2f8 100644 --- a/state/mock.go +++ b/state/mock.go @@ -100,14 +100,14 @@ func (*MockState) UpdateLastCertificate(_ *vote.Vote) error { return nil } -func (m *MockState) CommitBlock(b *block.Block, cert *certificate.BlockCertificate) error { +func (m *MockState) CommitBlock(blk *block.Block, cert *certificate.BlockCertificate) error { m.lk.Lock() defer m.lk.Unlock() if cert.Height() != m.TestStore.LastHeight+1 { return fmt.Errorf("invalid height") } - m.TestStore.SaveBlock(b, cert) + m.TestStore.SaveBlock(blk, cert) return nil } @@ -153,14 +153,14 @@ func (m *MockState) TotalAccounts() int32 { } func (m *MockState) TotalPower() int64 { - p := int64(0) + power := int64(0) m.TestStore.IterateValidators(func(val *validator.Validator) bool { - p += val.Power() + power += val.Power() return false }) - return p + return power } func (m *MockState) CommitteePower() int64 { @@ -176,11 +176,11 @@ func (m *MockState) CommittedBlock(height uint32) *store.CommittedBlock { return b } -func (m *MockState) CommittedTx(id tx.ID) *store.CommittedTx { +func (m *MockState) CommittedTx(txID tx.ID) *store.CommittedTx { m.lk.RLock() defer m.lk.RUnlock() - trx, _ := m.TestStore.Transaction(id) + trx, _ := m.TestStore.Transaction(txID) return trx } @@ -227,8 +227,8 @@ func (m *MockState) ValidatorByNumber(n int32) *validator.Validator { return v } -func (m *MockState) PendingTx(id tx.ID) *tx.Tx { - return m.TestPool.PendingTx(id) +func (m *MockState) PendingTx(txID tx.ID) *tx.Tx { + return m.TestPool.PendingTx(txID) } func (m *MockState) AddPendingTx(trx *tx.Tx) error { diff --git a/state/score/score_test.go b/state/score/score_test.go index de5ad9747..c4a4af741 100644 --- a/state/score/score_test.go +++ b/state/score/score_test.go @@ -9,7 +9,7 @@ import ( func TestScoreManager(t *testing.T) { maxCert := uint32(3) - sm := NewScoreManager(maxCert) + scoreMgr := NewScoreManager(maxCert) cert1 := certificate.NewBlockCertificate(1, 0) cert1.SetSignature([]int32{0, 1, 2, 3}, []int32{0}, nil) @@ -41,27 +41,27 @@ func TestScoreManager(t *testing.T) { {cert5, 1, 1, 0, 1, 1}, } - for i, test := range tests { - sm.SetCertificate(test.cert) + for no, tt := range tests { + scoreMgr.SetCertificate(tt.cert) - score0 := sm.AvailabilityScore(0) - assert.Equal(t, test.score0, score0, "#%v: invalid score0, expected %v, got %v", - i, test.score0, score0) + score0 := scoreMgr.AvailabilityScore(0) + assert.Equal(t, tt.score0, score0, "#%v: invalid score0, expected %v, got %v", + no, tt.score0, score0) - score1 := sm.AvailabilityScore(1) - assert.Equal(t, test.score1, score1, "#%v: invalid score1, expected %v, got %v", - i, test.score1, score1) + score1 := scoreMgr.AvailabilityScore(1) + assert.Equal(t, tt.score1, score1, "#%v: invalid score1, expected %v, got %v", + no, tt.score1, score1) - score2 := sm.AvailabilityScore(2) - assert.Equal(t, test.score2, score2, "#%v: invalid score2, expected %v, got %v", - i, test.score2, score2) + score2 := scoreMgr.AvailabilityScore(2) + assert.Equal(t, tt.score2, score2, "#%v: invalid score2, expected %v, got %v", + no, tt.score2, score2) - score3 := sm.AvailabilityScore(3) - assert.Equal(t, test.score3, score3, "#%v: invalid score3, expected %v, got %v", - i, test.score3, score3) + score3 := scoreMgr.AvailabilityScore(3) + assert.Equal(t, tt.score3, score3, "#%v: invalid score3, expected %v, got %v", + no, tt.score3, score3) - score4 := sm.AvailabilityScore(4) - assert.Equal(t, test.score4, score4, "#%v: invalid score4, expected %v, got %v", - i, test.score4, score4) + score4 := scoreMgr.AvailabilityScore(4) + assert.Equal(t, tt.score4, score4, "#%v: invalid score4, expected %v, got %v", + no, tt.score4, score4) } } diff --git a/state/state.go b/state/state.go index bdb4046f6..9de8951d9 100644 --- a/state/state.go +++ b/state/state.go @@ -55,62 +55,62 @@ type state struct { func LoadOrNewState( genDoc *genesis.Genesis, valKeys []*bls.ValidatorKey, - str store.Store, + store store.Store, txPool txpool.TxPool, eventCh chan event.Event, ) (Facade, error) { - st := &state{ + state := &state{ valKeys: valKeys, genDoc: genDoc, txPool: txPool, params: param.FromGenesis(genDoc.Params()), - store: str, + store: store, lastInfo: lastinfo.NewLastInfo(), accountMerkle: persistentmerkle.New(), validatorMerkle: persistentmerkle.New(), eventCh: eventCh, } - st.logger = logger.NewSubLogger("_state", st) - st.store = str + state.logger = logger.NewSubLogger("_state", state) + state.store = store // Check if the number of accounts is greater than the genesis time; // this indicates we are not at the genesis height anymore. - if str.TotalAccounts() > int32(len(genDoc.Accounts())) { - err := st.tryLoadLastInfo() + if store.TotalAccounts() > int32(len(genDoc.Accounts())) { + err := state.tryLoadLastInfo() if err != nil { return nil, err } } else { // We are at the genesis height. - err := st.makeGenesisState(genDoc) + err := state.makeGenesisState(genDoc) if err != nil { return nil, err } } - st.totalPower = st.retrieveTotalPower() + state.totalPower = state.retrieveTotalPower() - st.loadMerkels() + state.loadMerkels() - txPool.SetNewSandboxAndRecheck(st.concreteSandbox()) + txPool.SetNewSandboxAndRecheck(state.concreteSandbox()) // Restoring score manager - st.logger.Info("calculating the availability scores...") + state.logger.Info("calculating the availability scores...") scoreWindow := uint32(60000) startHeight := uint32(2) - endHeight := st.lastInfo.BlockHeight() + endHeight := state.lastInfo.BlockHeight() if endHeight > scoreWindow { startHeight = endHeight - scoreWindow } scoreMgr := score.NewScoreManager(scoreWindow) for h := startHeight; h <= endHeight; h++ { - cb, err := st.store.Block(h) + cBlk, err := state.store.Block(h) if err != nil { return nil, err } // This code decodes the block certificate from the block data // without decoding the header and transactions. - r := bytes.NewReader(cb.Data[138:]) // Block header is 138 bytes + r := bytes.NewReader(cBlk.Data[138:]) // Block header is 138 bytes cert := new(certificate.BlockCertificate) err = cert.Decode(r) if err != nil { @@ -118,15 +118,15 @@ func LoadOrNewState( } scoreMgr.SetCertificate(cert) } - st.scoreMgr = scoreMgr + state.scoreMgr = scoreMgr - for _, num := range st.committee.Committers() { - st.logger.Debug("availability score", "val", num, "score", st.scoreMgr.AvailabilityScore(num)) + for _, num := range state.committee.Committers() { + state.logger.Debug("availability score", "val", num, "score", state.scoreMgr.AvailabilityScore(num)) } - st.logger.Debug("last info", "committers", st.committee.Committers(), "state_root", st.stateRoot()) + state.logger.Debug("last info", "committers", state.committee.Committers(), "state_root", state.stateRoot()) - return st, nil + return state, nil } func (st *state) concreteSandbox() sandbox.Sandbox { @@ -264,31 +264,31 @@ func (st *state) LastCertificate() *certificate.BlockCertificate { return st.lastInfo.Certificate() } -func (st *state) UpdateLastCertificate(v *vote.Vote) error { +func (st *state) UpdateLastCertificate(vte *vote.Vote) error { st.lk.Lock() defer st.lk.Unlock() lastCert := st.lastInfo.Certificate() - if v.Type() != vote.VoteTypePrecommit || - v.Height() != lastCert.Height() || - v.Round() != lastCert.Round() { + if vte.Type() != vote.VoteTypePrecommit || + vte.Height() != lastCert.Height() || + vte.Round() != lastCert.Round() { return InvalidVoteForCertificateError{ - Vote: v, + Vote: vte, } } - val, err := st.store.Validator(v.Signer()) + val, err := st.store.Validator(vte.Signer()) if err != nil { return err } if !util.Contains(lastCert.Absentees(), val.Number()) { return InvalidVoteForCertificateError{ - Vote: v, + Vote: vte, } } - err = v.Verify(val.PublicKey()) + err = vte.Verify(val.PublicKey()) if err != nil { return err } @@ -296,7 +296,7 @@ func (st *state) UpdateLastCertificate(v *vote.Vote) error { // prevent race condition cloneLastCert := lastCert.Clone() - cloneLastCert.AddSignature(val.Number(), v.Signature()) + cloneLastCert.AddSignature(val.Number(), vte.Signature()) st.lastInfo.UpdateCertificate(cloneLastCert) st.logger.Debug("certificate updated", "validator", val.Address(), "power", val.Power()) @@ -315,8 +315,8 @@ func (st *state) ProposeBlock(valKey *bls.ValidatorKey, rewardAddr crypto.Addres st.lk.Lock() defer st.lk.Unlock() - // Create new sandbox and execute transactions - sb := st.concreteSandbox() + // Create new sbx and execute transactions + sbx := st.concreteSandbox() // Re-check all transactions strictly and remove invalid ones txs := st.txPool.PrepareBlockTransactions() @@ -331,14 +331,14 @@ func (st *state) ProposeBlock(valKey *bls.ValidatorKey, rewardAddr crypto.Addres continue } - if err := execution.CheckAndExecute(txs[i], sb, true); err != nil { + if err := execution.CheckAndExecute(txs[i], sbx, true); err != nil { st.logger.Debug("found invalid transaction", "tx", txs[i], "error", err) txs.Remove(i) i-- } } - subsidyTx := st.createSubsidyTx(rewardAddr, sb.AccumulatedFee()) + subsidyTx := st.createSubsidyTx(rewardAddr, sbx.AccumulatedFee()) if subsidyTx == nil { // probably the node is shutting down. st.logger.Error("no subsidy transaction") @@ -415,8 +415,8 @@ func (st *state) CommitBlock(blk *block.Block, cert *certificate.BlockCertificat // ----------------------------------- // Execute block - sb := st.concreteSandbox() - if err := st.executeBlock(blk, sb, false); err != nil { + sbx := st.concreteSandbox() + if err := st.executeBlock(blk, sbx, false); err != nil { return err } @@ -429,7 +429,7 @@ func (st *state) CommitBlock(blk *block.Block, cert *certificate.BlockCertificat st.lastInfo.UpdateValidators(st.committee.Validators()) // Commit and update the committee - st.commitSandbox(sb, cert.Round()) + st.commitSandbox(sbx, cert.Round()) st.store.SaveBlock(blk, cert) @@ -517,9 +517,9 @@ func (st *state) String() string { st.lastInfo.BlockTime().Format("15.04.05")) } -func (st *state) commitSandbox(sb sandbox.Sandbox, round int16) { +func (st *state) commitSandbox(sbx sandbox.Sandbox, round int16) { joiningCommittee := make([]*validator.Validator, 0) - sb.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { + sbx.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { if joined { st.logger.Debug("new validator joined", "address", val.Address(), "power", val.Power()) @@ -528,48 +528,48 @@ func (st *state) commitSandbox(sb sandbox.Sandbox, round int16) { }) st.committee.Update(round, joiningCommittee) - sb.IterateAccounts(func(addr crypto.Address, acc *account.Account, updated bool) { + sbx.IterateAccounts(func(addr crypto.Address, acc *account.Account, updated bool) { if updated { st.store.UpdateAccount(addr, acc) st.accountMerkle.SetHash(int(acc.Number()), acc.Hash()) } }) - sb.IterateValidators(func(val *validator.Validator, updated bool, _ bool) { + sbx.IterateValidators(func(val *validator.Validator, updated bool, _ bool) { if updated { st.store.UpdateValidator(val) st.validatorMerkle.SetHash(int(val.Number()), val.Hash()) } }) - st.totalPower += sb.PowerDelta() + st.totalPower += sbx.PowerDelta() } -func (st *state) validateBlockTime(t time.Time) error { - if t.Second()%st.params.BlockIntervalInSecond != 0 { +func (st *state) validateBlockTime(blockTime time.Time) error { + if blockTime.Second()%st.params.BlockIntervalInSecond != 0 { return InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is not rounded", - t.String()), + blockTime.String()), } } - if t.Before(st.lastInfo.BlockTime()) { + if blockTime.Before(st.lastInfo.BlockTime()) { return InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is before the last block time (%s)", - t.String(), st.lastInfo.BlockTime()), + blockTime.String(), st.lastInfo.BlockTime()), } } - if t.Equal(st.lastInfo.BlockTime()) { + if blockTime.Equal(st.lastInfo.BlockTime()) { return InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is same as the last block time", - t.String()), + blockTime.String()), } } proposeTime := st.proposeNextBlockTime() threshold := st.params.BlockInterval() - if t.After(proposeTime.Add(threshold)) { + if blockTime.After(proposeTime.Add(threshold)) { return InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is more than threshold (%s)", - t.String(), proposeTime.String()), + blockTime.String(), proposeTime.String()), } } @@ -643,20 +643,20 @@ func (st *state) IsValidator(addr crypto.Address) bool { } func (st *state) CommittedBlock(height uint32) *store.CommittedBlock { - b, err := st.store.Block(height) + blk, err := st.store.Block(height) if err != nil { st.logger.Trace("error on retrieving block", "error", err) return nil } - return b + return blk } -func (st *state) CommittedTx(id tx.ID) *store.CommittedTx { - transaction, err := st.store.Transaction(id) +func (st *state) CommittedTx(txID tx.ID) *store.CommittedTx { + transaction, err := st.store.Transaction(txID) if err != nil { - st.logger.Trace("searching transaction in local store failed", "id", id, "error", err) + st.logger.Trace("searching transaction in local store failed", "id", txID, "error", err) } return transaction @@ -702,8 +702,8 @@ func (st *state) ValidatorByNumber(n int32) *validator.Validator { return val } -func (st *state) PendingTx(id tx.ID) *tx.Tx { - return st.txPool.PendingTx(id) +func (st *state) PendingTx(txID tx.ID) *tx.Tx { + return st.txPool.PendingTx(txID) } func (st *state) AddPendingTx(trx *tx.Tx) error { diff --git a/state/state_test.go b/state/state_test.go index 593cd1fe2..0e701c838 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -229,14 +229,14 @@ func TestCommitSandbox(t *testing.T) { t.Run("Modify account", func(t *testing.T) { td := setup(t) - sb := td.state.concreteSandbox() + sbx := td.state.concreteSandbox() addr := td.genAccKey.PublicKeyNative().AccountAddress() - acc := sb.Account(addr) + acc := sbx.Account(addr) bal := acc.Balance() amt := td.RandAmount() acc.SubtractFromBalance(amt) - sb.UpdateAccount(addr, acc) - td.state.commitSandbox(sb, 0) + sbx.UpdateAccount(addr, acc) + td.state.commitSandbox(sbx, 0) stateAcc := td.state.AccountByAddress(addr) assert.Equal(t, bal-amt, stateAcc.Balance()) @@ -245,14 +245,14 @@ func TestCommitSandbox(t *testing.T) { t.Run("Modify validator", func(t *testing.T) { td := setup(t) - sb := td.state.concreteSandbox() + sbx := td.state.concreteSandbox() addr := td.genValKeys[0].Address() - val := sb.Validator(addr) + val := sbx.Validator(addr) stake := val.Stake() amt := td.RandAmount() val.AddToStake(amt) - sb.UpdateValidator(val) - td.state.commitSandbox(sb, 0) + sbx.UpdateValidator(val) + td.state.commitSandbox(sbx, 0) stateVal := td.state.ValidatorByAddress(addr) assert.Equal(t, stake+amt, stateVal.Stake(), val.Stake()) @@ -298,39 +298,39 @@ func TestUpdateLastCertificate(t *testing.T) { valKey4 := td.genValKeys[len(td.genValKeys)-1] invValKey := td.RandValKey() - v1 := vote.NewPrepareVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) - v2 := vote.NewPrecommitVote(blk.Hash(), cert.Height()+1, cert.Round(), valKey4.Address()) - v3 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round()-1, valKey4.Address()) - v4 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) - v5 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), invValKey.Address()) - v6 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey1.Address()) - v7 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) - - td.HelperSignVote(valKey4, v1) - td.HelperSignVote(valKey4, v2) - td.HelperSignVote(valKey4, v3) - td.HelperSignVote(invValKey, v4) - td.HelperSignVote(invValKey, v5) - td.HelperSignVote(valKey4, v6) - td.HelperSignVote(valKey4, v7) + vote1 := vote.NewPrepareVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) + vote2 := vote.NewPrecommitVote(blk.Hash(), cert.Height()+1, cert.Round(), valKey4.Address()) + vote3 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round()-1, valKey4.Address()) + vote4 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) + vote5 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), invValKey.Address()) + vote6 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey1.Address()) + vote7 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) + + td.HelperSignVote(valKey4, vote1) + td.HelperSignVote(valKey4, vote2) + td.HelperSignVote(valKey4, vote3) + td.HelperSignVote(invValKey, vote4) + td.HelperSignVote(invValKey, vote5) + td.HelperSignVote(valKey4, vote6) + td.HelperSignVote(valKey4, vote7) tests := []struct { vote *vote.Vote err error reason string }{ - {v1, InvalidVoteForCertificateError{Vote: v1}, "invalid vote type"}, - {v2, InvalidVoteForCertificateError{Vote: v2}, "invalid height"}, - {v3, InvalidVoteForCertificateError{Vote: v3}, "invalid round"}, - {v4, crypto.ErrInvalidSignature, "invalid signature"}, - {v5, store.ErrNotFound, "unknown validator"}, - {v6, InvalidVoteForCertificateError{Vote: v6}, "not in absentee"}, - {v7, nil, "ok"}, + {vote1, InvalidVoteForCertificateError{Vote: vote1}, "invalid vote type"}, + {vote2, InvalidVoteForCertificateError{Vote: vote2}, "invalid height"}, + {vote3, InvalidVoteForCertificateError{Vote: vote3}, "invalid round"}, + {vote4, crypto.ErrInvalidSignature, "invalid signature"}, + {vote5, store.ErrNotFound, "unknown validator"}, + {vote6, InvalidVoteForCertificateError{Vote: vote6}, "not in absentee"}, + {vote7, nil, "ok"}, } - for i, test := range tests { - err := td.state.UpdateLastCertificate(test.vote) - assert.ErrorIs(t, err, test.err, "error not matched for test %v", i) + for no, tt := range tests { + err := td.state.UpdateLastCertificate(tt.vote) + assert.ErrorIs(t, err, tt.err, "error not matched for test %v", no) } } diff --git a/store/block.go b/store/block.go index 2787a8bbe..9e542d974 100644 --- a/store/block.go +++ b/store/block.go @@ -49,27 +49,27 @@ func newBlockStore(db *leveldb.DB, seedCacheWindow uint32, publicKeyCacheSize in func (bs *blockStore) saveBlock(batch *leveldb.Batch, height uint32, blk *block.Block) []blockRegion { blockHash := blk.Hash() regs := make([]blockRegion, blk.Transactions().Len()) - w := bytes.NewBuffer(make([]byte, 0, blk.SerializeSize()+hash.HashSize)) - err := encoding.WriteElement(w, &blockHash) + buf := bytes.NewBuffer(make([]byte, 0, blk.SerializeSize()+hash.HashSize)) + err := encoding.WriteElement(buf, &blockHash) if err != nil { panic(err) // Should we panic? } - err = blk.Header().Encode(w) + err = blk.Header().Encode(buf) if err != nil { panic(err) // Should we panic? } if blk.PrevCertificate() != nil { - err = blk.PrevCertificate().Encode(w) + err = blk.PrevCertificate().Encode(buf) if err != nil { panic(err) // Should we panic? } } - err = encoding.WriteVarInt(w, uint64(blk.Transactions().Len())) + err = encoding.WriteVarInt(buf, uint64(blk.Transactions().Len())) if err != nil { panic(err) // Should we panic? } for i, trx := range blk.Transactions() { - offset := w.Len() + offset := buf.Len() regs[i].height = height regs[i].offset = uint32(offset) @@ -84,18 +84,18 @@ func (bs *blockStore) saveBlock(batch *leveldb.Batch, height uint32, blk *block. } } - err := trx.Encode(w) + err := trx.Encode(buf) if err != nil { panic(err) // Should we panic? } - regs[i].length = uint32(w.Len() - offset) + regs[i].length = uint32(buf.Len() - offset) trx.SetPublicKey(pubKey) } blockKey := blockKey(height) blockHashKey := blockHashKey(blockHash) - batch.Put(blockKey, w.Bytes()) + batch.Put(blockKey, buf.Bytes()) batch.Put(blockHashKey, util.Uint32ToSlice(height)) sortitionSeed := blk.Header().SortitionSeed() diff --git a/store/config_test.go b/store/config_test.go index a25f2a03f..9d18e79cf 100644 --- a/store/config_test.go +++ b/store/config_test.go @@ -9,7 +9,7 @@ import ( ) func TestConfigBasicCheck(t *testing.T) { - testCases := []struct { + tests := []struct { name string expectedErr error updateFn func(c *Config) @@ -56,17 +56,17 @@ func TestConfigBasicCheck(t *testing.T) { }, } - for i, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { + for no, tt := range tests { + t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() - tc.updateFn(conf) - if tc.expectedErr != nil { + tt.updateFn(conf) + if tt.expectedErr != nil { err := conf.BasicCheck() - assert.ErrorIs(t, err, tc.expectedErr, - "Expected error not matched for test %d-%s, expected: %s, got: %s", i, tc.name, tc.expectedErr, err) + assert.ErrorIs(t, err, tt.expectedErr, + "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() - assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", i, tc.name, err) + assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } diff --git a/store/interface.go b/store/interface.go index 81edcd844..e643ee0b2 100644 --- a/store/interface.go +++ b/store/interface.go @@ -82,8 +82,8 @@ type Reader interface { BlockHeight(h hash.Hash) uint32 BlockHash(height uint32) hash.Hash SortitionSeed(blockHeight uint32) *sortition.VerifiableSeed - Transaction(id tx.ID) (*CommittedTx, error) - RecentTransaction(id tx.ID) bool + Transaction(txID tx.ID) (*CommittedTx, error) + RecentTransaction(txID tx.ID) bool PublicKey(addr crypto.Address) (crypto.PublicKey, error) HasAccount(crypto.Address) bool Account(addr crypto.Address) (*account.Account, error) diff --git a/store/mock.go b/store/mock.go index d9c7045b0..49057f803 100644 --- a/store/mock.go +++ b/store/mock.go @@ -96,17 +96,17 @@ func (m *MockStore) PublicKey(addr crypto.Address) (crypto.PublicKey, error) { return nil, ErrNotFound } -func (m *MockStore) Transaction(id tx.ID) (*CommittedTx, error) { +func (m *MockStore) Transaction(txID tx.ID) (*CommittedTx, error) { for height, blk := range m.Blocks { for _, trx := range blk.Transactions() { - if trx.ID() == id { - d, _ := trx.Bytes() + if trx.ID() == txID { + data, _ := trx.Bytes() return &CommittedTx{ - TxID: id, + TxID: txID, Height: height, BlockTime: blk.Header().UnixTime(), - Data: d, + Data: data, }, nil } } @@ -115,10 +115,10 @@ func (m *MockStore) Transaction(id tx.ID) (*CommittedTx, error) { return nil, fmt.Errorf("not found") } -func (m *MockStore) RecentTransaction(id tx.ID) bool { +func (m *MockStore) RecentTransaction(txID tx.ID) bool { for _, blk := range m.Blocks { for _, trx := range blk.Transactions() { - if trx.ID() == id { + if trx.ID() == txID { return true } } @@ -226,8 +226,8 @@ func (m *MockStore) IterateValidators(consumer func(*validator.Validator) (stop } } -func (m *MockStore) SaveBlock(b *block.Block, cert *certificate.BlockCertificate) { - m.Blocks[cert.Height()] = b +func (m *MockStore) SaveBlock(blk *block.Block, cert *certificate.BlockCertificate) { + m.Blocks[cert.Height()] = blk m.LastHeight = cert.Height() m.LastCert = cert } diff --git a/store/store.go b/store/store.go index bc6657f17..eac98f303 100644 --- a/store/store.go +++ b/store/store.go @@ -52,14 +52,14 @@ func tryGet(db *leveldb.DB, key []byte) ([]byte, error) { } func tryHas(db *leveldb.DB, key []byte) bool { - ok, err := db.Has(key, nil) + has, err := db.Has(key, nil) if err != nil { logger.Error("database `has` error", "error", err, "key", key) return false } - return ok + return has } type store struct { @@ -85,7 +85,7 @@ func NewStore(conf *Config) (Store, error) { if err != nil { return nil, err } - s := &store{ + store := &store{ config: conf, db: db, batch: new(leveldb.Batch), @@ -96,25 +96,25 @@ func NewStore(conf *Config) (Store, error) { isPruned: false, } - lc := s.lastCertificate() - if lc == nil { - return s, nil + lastCert := store.lastCertificate() + if lastCert == nil { + return store, nil } // Check if the node is pruned by checking genesis block. - cBlkOne, _ := s.block(1) + cBlkOne, _ := store.block(1) if cBlkOne == nil { - s.isPruned = true + store.isPruned = true } - currentHeight := lc.Height() + currentHeight := lastCert.Height() startHeight := uint32(1) if currentHeight > conf.TxCacheWindow { startHeight = currentHeight - conf.TxCacheWindow } - for i := startHeight; i < currentHeight+1; i++ { - cBlk, err := s.block(i) + for height := startHeight; height < currentHeight+1; height++ { + cBlk, err := store.block(height) if err != nil { return nil, err } @@ -125,14 +125,14 @@ func NewStore(conf *Config) (Store, error) { txs := blk.Transactions() for _, transaction := range txs { - s.txStore.addToCache(transaction.ID(), i) + store.txStore.addToCache(transaction.ID(), height) } sortitionSeed := blk.Header().SortitionSeed() - s.blockStore.addToCache(i, sortitionSeed) + store.blockStore.addToCache(height, sortitionSeed) } - return s, nil + return store, nil } func (s *store) Close() { @@ -171,17 +171,17 @@ func (s *store) SaveBlock(blk *block.Block, cert *certificate.BlockCertificate) } // Save last certificate: [version: 4 bytes]+[certificate: variant] - w := bytes.NewBuffer(make([]byte, 0, 4+cert.SerializeSize())) - err := encoding.WriteElements(w, lastStoreVersion) + buf := bytes.NewBuffer(make([]byte, 0, 4+cert.SerializeSize())) + err := encoding.WriteElements(buf, lastStoreVersion) if err != nil { panic(err) } - err = cert.Encode(w) + err = cert.Encode(buf) if err != nil { panic(err) } - s.batch.Put(lastInfoKey, w.Bytes()) + s.batch.Put(lastInfoKey, buf.Bytes()) } func (s *store) Block(height uint32) (*CommittedBlock, error) { @@ -245,11 +245,11 @@ func (s *store) PublicKey(addr crypto.Address) (crypto.PublicKey, error) { return s.blockStore.publicKey(addr) } -func (s *store) Transaction(id tx.ID) (*CommittedTx, error) { +func (s *store) Transaction(txID tx.ID) (*CommittedTx, error) { s.lk.Lock() defer s.lk.Unlock() - pos, err := s.txStore.tx(id) + pos, err := s.txStore.tx(txID) if err != nil { return nil, err } @@ -266,7 +266,7 @@ func (s *store) Transaction(id tx.ID) (*CommittedTx, error) { return &CommittedTx{ store: s, - TxID: id, + TxID: txID, Height: pos.height, BlockTime: blockTime, Data: data[start:end], @@ -277,11 +277,11 @@ func (s *store) Transaction(id tx.ID) (*CommittedTx, error) { // within the last 8640 blocks. // The time window for recent transactions is determined by the // TransactionToLive interval, which is part of the consensus parameters. -func (s *store) RecentTransaction(id tx.ID) bool { +func (s *store) RecentTransaction(txID tx.ID) bool { s.lk.Lock() defer s.lk.Unlock() - return s.txStore.recentTransaction(id) + return s.txStore.recentTransaction(txID) } func (s *store) HasAccount(addr crypto.Address) bool { @@ -381,14 +381,14 @@ func (s *store) lastCertificate() *certificate.BlockCertificate { // Genesis block return nil } - r := bytes.NewReader(data) + reader := bytes.NewReader(data) version := int32(0) cert := new(certificate.BlockCertificate) - err := encoding.ReadElements(r, &version) + err := encoding.ReadElements(reader, &version) if err != nil { return nil } - err = cert.Decode(r) + err = cert.Decode(reader) if err != nil { return nil } @@ -459,8 +459,8 @@ func (s *store) Prune(callback func(pruned bool, pruningHeight uint32) bool) err } pruningHeight := cert.Height() - retentionBlocks - for i := pruningHeight; i >= 1; i-- { - deleted, err := s.pruneBlock(i) + for height := pruningHeight; height >= 1; height-- { + deleted, err := s.pruneBlock(height) if err != nil { return err } @@ -469,7 +469,7 @@ func (s *store) Prune(callback func(pruned bool, pruningHeight uint32) bool) err return err } - if callback(deleted, i) { + if callback(deleted, height) { // canceled break } diff --git a/store/store_test.go b/store/store_test.go index 5c9effacc..8998f26a0 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -39,14 +39,14 @@ func setup(t *testing.T, config *Config) *testData { config = testConfig() } - s, err := NewStore(config) + storeInt, err := NewStore(config) require.NoError(t, err) - assert.False(t, s.IsPruned(), "empty store should not be in prune mode") - assert.Zero(t, s.PruningHeight(), "pruning height should be zero for an empty store") + assert.False(t, storeInt.IsPruned(), "empty store should not be in prune mode") + assert.Zero(t, storeInt.PruningHeight(), "pruning height should be zero for an empty store") td := &testData{ TestSuite: ts, - store: s.(*store), + store: storeInt.(*store), } // Save 10 blocks @@ -198,8 +198,8 @@ func TestStrippedPublicKey(t *testing.T) { {trx5, true}, // unknown public key and stripped } - for i, test := range tests { - trxs := block.Txs{test.trx} + for no, tt := range tests { + trxs := block.Txs{tt.trx} blockHeight := td.store.LastCertificate().Height() blk, cert := td.GenerateTestBlock(blockHeight+1, testsuite.BlockWithTransactions(trxs)) td.store.SaveBlock(blk, cert) @@ -209,26 +209,26 @@ func TestStrippedPublicKey(t *testing.T) { cBlk, err := td.store.Block(blockHeight + 1) require.NoError(t, err) - cTrx, err := td.store.Transaction(test.trx.ID()) + cTrx, err := td.store.Transaction(tt.trx.ID()) require.NoError(t, err) // - if test.failed { + if tt.failed { _, err := cBlk.ToBlock() assert.ErrorIs(t, err, PublicKeyNotFoundError{ - Address: test.trx.Payload().Signer(), - }, "test %d failed, expected error", i+1) + Address: tt.trx.Payload().Signer(), + }, "test %d failed, expected error", no+1) _, err = cTrx.ToTx() assert.ErrorIs(t, err, PublicKeyNotFoundError{ - Address: test.trx.Payload().Signer(), - }, "test %d failed, expected error", i+1) + Address: tt.trx.Payload().Signer(), + }, "test %d failed, expected error", no+1) } else { _, err := cBlk.ToBlock() - assert.NoError(t, err, "test %d failed, not expected error", i+1) + assert.NoError(t, err, "test %d failed, not expected error", no+1) _, err = cTrx.ToTx() - assert.NoError(t, err, "test %d failed, not expected error", i+1) + assert.NoError(t, err, "test %d failed, not expected error", no+1) } } } @@ -289,7 +289,7 @@ func TestPrune(t *testing.T) { totalPruned := uint32(0) lastPruningHeight := uint32(0) - cb := func(pruned bool, pruningHeight uint32) bool { + callback := func(pruned bool, pruningHeight uint32) bool { if pruned { totalPruned++ } @@ -303,7 +303,7 @@ func TestPrune(t *testing.T) { lastPruningHeight = uint32(0) // Store doesn't have blocks for one day - err := td.store.Prune(cb) + err := td.store.Prune(callback) assert.NoError(t, err) assert.Zero(t, totalPruned) @@ -325,7 +325,7 @@ func TestPrune(t *testing.T) { require.NoError(t, err) // It should remove blocks [1..8] - err = td.store.Prune(cb) + err = td.store.Prune(callback) assert.NoError(t, err) assert.Equal(t, uint32(8), totalPruned) @@ -363,7 +363,7 @@ func TestCancelPrune(t *testing.T) { td := setup(t, conf) hits := uint32(0) - cb := func(_ bool, _ uint32) bool { + callback := func(_ bool, _ uint32) bool { hits++ return true // Cancel pruning @@ -375,7 +375,7 @@ func TestCancelPrune(t *testing.T) { err := td.store.WriteBatch() require.NoError(t, err) - err = td.store.Prune(cb) + err = td.store.Prune(callback) assert.NoError(t, err) assert.Equal(t, uint32(1), hits) diff --git a/store/tx.go b/store/tx.go index 6f0bbb970..7316bb81d 100644 --- a/store/tx.go +++ b/store/tx.go @@ -16,7 +16,7 @@ type blockRegion struct { length uint32 } -func txKey(id tx.ID) []byte { return append(txPrefix, id.Bytes()...) } +func txKey(txID tx.ID) []byte { return append(txPrefix, txID.Bytes()...) } type txStore struct { db *leveldb.DB @@ -34,18 +34,18 @@ func newTxStore(db *leveldb.DB, txCacheWindow uint32) *txStore { func (ts *txStore) saveTxs(batch *leveldb.Batch, txs block.Txs, regs []blockRegion) { for i, trx := range txs { - w := bytes.NewBuffer(make([]byte, 0, 32+4)) + buf := bytes.NewBuffer(make([]byte, 0, 32+4)) reg := regs[i] - err := encoding.WriteElements(w, ®.height, ®.offset, ®.length) + err := encoding.WriteElements(buf, ®.height, ®.offset, ®.length) if err != nil { panic(err) } - id := trx.ID() - key := txKey(id) - batch.Put(key, w.Bytes()) - ts.addToCache(id, reg.height) + txID := trx.ID() + key := txKey(txID) + batch.Put(key, buf.Bytes()) + ts.addToCache(txID, reg.height) } } @@ -61,12 +61,12 @@ func (ts *txStore) pruneCache(currentHeight uint32) { } } -func (ts *txStore) recentTransaction(id tx.ID) bool { - return ts.txCache.Has(id) +func (ts *txStore) recentTransaction(txID tx.ID) bool { + return ts.txCache.Has(txID) } -func (ts *txStore) tx(id tx.ID) (*blockRegion, error) { - data, err := tryGet(ts.db, txKey(id)) +func (ts *txStore) tx(txID tx.ID) (*blockRegion, error) { + data, err := tryGet(ts.db, txKey(txID)) if err != nil { return nil, err } @@ -79,6 +79,6 @@ func (ts *txStore) tx(id tx.ID) (*blockRegion, error) { return reg, nil } -func (ts *txStore) addToCache(id tx.ID, height uint32) { - ts.txCache.PushBack(id, height) +func (ts *txStore) addToCache(txID tx.ID, height uint32) { + ts.txCache.PushBack(txID, height) } diff --git a/sync/bundle/bundle_test.go b/sync/bundle/bundle_test.go index b96002bd0..0f28f98d5 100644 --- a/sync/bundle/bundle_test.go +++ b/sync/bundle/bundle_test.go @@ -14,15 +14,15 @@ import ( ) func TestInvalidCBOR(t *testing.T) { - d1, _ := hex.DecodeString("00") - d2, _ := hex.DecodeString("A3") - d3, _ := hex.DecodeString("A3010002000340") - m := new(Bundle) - _, err := m.Decode(bytes.NewReader(d1)) + data1, _ := hex.DecodeString("00") + data2, _ := hex.DecodeString("A3") + data3, _ := hex.DecodeString("A3010002000340") + bdl := new(Bundle) + _, err := bdl.Decode(bytes.NewReader(data1)) assert.Error(t, err) - _, err = m.Decode(bytes.NewReader(d2)) + _, err = bdl.Decode(bytes.NewReader(data2)) assert.Error(t, err) - _, err = m.Decode(bytes.NewReader(d3)) + _, err = bdl.Decode(bytes.NewReader(data3)) assert.Error(t, err) } @@ -32,8 +32,8 @@ func TestMessageCompress(t *testing.T) { blocksData := [][]byte{} for i := 0; i < 10; i++ { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) - d, _ := blk.Bytes() - blocksData = append(blocksData, d) + data, _ := blk.Bytes() + blocksData = append(blocksData, data) } msg := message.NewBlocksResponseMessage(message.ResponseCodeOK, message.ResponseCodeOK.String(), 1234, 888, blocksData, nil) @@ -74,7 +74,7 @@ func TestDecodeVoteMessage(t *testing.T) { } func TestDecodeVoteCBOR(t *testing.T) { - d1, _ := hex.DecodeString( + dat1, _ := hex.DecodeString( "a3" + "0100" + // flags: 0 "0207" + // Type (vote) @@ -83,7 +83,7 @@ func TestDecodeVoteCBOR(t *testing.T) { "99943016d6a0f379cf09846c6f06f60758308ab7aecbe03c4ed5b688bcb7e848baffa62bcbf1a4021522c56693f0a7bbcc1f" + "e865277556ee59c1f63ba592acfe1b43" + "0401") // SequenceNo - d2, _ := hex.DecodeString( + data2, _ := hex.DecodeString( "a3" + "01190100" + // flags: 0x0100 (compressed) "0207" + // Type (vote) @@ -95,9 +95,9 @@ func TestDecodeVoteCBOR(t *testing.T) { bdl1 := new(Bundle) bdl2 := new(Bundle) - _, err := bdl1.Decode(bytes.NewReader(d1)) + _, err := bdl1.Decode(bytes.NewReader(dat1)) require.NoError(t, err) - _, err = bdl2.Decode(bytes.NewReader(d2)) + _, err = bdl2.Decode(bytes.NewReader(data2)) require.NoError(t, err) assert.NoError(t, bdl2.BasicCheck()) diff --git a/sync/bundle/message/block_announce_test.go b/sync/bundle/message/block_announce_test.go index 95756e727..22a70fab7 100644 --- a/sync/bundle/message/block_announce_test.go +++ b/sync/bundle/message/block_announce_test.go @@ -10,8 +10,8 @@ import ( ) func TestBlockAnnounceType(t *testing.T) { - m := &BlockAnnounceMessage{} - assert.Equal(t, TypeBlockAnnounce, m.Type()) + smg := &BlockAnnounceMessage{} + assert.Equal(t, TypeBlockAnnounce, smg.Type()) } func TestBlockAnnounceMessage(t *testing.T) { @@ -20,8 +20,8 @@ func TestBlockAnnounceMessage(t *testing.T) { t.Run("Invalid certificate", func(t *testing.T) { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) cert := certificate.NewBlockCertificate(0, 0) - m := NewBlockAnnounceMessage(blk, cert) - err := m.BasicCheck() + msg := NewBlockAnnounceMessage(blk, cert) + err := msg.BasicCheck() assert.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "height is not positive: 0", @@ -31,10 +31,10 @@ func TestBlockAnnounceMessage(t *testing.T) { t.Run("OK", func(t *testing.T) { height := ts.RandHeight() blk, cert := ts.GenerateTestBlock(height) - m := NewBlockAnnounceMessage(blk, cert) + msg := NewBlockAnnounceMessage(blk, cert) - assert.NoError(t, m.BasicCheck()) - assert.Equal(t, height, m.Height()) - assert.Contains(t, m.String(), fmt.Sprintf("%d", height)) + assert.NoError(t, msg.BasicCheck()) + assert.Equal(t, height, msg.Height()) + assert.Contains(t, msg.String(), fmt.Sprintf("%d", height)) }) } diff --git a/sync/bundle/message/blocks_request_test.go b/sync/bundle/message/blocks_request_test.go index 6b4a5cb4e..46589b6cb 100644 --- a/sync/bundle/message/blocks_request_test.go +++ b/sync/bundle/message/blocks_request_test.go @@ -7,29 +7,29 @@ import ( ) func TestLatestBlocksRequestType(t *testing.T) { - m := &BlocksRequestMessage{} - assert.Equal(t, TypeBlocksRequest, m.Type()) + msg := &BlocksRequestMessage{} + assert.Equal(t, TypeBlocksRequest, msg.Type()) } func TestBlocksRequestMessage(t *testing.T) { t.Run("Invalid height", func(t *testing.T) { - m := NewBlocksRequestMessage(1, 0, 0) + msg := NewBlocksRequestMessage(1, 0, 0) - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, BasicCheckError{Reason: "invalid height"}) }) t.Run("Invalid count", func(t *testing.T) { - m := NewBlocksRequestMessage(1, 200, 0) + msg := NewBlocksRequestMessage(1, 200, 0) - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, BasicCheckError{Reason: "count is zero"}) }) t.Run("OK", func(t *testing.T) { - m := NewBlocksRequestMessage(1, 100, 7) + msg := NewBlocksRequestMessage(1, 100, 7) - assert.NoError(t, m.BasicCheck()) - assert.Equal(t, uint32(106), m.To()) - assert.Contains(t, m.String(), "100") + assert.NoError(t, msg.BasicCheck()) + assert.Equal(t, uint32(106), msg.To()) + assert.Contains(t, msg.String(), "100") }) } diff --git a/sync/bundle/message/blocks_response_test.go b/sync/bundle/message/blocks_response_test.go index a1aa2ea7a..7317d1fef 100644 --- a/sync/bundle/message/blocks_response_test.go +++ b/sync/bundle/message/blocks_response_test.go @@ -9,8 +9,8 @@ import ( ) func TestLatestBlocksResponseType(t *testing.T) { - m := &BlocksResponseMessage{} - assert.Equal(t, TypeBlocksResponse, m.Type()) + msg := &BlocksResponseMessage{} + assert.Equal(t, TypeBlocksResponse, msg.Type()) } func TestBlocksResponseMessage(t *testing.T) { @@ -21,9 +21,9 @@ func TestBlocksResponseMessage(t *testing.T) { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) cert := certificate.NewBlockCertificate(0, 0) d, _ := blk.Bytes() - m := NewBlocksResponseMessage(ResponseCodeMoreBlocks, ResponseCodeMoreBlocks.String(), + msg := NewBlocksResponseMessage(ResponseCodeMoreBlocks, ResponseCodeMoreBlocks.String(), sid, ts.RandHeight(), [][]byte{d}, cert) - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "height is not positive: 0", @@ -36,12 +36,12 @@ func TestBlocksResponseMessage(t *testing.T) { blk2, cert2 := ts.GenerateTestBlock(height + 1) d1, _ := blk1.Bytes() d2, _ := blk2.Bytes() - m := NewBlocksResponseMessage(ResponseCodeMoreBlocks, ResponseCodeMoreBlocks.String(), + msg := NewBlocksResponseMessage(ResponseCodeMoreBlocks, ResponseCodeMoreBlocks.String(), sid, 100, [][]byte{d1, d2}, cert2) - assert.NoError(t, m.BasicCheck()) - assert.Contains(t, m.String(), "100") - assert.Equal(t, ResponseCodeMoreBlocks.String(), m.Reason) + assert.NoError(t, msg.BasicCheck()) + assert.Contains(t, msg.String(), "100") + assert.Equal(t, ResponseCodeMoreBlocks.String(), msg.Reason) }) } @@ -50,14 +50,14 @@ func TestLatestBlocksResponseCode(t *testing.T) { t.Run("rejected", func(t *testing.T) { reason := ts.RandString(16) - m := NewBlocksResponseMessage(ResponseCodeRejected, reason, 1, 0, nil, nil) - - assert.NoError(t, m.BasicCheck()) - assert.Zero(t, m.From) - assert.Zero(t, m.To()) - assert.Zero(t, m.Count()) - assert.True(t, m.IsRequestRejected()) - assert.Equal(t, reason, m.Reason) + msg := NewBlocksResponseMessage(ResponseCodeRejected, reason, 1, 0, nil, nil) + + assert.NoError(t, msg.BasicCheck()) + assert.Zero(t, msg.From) + assert.Zero(t, msg.To()) + assert.Zero(t, msg.Count()) + assert.True(t, msg.IsRequestRejected()) + assert.Equal(t, reason, msg.Reason) }) t.Run("OK - MoreBlocks", func(t *testing.T) { @@ -67,14 +67,14 @@ func TestLatestBlocksResponseCode(t *testing.T) { d1, _ := blk1.Bytes() d2, _ := blk2.Bytes() reason := ts.RandString(16) - m := NewBlocksResponseMessage(ResponseCodeMoreBlocks, reason, 1, 100, [][]byte{d1, d2}, nil) - - assert.NoError(t, m.BasicCheck()) - assert.Equal(t, uint32(100), m.From) - assert.Equal(t, uint32(101), m.To()) - assert.Equal(t, uint32(2), m.Count()) - assert.False(t, m.IsRequestRejected()) - assert.Equal(t, reason, m.Reason) + msg := NewBlocksResponseMessage(ResponseCodeMoreBlocks, reason, 1, 100, [][]byte{d1, d2}, nil) + + assert.NoError(t, msg.BasicCheck()) + assert.Equal(t, uint32(100), msg.From) + assert.Equal(t, uint32(101), msg.To()) + assert.Equal(t, uint32(2), msg.Count()) + assert.False(t, msg.IsRequestRejected()) + assert.Equal(t, reason, msg.Reason) }) t.Run("OK - Synced", func(t *testing.T) { @@ -82,13 +82,13 @@ func TestLatestBlocksResponseCode(t *testing.T) { _, cert := ts.GenerateTestBlock(height) reason := ts.RandString(16) - m := NewBlocksResponseMessage(ResponseCodeSynced, reason, 1, 100, nil, cert) - - assert.NoError(t, m.BasicCheck()) - assert.Equal(t, uint32(100), m.From) - assert.Zero(t, m.To()) - assert.Zero(t, m.Count()) - assert.False(t, m.IsRequestRejected()) - assert.Equal(t, reason, m.Reason) + msg := NewBlocksResponseMessage(ResponseCodeSynced, reason, 1, 100, nil, cert) + + assert.NoError(t, msg.BasicCheck()) + assert.Equal(t, uint32(100), msg.From) + assert.Zero(t, msg.To()) + assert.Zero(t, msg.Count()) + assert.False(t, msg.IsRequestRejected()) + assert.Equal(t, reason, msg.Reason) }) } diff --git a/sync/bundle/message/hello_ack_test.go b/sync/bundle/message/hello_ack_test.go index 0b3d54662..fb8f14038 100644 --- a/sync/bundle/message/hello_ack_test.go +++ b/sync/bundle/message/hello_ack_test.go @@ -7,11 +7,11 @@ import ( ) func TestHelloAckType(t *testing.T) { - m := &HelloAckMessage{} - assert.Equal(t, TypeHelloAck, m.Type()) + smg := &HelloAckMessage{} + assert.Equal(t, TypeHelloAck, smg.Type()) } func TestHelloAckMessage(t *testing.T) { - m := NewHelloAckMessage(ResponseCodeRejected, "rejected", 0) - assert.NoError(t, m.BasicCheck()) + msg := NewHelloAckMessage(ResponseCodeRejected, "rejected", 0) + assert.NoError(t, msg.BasicCheck()) } diff --git a/sync/bundle/message/hello_test.go b/sync/bundle/message/hello_test.go index c964ee68f..ddce4fba0 100644 --- a/sync/bundle/message/hello_test.go +++ b/sync/bundle/message/hello_test.go @@ -12,8 +12,8 @@ import ( ) func TestHelloType(t *testing.T) { - m := &HelloMessage{} - assert.Equal(t, TypeHello, m.Type()) + msg := &HelloMessage{} + assert.Equal(t, TypeHello, msg.Type()) } func TestHelloMessage(t *testing.T) { @@ -21,34 +21,34 @@ func TestHelloMessage(t *testing.T) { t.Run("Invalid signature", func(t *testing.T) { valKey := ts.RandValKey() - m := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), + msg := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) - m.Sign([]*bls.ValidatorKey{valKey}) - m.Signature = ts.RandBLSSignature() + msg.Sign([]*bls.ValidatorKey{valKey}) + msg.Signature = ts.RandBLSSignature() - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, crypto.ErrInvalidSignature) }) t.Run("Signature is nil", func(t *testing.T) { valKey := ts.RandValKey() - m := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), + msg := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) - m.Sign([]*bls.ValidatorKey{valKey}) - m.Signature = nil + msg.Sign([]*bls.ValidatorKey{valKey}) + msg.Signature = nil - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, BasicCheckError{"no signature"}) }) t.Run("PublicKeys are empty", func(t *testing.T) { valKey := ts.RandValKey() - m := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), + msg := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) - m.Sign([]*bls.ValidatorKey{valKey}) - m.PublicKeys = make([]*bls.PublicKey, 0) + msg.Sign([]*bls.ValidatorKey{valKey}) + msg.PublicKeys = make([]*bls.PublicKey, 0) - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, BasicCheckError{"no public key"}) }) @@ -56,21 +56,21 @@ func TestHelloMessage(t *testing.T) { time1 := time.Now() myTimeUnixMilli := time1.UnixMilli() - m := NewHelloMessage(ts.RandPeerID(), "Alice", service.New(service.FullNode), + msg := NewHelloMessage(ts.RandPeerID(), "Alice", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) - assert.LessOrEqual(t, m.MyTimeUnixMilli, time.Now().UnixMilli()) - assert.GreaterOrEqual(t, m.MyTimeUnixMilli, myTimeUnixMilli) + assert.LessOrEqual(t, msg.MyTimeUnixMilli, time.Now().UnixMilli()) + assert.GreaterOrEqual(t, msg.MyTimeUnixMilli, myTimeUnixMilli) }) t.Run("Ok", func(t *testing.T) { valKey := ts.RandValKey() - m := NewHelloMessage(ts.RandPeerID(), "Alice", service.New(service.FullNode), + msg := NewHelloMessage(ts.RandPeerID(), "Alice", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) - m.Sign([]*bls.ValidatorKey{valKey}) + msg.Sign([]*bls.ValidatorKey{valKey}) - assert.NoError(t, m.BasicCheck()) - assert.Contains(t, m.String(), "Alice") - assert.Contains(t, m.String(), "FULL") + assert.NoError(t, msg.BasicCheck()) + assert.Contains(t, msg.String(), "Alice") + assert.Contains(t, msg.String(), "FULL") }) } diff --git a/sync/bundle/message/message.go b/sync/bundle/message/message.go index 1db1e2bbd..05227890b 100644 --- a/sync/bundle/message/message.go +++ b/sync/bundle/message/message.go @@ -89,9 +89,9 @@ func (t Type) String() string { } } -func MakeMessage(t Type) (Message, error) { +func MakeMessage(msgType Type) (Message, error) { var msg Message - switch t { + switch msgType { case TypeHello: msg = &HelloMessage{} @@ -123,7 +123,7 @@ func MakeMessage(t Type) (Message, error) { msg = &BlocksResponseMessage{} default: - return nil, InvalidMessageTypeError{Type: int(t)} + return nil, InvalidMessageTypeError{Type: int(msgType)} } // diff --git a/sync/bundle/message/message_test.go b/sync/bundle/message/message_test.go index f4a80c725..f22072abf 100644 --- a/sync/bundle/message/message_test.go +++ b/sync/bundle/message/message_test.go @@ -9,7 +9,7 @@ import ( ) func TestMessage(t *testing.T) { - testCases := []struct { + tests := []struct { msgType Type typeName string topicID network.TopicID @@ -27,13 +27,13 @@ func TestMessage(t *testing.T) { {TypeBlocksResponse, "blocks-response", network.TopicIDUnspecified, false}, } - for _, tc := range testCases { - msg, err := MakeMessage(tc.msgType) + for _, tt := range tests { + msg, err := MakeMessage(tt.msgType) require.NoError(t, err) - assert.Equal(t, tc.typeName, msg.Type().String()) - assert.Equal(t, tc.topicID, msg.TopicID()) - assert.Equal(t, tc.shouldBroadcast, msg.ShouldBroadcast()) + assert.Equal(t, tt.typeName, msg.Type().String()) + assert.Equal(t, tt.topicID, msg.TopicID()) + assert.Equal(t, tt.shouldBroadcast, msg.ShouldBroadcast()) } } diff --git a/sync/bundle/message/proposal_test.go b/sync/bundle/message/proposal_test.go index 149bbcaef..338c8f87d 100644 --- a/sync/bundle/message/proposal_test.go +++ b/sync/bundle/message/proposal_test.go @@ -8,18 +8,18 @@ import ( ) func TestProposalType(t *testing.T) { - m := &ProposalMessage{} - assert.Equal(t, TypeProposal, m.Type()) + msg := &ProposalMessage{} + assert.Equal(t, TypeProposal, msg.Type()) } func TestProposalMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("OK", func(t *testing.T) { - prop, _ := ts.GenerateTestProposal(100, 0) - m := NewProposalMessage(prop) + prop := ts.GenerateTestProposal(100, 0) + msg := NewProposalMessage(prop) - assert.NoError(t, m.BasicCheck()) - assert.Contains(t, m.String(), "100") + assert.NoError(t, msg.BasicCheck()) + assert.Contains(t, msg.String(), "100") }) } diff --git a/sync/bundle/message/query_proposal_test.go b/sync/bundle/message/query_proposal_test.go index bfe2a451d..2424a517c 100644 --- a/sync/bundle/message/query_proposal_test.go +++ b/sync/bundle/message/query_proposal_test.go @@ -8,24 +8,24 @@ import ( ) func TestQueryProposalType(t *testing.T) { - m := &QueryProposalMessage{} - assert.Equal(t, TypeQueryProposal, m.Type()) + msg := &QueryProposalMessage{} + assert.Equal(t, TypeQueryProposal, msg.Type()) } func TestQueryProposalMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid round", func(t *testing.T) { - m := NewQueryProposalMessage(0, -1, ts.RandValAddress()) + msg := NewQueryProposalMessage(0, -1, ts.RandValAddress()) - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, BasicCheckError{"invalid round"}) }) t.Run("OK", func(t *testing.T) { - m := NewQueryProposalMessage(100, 0, ts.RandValAddress()) + msg := NewQueryProposalMessage(100, 0, ts.RandValAddress()) - assert.NoError(t, m.BasicCheck()) - assert.Contains(t, m.String(), "100") + assert.NoError(t, msg.BasicCheck()) + assert.Contains(t, msg.String(), "100") }) } diff --git a/sync/bundle/message/query_votes_test.go b/sync/bundle/message/query_votes_test.go index e7b520a98..cc8b6c0c3 100644 --- a/sync/bundle/message/query_votes_test.go +++ b/sync/bundle/message/query_votes_test.go @@ -8,24 +8,24 @@ import ( ) func TestQueryVotesType(t *testing.T) { - m := &QueryVoteMessage{} - assert.Equal(t, TypeQueryVote, m.Type()) + msg := &QueryVoteMessage{} + assert.Equal(t, TypeQueryVote, msg.Type()) } func TestQueryVoteMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid round", func(t *testing.T) { - m := NewQueryVoteMessage(0, -1, ts.RandValAddress()) + msg := NewQueryVoteMessage(0, -1, ts.RandValAddress()) - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, BasicCheckError{Reason: "invalid round"}) }) t.Run("OK", func(t *testing.T) { - m := NewQueryVoteMessage(100, 0, ts.RandValAddress()) + msg := NewQueryVoteMessage(100, 0, ts.RandValAddress()) - assert.NoError(t, m.BasicCheck()) - assert.Contains(t, m.String(), "100") + assert.NoError(t, msg.BasicCheck()) + assert.Contains(t, msg.String(), "100") }) } diff --git a/sync/bundle/message/transactions_test.go b/sync/bundle/message/transactions_test.go index 30ea9d82e..64100220e 100644 --- a/sync/bundle/message/transactions_test.go +++ b/sync/bundle/message/transactions_test.go @@ -9,25 +9,25 @@ import ( ) func TestTransactionsType(t *testing.T) { - m := &TransactionsMessage{} - assert.Equal(t, TypeTransaction, m.Type()) + msg := &TransactionsMessage{} + assert.Equal(t, TypeTransaction, msg.Type()) } func TestTransactionsMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("No transactions", func(t *testing.T) { - m := NewTransactionsMessage(nil) + msg := NewTransactionsMessage(nil) - err := m.BasicCheck() + err := msg.BasicCheck() assert.ErrorIs(t, err, BasicCheckError{Reason: "no transaction"}) }) t.Run("OK", func(t *testing.T) { trx := ts.GenerateTestTransferTx() - m := NewTransactionsMessage([]*tx.Tx{trx}) + msg := NewTransactionsMessage([]*tx.Tx{trx}) - assert.NoError(t, m.BasicCheck()) - assert.Contains(t, m.String(), trx.ID().ShortString()) + assert.NoError(t, msg.BasicCheck()) + assert.Contains(t, msg.String(), trx.ID().ShortString()) }) } diff --git a/sync/bundle/message/vote_test.go b/sync/bundle/message/vote_test.go index 5ed86c7e5..d7a49a1cb 100644 --- a/sync/bundle/message/vote_test.go +++ b/sync/bundle/message/vote_test.go @@ -9,25 +9,25 @@ import ( ) func TestVoteType(t *testing.T) { - m := &VoteMessage{} - assert.Equal(t, TypeVote, m.Type()) + msg := &VoteMessage{} + assert.Equal(t, TypeVote, msg.Type()) } func TestVoteMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid vote", func(t *testing.T) { - v := vote.NewPrepareVote(ts.RandHash(), ts.RandHeight(), -1, ts.RandValAddress()) - m := NewVoteMessage(v) + vte := vote.NewPrepareVote(ts.RandHash(), ts.RandHeight(), -1, ts.RandValAddress()) + msg := NewVoteMessage(vte) - assert.ErrorIs(t, m.BasicCheck(), vote.BasicCheckError{Reason: "invalid round"}) + assert.ErrorIs(t, msg.BasicCheck(), vote.BasicCheckError{Reason: "invalid round"}) }) t.Run("OK", func(t *testing.T) { - v, _ := ts.GenerateTestPrepareVote(100, 0) - m := NewVoteMessage(v) + vte, _ := ts.GenerateTestPrepareVote(100, 0) + msg := NewVoteMessage(vte) - assert.NoError(t, m.BasicCheck()) - assert.Contains(t, m.String(), v.String()) + assert.NoError(t, msg.BasicCheck()) + assert.Contains(t, msg.String(), vte.String()) }) } diff --git a/sync/cache/cache.go b/sync/cache/cache.go index 5216f862a..e05f16e63 100644 --- a/sync/cache/cache.go +++ b/sync/cache/cache.go @@ -13,19 +13,19 @@ type Cache struct { } func NewCache(size int) (*Cache, error) { - b, err := lru.New[uint32, *block.Block](size) + blockCache, err := lru.New[uint32, *block.Block](size) if err != nil { return nil, err } - c, err := lru.New[uint32, *certificate.BlockCertificate](size) + certCache, err := lru.New[uint32, *certificate.BlockCertificate](size) if err != nil { return nil, err } return &Cache{ - blocks: b, - certs: c, + blocks: blockCache, + certs: certCache, }, nil } diff --git a/sync/cache/cache_test.go b/sync/cache/cache_test.go index f167c2065..23e42299b 100644 --- a/sync/cache/cache_test.go +++ b/sync/cache/cache_test.go @@ -62,16 +62,16 @@ func TestCacheIsFull(t *testing.T) { cache, _ := NewCache(10) - i := int32(0) - for ; i < 10; i++ { - blk, _ := ts.GenerateTestBlock(uint32(i + 1)) + height := uint32(0) + for ; height < 10; height++ { + blk, _ := ts.GenerateTestBlock(height + 1) cache.AddBlock(blk) } - newBlock, _ := ts.GenerateTestBlock(uint32(i + 1)) + newBlock, _ := ts.GenerateTestBlock(height + 1) cache.AddBlock(newBlock) - assert.NotNil(t, cache.GetBlock(uint32(i+1))) + assert.NotNil(t, cache.GetBlock(height+1)) assert.Nil(t, cache.GetBlock(1)) } diff --git a/sync/firewall/firewall.go b/sync/firewall/firewall.go index 31fb27ac3..278fdbf55 100644 --- a/sync/firewall/firewall.go +++ b/sync/firewall/firewall.go @@ -31,7 +31,7 @@ type Firewall struct { logger *logger.SubLogger } -func NewFirewall(conf *Config, net network.Network, peerSet *peerset.PeerSet, st state.Facade, +func NewFirewall(conf *Config, network network.Network, peerSet *peerset.PeerSet, state state.Facade, log *logger.SubLogger, ) (*Firewall, error) { blocker, err := ipblocker.New(conf.BannedNets) @@ -45,9 +45,9 @@ func NewFirewall(conf *Config, net network.Network, peerSet *peerset.PeerSet, st return &Firewall{ config: conf, - network: net, + network: network, peerSet: peerSet, - state: st, + state: state, ipBlocker: blocker, blockRateLimit: blockRateLimit, transactionRateLimit: transactionRateLimit, @@ -110,23 +110,23 @@ func (f *Firewall) OpenStreamBundle(r io.Reader, from peer.ID) (*bundle.Bundle, func (f *Firewall) openBundle(r io.Reader, from peer.ID) (*bundle.Bundle, error) { f.peerSet.UpdateLastReceived(from) - p := f.peerSet.GetPeer(from) - if p.Status.IsBanned() { + peer := f.peerSet.GetPeer(from) + if peer.Status.IsBanned() { f.closeConnection(from) return nil, PeerBannedError{ - PeerID: p.PeerID, - Address: p.Address, + PeerID: peer.PeerID, + Address: peer.Address, } } - if f.IsBannedAddress(p.Address) { + if f.IsBannedAddress(peer.Address) { f.closeConnection(from) f.peerSet.UpdateStatus(from, status.StatusBanned) return nil, PeerBannedError{ - PeerID: p.PeerID, - Address: p.Address, + PeerID: peer.PeerID, + Address: peer.Address, } } diff --git a/sync/firewall/firewall_test.go b/sync/firewall/firewall_test.go index c5c95ae08..57998996b 100644 --- a/sync/firewall/firewall_test.go +++ b/sync/firewall/firewall_test.go @@ -38,14 +38,14 @@ func setup(t *testing.T, conf *Config) *testData { subLogger := logger.NewSubLogger("firewall", nil) peerSet := peerset.NewPeerSet(1 * time.Minute) - st := state.MockingState(ts) + state := state.MockingState(ts) net := network.MockingNetwork(ts, ts.RandPeerID()) if conf == nil { conf = DefaultConfig() } require.NoError(t, conf.BasicCheck()) - firewall, err := NewFirewall(conf, net, peerSet, st, subLogger) + firewall, err := NewFirewall(conf, net, peerSet, state, subLogger) if err != nil { return nil } @@ -66,7 +66,7 @@ func setup(t *testing.T, conf *Config) *testData { TestSuite: ts, firewall: firewall, network: net, - state: st, + state: state, bannedPeerID: bannedPeerID, goodPeerID: goodPeerID, unknownPeerID: unknownPeerID, @@ -92,7 +92,7 @@ func (td *testData) testStreamBundle() []byte { func TestDecodeBundles(t *testing.T) { td := setup(t, nil) - testCases := []struct { + tests := []struct { name string data string peerID string @@ -150,11 +150,11 @@ func TestDecodeBundles(t *testing.T) { }, } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - bs := td.DecodingHex(tc.data) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + bs := td.DecodingHex(tt.data) _, err := td.firewall.OpenGossipBundle(bs, td.unknownPeerID) - if tc.wantErr { + if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) @@ -281,7 +281,7 @@ func TestBannedAddress(t *testing.T) { } td := setup(t, conf) - testCases := []struct { + tests := []struct { addr string banned bool }{ @@ -303,22 +303,22 @@ func TestBannedAddress(t *testing.T) { }, } - for i, tc := range testCases { + for no, tt := range tests { peerID := td.RandPeerID() - td.firewall.peerSet.UpdateAddress(peerID, tc.addr, "inbound") + td.firewall.peerSet.UpdateAddress(peerID, tt.addr, "inbound") data := td.testGossipBundle() _, err := td.firewall.OpenGossipBundle(data, peerID) - if tc.banned { + if tt.banned { expectedErr := PeerBannedError{ PeerID: peerID, - Address: tc.addr, + Address: tt.addr, } assert.ErrorIs(t, err, expectedErr, - "test %v failed, addr %v should be banned", i, tc.addr) + "test %v failed, addr %v should be banned", no, tt.addr) } else { assert.NoError(t, err, - "test %v failed, addr %v should not be banned", i, tc.addr) + "test %v failed, addr %v should not be banned", no, tt.addr) } } } diff --git a/sync/handler_blocks_request.go b/sync/handler_blocks_request.go index 9e9450004..daf96c38f 100644 --- a/sync/handler_blocks_request.go +++ b/sync/handler_blocks_request.go @@ -23,8 +23,8 @@ func (handler *blocksRequestHandler) ParseMessage(m message.Message, pid peer.ID msg := m.(*message.BlocksRequestMessage) handler.logger.Trace("parsing BlocksRequest message", "msg", msg) - p := handler.peerSet.GetPeer(pid) - if p == nil { + peer := handler.peerSet.GetPeer(pid) + if peer == nil { response := message.NewBlocksResponseMessage(message.ResponseCodeRejected, fmt.Sprintf("unknown peer (%s)", pid.String()), msg.SessionID, 0, nil, nil) @@ -33,9 +33,9 @@ func (handler *blocksRequestHandler) ParseMessage(m message.Message, pid peer.ID return } - if !p.Status.IsKnown() { + if !peer.Status.IsKnown() { response := message.NewBlocksResponseMessage(message.ResponseCodeRejected, - fmt.Sprintf("not handshaked (%s)", p.Status.String()), msg.SessionID, 0, nil, nil) + fmt.Sprintf("not handshaked (%s)", peer.Status.String()), msg.SessionID, 0, nil, nil) handler.respond(response, pid) @@ -104,15 +104,15 @@ func (*blocksRequestHandler) PrepareBundle(m message.Message) *bundle.Bundle { return bundle.NewBundle(m) } -func (handler *blocksRequestHandler) respond(msg *message.BlocksResponseMessage, to peer.ID) { +func (handler *blocksRequestHandler) respond(msg *message.BlocksResponseMessage, pid peer.ID) { if msg.ResponseCode == message.ResponseCodeRejected { handler.logger.Debug("rejecting block request message", "msg", msg, - "to", to, "reason", msg.Reason) + "pid", pid, "reason", msg.Reason) - handler.sendTo(msg, to) + handler.sendTo(msg, pid) } else { - handler.logger.Info("responding block request message", "msg", msg, "to", to) + handler.logger.Info("responding block request message", "msg", msg, "pid", pid) - handler.sendTo(msg, to) + handler.sendTo(msg, pid) } } diff --git a/sync/handler_blocks_response_test.go b/sync/handler_blocks_response_test.go index 18ab66176..64babee45 100644 --- a/sync/handler_blocks_response_test.go +++ b/sync/handler_blocks_response_test.go @@ -34,12 +34,12 @@ func TestInvalidBlockData(t *testing.T) { {data: data}, } - for _, test := range tests { + for _, tt := range tests { pid := td.RandPeerID() sid := td.RandInt(1000) msg := message.NewBlocksResponseMessage(message.ResponseCodeMoreBlocks, message.ResponseCodeMoreBlocks.String(), - sid, lastHeight+1, [][]byte{test.data}, cert) + sid, lastHeight+1, [][]byte{tt.data}, cert) td.receivingNewMessage(td.sync, msg, pid) assert.Nil(t, td.sync.cache.GetBlock(msg.From)) @@ -109,15 +109,15 @@ func TestStrippedPublicKey(t *testing.T) { // Add a peer pid := td.addPeer(t, status.StatusKnown, service.New(service.None)) - for _, tc := range tests { - blkData, _ := tc.receivedBlock.Bytes() + for _, tt := range tests { + blkData, _ := tt.receivedBlock.Bytes() sid := td.RandInt(1000) cert := td.GenerateTestBlockCertificate(lastHeight + 1) msg := message.NewBlocksResponseMessage(message.ResponseCodeMoreBlocks, message.ResponseCodeMoreBlocks.String(), sid, lastHeight+1, [][]byte{blkData}, cert) td.receivingNewMessage(td.sync, msg, pid) - if tc.shouldFail { + if tt.shouldFail { assert.Nil(t, td.sync.cache.GetBlock(msg.From)) } else { assert.NotNil(t, td.sync.cache.GetBlock(msg.From)) @@ -244,13 +244,13 @@ func makeAliceAndBobNetworks(t *testing.T) *networkAliceBob { // TestIdenticalBundles tests if two different peers publish the same message, // whether the bundle data is also the same. func TestIdenticalBundles(t *testing.T) { - td := makeAliceAndBobNetworks(t) + nets := makeAliceAndBobNetworks(t) - blk, cert := td.GenerateTestBlock(td.RandHeight()) + blk, cert := nets.GenerateTestBlock(nets.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert) - bdlAlice := td.syncAlice.prepareBundle(msg) - bdlBob := td.syncBob.prepareBundle(msg) + bdlAlice := nets.syncAlice.prepareBundle(msg) + bdlBob := nets.syncBob.prepareBundle(msg) assert.Equal(t, bdlAlice, bdlBob) } @@ -259,100 +259,100 @@ func TestIdenticalBundles(t *testing.T) { // test nodes, Alice and Bob. In real-world scenarios, multiple nodes are typically // involved, but the procedure remains similar. func TestSyncing(t *testing.T) { - td := makeAliceAndBobNetworks(t) + nets := makeAliceAndBobNetworks(t) // Adding 100 blocks for Bob - blockInterval := td.syncBob.state.Genesis().Params().BlockInterval() - blockTime := td.syncBob.state.Genesis().GenesisTime() + blockInterval := nets.syncBob.state.Genesis().Params().BlockInterval() + blockTime := nets.syncBob.state.Genesis().GenesisTime() for i := uint32(0); i < 100; i++ { - blk, cert := td.GenerateTestBlock(i+1, testsuite.BlockWithTime(blockTime)) - assert.NoError(t, td.syncBob.state.CommitBlock(blk, cert)) + blk, cert := nets.GenerateTestBlock(i+1, testsuite.BlockWithTime(blockTime)) + assert.NoError(t, nets.syncBob.state.CommitBlock(blk, cert)) blockTime = blockTime.Add(blockInterval) } - assert.Equal(t, uint32(0), td.syncAlice.state.LastBlockHeight()) - assert.Equal(t, uint32(100), td.syncBob.state.LastBlockHeight()) + assert.Equal(t, uint32(0), nets.syncAlice.state.LastBlockHeight()) + assert.Equal(t, uint32(100), nets.syncBob.state.LastBlockHeight()) // Announcing a block - blk, cert := td.GenerateTestBlock(td.RandHeight()) + blk, cert := nets.GenerateTestBlock(nets.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert) - td.syncBob.broadcast(msg) - shouldPublishMessageWithThisType(t, td.networkBob, message.TypeBlockAnnounce) + nets.syncBob.broadcast(msg) + shouldPublishMessageWithThisType(t, nets.networkBob, message.TypeBlockAnnounce) // Perform block syncing - assert.Equal(t, uint32(11), td.syncAlice.config.BlockPerMessage) - assert.Equal(t, uint32(23), td.syncAlice.config.BlockPerSession) - - shouldNotPublishMessageWithThisType(t, td.networkBob, message.TypeBlocksRequest) - shouldPublishBlockRequest(t, td.networkAlice, 1) - shouldPublishBlockResponse(t, td.networkBob, 1, 11, message.ResponseCodeMoreBlocks) // 1-11 - shouldPublishBlockResponse(t, td.networkBob, 12, 11, message.ResponseCodeMoreBlocks) // 12-22 - shouldPublishBlockResponse(t, td.networkBob, 23, 1, message.ResponseCodeMoreBlocks) // 23-23 - shouldPublishBlockResponse(t, td.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock - - shouldPublishBlockRequest(t, td.networkAlice, 24) - shouldPublishBlockResponse(t, td.networkBob, 24, 11, message.ResponseCodeMoreBlocks) // 24-34 - shouldPublishBlockResponse(t, td.networkBob, 35, 11, message.ResponseCodeMoreBlocks) // 35-45 - shouldPublishBlockResponse(t, td.networkBob, 46, 1, message.ResponseCodeMoreBlocks) // 46-46 - shouldPublishBlockResponse(t, td.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock - - shouldPublishBlockRequest(t, td.networkAlice, 47) - shouldPublishBlockResponse(t, td.networkBob, 47, 11, message.ResponseCodeMoreBlocks) // 47-57 - shouldPublishBlockResponse(t, td.networkBob, 58, 11, message.ResponseCodeMoreBlocks) // 58-68 - shouldPublishBlockResponse(t, td.networkBob, 69, 1, message.ResponseCodeMoreBlocks) // 69-69 - shouldPublishBlockResponse(t, td.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock - - shouldPublishBlockRequest(t, td.networkAlice, 70) - shouldPublishBlockResponse(t, td.networkBob, 70, 11, message.ResponseCodeMoreBlocks) // 70-80 - shouldPublishBlockResponse(t, td.networkBob, 81, 11, message.ResponseCodeMoreBlocks) // 81-91 - shouldPublishBlockResponse(t, td.networkBob, 92, 1, message.ResponseCodeMoreBlocks) // 92-92 - shouldPublishBlockResponse(t, td.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock + assert.Equal(t, uint32(11), nets.syncAlice.config.BlockPerMessage) + assert.Equal(t, uint32(23), nets.syncAlice.config.BlockPerSession) + + shouldNotPublishMessageWithThisType(t, nets.networkBob, message.TypeBlocksRequest) + shouldPublishBlockRequest(t, nets.networkAlice, 1) + shouldPublishBlockResponse(t, nets.networkBob, 1, 11, message.ResponseCodeMoreBlocks) // 1-11 + shouldPublishBlockResponse(t, nets.networkBob, 12, 11, message.ResponseCodeMoreBlocks) // 12-22 + shouldPublishBlockResponse(t, nets.networkBob, 23, 1, message.ResponseCodeMoreBlocks) // 23-23 + shouldPublishBlockResponse(t, nets.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock + + shouldPublishBlockRequest(t, nets.networkAlice, 24) + shouldPublishBlockResponse(t, nets.networkBob, 24, 11, message.ResponseCodeMoreBlocks) // 24-34 + shouldPublishBlockResponse(t, nets.networkBob, 35, 11, message.ResponseCodeMoreBlocks) // 35-45 + shouldPublishBlockResponse(t, nets.networkBob, 46, 1, message.ResponseCodeMoreBlocks) // 46-46 + shouldPublishBlockResponse(t, nets.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock + + shouldPublishBlockRequest(t, nets.networkAlice, 47) + shouldPublishBlockResponse(t, nets.networkBob, 47, 11, message.ResponseCodeMoreBlocks) // 47-57 + shouldPublishBlockResponse(t, nets.networkBob, 58, 11, message.ResponseCodeMoreBlocks) // 58-68 + shouldPublishBlockResponse(t, nets.networkBob, 69, 1, message.ResponseCodeMoreBlocks) // 69-69 + shouldPublishBlockResponse(t, nets.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock + + shouldPublishBlockRequest(t, nets.networkAlice, 70) + shouldPublishBlockResponse(t, nets.networkBob, 70, 11, message.ResponseCodeMoreBlocks) // 70-80 + shouldPublishBlockResponse(t, nets.networkBob, 81, 11, message.ResponseCodeMoreBlocks) // 81-91 + shouldPublishBlockResponse(t, nets.networkBob, 92, 1, message.ResponseCodeMoreBlocks) // 92-92 + shouldPublishBlockResponse(t, nets.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock // Last block requests - shouldPublishBlockRequest(t, td.networkAlice, 93) // 93-116 - shouldPublishBlockResponse(t, td.networkBob, 93, 8, message.ResponseCodeMoreBlocks) // 93-100 - shouldPublishBlockResponse(t, td.networkBob, 100, 0, message.ResponseCodeSynced) // Synced + shouldPublishBlockRequest(t, nets.networkAlice, 93) // 93-116 + shouldPublishBlockResponse(t, nets.networkBob, 93, 8, message.ResponseCodeMoreBlocks) // 93-100 + shouldPublishBlockResponse(t, nets.networkBob, 100, 0, message.ResponseCodeSynced) // Synced assert.Eventually(t, func() bool { - return td.syncAlice.state.LastBlockHeight() == uint32(100) + return nets.syncAlice.state.LastBlockHeight() == uint32(100) }, 10*time.Second, 1*time.Second) } func TestSyncingHasBlockInCache(t *testing.T) { - td := makeAliceAndBobNetworks(t) + nets := makeAliceAndBobNetworks(t) // Adding 100 blocks for Bob - blockInterval := td.syncBob.state.Genesis().Params().BlockInterval() - blockTime := td.syncBob.state.Genesis().GenesisTime() + blockInterval := nets.syncBob.state.Genesis().Params().BlockInterval() + blockTime := nets.syncBob.state.Genesis().GenesisTime() for i := uint32(0); i < 23; i++ { - blk, cert := td.GenerateTestBlock(i+1, testsuite.BlockWithTime(blockTime)) - assert.NoError(t, td.syncBob.state.CommitBlock(blk, cert)) + blk, cert := nets.GenerateTestBlock(i+1, testsuite.BlockWithTime(blockTime)) + assert.NoError(t, nets.syncBob.state.CommitBlock(blk, cert)) blockTime = blockTime.Add(blockInterval) } - assert.Equal(t, uint32(0), td.syncAlice.state.LastBlockHeight()) - assert.Equal(t, uint32(23), td.syncBob.state.LastBlockHeight()) + assert.Equal(t, uint32(0), nets.syncAlice.state.LastBlockHeight()) + assert.Equal(t, uint32(23), nets.syncBob.state.LastBlockHeight()) // Adding some blocs to the cache - blk1 := td.stateBob.TestStore.Blocks[1] - blk2 := td.stateBob.TestStore.Blocks[2] - blk3 := td.stateBob.TestStore.Blocks[3] - td.syncAlice.cache.AddBlock(blk1) - td.syncAlice.cache.AddBlock(blk2) - td.syncAlice.cache.AddBlock(blk3) + blk1 := nets.stateBob.TestStore.Blocks[1] + blk2 := nets.stateBob.TestStore.Blocks[2] + blk3 := nets.stateBob.TestStore.Blocks[3] + nets.syncAlice.cache.AddBlock(blk1) + nets.syncAlice.cache.AddBlock(blk2) + nets.syncAlice.cache.AddBlock(blk3) // Announcing a block - blk, cert := td.GenerateTestBlock(td.RandHeight()) + blk, cert := nets.GenerateTestBlock(nets.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert) - td.syncBob.broadcast(msg) - shouldPublishMessageWithThisType(t, td.networkBob, message.TypeBlockAnnounce) + nets.syncBob.broadcast(msg) + shouldPublishMessageWithThisType(t, nets.networkBob, message.TypeBlockAnnounce) - shouldNotPublishMessageWithThisType(t, td.networkBob, message.TypeBlocksRequest) + shouldNotPublishMessageWithThisType(t, nets.networkBob, message.TypeBlocksRequest) // blocks 1-2 are inside the cache - shouldPublishBlockRequest(t, td.networkAlice, 4) - shouldPublishBlockResponse(t, td.networkBob, 4, 11, message.ResponseCodeMoreBlocks) // 4-14 - shouldPublishBlockResponse(t, td.networkBob, 15, 9, message.ResponseCodeMoreBlocks) // 15-23 - shouldPublishBlockResponse(t, td.networkBob, 23, 0, message.ResponseCodeSynced) // Synced + shouldPublishBlockRequest(t, nets.networkAlice, 4) + shouldPublishBlockResponse(t, nets.networkBob, 4, 11, message.ResponseCodeMoreBlocks) // 4-14 + shouldPublishBlockResponse(t, nets.networkBob, 15, 9, message.ResponseCodeMoreBlocks) // 15-23 + shouldPublishBlockResponse(t, nets.networkBob, 23, 0, message.ResponseCodeSynced) // Synced } diff --git a/sync/handler_hello.go b/sync/handler_hello.go index 11568cb37..f1d9a9684 100644 --- a/sync/handler_hello.go +++ b/sync/handler_hello.go @@ -91,17 +91,17 @@ func (*helloHandler) PrepareBundle(m message.Message) *bundle.Bundle { return bdl } -func (handler *helloHandler) acknowledge(msg *message.HelloAckMessage, to peer.ID) { +func (handler *helloHandler) acknowledge(msg *message.HelloAckMessage, pid peer.ID) { if msg.ResponseCode == message.ResponseCodeRejected { handler.logger.Info("rejecting hello message", "msg", msg, - "to", to, "reason", msg.Reason) + "pid", pid, "reason", msg.Reason) - handler.sendTo(msg, to) - handler.peerSet.UpdateStatus(to, status.StatusBanned) + handler.sendTo(msg, pid) + handler.peerSet.UpdateStatus(pid, status.StatusBanned) } else { handler.logger.Info("acknowledging hello message", "msg", msg, - "to", to) + "pid", pid) - handler.sendTo(msg, to) + handler.sendTo(msg, pid) } } diff --git a/sync/handler_hello_test.go b/sync/handler_hello_test.go index 841f1c66e..13ec27c0b 100644 --- a/sync/handler_hello_test.go +++ b/sync/handler_hello_test.go @@ -129,16 +129,16 @@ func TestParsingHelloMessages(t *testing.T) { assert.Equal(t, message.ResponseCodeOK, bdl.Message.(*message.HelloAckMessage).ResponseCode) // Check if the peer info is updated - p := td.sync.peerSet.GetPeer(pid) + peer := td.sync.peerSet.GetPeer(pid) pub := valKey.PublicKey() - assert.Equal(t, status.StatusConnected, p.Status) - assert.Equal(t, version.NodeAgent.String(), p.Agent) - assert.Equal(t, "kitty", p.Moniker) - assert.Contains(t, p.ConsensusKeys, pub) - assert.Equal(t, pid, p.PeerID) - assert.Equal(t, peerHeight, p.Height) - assert.True(t, p.IsFullNode()) + assert.Equal(t, status.StatusConnected, peer.Status) + assert.Equal(t, version.NodeAgent.String(), peer.Agent) + assert.Equal(t, "kitty", peer.Moniker) + assert.Contains(t, peer.ConsensusKeys, pub) + assert.Equal(t, pid, peer.PeerID) + assert.Equal(t, peerHeight, peer.Height) + assert.True(t, peer.IsFullNode()) }) } diff --git a/sync/handler_proposal_test.go b/sync/handler_proposal_test.go index fa06f6f43..55c93f6bd 100644 --- a/sync/handler_proposal_test.go +++ b/sync/handler_proposal_test.go @@ -12,7 +12,7 @@ func TestParsingProposalMessages(t *testing.T) { t.Run("Parsing proposal message", func(t *testing.T) { consensusHeight := td.state.LastBlockHeight() + 1 - prop, _ := td.GenerateTestProposal(consensusHeight, 0) + prop := td.GenerateTestProposal(consensusHeight, 0) msg := message.NewProposalMessage(prop) pid := td.RandPeerID() diff --git a/sync/handler_query_proposal_test.go b/sync/handler_query_proposal_test.go index 1b900e738..ade4101ac 100644 --- a/sync/handler_query_proposal_test.go +++ b/sync/handler_query_proposal_test.go @@ -21,7 +21,7 @@ func TestParsingQueryProposalMessages(t *testing.T) { }) t.Run("should respond to the query proposal message", func(t *testing.T) { - prop, _ := td.GenerateTestProposal(consHeight, 0) + prop := td.GenerateTestProposal(consHeight, 0) pid := td.RandPeerID() td.consMgr.SetProposal(prop) msg := message.NewQueryProposalMessage(consHeight, consRound, td.RandValAddress()) diff --git a/sync/handler_query_votes_test.go b/sync/handler_query_votes_test.go index 731dc3c92..d79c8ad6e 100644 --- a/sync/handler_query_votes_test.go +++ b/sync/handler_query_votes_test.go @@ -20,14 +20,14 @@ func TestParsingQueryVoteMessages(t *testing.T) { }) t.Run("should respond to the query votes message", func(t *testing.T) { - v1, _ := td.GenerateTestPrecommitVote(consHeight, consRound) - td.consMgr.AddVote(v1) + vote, _ := td.GenerateTestPrecommitVote(consHeight, consRound) + td.consMgr.AddVote(vote) pid := td.RandPeerID() msg := message.NewQueryVoteMessage(consHeight, consRound, td.RandValAddress()) td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeVote) - assert.Equal(t, v1.Hash(), bdl.Message.(*message.VoteMessage).Vote.Hash()) + assert.Equal(t, vote.Hash(), bdl.Message.(*message.VoteMessage).Vote.Hash()) }) } diff --git a/sync/mock.go b/sync/mock.go index 542fb182a..df84cf3b8 100644 --- a/sync/mock.go +++ b/sync/mock.go @@ -20,32 +20,32 @@ type MockSync struct { } func MockingSync(ts *testsuite.TestSuite) *MockSync { - ps := peerset.NewPeerSet(1 * time.Second) + peerSet := peerset.NewPeerSet(1 * time.Second) pub1, _ := ts.RandBLSKeyPair() pub2, _ := ts.RandBLSKeyPair() pid1 := ts.RandPeerID() pid2 := ts.RandPeerID() - ps.UpdateInfo( + peerSet.UpdateInfo( pid1, "test-peer-1", version.NodeAgent.String(), []*bls.PublicKey{pub1}, service.New(service.FullNode)) - ps.UpdateHeight(pid1, ts.RandHeight(), ts.RandHash()) + peerSet.UpdateHeight(pid1, ts.RandHeight(), ts.RandHash()) - ps.UpdateInfo( + peerSet.UpdateInfo( pid2, "test-peer-2", version.NodeAgent.String(), []*bls.PublicKey{pub2}, service.New(service.None)) - ps.UpdateHeight(pid1, ts.RandHeight(), ts.RandHash()) + peerSet.UpdateHeight(pid1, ts.RandHeight(), ts.RandHash()) services := service.New() return &MockSync{ TestID: ts.RandPeerID(), - TestPeerSet: ps, + TestPeerSet: peerSet, TestServices: services, } } diff --git a/sync/peerset/peer/peer_test.go b/sync/peerset/peer/peer_test.go index 57eadba25..afd802399 100644 --- a/sync/peerset/peer/peer_test.go +++ b/sync/peerset/peer/peer_test.go @@ -9,7 +9,7 @@ import ( ) func TestPeerStatus(t *testing.T) { - testCases := []struct { + tests := []struct { status status.Status isDisconnected bool isBanned bool @@ -23,15 +23,15 @@ func TestPeerStatus(t *testing.T) { {status: status.StatusKnown, isKnown: true, isKnownOrConnected: true}, } - for _, testCase := range testCases { - p := NewPeer("test") - p.Status = testCase.status + for _, tt := range tests { + peer := NewPeer("test") + peer.Status = tt.status - assert.Equal(t, testCase.isDisconnected, p.Status.IsDisconnected()) - assert.Equal(t, testCase.isBanned, p.Status.IsBanned()) - assert.Equal(t, testCase.isConnected, p.Status.IsConnected()) - assert.Equal(t, testCase.isKnown, p.Status.IsKnown()) - assert.Equal(t, testCase.isKnownOrConnected, p.Status.IsConnectedOrKnown()) + assert.Equal(t, tt.isDisconnected, peer.Status.IsDisconnected()) + assert.Equal(t, tt.isBanned, peer.Status.IsBanned()) + assert.Equal(t, tt.isConnected, peer.Status.IsConnected()) + assert.Equal(t, tt.isKnown, peer.Status.IsKnown()) + assert.Equal(t, tt.isKnownOrConnected, peer.Status.IsConnectedOrKnown()) } } @@ -46,7 +46,7 @@ func TestIsFullNode(t *testing.T) { } func TestDownloadScore(t *testing.T) { - testCases := []struct { + tests := []struct { totalSession int completedSession int expectedScore int @@ -61,14 +61,14 @@ func TestDownloadScore(t *testing.T) { {7, 6, 87}, } - for i, testCase := range testCases { - p := NewPeer("test") - p.TotalSessions = testCase.totalSession - p.CompletedSessions = testCase.completedSession + for no, tt := range tests { + peer := NewPeer("test") + peer.TotalSessions = tt.totalSession + peer.CompletedSessions = tt.completedSession - score := p.DownloadScore() - assert.Equal(t, testCase.expectedScore, score, + score := peer.DownloadScore() + assert.Equal(t, tt.expectedScore, score, "Test %v failed. expected score %d, got %d", - i+1, testCase.expectedScore, score) + no+1, tt.expectedScore, score) } } diff --git a/sync/peerset/peer/service/services_test.go b/sync/peerset/peer/service/services_test.go index 1b41f1e6b..c5a7dc3a0 100644 --- a/sync/peerset/peer/service/services_test.go +++ b/sync/peerset/peer/service/services_test.go @@ -16,11 +16,11 @@ func TestServicesString(t *testing.T) { } func TestAppend(t *testing.T) { - s := New(FullNode) - assert.True(t, s.IsFullNode()) - assert.False(t, s.IsPrunedNode()) + services := New(FullNode) + assert.True(t, services.IsFullNode()) + assert.False(t, services.IsPrunedNode()) - s.Append(PrunedNode) - assert.True(t, s.IsFullNode()) - assert.True(t, s.IsPrunedNode()) + services.Append(PrunedNode) + assert.True(t, services.IsFullNode()) + assert.True(t, services.IsPrunedNode()) } diff --git a/sync/peerset/peer_set.go b/sync/peerset/peer_set.go index da538d8aa..f4181f7d8 100644 --- a/sync/peerset/peer_set.go +++ b/sync/peerset/peer_set.go @@ -163,13 +163,13 @@ func (ps *PeerSet) findPeer(pid peer.ID) *peer.Peer { // FindOrCreatePeer tries to find a peer with the given pid. // If not found, it creates a new peer and assigns the pid to it. func (ps *PeerSet) findOrCreatePeer(pid peer.ID) *peer.Peer { - p := ps.findPeer(pid) - if p == nil { - p = peer.NewPeer(pid) - ps.peers[pid] = p + per := ps.findPeer(pid) + if per == nil { + per = peer.NewPeer(pid) + ps.peers[pid] = per } - return p + return per } func (ps *PeerSet) UpdateInfo( @@ -207,7 +207,7 @@ func (ps *PeerSet) UpdateAddress(pid peer.ID, addr, direction string) { p.Direction = direction } -func (ps *PeerSet) UpdateStatus(pid peer.ID, s status.Status) { +func (ps *PeerSet) UpdateStatus(pid peer.ID, status status.Status) { ps.lk.Lock() defer ps.lk.Unlock() @@ -215,11 +215,11 @@ func (ps *PeerSet) UpdateStatus(pid peer.ID, s status.Status) { if !p.Status.IsBanned() || // Don't update the status if peer is banned // Don't change status to connected if peer is known already - !(p.Status.IsKnown() && s.IsConnected()) { - p.Status = s + !(p.Status.IsKnown() && status.IsConnected()) { + p.Status = status } - if s.IsDisconnected() { + if status.IsDisconnected() { for _, ssn := range ps.sessionManager.Sessions() { if ssn.PeerID == pid { ssn.Status = session.Uncompleted @@ -338,15 +338,15 @@ func (ps *PeerSet) GetRandomPeer() *peer.Peer { // totalScore := 0 peers := make([]scoredPeer, 0, len(ps.peers)) - for _, p := range ps.peers { - if !p.Status.IsConnectedOrKnown() { + for _, peer := range ps.peers { + if !peer.Status.IsConnectedOrKnown() { continue } - score := p.DownloadScore() + score := peer.DownloadScore() totalScore += score peers = append(peers, scoredPeer{ - peer: p, + peer: peer, score: score, }) } diff --git a/sync/peerset/peer_set_test.go b/sync/peerset/peer_set_test.go index 3b3917296..66515f547 100644 --- a/sync/peerset/peer_set_test.go +++ b/sync/peerset/peer_set_test.go @@ -96,12 +96,12 @@ func TestPeerSet(t *testing.T) { assert.Equal(t, int64(150), peer1.Metric.MessageReceived[message.TypeTransaction].Bytes) assert.Equal(t, int64(250), peer1.Metric.MessageSent[message.TypeBlocksRequest].Bytes) - peersetMetric := peerSet.Metric() - assert.Equal(t, int64(250), peersetMetric.TotalReceived.Bytes) - assert.Equal(t, int64(100), peersetMetric.MessageReceived[message.TypeBlocksResponse].Bytes) - assert.Equal(t, int64(150), peersetMetric.MessageReceived[message.TypeTransaction].Bytes) - assert.Equal(t, int64(450), peersetMetric.TotalSent.Bytes) - assert.Equal(t, int64(450), peersetMetric.MessageSent[message.TypeBlocksRequest].Bytes) + peerSetMetric := peerSet.Metric() + assert.Equal(t, int64(250), peerSetMetric.TotalReceived.Bytes) + assert.Equal(t, int64(100), peerSetMetric.MessageReceived[message.TypeBlocksResponse].Bytes) + assert.Equal(t, int64(150), peerSetMetric.MessageReceived[message.TypeTransaction].Bytes) + assert.Equal(t, int64(450), peerSetMetric.TotalSent.Bytes) + assert.Equal(t, int64(450), peerSetMetric.MessageSent[message.TypeBlocksRequest].Bytes) assert.Equal(t, 2, peerSet.TotalSentBundles()) }) @@ -156,15 +156,15 @@ func TestPeerSet(t *testing.T) { func TestOpenSession(t *testing.T) { ts := testsuite.NewTestSuite(t) - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) pid1 := ts.RandPeerID() pid2 := ts.RandPeerID() - sid1 := ps.OpenSession(pid1, 100, 10) - sid2 := ps.OpenSession(pid2, 110, 10) + sid1 := peerSet.OpenSession(pid1, 100, 10) + sid2 := peerSet.OpenSession(pid2, 110, 10) - ssn1 := getSessionByID(ps, sid1) - ssn2 := getSessionByID(ps, sid1) + ssn1 := getSessionByID(peerSet, sid1) + ssn2 := getSessionByID(peerSet, sid1) assert.NotNil(t, ssn1) assert.Equal(t, uint32(100), ssn1.From) assert.Equal(t, uint32(100), ssn2.From) @@ -175,88 +175,88 @@ func TestOpenSession(t *testing.T) { assert.LessOrEqual(t, ssn1.LastActivity, time.Now()) assert.Equal(t, 0, sid1) assert.Equal(t, 1, sid2) - assert.True(t, ps.HasOpenSession(pid1)) - assert.True(t, ps.HasOpenSession(pid2)) - assert.False(t, ps.HasOpenSession(ts.RandPeerID())) - assert.Equal(t, 2, ps.NumberOfSessions()) + assert.True(t, peerSet.HasOpenSession(pid1)) + assert.True(t, peerSet.HasOpenSession(pid2)) + assert.False(t, peerSet.HasOpenSession(ts.RandPeerID())) + assert.Equal(t, 2, peerSet.NumberOfSessions()) } func TestNumberOfSessions(t *testing.T) { - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) // Test when there are no open sessions - assert.Equal(t, 0, ps.NumberOfSessions()) + assert.Equal(t, 0, peerSet.NumberOfSessions()) // Test when there are multiple open sessions - ps.OpenSession("peer1", 100, 101) - ps.OpenSession("peer2", 200, 201) - ps.OpenSession("peer3", 300, 301) + peerSet.OpenSession("peer1", 100, 101) + peerSet.OpenSession("peer2", 200, 201) + peerSet.OpenSession("peer3", 300, 301) - assert.Equal(t, 3, ps.NumberOfSessions()) + assert.Equal(t, 3, peerSet.NumberOfSessions()) } func TestHasAnyOpenSession(t *testing.T) { - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) // Test when there are no open sessions - assert.False(t, ps.HasAnyOpenSession()) + assert.False(t, peerSet.HasAnyOpenSession()) - sid := ps.OpenSession("peer1", 100, 101) - assert.True(t, ps.HasAnyOpenSession()) + sid := peerSet.OpenSession("peer1", 100, 101) + assert.True(t, peerSet.HasAnyOpenSession()) - ps.SetSessionCompleted(sid) - assert.False(t, ps.HasAnyOpenSession()) + peerSet.SetSessionCompleted(sid) + assert.False(t, peerSet.HasAnyOpenSession()) } func TestRemoveAllSessions(t *testing.T) { - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) - _ = ps.OpenSession("peer1", 100, 101) - _ = ps.OpenSession("peer2", 100, 101) - _ = ps.OpenSession("peer3", 100, 101) + _ = peerSet.OpenSession("peer1", 100, 101) + _ = peerSet.OpenSession("peer2", 100, 101) + _ = peerSet.OpenSession("peer3", 100, 101) - ps.RemoveAllSessions() - assert.Zero(t, ps.NumberOfSessions()) - assert.False(t, ps.HasAnyOpenSession()) + peerSet.RemoveAllSessions() + assert.Zero(t, peerSet.NumberOfSessions()) + assert.False(t, peerSet.HasAnyOpenSession()) } func TestCompletedSession(t *testing.T) { - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) - sid := ps.OpenSession("peer1", 100, 101) - ssn := getSessionByID(ps, sid) + sid := peerSet.OpenSession("peer1", 100, 101) + ssn := getSessionByID(peerSet, sid) assert.Equal(t, session.Open, ssn.Status) - ps.SetSessionCompleted(sid) - assert.Equal(t, 1, ps.NumberOfSessions()) - assert.False(t, ps.HasAnyOpenSession()) + peerSet.SetSessionCompleted(sid) + assert.Equal(t, 1, peerSet.NumberOfSessions()) + assert.False(t, peerSet.HasAnyOpenSession()) assert.Equal(t, session.Completed, ssn.Status) } func TestUncompletedSession(t *testing.T) { - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) - sid := ps.OpenSession("peer1", 100, 101) - ssn := getSessionByID(ps, sid) + sid := peerSet.OpenSession("peer1", 100, 101) + ssn := getSessionByID(peerSet, sid) assert.Equal(t, session.Open, ssn.Status) - ps.SetSessionUncompleted(sid) - assert.Equal(t, 1, ps.NumberOfSessions()) - assert.False(t, ps.HasAnyOpenSession()) + peerSet.SetSessionUncompleted(sid) + assert.Equal(t, 1, peerSet.NumberOfSessions()) + assert.False(t, peerSet.HasAnyOpenSession()) assert.Equal(t, session.Uncompleted, ssn.Status) } func TestExpireSessions(t *testing.T) { timeout := 100 * time.Millisecond - ps := NewPeerSet(timeout) + peerSet := NewPeerSet(timeout) - sid := ps.OpenSession("peer1", 100, 101) - ssn := getSessionByID(ps, sid) + sid := peerSet.OpenSession("peer1", 100, 101) + ssn := getSessionByID(peerSet, sid) time.Sleep(timeout) - ps.SetExpiredSessionsAsUncompleted() - assert.Equal(t, 1, ps.NumberOfSessions()) - assert.False(t, ps.HasAnyOpenSession()) + peerSet.SetExpiredSessionsAsUncompleted() + assert.Equal(t, 1, peerSet.NumberOfSessions()) + assert.False(t, peerSet.HasAnyOpenSession()) assert.Equal(t, session.Uncompleted, ssn.Status) } @@ -270,15 +270,15 @@ func TestGetRandomPeer(t *testing.T) { // peer_5 has score 33 // peer_6 has score 16 peerSet := NewPeerSet(time.Minute) - for i := 0; i < 6; i++ { - pid := peer.ID(fmt.Sprintf("peer_%v", i+1)) - peerSet.UpdateInfo(pid, fmt.Sprintf("Moniker_%v", i+1), "Agent1", nil, service.New()) + for index := 0; index < 6; index++ { + pid := peer.ID(fmt.Sprintf("peer_%v", index+1)) + peerSet.UpdateInfo(pid, fmt.Sprintf("Moniker_%v", index+1), "Agent1", nil, service.New()) peerSet.UpdateStatus(pid, status.StatusKnown) for r := 0; r < 5; r++ { sid := peerSet.OpenSession(pid, 0, 0) - if r < 5-i { + if r < 5-index { peerSet.SetSessionCompleted(sid) } } @@ -311,11 +311,11 @@ func TestGetRandomPeerConnected(t *testing.T) { peerSet.UpdateStatus(pidConnected, status.StatusConnected) peerSet.UpdateStatus(pidDisconnected, status.StatusDisconnected) - p := peerSet.GetRandomPeer() + peer := peerSet.GetRandomPeer() - assert.NotEqual(t, p.PeerID, pidBanned) - assert.NotEqual(t, p.PeerID, pidDisconnected) - assert.Equal(t, p.PeerID, pidConnected) + assert.NotEqual(t, peer.PeerID, pidBanned) + assert.NotEqual(t, peer.PeerID, pidDisconnected) + assert.Equal(t, peer.PeerID, pidConnected) } func TestGetRandomPeerNoPeer(t *testing.T) { @@ -337,36 +337,36 @@ func TestGetRandomPeerOnePeer(t *testing.T) { } func TestUpdateAddress(t *testing.T) { - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) pid := peer.ID("peer1") addr := "pid-1-address" dir := "Inbound" - ps.UpdateAddress(pid, addr, dir) + peerSet.UpdateAddress(pid, addr, dir) - p := ps.GetPeer(pid) + p := peerSet.GetPeer(pid) assert.Equal(t, addr, p.Address) assert.Equal(t, dir, p.Direction) } func TestUpdateSessionLastActivity(t *testing.T) { - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) - sid := ps.OpenSession("peer1", 100, 101) - ssn := getSessionByID(ps, sid) + sid := peerSet.OpenSession("peer1", 100, 101) + ssn := getSessionByID(peerSet, sid) activity1 := ssn.LastActivity time.Sleep(10 * time.Millisecond) - ps.UpdateSessionLastActivity(sid) + peerSet.UpdateSessionLastActivity(sid) assert.Greater(t, ssn.LastActivity, activity1) } func TestUpdateProtocols(t *testing.T) { - ps := NewPeerSet(time.Minute) + peerSet := NewPeerSet(time.Minute) pid := peer.ID("peer-1") protocols := []string{"protocol-1"} - ps.UpdateProtocols(pid, protocols) + peerSet.UpdateProtocols(pid, protocols) - p := ps.GetPeer(pid) + p := peerSet.GetPeer(pid) assert.Equal(t, protocols, p.Protocols) } diff --git a/sync/sync.go b/sync/sync.go index 6885f86a4..4d7738322 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -53,9 +53,9 @@ type synchronizer struct { func NewSynchronizer( conf *Config, valKeys []*bls.ValidatorKey, - st state.Facade, + state state.Facade, consMgr consensus.Manager, - net network.Network, + network network.Network, broadcastCh <-chan message.Message, ) (Synchronizer, error) { ctx, cancel := context.WithCancel(context.Background()) @@ -64,17 +64,17 @@ func NewSynchronizer( cancel: cancel, config: conf, valKeys: valKeys, - state: st, + state: state, consMgr: consMgr, - network: net, + network: network, broadcastCh: broadcastCh, - networkCh: net.EventChannel(), + networkCh: network.EventChannel(), ntp: ntp.NewNtpChecker(), } sync.peerSet = peerset.NewPeerSet(conf.SessionTimeout) sync.logger = logger.NewSubLogger("_sync", sync) - fw, err := firewall.NewFirewall(conf.Firewall, net, sync.peerSet, st, sync.logger) + fw, err := firewall.NewFirewall(conf.Firewall, network, sync.peerSet, state, sync.logger) if err != nil { return nil, err } @@ -177,15 +177,15 @@ func (sync *synchronizer) prepareBundle(msg message.Message) *bundle.Bundle { return bdl } -func (sync *synchronizer) sendTo(msg message.Message, to peer.ID) { +func (sync *synchronizer) sendTo(msg message.Message, pid peer.ID) { bdl := sync.prepareBundle(msg) data, _ := bdl.Encode() - sync.network.SendTo(data, to) - sync.peerSet.UpdateLastSent(to) - sync.peerSet.UpdateSentMetric(&to, msg.Type(), int64(len(data))) + sync.network.SendTo(data, pid) + sync.peerSet.UpdateLastSent(pid) + sync.peerSet.UpdateSentMetric(&pid, msg.Type(), int64(len(data))) - sync.logger.Debug("bundle sent", "bundle", bdl, "to", to) + sync.logger.Debug("bundle sent", "bundle", bdl, "pid", pid) } func (sync *synchronizer) broadcast(msg message.Message) { @@ -225,8 +225,8 @@ func (sync *synchronizer) Services() service.Services { return sync.config.Services } -func (sync *synchronizer) sayHello(to peer.ID) { - s := sync.peerSet.GetPeerStatus(to) +func (sync *synchronizer) sayHello(pid peer.ID) { + s := sync.peerSet.GetPeerStatus(pid) if s.IsKnown() { return } @@ -241,8 +241,8 @@ func (sync *synchronizer) sayHello(to peer.ID) { ) msg.Sign(sync.valKeys) - sync.logger.Info("sending Hello message", "to", to) - sync.sendTo(msg, to) + sync.logger.Info("sending Hello message", "to", pid) + sync.sendTo(msg, pid) } func (sync *synchronizer) broadcastLoop() { @@ -263,26 +263,26 @@ func (sync *synchronizer) receiveLoop() { case <-sync.ctx.Done(): return - case e := <-sync.networkCh: - switch e.Type() { + case evt := <-sync.networkCh: + switch evt.Type() { case network.EventTypeGossip: - ge := e.(*network.GossipMessage) + ge := evt.(*network.GossipMessage) sync.processGossipMessage(ge) case network.EventTypeStream: - se := e.(*network.StreamMessage) + se := evt.(*network.StreamMessage) sync.processStreamMessage(se) case network.EventTypeConnect: - ce := e.(*network.ConnectEvent) + ce := evt.(*network.ConnectEvent) sync.processConnectEvent(ce) case network.EventTypeDisconnect: - de := e.(*network.DisconnectEvent) + de := evt.(*network.DisconnectEvent) sync.processDisconnectEvent(de) case network.EventTypeProtocols: - pe := e.(*network.ProtocolsEvents) + pe := evt.(*network.ProtocolsEvents) sync.processProtocolsEvent(pe) } } @@ -343,14 +343,14 @@ func (sync *synchronizer) processDisconnectEvent(de *network.DisconnectEvent) { func (sync *synchronizer) processIncomingBundle(bdl *bundle.Bundle, from peer.ID) { sync.logger.Debug("received a bundle", "from", from, "bundle", bdl) - h := sync.handlers[bdl.Message.Type()] - if h == nil { + handler := sync.handlers[bdl.Message.Type()] + if handler == nil { sync.logger.Error("invalid message type", "type", bdl.Message.Type()) return } - h.ParseMessage(bdl.Message, from) + handler.ParseMessage(bdl.Message, from) } func (sync *synchronizer) String() string { @@ -459,40 +459,40 @@ func (sync *synchronizer) sendBlockRequestToRandomPeer(from, count uint32, onlyF } for i := sync.peerSet.NumberOfSessions(); i < sync.config.MaxSessions; i++ { - p := sync.peerSet.GetRandomPeer() - if p == nil { + peer := sync.peerSet.GetRandomPeer() + if peer == nil { break } // Don't open a new session if we already have an open session with the same peer. // This helps us to get blocks from different peers. - if sync.peerSet.HasOpenSession(p.PeerID) { + if sync.peerSet.HasOpenSession(peer.PeerID) { continue } // We haven't completed the handshake with this peer. - if !p.Status.IsKnown() { + if !peer.Status.IsKnown() { if onlyFullNodes { - sync.network.CloseConnection(p.PeerID) + sync.network.CloseConnection(peer.PeerID) } continue } - if onlyFullNodes && !p.IsFullNode() { + if onlyFullNodes && !peer.IsFullNode() { if onlyFullNodes { - sync.network.CloseConnection(p.PeerID) + sync.network.CloseConnection(peer.PeerID) } continue } - sid := sync.peerSet.OpenSession(p.PeerID, from, count) + sid := sync.peerSet.OpenSession(peer.PeerID, from, count) msg := message.NewBlocksRequestMessage(sid, from, count) - sync.sendTo(msg, p.PeerID) + sync.sendTo(msg, peer.PeerID) sync.logger.Info("blocks request sent", - "from", from+1, "count", count, "pid", p.PeerID, "sid", sid) + "from", from+1, "count", count, "pid", peer.PeerID, "sid", sid) return true } @@ -571,15 +571,15 @@ func (sync *synchronizer) prepareBlocks(from, count uint32) [][]byte { blocks := make([][]byte, 0, count) - for h := from; h < from+count; h++ { - b := sync.state.CommittedBlock(h) - if b == nil { - sync.logger.Warn("unable to find a block", "height", h) + for height := from; height < from+count; height++ { + cBlk := sync.state.CommittedBlock(height) + if cBlk == nil { + sync.logger.Warn("unable to find a block", "height", height) return nil } - blocks = append(blocks, b.Data) + blocks = append(blocks, cBlk.Data) } return blocks diff --git a/sync/sync_test.go b/sync/sync_test.go index 5ff2ff76a..90e87a19e 100644 --- a/sync/sync_test.go +++ b/sync/sync_test.go @@ -111,11 +111,11 @@ func shouldPublishMessageWithThisType(t *testing.T, net *network.MockNetwork, ms require.NoError(t, fmt.Errorf("shouldPublishMessageWithThisType %v: Timeout, test: %v", msgType, t.Name())) return nil - case b := <-net.PublishCh: - net.SendToOthers(b.Data, b.Target) + case data := <-net.PublishCh: + net.SendToOthers(data.Data, data.Target) // Decode message again to check the message type bdl := new(bundle.Bundle) - _, err := bdl.Decode(bytes.NewReader(b.Data)) + _, err := bdl.Decode(bytes.NewReader(data.Data)) require.NoError(t, err) // ----------- @@ -123,7 +123,7 @@ func shouldPublishMessageWithThisType(t *testing.T, net *network.MockNetwork, ms require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagCarrierLibP2P), "invalid flag: %v", bdl) require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagNetworkMainnet), "invalid flag: %v", bdl) - if b.Target == nil { + if data.Target == nil { require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagBroadcasted), "invalid flag: %v", bdl) } else { require.False(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagBroadcasted), "invalid flag: %v", bdl) @@ -188,7 +188,7 @@ func (*testData) receivingNewMessage(sync *synchronizer, msg message.Message, fr sync.processIncomingBundle(bdl, from) } -func (td *testData) addPeer(t *testing.T, s status.Status, services service.Services) peer.ID { +func (td *testData) addPeer(t *testing.T, status status.Status, services service.Services) peer.ID { t.Helper() pid := td.RandPeerID() @@ -196,7 +196,7 @@ func (td *testData) addPeer(t *testing.T, s status.Status, services service.Serv td.sync.peerSet.UpdateInfo(pid, t.Name(), version.NodeAgent.String(), []*bls.PublicKey{pub}, services) - td.sync.peerSet.UpdateStatus(pid, s) + td.sync.peerSet.UpdateStatus(pid, status) return pid } @@ -250,13 +250,13 @@ func TestConnectEvent(t *testing.T) { td.network.EventCh <- ce assert.Eventually(t, func() bool { - p := td.sync.peerSet.GetPeer(pid) - if p == nil { + peer := td.sync.peerSet.GetPeer(pid) + if peer == nil { return false } - assert.Equal(t, "/ip4/2.2.2.2/tcp/21888", p.Address) + assert.Equal(t, "/ip4/2.2.2.2/tcp/21888", peer.Address) - return p.Status == status.StatusConnected + return peer.Status == status.StatusConnected }, time.Second, 100*time.Millisecond) p1 := td.sync.peerSet.GetPeer(pid) diff --git a/tests/main_test.go b/tests/main_test.go index 1f0d11156..b5cd10744 100644 --- a/tests/main_test.go +++ b/tests/main_test.go @@ -201,15 +201,15 @@ func TestMain(m *testing.M) { tNodes[i].Stop() } - s, _ := store.NewStore(tConfigs[tNodeIdx1].Store) + store, _ := store.NewStore(tConfigs[tNodeIdx1].Store) total := amount.Amount(0) - s.IterateAccounts(func(_ crypto.Address, acc *account.Account) bool { + store.IterateAccounts(func(_ crypto.Address, acc *account.Account) bool { total += acc.Balance() return false }) - s.IterateValidators(func(v *validator.Validator) bool { + store.IterateValidators(func(v *validator.Validator) bool { total += v.Stake() return false diff --git a/txpool/config_test.go b/txpool/config_test.go index a3a1414b9..5399902d3 100644 --- a/txpool/config_test.go +++ b/txpool/config_test.go @@ -8,26 +8,26 @@ import ( ) func TestDefaultConfig(t *testing.T) { - c := DefaultConfig() - assert.NoError(t, c.BasicCheck()) + conf := DefaultConfig() + assert.NoError(t, conf.BasicCheck()) - assert.Equal(t, 600, c.transferPoolSize()) - assert.Equal(t, 100, c.bondPoolSize()) - assert.Equal(t, 100, c.unbondPoolSize()) - assert.Equal(t, 100, c.withdrawPoolSize()) - assert.Equal(t, 100, c.sortitionPoolSize()) - assert.Equal(t, amount.Amount(0.1e8), c.minFee()) + assert.Equal(t, 600, conf.transferPoolSize()) + assert.Equal(t, 100, conf.bondPoolSize()) + assert.Equal(t, 100, conf.unbondPoolSize()) + assert.Equal(t, 100, conf.withdrawPoolSize()) + assert.Equal(t, 100, conf.sortitionPoolSize()) + assert.Equal(t, amount.Amount(0.1e8), conf.minFee()) assert.Equal(t, - c.transferPoolSize()+ - c.bondPoolSize()+ - c.unbondPoolSize()+ - c.withdrawPoolSize()+ - c.sortitionPoolSize(), c.MaxSize) + conf.transferPoolSize()+ + conf.bondPoolSize()+ + conf.unbondPoolSize()+ + conf.withdrawPoolSize()+ + conf.sortitionPoolSize(), conf.MaxSize) } func TestConfigBasicCheck(t *testing.T) { - testCases := []struct { + tests := []struct { name string expectedErr error updateFn func(c *Config) @@ -76,17 +76,17 @@ func TestConfigBasicCheck(t *testing.T) { }, } - for i, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { + for no, tt := range tests { + t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() - tc.updateFn(conf) - if tc.expectedErr != nil { + tt.updateFn(conf) + if tt.expectedErr != nil { err := conf.BasicCheck() - assert.ErrorIs(t, tc.expectedErr, err, - "Expected error not matched for test %d-%s, expected: %s, got: %s", i, tc.name, tc.expectedErr, err) + assert.ErrorIs(t, tt.expectedErr, err, + "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() - assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", i, tc.name, err) + assert.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } diff --git a/txpool/interface.go b/txpool/interface.go index 34ee3b4ac..9abf917e7 100644 --- a/txpool/interface.go +++ b/txpool/interface.go @@ -10,8 +10,8 @@ import ( type Reader interface { PrepareBlockTransactions() block.Txs - PendingTx(id tx.ID) *tx.Tx - HasTx(id tx.ID) bool + PendingTx(txID tx.ID) *tx.Tx + HasTx(txID tx.ID) bool Size() int EstimatedFee(amt amount.Amount, payloadType payload.Type) amount.Amount AllPendingTxs() []*tx.Tx @@ -20,7 +20,7 @@ type Reader interface { type TxPool interface { Reader - SetNewSandboxAndRecheck(sb sandbox.Sandbox) + SetNewSandboxAndRecheck(sbx sandbox.Sandbox) AppendTxAndBroadcast(trx *tx.Tx) error AppendTx(trx *tx.Tx) error HandleCommittedBlock(blk *block.Block) error diff --git a/txpool/mock.go b/txpool/mock.go index e305a6aca..3a6314af7 100644 --- a/txpool/mock.go +++ b/txpool/mock.go @@ -25,9 +25,9 @@ func MockingTxPool() *MockTxPool { } } func (*MockTxPool) SetNewSandboxAndRecheck(_ sandbox.Sandbox) {} -func (m *MockTxPool) PendingTx(id tx.ID) *tx.Tx { +func (m *MockTxPool) PendingTx(txID tx.ID) *tx.Tx { for _, t := range m.Txs { - if t.ID() == id { + if t.ID() == txID { return t } } @@ -35,13 +35,13 @@ func (m *MockTxPool) PendingTx(id tx.ID) *tx.Tx { return nil } -func (m *MockTxPool) QueryTx(id tx.ID) *tx.Tx { - return m.PendingTx(id) +func (m *MockTxPool) QueryTx(txID tx.ID) *tx.Tx { + return m.PendingTx(txID) } -func (m *MockTxPool) HasTx(id tx.ID) bool { +func (m *MockTxPool) HasTx(txID tx.ID) bool { for _, t := range m.Txs { - if t.ID() == id { + if t.ID() == txID { return true } } diff --git a/txpool/txpool.go b/txpool/txpool.go index 5c1dd02bb..03b7ee9bf 100644 --- a/txpool/txpool.go +++ b/txpool/txpool.go @@ -22,11 +22,11 @@ type txPool struct { lk sync.RWMutex config *Config - sandbox sandbox.Sandbox + sbx sandbox.Sandbox pools map[payload.Type]pool consumptionMap map[crypto.Address]uint32 broadcastCh chan message.Message - strReader store.Reader + store store.Reader logger *logger.SubLogger } @@ -44,7 +44,7 @@ func NewTxPool(conf *Config, storeReader store.Reader, broadcastCh chan message. config: conf, pools: pools, consumptionMap: make(map[crypto.Address]uint32), - strReader: storeReader, + store: storeReader, broadcastCh: broadcastCh, } @@ -55,11 +55,11 @@ func NewTxPool(conf *Config, storeReader store.Reader, broadcastCh chan message. // SetNewSandboxAndRecheck updates the sandbox and rechecks all transactions, // removing expired or invalid ones. -func (p *txPool) SetNewSandboxAndRecheck(sb sandbox.Sandbox) { +func (p *txPool) SetNewSandboxAndRecheck(sbx sandbox.Sandbox) { p.lk.Lock() defer p.lk.Unlock() - p.sandbox = sb + p.sbx = sbx p.logger.Debug("set new sandbox") var next *linkedlist.Element[linkedmap.Pair[tx.ID, *tx.Tx]] @@ -134,7 +134,7 @@ func (p *txPool) appendTx(trx *tx.Tx) error { } func (p *txPool) checkTx(trx *tx.Tx) error { - if err := execution.CheckAndExecute(trx, p.sandbox, false); err != nil { + if err := execution.CheckAndExecute(trx, p.sbx, false); err != nil { p.logger.Debug("invalid transaction", "tx", trx, "error", err) return err @@ -172,7 +172,7 @@ func (p *txPool) handleDecreaseConsumption(height uint32) error { // Calculate the block height that has passed out of the consumption window. windowedBlockHeight := height - p.config.ConsumptionWindow - committedBlock, err := p.strReader.Block(windowedBlockHeight) + committedBlock, err := p.store.Block(windowedBlockHeight) if err != nil { return err } @@ -185,16 +185,16 @@ func (p *txPool) handleDecreaseConsumption(height uint32) error { for _, trx := range blk.Transactions() { if trx.IsTransferTx() || trx.IsBondTx() || trx.IsWithdrawTx() { signer := trx.Payload().Signer() - if v, ok := p.consumptionMap[signer]; ok { + if consumption, ok := p.consumptionMap[signer]; ok { // Decrease the consumption by the size of the transaction - v -= uint32(trx.SerializeSize()) + consumption -= uint32(trx.SerializeSize()) - if v == 0 { + if consumption == 0 { // If the new value is zero, remove the signer from the consumptionMap delete(p.consumptionMap, signer) } else { // Otherwise, update the map with the new value - p.consumptionMap[signer] = v + p.consumptionMap[signer] = consumption } } } @@ -203,9 +203,9 @@ func (p *txPool) handleDecreaseConsumption(height uint32) error { return nil } -func (p *txPool) removeTx(id tx.ID) { +func (p *txPool) removeTx(txID tx.ID) { for _, pool := range p.pools { - if pool.list.Remove(id) { + if pool.list.Remove(txID) { break } } @@ -213,12 +213,12 @@ func (p *txPool) removeTx(id tx.ID) { // PendingTx searches inside the transaction pool and returns the associated transaction. // If transaction doesn't exist inside the pool, it returns nil. -func (p *txPool) PendingTx(id tx.ID) *tx.Tx { +func (p *txPool) PendingTx(txID tx.ID) *tx.Tx { p.lk.Lock() defer p.lk.Unlock() for _, pool := range p.pools { - n := pool.list.GetNode(id) + n := pool.list.GetNode(txID) if n != nil { return n.Data.Value } @@ -266,12 +266,12 @@ func (p *txPool) PrepareBlockTransactions() block.Txs { return trxs } -func (p *txPool) HasTx(id tx.ID) bool { +func (p *txPool) HasTx(txID tx.ID) bool { p.lk.RLock() defer p.lk.RUnlock() for _, pool := range p.pools { - if pool.list.Has(id) { + if pool.list.Has(txID) { return true } } diff --git a/txpool/txpool_test.go b/txpool/txpool_test.go index 452e31c06..88cbb6794 100644 --- a/txpool/txpool_test.go +++ b/txpool/txpool_test.go @@ -22,10 +22,10 @@ import ( type testData struct { *testsuite.TestSuite - pool *txPool - sandbox *sandbox.MockSandbox - str *store.MockStore - ch chan message.Message + pool *txPool + sbx *sandbox.MockSandbox + store *store.MockStore + ch chan message.Message } func testConfig() *Config { @@ -45,25 +45,25 @@ func setup(t *testing.T) *testData { ts := testsuite.NewTestSuite(t) - ch := make(chan message.Message, 10) - sb := sandbox.MockingSandbox(ts) + broadcastCh := make(chan message.Message, 10) + sbx := sandbox.MockingSandbox(ts) config := testConfig() mockStore := store.MockingStore(ts) - p := NewTxPool(config, mockStore, ch) - p.SetNewSandboxAndRecheck(sb) - pool := p.(*txPool) + poolInt := NewTxPool(config, mockStore, broadcastCh) + poolInt.SetNewSandboxAndRecheck(sbx) + pool := poolInt.(*txPool) assert.NotNil(t, pool) return &testData{ TestSuite: ts, pool: pool, - sandbox: sb, - str: mockStore, - ch: ch, + sbx: sbx, + store: mockStore, + ch: broadcastCh, } } -func (td *testData) shouldPublishTransaction(t *testing.T, id tx.ID) { +func (td *testData) shouldPublishTransaction(t *testing.T, txID tx.ID) { t.Helper() timer := time.NewTimer(1 * time.Second) @@ -80,7 +80,7 @@ func (td *testData) shouldPublishTransaction(t *testing.T, id tx.ID) { if msg.Type() == message.TypeTransaction { m := msg.(*message.TransactionsMessage) - assert.Equal(t, id, m.Transactions[0].ID()) + assert.Equal(t, txID, m.Transactions[0].ID()) return } @@ -92,7 +92,7 @@ func TestAppendAndRemove(t *testing.T) { td := setup(t) height := td.RandHeight() - td.sandbox.TestStore.AddTestBlock(height) + td.sbx.TestStore.AddTestBlock(height) testTrx := tx.NewSubsidyTx(height+1, td.RandAccAddress(), 1e9) assert.NoError(t, td.pool.AppendTx(testTrx)) @@ -148,7 +148,7 @@ func TestCalculatingConsumption(t *testing.T) { blk, cert := td.TestSuite.GenerateTestBlock(tt.height, func(bm *testsuite.BlockMaker) { bm.Txs = tt.txs }) - td.str.SaveBlock(blk, cert) + td.store.SaveBlock(blk, cert) // Handle the block in the transaction pool err := td.pool.HandleCommittedBlock(blk) @@ -170,13 +170,13 @@ func TestFullPool(t *testing.T) { td := setup(t) randHeight := td.RandHeight() - _ = td.sandbox.TestStore.AddTestBlock(randHeight) + _ = td.sbx.TestStore.AddTestBlock(randHeight) trxs := make([]*tx.Tx, td.pool.config.transferPoolSize()+1) senderAddr := td.RandAccAddress() senderAcc := account.NewAccount(0) senderAcc.AddToBalance(1000e9) - td.sandbox.UpdateAccount(senderAddr, senderAcc) + td.sbx.UpdateAccount(senderAddr, senderAcc) // Make sure the pool is empty assert.Equal(t, 0, td.pool.Size()) @@ -202,29 +202,29 @@ func TestEmptyPool(t *testing.T) { func TestPrepareBlockTransactions(t *testing.T) { td := setup(t) - randHeight := td.RandHeight() + td.sandbox.TestParams.UnbondInterval - _ = td.sandbox.TestStore.AddTestBlock(randHeight) + randHeight := td.RandHeight() + td.sbx.TestParams.UnbondInterval + _ = td.sbx.TestStore.AddTestBlock(randHeight) acc1Addr := td.RandAccAddress() acc1 := account.NewAccount(0) acc1.AddToBalance(1000e9) - td.sandbox.UpdateAccount(acc1Addr, acc1) + td.sbx.UpdateAccount(acc1Addr, acc1) val1PubKey, _ := td.RandBLSKeyPair() val1 := validator.NewValidator(val1PubKey, 0) val1.AddToStake(1000e9) - td.sandbox.UpdateValidator(val1) + td.sbx.UpdateValidator(val1) val2PubKey, _ := td.RandBLSKeyPair() val2 := validator.NewValidator(val2PubKey, 0) val2.AddToStake(1000e9) val2.UpdateUnbondingHeight(1) - td.sandbox.UpdateValidator(val2) + td.sbx.UpdateValidator(val2) val3PubKey, _ := td.RandBLSKeyPair() val3 := validator.NewValidator(val3PubKey, 0) val3.AddToStake(1000e9) - td.sandbox.UpdateValidator(val3) + td.sbx.UpdateValidator(val3) transferTx := tx.NewTransferTx(randHeight+1, acc1Addr, td.RandAccAddress(), 1e9, 100_000_000) @@ -235,7 +235,7 @@ func TestPrepareBlockTransactions(t *testing.T) { withdrawTx := tx.NewWithdrawTx(randHeight+4, val2.Address(), td.RandAccAddress(), 1e9, 100_000_000) - td.sandbox.TestAcceptSortition = true + td.sbx.TestAcceptSortition = true sortitionTx := tx.NewSortitionTx(randHeight, val3.Address(), td.RandProof()) @@ -258,7 +258,7 @@ func TestAppendAndBroadcast(t *testing.T) { td := setup(t) height := td.RandHeight() - td.sandbox.TestStore.AddTestBlock(height) + td.sbx.TestStore.AddTestBlock(height) testTrx := tx.NewSubsidyTx(height+1, td.RandAccAddress(), 1e9) assert.NoError(t, td.pool.AppendTxAndBroadcast(testTrx)) @@ -272,7 +272,7 @@ func TestAddSubsidyTransactions(t *testing.T) { td := setup(t) randHeight := td.RandHeight() - td.sandbox.TestStore.AddTestBlock(randHeight) + td.sbx.TestStore.AddTestBlock(randHeight) proposer1 := td.RandAccAddress() proposer2 := td.RandAccAddress() trx1 := tx.NewSubsidyTx(randHeight, proposer1, 1e9, tx.WithMemo("subsidy-tx-1")) @@ -292,8 +292,8 @@ func TestAddSubsidyTransactions(t *testing.T) { err = td.pool.AppendTx(trx3) assert.NoError(t, err) - td.sandbox.TestStore.AddTestBlock(randHeight + 1) + td.sbx.TestStore.AddTestBlock(randHeight + 1) - td.pool.SetNewSandboxAndRecheck(td.sandbox) + td.pool.SetNewSandboxAndRecheck(td.sbx) assert.Zero(t, td.pool.Size()) } diff --git a/types/account/account.go b/types/account/account.go index 2b47b87b6..6b5e6e184 100644 --- a/types/account/account.go +++ b/types/account/account.go @@ -80,15 +80,15 @@ func (*Account) SerializeSize() int { // Bytes returns the serialized byte representation of the account. func (acc *Account) Bytes() ([]byte, error) { - w := bytes.NewBuffer(make([]byte, 0, acc.SerializeSize())) - err := encoding.WriteElements(w, + buf := bytes.NewBuffer(make([]byte, 0, acc.SerializeSize())) + err := encoding.WriteElements(buf, acc.data.Number, acc.data.Balance) if err != nil { return nil, err } - return w.Bytes(), nil + return buf.Bytes(), nil } // Clone creates a deep copy of the account. diff --git a/types/account/account_test.go b/types/account/account_test.go index 260d445f2..c38ca21c6 100644 --- a/types/account/account_test.go +++ b/types/account/account_test.go @@ -28,20 +28,20 @@ func TestFromBytes(t *testing.T) { } func TestDecoding(t *testing.T) { - d, _ := hex.DecodeString( + data, _ := hex.DecodeString( "01000000" + // number "0200000000000000") // balance - acc, err := account.FromBytes(d) + acc, err := account.FromBytes(data) require.NoError(t, err) assert.Equal(t, int32(1), acc.Number()) assert.Equal(t, amount.Amount(2), acc.Balance()) - d2, _ := acc.Bytes() - assert.Equal(t, d, d2) - assert.Equal(t, hash.CalcHash(d), acc.Hash()) + accData, _ := acc.Bytes() + assert.Equal(t, data, accData) + assert.Equal(t, hash.CalcHash(data), acc.Hash()) expected, _ := hash.FromString("c3b75f08e64a66cb980fdc03c3a0b78635a7b1db049096e8bbbd9a2873f3071a") assert.Equal(t, expected, acc.Hash()) - assert.Equal(t, len(d), acc.SerializeSize()) + assert.Equal(t, len(data), acc.SerializeSize()) } func TestAddToBalance(t *testing.T) { diff --git a/types/amount/amount.go b/types/amount/amount.go index b6f5ae910..11962b371 100644 --- a/types/amount/amount.go +++ b/types/amount/amount.go @@ -83,17 +83,17 @@ func round(f float64) Amount { // NewAmount is specifically for converting PAC to NanoPAC. // For creating a new Amount with an int64 value which denotes a quantity of NanoPAC, // do a simple type conversion from type int64 to Amount. -func NewAmount(f float64) (Amount, error) { +func NewAmount(pac float64) (Amount, error) { // The amount is only considered invalid if it cannot be represented // as an integer type. This may happen if f is NaN or +-Infinity. switch { - case math.IsNaN(f), - math.IsInf(f, 1), - math.IsInf(f, -1): + case math.IsNaN(pac), + math.IsInf(pac, 1), + math.IsInf(pac, -1): return 0, errors.New("invalid PAC amount") } - return round(f * float64(NanoPACPerPAC)), nil + return round(pac * float64(NanoPACPerPAC)), nil } // FromString parses a string representing a value in PAC. diff --git a/types/amount/amount_test.go b/types/amount/amount_test.go index a1f926c0f..4e6f027f4 100644 --- a/types/amount/amount_test.go +++ b/types/amount/amount_test.go @@ -96,18 +96,18 @@ func TestAmountCreation(t *testing.T) { }, } - for _, test := range tests { - amt, err := amount.NewAmount(test.amount) - if test.valid { + for _, tt := range tests { + amt, err := amount.NewAmount(tt.amount) + if tt.valid { assert.NoErrorf(t, err, - "%v: Positive test Amount creation failed with: %v", test.name, err) + "%v: Positive test Amount creation failed with: %v", tt.name, err) } else { assert.Errorf(t, err, - "%v: Negative test Amount creation succeeded (value %v) when should fail", test.name, amt) + "%v: Negative test Amount creation succeeded (value %v) when should fail", tt.name, amt) } - assert.Equal(t, test.expected, amt, - "%v: Created amount %v does not match expected %v", test.name, amt, test.expected) + assert.Equal(t, tt.expected, amt, + "%v: Created amount %v does not match expected %v", tt.name, amt, tt.expected) } } @@ -191,26 +191,26 @@ func TestAmountUnitConversions(t *testing.T) { }, } - for _, test := range tests { - f := test.amount.ToUnit(test.unit) - assert.Equal(t, test.converted, f, - "%v: converted value %v does not match expected %v", test.name, f, test.converted) + for _, tt := range tests { + f := tt.amount.ToUnit(tt.unit) + assert.Equal(t, tt.converted, f, + "%v: converted value %v does not match expected %v", tt.name, f, tt.converted) - str := test.amount.Format(test.unit) - assert.Equal(t, test.str, str, - "%v: format '%v' does not match expected '%v'", test.name, str, test.str) + str := tt.amount.Format(tt.unit) + assert.Equal(t, tt.str, str, + "%v: format '%v' does not match expected '%v'", tt.name, str, tt.str) // Verify that Amount.ToPAC works as advertised. - f1 := test.amount.ToUnit(amount.UnitPAC) - f2 := test.amount.ToPAC() + f1 := tt.amount.ToUnit(amount.UnitPAC) + f2 := tt.amount.ToPAC() assert.Equal(t, f1, f2, - "%v: ToPAC does not match ToUnit(AmountPAC): %v != %v", test.name, f1, f2) + "%v: ToPAC does not match ToUnit(AmountPAC): %v != %v", tt.name, f1, f2) // Verify that Amount.String works as advertised. - s1 := test.amount.Format(amount.UnitPAC) - s2 := test.amount.String() + s1 := tt.amount.Format(amount.UnitPAC) + s2 := tt.amount.String() assert.Equal(t, s1, s2, - "%v: String does not match Format(AmountPac): %v != %v", test.name, s1, s2) + "%v: String does not match Format(AmountPac): %v != %v", tt.name, s1, s2) } } @@ -313,10 +313,10 @@ func TestAmountMulF64(t *testing.T) { }, } - for _, test := range tests { - a := test.amt.MulF64(test.mul) - if a != test.res { - t.Errorf("%v: expected %v got %v", test.name, test.res, a) + for _, tt := range tests { + a := tt.amt.MulF64(tt.mul) + if a != tt.res { + t.Errorf("%v: expected %v got %v", tt.name, tt.res, a) } } } @@ -342,15 +342,15 @@ func TestCoinToChangeConversion(t *testing.T) { {"123.0000001234", 123.000000123, 123000000123, "123.000000123 PAC", nil}, {"1coin", 0, 0, "0", strconv.ErrSyntax}, } - for _, test := range tests { - amt, err := amount.FromString(test.amount) - if test.parsErr == nil { + for _, tt := range tests { + amt, err := amount.FromString(tt.amount) + if tt.parsErr == nil { assert.NoError(t, err) - assert.Equal(t, test.NanoPac, amt.ToNanoPAC()) - assert.Equal(t, test.PAC, amt.ToPAC()) - assert.Equal(t, test.str, amt.String()) + assert.Equal(t, tt.NanoPac, amt.ToNanoPAC()) + assert.Equal(t, tt.PAC, amt.ToPAC()) + assert.Equal(t, tt.str, amt.String()) } else { - assert.ErrorIs(t, err, test.parsErr) + assert.ErrorIs(t, err, tt.parsErr) } } } diff --git a/types/block/block.go b/types/block/block.go index ccec41de0..5fb81cd99 100644 --- a/types/block/block.go +++ b/types/block/block.go @@ -40,13 +40,13 @@ func NewBlock(header *Header, prevCert *certificate.BlockCertificate, txs Txs) * // FromBytes constructs a new block from byte array. func FromBytes(data []byte) (*Block, error) { - b := new(Block) - r := bytes.NewReader(data) - if err := b.Decode(r); err != nil { + blk := new(Block) + reader := bytes.NewReader(data) + if err := blk.Decode(reader); err != nil { return nil, err } - return b, nil + return blk, nil } func MakeBlock(version uint8, timestamp time.Time, txs Txs, @@ -117,18 +117,18 @@ func (b *Block) Hash() hash.Hash { return *b.memorizedHash } - w := &bytes.Buffer{} - if err := b.data.Header.Encode(w); err != nil { + buf := bytes.NewBuffer(make([]byte, 0, b.SerializeSize())) + if err := b.data.Header.Encode(buf); err != nil { return hash.UndefHash } // Genesis block has no certificate if b.data.PrevCert != nil { - w.Write(b.data.PrevCert.Hash().Bytes()) + buf.Write(b.data.PrevCert.Hash().Bytes()) } - w.Write(b.data.Txs.Root().Bytes()) - w.Write(util.Int32ToSlice(int32(b.data.Txs.Len()))) + buf.Write(b.data.Txs.Root().Bytes()) + buf.Write(util.Int32ToSlice(int32(b.data.Txs.Len()))) - h := hash.CalcHash(w.Bytes()) + h := hash.CalcHash(buf.Bytes()) b.memorizedHash = &h return h @@ -221,18 +221,18 @@ func (b *Block) Decode(r io.Reader) error { // SerializeSize returns the number of bytes it would take to serialize the block. func (b *Block) SerializeSize() int { - n := b.Header().SerializeSize() + size := b.Header().SerializeSize() if b.PrevCertificate() != nil { - n += b.PrevCertificate().SerializeSize() + size += b.PrevCertificate().SerializeSize() } - n += encoding.VarIntSerializeSize(uint64(b.Transactions().Len())) + size += encoding.VarIntSerializeSize(uint64(b.Transactions().Len())) for _, trx := range b.Transactions() { - n += trx.SerializeSize() + size += trx.SerializeSize() } - return n + return size } // Bytes returns the serialized bytes for the Block. It caches the @@ -243,14 +243,14 @@ func (b *Block) Bytes() ([]byte, error) { return b.memorizedData, nil } - w := bytes.NewBuffer(make([]byte, 0, b.SerializeSize())) - err := b.Encode(w) + writer := bytes.NewBuffer(make([]byte, 0, b.SerializeSize())) + err := b.Encode(writer) if err != nil { return nil, err } // Cache the serialized bytes and return them. - b.memorizedData = w.Bytes() + b.memorizedData = writer.Bytes() return b.memorizedData, nil } diff --git a/types/block/block_test.go b/types/block/block_test.go index cfbaf4ced..ada6cb875 100644 --- a/types/block/block_test.go +++ b/types/block/block_test.go @@ -17,7 +17,7 @@ func TestBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("No transactions", func(t *testing.T) { - d := ts.DecodingHex( + data := ts.DecodingHex( "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash @@ -33,25 +33,25 @@ func TestBasicCheck(t *testing.T) { "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "00") // Txs: Len - b, _ := block.FromBytes(d) + blk, _ := block.FromBytes(data) - err := b.BasicCheck() + err := blk.BasicCheck() assert.ErrorIs(t, err, block.BasicCheckError{ Reason: "no subsidy transaction", }) }) t.Run("Without the previous certificate", func(t *testing.T) { - b, _ := ts.GenerateTestBlock(ts.RandHeight(), testsuite.BlockWithPrevCert(nil)) + blk, _ := ts.GenerateTestBlock(ts.RandHeight(), testsuite.BlockWithPrevCert(nil)) - err := b.BasicCheck() + err := blk.BasicCheck() assert.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid genesis block hash", }) }) t.Run("Invalid certificate", func(t *testing.T) { - d := ts.DecodingHex( + data := ts.DecodingHex( "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash @@ -76,16 +76,16 @@ func TestBasicCheck(t *testing.T) { "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01") // Tx[0]: Amount - b, _ := block.FromBytes(d) + blk, _ := block.FromBytes(data) - err := b.BasicCheck() + err := blk.BasicCheck() assert.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid certificate: height is not positive: 0", }) }) t.Run("Invalid transaction", func(t *testing.T) { - d := ts.DecodingHex( + data := ts.DecodingHex( "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash @@ -110,16 +110,16 @@ func TestBasicCheck(t *testing.T) { "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01") // Tx[0]: Amount - b, _ := block.FromBytes(d) + blk, _ := block.FromBytes(data) - err := b.BasicCheck() + err := blk.BasicCheck() assert.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid transaction: invalid version: 0", }) }) t.Run("Invalid previous block hash", func(t *testing.T) { - d := ts.DecodingHex( + data := ts.DecodingHex( "01" + // Version "00000000" + // UnixTime "0000000000000000000000000000000000000000000000000000000000000000" + // PrevBlockHash @@ -144,12 +144,12 @@ func TestBasicCheck(t *testing.T) { "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01") // Tx[0]: Amount - _, err := block.FromBytes(d) + _, err := block.FromBytes(data) assert.Error(t, err) }) t.Run("Invalid proposer address (type is 2)", func(t *testing.T) { - d := ts.DecodingHex( + data := ts.DecodingHex( "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash @@ -174,15 +174,15 @@ func TestBasicCheck(t *testing.T) { "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01") // Tx[0]: Amount - b, _ := block.FromBytes(d) - err := b.BasicCheck() + blk, _ := block.FromBytes(data) + err := blk.BasicCheck() assert.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid proposer address: pc1z42424242424242424242424242424242klpmq4", }) }) t.Run("Ok", func(t *testing.T) { - d := ts.DecodingHex( + data := ts.DecodingHex( "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash @@ -207,10 +207,10 @@ func TestBasicCheck(t *testing.T) { "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01") // Tx[0]: Amount - b, _ := block.FromBytes(d) - assert.NoError(t, b.BasicCheck()) - assert.Zero(t, b.Header().UnixTime()) - assert.Equal(t, uint8(1), b.Header().Version()) + blk, _ := block.FromBytes(data) + assert.NoError(t, blk.BasicCheck()) + assert.Zero(t, blk.Header().UnixTime()) + assert.Equal(t, uint8(1), blk.Header().Version()) }) } @@ -242,17 +242,17 @@ func TestEncodingBlock(t *testing.T) { w := util.NewFixedWriter(i) assert.Error(t, blk.Encode(w), "encode test %v failed", i) } - w := util.NewFixedWriter(length) - assert.NoError(t, blk.Encode(w)) + writer := util.NewFixedWriter(length) + assert.NoError(t, blk.Encode(writer)) for i := 0; i < length; i++ { blk2 := new(block.Block) - r := util.NewFixedReader(i, w.Bytes()) + r := util.NewFixedReader(i, writer.Bytes()) assert.Error(t, blk2.Decode(r), "decode test %v failed", i) } blk2 := new(block.Block) - r := util.NewFixedReader(length, w.Bytes()) + r := util.NewFixedReader(length, writer.Bytes()) assert.NoError(t, blk2.Decode(r)) assert.Equal(t, blk.Hash(), blk2.Hash()) assert.Equal(t, blk.Header(), blk2.Header()) @@ -274,7 +274,7 @@ func TestTxFromBytes(t *testing.T) { } func TestBlockHash(t *testing.T) { - d, _ := hex.DecodeString( + data, _ := hex.DecodeString( "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash @@ -299,20 +299,21 @@ func TestBlockHash(t *testing.T) { "012222222222222222222222222222222222222222" + // Tx[0]: Receiver "01") // Tx[0]: Amount - b, err := block.FromBytes(d) + blk, err := block.FromBytes(data) assert.NoError(t, err) - assert.Equal(t, len(d), b.SerializeSize()) - d2, _ := b.Bytes() - assert.Equal(t, d, d2) - - headerSize := b.Header().SerializeSize() - headerData := d[:headerSize] - certSize := b.PrevCertificate().SerializeSize() - certData := d[headerSize : headerSize+certSize] + assert.Equal(t, len(data), blk.SerializeSize()) + + blockData, _ := blk.Bytes() + assert.Equal(t, data, blockData) + + headerSize := blk.Header().SerializeSize() + headerData := data[:headerSize] + certSize := blk.PrevCertificate().SerializeSize() + certData := data[headerSize : headerSize+certSize] certHash := hash.CalcHash(certData) txHashes := make([]hash.Hash, 0) - for _, trx := range b.Transactions() { + for _, trx := range blk.Transactions() { txHashes = append(txHashes, trx.ID()) } txRoot := simplemerkle.NewTreeFromHashes(txHashes).Root() @@ -320,12 +321,12 @@ func TestBlockHash(t *testing.T) { hashData := headerData hashData = append(hashData, certHash.Bytes()...) hashData = append(hashData, txRoot.Bytes()...) - hashData = append(hashData, util.Int32ToSlice(int32(b.Transactions().Len()))...) + hashData = append(hashData, util.Int32ToSlice(int32(blk.Transactions().Len()))...) expected1 := hash.CalcHash(hashData) expected2, _ := hash.FromString("43399fa59adcfb7d8c515460ec9ca27b6a1cb865f5b7d9bde8fe56c18eaec9ab") - assert.Equal(t, expected1, b.Hash()) - assert.Equal(t, expected2, b.Hash()) + assert.Equal(t, expected1, blk.Hash()) + assert.Equal(t, expected2, blk.Hash()) } func TestMakeBlock(t *testing.T) { diff --git a/types/certificate/block_certificate.go b/types/certificate/block_certificate.go index 10773c2a3..3c4c830d2 100644 --- a/types/certificate/block_certificate.go +++ b/types/certificate/block_certificate.go @@ -24,11 +24,11 @@ func NewBlockCertificate(height uint32, round int16) *BlockCertificate { } func (cert *BlockCertificate) SignBytes(blockHash hash.Hash) []byte { - sb := blockHash.Bytes() - sb = append(sb, util.Uint32ToSlice(cert.height)...) - sb = append(sb, util.Int16ToSlice(cert.round)...) + signBytes := blockHash.Bytes() + signBytes = append(signBytes, util.Uint32ToSlice(cert.height)...) + signBytes = append(signBytes, util.Int16ToSlice(cert.round)...) - return sb + return signBytes } func (cert *BlockCertificate) Validate(validators []*validator.Validator, blockHash hash.Hash) error { diff --git a/types/certificate/certificate.go b/types/certificate/certificate.go index 1091953f1..015c8e5d9 100644 --- a/types/certificate/certificate.go +++ b/types/certificate/certificate.go @@ -81,12 +81,12 @@ func (cert *baseCertificate) BasicCheck() error { } func (cert *baseCertificate) Hash() hash.Hash { - w := bytes.NewBuffer(make([]byte, 0, cert.SerializeSize())) - if err := cert.Encode(w); err != nil { + buf := bytes.NewBuffer(make([]byte, 0, cert.SerializeSize())) + if err := cert.Encode(buf); err != nil { return hash.UndefHash } - return hash.CalcHash(w.Bytes()) + return hash.CalcHash(buf.Bytes()) } func (cert *baseCertificate) SetSignature(committers, absentees []int32, signature *bls.Signature) { @@ -97,20 +97,20 @@ func (cert *baseCertificate) SetSignature(committers, absentees []int32, signatu // SerializeSize returns the number of bytes it would take to serialize the block. func (cert *baseCertificate) SerializeSize() int { - sz := 6 + // height (4) + round(2) + size := 6 + // height (4) + round(2) encoding.VarIntSerializeSize(uint64(len(cert.committers))) + encoding.VarIntSerializeSize(uint64(len(cert.absentees))) + bls.SignatureSize for _, n := range cert.committers { - sz += encoding.VarIntSerializeSize(uint64(n)) + size += encoding.VarIntSerializeSize(uint64(n)) } for _, n := range cert.absentees { - sz += encoding.VarIntSerializeSize(uint64(n)) + size += encoding.VarIntSerializeSize(uint64(n)) } - return sz + return size } func (cert *baseCertificate) MarshalCBOR() ([]byte, error) { diff --git a/types/certificate/certificate_test.go b/types/certificate/certificate_test.go index c7b59aa2a..3130fdd94 100644 --- a/types/certificate/certificate_test.go +++ b/types/certificate/certificate_test.go @@ -114,18 +114,18 @@ func TestEncodingCertificate(t *testing.T) { w := util.NewFixedWriter(i) assert.Error(t, cert1.Encode(w), "encode test %v failed", i) } - w := util.NewFixedWriter(length) - assert.NoError(t, cert1.Encode(w)) + writer := util.NewFixedWriter(length) + assert.NoError(t, cert1.Encode(writer)) for i := 0; i < length; i++ { cert := new(certificate.BlockCertificate) - r := util.NewFixedReader(i, w.Bytes()) + r := util.NewFixedReader(i, writer.Bytes()) assert.Error(t, cert.Decode(r), "decode test %v failed", i) } cert2 := new(certificate.BlockCertificate) - r := util.NewFixedReader(length, w.Bytes()) - assert.NoError(t, cert2.Decode(r)) + reader := util.NewFixedReader(length, writer.Bytes()) + assert.NoError(t, cert2.Decode(reader)) assert.Equal(t, cert1.Hash(), cert2.Hash()) } diff --git a/types/certificate/vote_certificate.go b/types/certificate/vote_certificate.go index 72ba00147..1fcdf48c2 100644 --- a/types/certificate/vote_certificate.go +++ b/types/certificate/vote_certificate.go @@ -25,14 +25,14 @@ func NewVoteCertificate(height uint32, round int16) *VoteCertificate { // SignBytes returns the sign bytes for the vote certificate. // This method provides the same data as the `SignBytes` function in vote struct. func (cert *VoteCertificate) SignBytes(blockHash hash.Hash, extraData ...[]byte) []byte { - sb := blockHash.Bytes() - sb = append(sb, util.Uint32ToSlice(cert.height)...) - sb = append(sb, util.Int16ToSlice(cert.round)...) + signBytes := blockHash.Bytes() + signBytes = append(signBytes, util.Uint32ToSlice(cert.height)...) + signBytes = append(signBytes, util.Int16ToSlice(cert.round)...) for _, data := range extraData { - sb = append(sb, data...) + signBytes = append(signBytes, data...) } - return sb + return signBytes } func (cert *VoteCertificate) ValidatePrepare(validators []*validator.Validator, diff --git a/types/proposal/proposal_test.go b/types/proposal/proposal_test.go index da1390050..c3d574b01 100644 --- a/types/proposal/proposal_test.go +++ b/types/proposal/proposal_test.go @@ -15,44 +15,52 @@ import ( func TestProposalMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) - p1, _ := ts.GenerateTestProposal(10, 10) - bz1, err := p1.MarshalCBOR() + prop := ts.GenerateTestProposal(10, 10) + data, err := prop.MarshalCBOR() assert.NoError(t, err) var p2 proposal.Proposal - err = p2.UnmarshalCBOR(bz1) + err = p2.UnmarshalCBOR(data) assert.NoError(t, err) } func TestProposalSignBytes(t *testing.T) { ts := testsuite.NewTestSuite(t) - p, _ := ts.GenerateTestProposal(ts.RandHeight(), ts.RandRound()) - sb := p.Block().Hash().Bytes() - sb = append(sb, util.Uint32ToSlice(p.Height())...) - sb = append(sb, util.Int16ToSlice(p.Round())...) + prop := ts.GenerateTestProposal(ts.RandHeight(), ts.RandRound()) + sb := prop.Block().Hash().Bytes() + sb = append(sb, util.Uint32ToSlice(prop.Height())...) + sb = append(sb, util.Int16ToSlice(prop.Round())...) - assert.Equal(t, sb, p.SignBytes()) - assert.Equal(t, hash.CalcHash(sb), p.Hash()) + assert.Equal(t, sb, prop.SignBytes()) + assert.Equal(t, hash.CalcHash(sb), prop.Hash()) +} + +func TestIsForBlock(t *testing.T) { + ts := testsuite.NewTestSuite(t) + + prop := ts.GenerateTestProposal(ts.RandHeight(), ts.RandRound()) + assert.False(t, prop.IsForBlock(ts.RandHash())) + assert.True(t, prop.IsForBlock(prop.Block().Hash())) } func TestProposalSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) - rndValKey := ts.RandValKey() - p, valKey := ts.GenerateTestProposal(ts.RandHeight(), ts.RandRound()) - pub := valKey.PublicKey() - assert.NoError(t, p.Verify(pub)) - assert.False(t, p.IsForBlock(ts.RandHash())) - assert.True(t, p.IsForBlock(p.Block().Hash())) + proposerKey := ts.RandValKey() + prop := ts.GenerateTestProposal(ts.RandHeight(), ts.RandRound(), testsuite.WithProposerKey(proposerKey)) - err := p.Verify(rndValKey.PublicKey()) + err := prop.Verify(proposerKey.PublicKey()) + assert.NoError(t, err) + + rndValKey := ts.RandValKey() + err = prop.Verify(rndValKey.PublicKey()) assert.ErrorIs(t, err, crypto.AddressMismatchError{ Expected: rndValKey.Address(), - Got: valKey.Address(), + Got: prop.Block().Header().ProposerAddress(), }) - ts.HelperSignProposal(rndValKey, p) - err = p.Verify(pub) + ts.HelperSignProposal(rndValKey, prop) + err = prop.Verify(proposerKey.PublicKey()) assert.ErrorIs(t, crypto.ErrInvalidSignature, err) } @@ -89,26 +97,26 @@ func TestBasicCheck(t *testing.T) { t.Run("No signature", func(t *testing.T) { pub, _ := ts.RandBLSKeyPair() - d := ts.DecodingHex( + data := ts.DecodingHex( "a401186402000358c80140da9b641551048b59a859946ca7f9ab95c9cf84da488a1a5c49ba643b29b653dc223bc20a4e9ff03158165f3d42" + "4e2a74677bfe24a7295d1ce2e55ca3644cbe9a5a5e7d913b8e1ba6a020afbd5a25024a12b37cf8e1ed0b9498f91d75b294db0f95123d8593" + "05aa5deea3d4216777e74310b6a601bb4d4d6b13c9b295781ab1533aea032978d4f89305000000010004060f1b23010fab4f72234cc7c120" + "48bbbc616c005573d8ad4d5c6997996d6f488946cdd78410f0a400c4a7f9bdb41506bdf717a892fa0004f6") - p := &proposal.Proposal{} - err := cbor.Unmarshal(d, &p) + prop := &proposal.Proposal{} + err := cbor.Unmarshal(data, &prop) assert.NoError(t, err) - err = p.BasicCheck() + err = prop.BasicCheck() assert.ErrorIs(t, err, proposal.BasicCheckError{ Reason: "no signature", }) - err = p.Verify(pub) + err = prop.Verify(pub) assert.Error(t, err, crypto.ErrInvalidSignature) }) t.Run("Ok", func(t *testing.T) { - p, _ := ts.GenerateTestProposal(100, 0) - assert.NoError(t, p.BasicCheck()) + prop := ts.GenerateTestProposal(100, 0) + assert.NoError(t, prop.BasicCheck()) }) } diff --git a/types/tx/payload/bond_test.go b/types/tx/payload/bond_test.go index 2aca0192a..ae6eb80cf 100644 --- a/types/tx/payload/bond_test.go +++ b/types/tx/payload/bond_test.go @@ -236,35 +236,35 @@ func TestBondDecoding(t *testing.T) { }, } - for n, test := range tests { + for no, tt := range tests { pld := BondPayload{} - r := util.NewFixedReader(len(test.raw), test.raw) + r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(r) - if test.readErr != nil { - assert.ErrorIs(t, err, test.readErr) + if tt.readErr != nil { + assert.ErrorIs(t, err, tt.readErr) } else { assert.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) - require.Error(t, pld.Encode(w), "encode %v failed", n) + require.Error(t, pld.Encode(w), "encode %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Equal(t, pld.SerializeSize(), len(w.Bytes())) - assert.Equal(t, test.raw, w.Bytes()) + assert.Equal(t, tt.raw, w.Bytes()) // Basic check - if test.basicErr != nil { + if tt.basicErr != nil { err := pld.BasicCheck() - require.ErrorIs(t, err, test.basicErr, "basic check %v failed", n) + require.ErrorIs(t, err, tt.basicErr, "basic check %v failed", no) } else { assert.NoError(t, pld.BasicCheck()) // Check signer - assert.Equal(t, crypto.Address(test.raw[:21]), pld.Signer()) - assert.Equal(t, crypto.Address(test.raw[21:42]), *pld.Receiver()) - assert.Equal(t, test.value, pld.Value()) + assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) + assert.Equal(t, crypto.Address(tt.raw[21:42]), *pld.Receiver()) + assert.Equal(t, tt.value, pld.Value()) } } } diff --git a/types/tx/payload/sortition_test.go b/types/tx/payload/sortition_test.go index af7369981..de64df323 100644 --- a/types/tx/payload/sortition_test.go +++ b/types/tx/payload/sortition_test.go @@ -90,38 +90,38 @@ func TestSortitionDecoding(t *testing.T) { }, } - for n, test := range tests { + for no, tt := range tests { pld := SortitionPayload{} - r := util.NewFixedReader(len(test.raw), test.raw) + r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(r) - if test.readErr != nil { - assert.ErrorIs(t, err, test.readErr) + if tt.readErr != nil { + assert.ErrorIs(t, err, tt.readErr) } else { assert.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) - assert.Error(t, pld.Encode(w), "encode test %v failed", n) + assert.Error(t, pld.Encode(w), "encode test %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) assert.NoError(t, pld.Encode(w)) assert.Equal(t, pld.SerializeSize(), len(w.Bytes())) - assert.Equal(t, test.raw, w.Bytes()) + assert.Equal(t, tt.raw, w.Bytes()) // Basic check - if test.basicErr != nil { - assert.ErrorIs(t, pld.BasicCheck(), test.basicErr) + if tt.basicErr != nil { + assert.ErrorIs(t, pld.BasicCheck(), tt.basicErr) } else { assert.NoError(t, pld.BasicCheck()) // Check signer - if test.raw[0] != 0 { - assert.Equal(t, crypto.Address(test.raw[:21]), pld.Signer()) + if tt.raw[0] != 0 { + assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) } else { assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) } - assert.Equal(t, test.value, pld.Value()) + assert.Equal(t, tt.value, pld.Value()) assert.Nil(t, pld.Receiver()) } } diff --git a/types/tx/payload/transfer_test.go b/types/tx/payload/transfer_test.go index 8176add36..f0d5f6dbb 100644 --- a/types/tx/payload/transfer_test.go +++ b/types/tx/payload/transfer_test.go @@ -121,39 +121,39 @@ func TestTransferDecoding(t *testing.T) { }, } - for n, test := range tests { + for no, tt := range tests { pld := TransferPayload{} - r := util.NewFixedReader(len(test.raw), test.raw) + r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(r) - if test.readErr != nil { - assert.ErrorIs(t, err, test.readErr) + if tt.readErr != nil { + assert.ErrorIs(t, err, tt.readErr) } else { assert.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) - assert.Error(t, pld.Encode(w), "encode test %v failed", n) + assert.Error(t, pld.Encode(w), "encode test %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) assert.NoError(t, pld.Encode(w)) assert.Equal(t, pld.SerializeSize(), len(w.Bytes())) - assert.Equal(t, test.raw, w.Bytes()) + assert.Equal(t, tt.raw, w.Bytes()) // Basic check - if test.basicErr != nil { - assert.ErrorIs(t, pld.BasicCheck(), test.basicErr) + if tt.basicErr != nil { + assert.ErrorIs(t, pld.BasicCheck(), tt.basicErr) } else { assert.NoError(t, pld.BasicCheck()) // Check signer - if test.raw[0] != 0 { - assert.Equal(t, crypto.Address(test.raw[:21]), pld.Signer()) - assert.Equal(t, crypto.Address(test.raw[21:42]), *pld.Receiver()) + if tt.raw[0] != 0 { + assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) + assert.Equal(t, crypto.Address(tt.raw[21:42]), *pld.Receiver()) } else { assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) - assert.Equal(t, crypto.Address(test.raw[1:22]), *pld.Receiver()) + assert.Equal(t, crypto.Address(tt.raw[1:22]), *pld.Receiver()) } - assert.Equal(t, test.value, pld.Value()) + assert.Equal(t, tt.value, pld.Value()) } } } diff --git a/types/tx/tx.go b/types/tx/tx.go index 7e12a7cdc..ae02d45b3 100644 --- a/types/tx/tx.go +++ b/types/tx/tx.go @@ -69,13 +69,13 @@ func newTx(lockTime uint32, pld payload.Payload, fee amount.Amount, opts ...TxOp // FromBytes constructs a new transaction from byte array. func FromBytes(bs []byte) (*Tx, error) { - tx := new(Tx) + trx := new(Tx) r := bytes.NewReader(bs) - if err := tx.Decode(r); err != nil { + if err := trx.Decode(r); err != nil { return nil, err } - return tx, nil + return trx, nil } func (tx *Tx) Version() uint8 { @@ -208,8 +208,8 @@ func (tx *Tx) checkSignature() error { } } - bs := tx.SignBytes() - if err := tx.PublicKey().Verify(bs, tx.Signature()); err != nil { + signBytes := tx.SignBytes() + if err := tx.PublicKey().Verify(signBytes, tx.Signature()); err != nil { return BasicCheckError{ Reason: "invalid signature", } @@ -220,13 +220,13 @@ func (tx *Tx) checkSignature() error { // Bytes returns the serialized bytes for the Transaction. func (tx *Tx) Bytes() ([]byte, error) { - w := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) - err := tx.Encode(w) + buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) + err := tx.Encode(buf) if err != nil { return nil, err } - return w.Bytes(), nil + return buf.Bytes(), nil } func (tx *Tx) MarshalCBOR() ([]byte, error) { @@ -251,20 +251,20 @@ func (tx *Tx) UnmarshalCBOR(bs []byte) error { // SerializeSize returns the number of bytes it would take to serialize the transaction. func (tx *Tx) SerializeSize() int { - n := 7 + // flag (1) + version (1) + payload type (1) + lock_time (4) + size := 7 + // flag (1) + version (1) + payload type (1) + lock_time (4) encoding.VarIntSerializeSize(uint64(tx.Fee())) + encoding.VarStringSerializeSize(tx.Memo()) if tx.Payload() != nil { - n += tx.Payload().SerializeSize() + size += tx.Payload().SerializeSize() } if tx.data.Signature != nil { - n += tx.data.Signature.SerializeSize() + size += tx.data.Signature.SerializeSize() } if tx.data.PublicKey != nil { - n += tx.data.PublicKey.SerializeSize() + size += tx.data.PublicKey.SerializeSize() } - return n + return size } func (tx *Tx) Encode(w io.Writer) error { @@ -337,7 +337,7 @@ func (tx *Tx) Decode(r io.Reader) error { return err } - switch t := payload.Type(payloadType); t { + switch typ := payload.Type(payloadType); typ { case payload.TypeTransfer: tx.data.Payload = new(payload.TransferPayload) case payload.TypeBond: @@ -351,7 +351,7 @@ func (tx *Tx) Decode(r io.Reader) error { default: return InvalidPayloadTypeError{ - PayloadType: t, + PayloadType: typ, } } diff --git a/types/tx/tx_test.go b/types/tx/tx_test.go index f8c96dd6e..42b827be0 100644 --- a/types/tx/tx_test.go +++ b/types/tx/tx_test.go @@ -176,7 +176,7 @@ func TestBasicCheck(t *testing.T) { }) t.Run("Invalid version", func(t *testing.T) { - d := ts.DecodingHex( + data := ts.DecodingHex( "02" + // Flags "02" + // Version "01020304" + // LockTime @@ -187,20 +187,20 @@ func TestBasicCheck(t *testing.T) { "012222222222222222222222222222222222222222" + // Receiver "01") // Amount - trx, err := tx.FromBytes(d) + trx, err := tx.FromBytes(data) assert.NoError(t, err) err = trx.BasicCheck() assert.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid version: 2", }) - assert.Equal(t, len(d), trx.SerializeSize()) + assert.Equal(t, len(data), trx.SerializeSize()) }) } func TestInvalidPayloadType(t *testing.T) { ts := testsuite.NewTestSuite(t) - d := ts.DecodingHex( + data := ts.DecodingHex( "02" + // Flags "01" + // Version "01020300" + // LockTime @@ -211,7 +211,7 @@ func TestInvalidPayloadType(t *testing.T) { "012222222222222222222222222222222222222222" + // Receiver "01") // Amount - _, err := tx.FromBytes(d) + _, err := tx.FromBytes(data) assert.ErrorIs(t, err, tx.InvalidPayloadTypeError{ PayloadType: payload.Type(6), }) @@ -341,7 +341,7 @@ func TestInvalidSignature(t *testing.T) { } func TestSignBytesBLS(t *testing.T) { - d, _ := hex.DecodeString( + data, _ := hex.DecodeString( "00" + // Flags "01" + // Version "01020304" + // LockTime @@ -355,15 +355,15 @@ func TestSignBytesBLS(t *testing.T) { "b805043a816c3213c67f365f83c6946546049f517ebe470f186b36ff53fb996ae2468b119582a7f18fe8f0bfb4e055d5" + // PublicKey "190601a983fb4636c36287a73d80dbb14f244f319da5eeac02ce7ee9026245ac36b9978cabd6d2cbb3c1f87e55e2fc29") - h, _ := hash.FromString("7ab1287fe4882918e69b9f83215378ea08f2d91e0700c2e35a73b7aae1d7bf2d") - trx, err := tx.FromBytes(d) + txID, _ := hash.FromString("7ab1287fe4882918e69b9f83215378ea08f2d91e0700c2e35a73b7aae1d7bf2d") + trx, err := tx.FromBytes(data) assert.NoError(t, err) - assert.Equal(t, len(d), trx.SerializeSize()) + assert.Equal(t, len(data), trx.SerializeSize()) - sb := d[1 : len(d)-bls.PublicKeySize-bls.SignatureSize] - assert.Equal(t, sb, trx.SignBytes()) - assert.Equal(t, h, trx.ID()) - assert.Equal(t, hash.CalcHash(sb), trx.ID()) + signBytes := data[1 : len(data)-bls.PublicKeySize-bls.SignatureSize] + assert.Equal(t, signBytes, trx.SignBytes()) + assert.Equal(t, hash.CalcHash(signBytes), trx.ID()) + assert.Equal(t, txID, trx.ID()) assert.Equal(t, uint32(0x04030201), trx.LockTime()) assert.Equal(t, "test", trx.Memo()) assert.Equal(t, amount.Amount(1000), trx.Fee()) @@ -372,7 +372,7 @@ func TestSignBytesBLS(t *testing.T) { } func TestSignBytesEd25519(t *testing.T) { - d, _ := hex.DecodeString( + data, _ := hex.DecodeString( "00" + // Flags "01" + // Version "01020300" + // LockTime @@ -386,15 +386,15 @@ func TestSignBytesEd25519(t *testing.T) { "50ac25c7125271489b0cd230549257c93fb8c6265f2914a988ba7b81c1bc47ff" + // PublicKey "f027412dd59447867911035ff69742d171060a1f132ac38b95acc6e39ec0bd09") - h, _ := hash.FromString("34cd4656a98f7eb996e83efdc384cefbe3a9c52dca79a99245b4eacc0b0b4311") - trx, err := tx.FromBytes(d) + txID, _ := hash.FromString("34cd4656a98f7eb996e83efdc384cefbe3a9c52dca79a99245b4eacc0b0b4311") + trx, err := tx.FromBytes(data) assert.NoError(t, err) - assert.Equal(t, len(d), trx.SerializeSize()) + assert.Equal(t, len(data), trx.SerializeSize()) - sb := d[1 : len(d)-ed25519.PublicKeySize-ed25519.SignatureSize] - assert.Equal(t, sb, trx.SignBytes()) - assert.Equal(t, h, trx.ID()) - assert.Equal(t, hash.CalcHash(sb), trx.ID()) + signBytes := data[1 : len(data)-ed25519.PublicKeySize-ed25519.SignatureSize] + assert.Equal(t, signBytes, trx.SignBytes()) + assert.Equal(t, hash.CalcHash(signBytes), trx.ID()) + assert.Equal(t, txID, trx.ID()) assert.Equal(t, uint32(0x00030201), trx.LockTime()) assert.Equal(t, "test", trx.Memo()) assert.Equal(t, amount.Amount(1000), trx.Fee()) diff --git a/types/validator/validator.go b/types/validator/validator.go index fe2298ccd..bc859f630 100644 --- a/types/validator/validator.go +++ b/types/validator/validator.go @@ -41,14 +41,14 @@ func NewValidator(publicKey *bls.PublicKey, number int32) *Validator { // FromBytes constructs a new validator from a byte array. func FromBytes(data []byte) (*Validator, error) { acc := new(Validator) - r := bytes.NewReader(data) + reader := bytes.NewReader(data) acc.data.PublicKey = new(bls.PublicKey) - if err := acc.data.PublicKey.Decode(r); err != nil { + if err := acc.data.PublicKey.Decode(reader); err != nil { return nil, err } - err := encoding.ReadElements(r, + err := encoding.ReadElements(reader, &acc.data.Number, &acc.data.Stake, &acc.data.LastBondingHeight, @@ -152,13 +152,13 @@ func (*Validator) SerializeSize() int { // Bytes returns the serialized byte representation of the validator. func (val *Validator) Bytes() ([]byte, error) { - w := bytes.NewBuffer(make([]byte, 0, val.SerializeSize())) + buf := bytes.NewBuffer(make([]byte, 0, val.SerializeSize())) - if err := val.data.PublicKey.Encode(w); err != nil { + if err := val.data.PublicKey.Encode(buf); err != nil { return nil, err } - err := encoding.WriteElements(w, + err := encoding.WriteElements(buf, val.data.Number, val.data.Stake, val.data.LastBondingHeight, @@ -168,7 +168,7 @@ func (val *Validator) Bytes() ([]byte, error) { return nil, err } - return w.Bytes(), nil + return buf.Bytes(), nil } // Clone creates a deep copy of the validator. diff --git a/types/validator/validator_test.go b/types/validator/validator_test.go index f460ffe16..53dcd6bf9 100644 --- a/types/validator/validator_test.go +++ b/types/validator/validator_test.go @@ -20,10 +20,10 @@ func TestFromBytes(t *testing.T) { val.UpdateLastBondingHeight(ts.RandHeight()) val.UpdateLastSortitionHeight(ts.RandHeight()) val.UpdateUnbondingHeight(ts.RandHeight()) - bs, err := val.Bytes() + data, err := val.Bytes() require.NoError(t, err) - require.Equal(t, val.SerializeSize(), len(bs)) - val2, err := validator.FromBytes(bs) + require.Equal(t, val.SerializeSize(), len(data)) + val2, err := validator.FromBytes(data) require.NoError(t, err) assert.Equal(t, val.Address(), val2.Address()) assert.Equal(t, val.Number(), val2.Number()) @@ -35,13 +35,13 @@ func TestFromBytes(t *testing.T) { _, err = validator.FromBytes([]byte("asdfghjkl")) require.Error(t, err) - bs = bs[:len(bs)-1] - _, err = validator.FromBytes(bs) + data = data[:len(data)-1] + _, err = validator.FromBytes(data) require.Error(t, err) } func TestDecoding(t *testing.T) { - d, _ := hex.DecodeString( + data, _ := hex.DecodeString( "8d82fa4fcac04a3b565267685e90db1b01420285d2f8295683c138c092c209479983ba1591370778846681b7b558e061" + // PublicKey "1776208c0718006311c84b4a113335c70d1f5c7c5dd93a5625c4af51c48847abd0b590c055306162d2a03ca1cbf7bcc1" + "01000000" + // Number @@ -50,7 +50,7 @@ func TestDecoding(t *testing.T) { "04000000" + // UnbondingHeight "05000000") // LastSortitionHeight - val, err := validator.FromBytes(d) + val, err := validator.FromBytes(data) require.NoError(t, err) assert.Equal(t, int32(1), val.Number()) assert.Equal(t, amount.Amount(2), val.Stake()) @@ -58,13 +58,13 @@ func TestDecoding(t *testing.T) { assert.Equal(t, uint32(4), val.UnbondingHeight()) assert.Equal(t, uint32(5), val.LastSortitionHeight()) d2, _ := val.Bytes() - assert.Equal(t, d, d2) - assert.Equal(t, hash.CalcHash(d), val.Hash()) + assert.Equal(t, data, d2) + assert.Equal(t, hash.CalcHash(data), val.Hash()) expected, _ := hash.FromString("243e65ae04727f21d5f7618cea9ff8d4bc82fded1179cf8bd9e11a6b99ac42b2") assert.Equal(t, expected, val.Hash()) - pub, _ := bls.PublicKeyFromBytes(d[:96]) + pub, _ := bls.PublicKeyFromBytes(data[:96]) assert.True(t, val.PublicKey().EqualsTo(pub)) - assert.Equal(t, len(d), val.SerializeSize()) + assert.Equal(t, len(data), val.SerializeSize()) } func TestPower(t *testing.T) { diff --git a/types/vote/vote.go b/types/vote/vote.go index 9fdb6eeac..50e976da5 100644 --- a/types/vote/vote.go +++ b/types/vote/vote.go @@ -39,42 +39,42 @@ func NewPrecommitVote(blockHash hash.Hash, height uint32, round int16, signer cr func NewCPPreVote(blockHash hash.Hash, height uint32, round int16, cpRound int16, cpValue CPValue, just Just, signer crypto.Address, ) *Vote { - v := newVote(VoteTypeCPPreVote, blockHash, height, round, signer) - v.data.CPVote = &cpVote{ + vote := newVote(VoteTypeCPPreVote, blockHash, height, round, signer) + vote.data.CPVote = &cpVote{ Round: cpRound, Value: cpValue, Just: just, } - return v + return vote } // NewCPMainVote creates a new cp:MAIN-VOTE with the specified parameters. func NewCPMainVote(blockHash hash.Hash, height uint32, round int16, cpRound int16, cpValue CPValue, just Just, signer crypto.Address, ) *Vote { - v := newVote(VoteTypeCPMainVote, blockHash, height, round, signer) - v.data.CPVote = &cpVote{ + vote := newVote(VoteTypeCPMainVote, blockHash, height, round, signer) + vote.data.CPVote = &cpVote{ Round: cpRound, Value: cpValue, Just: just, } - return v + return vote } // NewCPDecidedVote creates a new cp:Decided with the specified parameters. func NewCPDecidedVote(blockHash hash.Hash, height uint32, round int16, cpRound int16, cpValue CPValue, just Just, signer crypto.Address, ) *Vote { - v := newVote(VoteTypeCPDecided, blockHash, height, round, signer) - v.data.CPVote = &cpVote{ + vote := newVote(VoteTypeCPDecided, blockHash, height, round, signer) + vote.data.CPVote = &cpVote{ Round: cpRound, Value: cpValue, Just: just, } - return v + return vote } // newVote creates a new vote with the specified parameters. @@ -94,24 +94,24 @@ func newVote(voteType Type, blockHash hash.Hash, height uint32, round int16, // SignBytes generates the bytes to be signed for the vote. func (v *Vote) SignBytes() []byte { - sb := v.data.BlockHash.Bytes() - sb = append(sb, util.Uint32ToSlice(v.data.Height)...) - sb = append(sb, util.Int16ToSlice(v.data.Round)...) + signBytes := v.data.BlockHash.Bytes() + signBytes = append(signBytes, util.Uint32ToSlice(v.data.Height)...) + signBytes = append(signBytes, util.Int16ToSlice(v.data.Round)...) - switch t := v.Type(); t { + switch typ := v.Type(); typ { case VoteTypePrecommit: // Nothing case VoteTypePrepare: - sb = append(sb, util.StringToBytes(t.String())...) + signBytes = append(signBytes, util.StringToBytes(typ.String())...) case VoteTypeCPPreVote, VoteTypeCPMainVote, VoteTypeCPDecided: - sb = append(sb, util.StringToBytes(t.String())...) - sb = append(sb, util.Int16ToSlice(v.data.CPVote.Round)...) - sb = append(sb, byte(v.data.CPVote.Value)) + signBytes = append(signBytes, util.StringToBytes(typ.String())...) + signBytes = append(signBytes, util.Int16ToSlice(v.data.CPVote.Round)...) + signBytes = append(signBytes, byte(v.data.CPVote.Value)) } - return sb + return signBytes } // Type returns the type of the vote. diff --git a/types/vote/vote_test.go b/types/vote/vote_test.go index ed05464b3..712f0a9e9 100644 --- a/types/vote/vote_test.go +++ b/types/vote/vote_test.go @@ -194,29 +194,29 @@ func TestVoteMarshaling(t *testing.T) { } ts := testsuite.NewTestSuite(t) - for _, test := range tests { - bz1, _ := hex.DecodeString(test.data) + for _, tt := range tests { + bz1, _ := hex.DecodeString(tt.data) - v := new(vote.Vote) - err := v.UnmarshalCBOR(bz1) + vote := new(vote.Vote) + err := vote.UnmarshalCBOR(bz1) assert.NoError(t, err) - bz2, err := v.MarshalCBOR() + bz2, err := vote.MarshalCBOR() assert.NoError(t, err) assert.Equal(t, bz1, bz2) expectedHash := hash.CalcHash(bz1) - assert.Equal(t, expectedHash, v.Hash()) + assert.Equal(t, expectedHash, vote.Hash()) - v.SetSignature(ts.RandBLSSignature()) - assert.NoError(t, v.BasicCheck()) + vote.SetSignature(ts.RandBLSSignature()) + assert.NoError(t, vote.BasicCheck()) - expectedSignBytes, _ := hex.DecodeString(test.signBytes) - assert.Equal(t, expectedSignBytes, v.SignBytes()) + expectedSignBytes, _ := hex.DecodeString(tt.signBytes) + assert.Equal(t, expectedSignBytes, vote.SignBytes()) - if test.justType != "" { - assert.Equal(t, test.justType, v.CPJust().Type().String()) + if tt.justType != "" { + assert.Equal(t, tt.justType, vote.CPJust().Type().String()) } } } @@ -224,131 +224,132 @@ func TestVoteMarshaling(t *testing.T) { func TestVoteSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) - h1 := ts.RandHash() - pb1, pv1 := ts.RandBLSKeyPair() - pb2, pv2 := ts.RandBLSKeyPair() + hash1 := ts.RandHash() + pub1, prv1 := ts.RandBLSKeyPair() + pub2, prv2 := ts.RandBLSKeyPair() - v1 := vote.NewPrepareVote(h1, 101, 5, pb1.ValidatorAddress()) - v2 := vote.NewPrepareVote(h1, 101, 5, pb2.ValidatorAddress()) + vote1 := vote.NewPrepareVote(hash1, 101, 5, pub1.ValidatorAddress()) + vote2 := vote.NewPrepareVote(hash1, 101, 5, pub2.ValidatorAddress()) - assert.Error(t, v1.BasicCheck(), "No signature") + assert.Error(t, vote1.BasicCheck(), "No signature") - sig1 := pv1.SignNative(v1.SignBytes()) - v1.SetSignature(sig1) - err1 := v1.Verify(pb1) + sig1 := prv1.SignNative(vote1.SignBytes()) + vote1.SetSignature(sig1) + err1 := vote1.Verify(pub1) assert.NoError(t, err1, "Ok") - sig2 := pv2.SignNative(v2.SignBytes()) - v2.SetSignature(sig2) - err2 := v2.Verify(pb1) + sig2 := prv2.SignNative(vote2.SignBytes()) + vote2.SetSignature(sig2) + err2 := vote2.Verify(pub1) assert.ErrorIs(t, err2, vote.InvalidSignerError{ - Expected: pb1.ValidatorAddress(), - Got: pb2.ValidatorAddress(), + Expected: pub1.ValidatorAddress(), + Got: pub2.ValidatorAddress(), }) - sig3 := pv1.SignNative(v2.SignBytes()) - v2.SetSignature(sig3) - err3 := v2.Verify(pb2) + sig3 := prv1.SignNative(vote2.SignBytes()) + vote2.SetSignature(sig3) + err3 := vote2.Verify(pub2) assert.ErrorIs(t, err3, crypto.ErrInvalidSignature) } func TestCPPreVote(t *testing.T) { ts := testsuite.NewTestSuite(t) - h := ts.RandHeight() - r := ts.RandRound() + height := ts.RandHeight() + round := ts.RandRound() just := &vote.JustInitYes{} t.Run("Invalid CP round", func(t *testing.T) { invalidCPRound := int16(-1) - v := vote.NewCPPreVote(hash.UndefHash, h, r, + cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, invalidCPRound, vote.CPValueYes, just, ts.RandAccAddress()) - err := v.BasicCheck() + err := cpVote.BasicCheck() assert.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP round"}) }) t.Run("invalid CP value", func(t *testing.T) { invalidCPValue := vote.CPValue(3) - v := vote.NewCPPreVote(hash.UndefHash, h, r, + cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, 1, invalidCPValue, just, ts.RandAccAddress()) - err := v.BasicCheck() + err := cpVote.BasicCheck() assert.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP value"}) }) t.Run("Ok", func(t *testing.T) { - v := vote.NewCPPreVote(hash.UndefHash, h, r, + cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, 1, vote.CPValueNo, just, ts.RandAccAddress()) - v.SetSignature(ts.RandBLSSignature()) + cpVote.SetSignature(ts.RandBLSSignature()) - err := v.BasicCheck() + err := cpVote.BasicCheck() assert.NoError(t, err) - assert.Equal(t, int16(1), v.CPRound()) - assert.Equal(t, vote.CPValueNo, v.CPValue()) - assert.NotNil(t, v.CPJust()) + assert.Equal(t, int16(1), cpVote.CPRound()) + assert.Equal(t, vote.CPValueNo, cpVote.CPValue()) + assert.NotNil(t, cpVote.CPJust()) }) } func TestCPMainVote(t *testing.T) { ts := testsuite.NewTestSuite(t) - h := ts.RandHeight() - r := ts.RandRound() + height := ts.RandHeight() + round := ts.RandRound() just := &vote.JustInitYes{} t.Run("Invalid CP round", func(t *testing.T) { invalidCPRound := int16(-1) - v := vote.NewCPMainVote(hash.UndefHash, h, r, + invVote := vote.NewCPMainVote(hash.UndefHash, height, round, invalidCPRound, vote.CPValueNo, just, ts.RandAccAddress()) - err := v.BasicCheck() + err := invVote.BasicCheck() assert.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP round"}) }) t.Run("No CP data", func(t *testing.T) { - data, _ := hex.DecodeString("A701040218320301045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + - "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA06f607f6") - v := new(vote.Vote) - _ = v.UnmarshalCBOR(data) - v.SetSignature(ts.RandBLSSignature()) - - err := v.BasicCheck() + data, _ := hex.DecodeString( + "A701040218320301045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + + "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA06f607f6") + decVote := new(vote.Vote) + _ = decVote.UnmarshalCBOR(data) + decVote.SetSignature(ts.RandBLSSignature()) + + err := decVote.BasicCheck() assert.ErrorIs(t, err, vote.BasicCheckError{Reason: "should have CP data"}) }) t.Run("Invalid CP value", func(t *testing.T) { invalidCPValue := vote.CPValue(3) - v := vote.NewCPMainVote(hash.UndefHash, h, r, + cpVote := vote.NewCPMainVote(hash.UndefHash, height, round, 1, invalidCPValue, just, ts.RandAccAddress()) - err := v.BasicCheck() + err := cpVote.BasicCheck() assert.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP value"}) }) t.Run("Ok", func(t *testing.T) { - v := vote.NewCPMainVote(hash.UndefHash, h, r, + cpVote := vote.NewCPMainVote(hash.UndefHash, height, round, 1, vote.CPValueAbstain, just, ts.RandAccAddress()) - v.SetSignature(ts.RandBLSSignature()) + cpVote.SetSignature(ts.RandBLSSignature()) - err := v.BasicCheck() + err := cpVote.BasicCheck() assert.NoError(t, err) - assert.Equal(t, int16(1), v.CPRound()) - assert.Equal(t, vote.CPValueAbstain, v.CPValue()) - assert.NotNil(t, v.CPJust()) + assert.Equal(t, int16(1), cpVote.CPRound()) + assert.Equal(t, vote.CPValueAbstain, cpVote.CPValue()) + assert.NotNil(t, cpVote.CPJust()) }) } func TestCPDecided(t *testing.T) { ts := testsuite.NewTestSuite(t) - h := ts.RandHeight() - r := ts.RandRound() + height := ts.RandHeight() + round := ts.RandRound() just := &vote.JustInitYes{} t.Run("Invalid round", func(t *testing.T) { invalidCPRound := int16(-1) - v := vote.NewCPDecidedVote(hash.UndefHash, h, r, + v := vote.NewCPDecidedVote(hash.UndefHash, height, round, invalidCPRound, vote.CPValueNo, just, ts.RandAccAddress()) err := v.BasicCheck() @@ -368,7 +369,7 @@ func TestCPDecided(t *testing.T) { t.Run("Invalid CP value", func(t *testing.T) { invalidCPValue := vote.CPValue(3) - v := vote.NewCPDecidedVote(hash.UndefHash, h, r, + v := vote.NewCPDecidedVote(hash.UndefHash, height, round, 1, invalidCPValue, just, ts.RandAccAddress()) err := v.BasicCheck() @@ -376,15 +377,15 @@ func TestCPDecided(t *testing.T) { }) t.Run("Ok", func(t *testing.T) { - v := vote.NewCPDecidedVote(hash.UndefHash, h, r, + vte := vote.NewCPDecidedVote(hash.UndefHash, height, round, 1, vote.CPValueAbstain, just, ts.RandAccAddress()) - v.SetSignature(ts.RandBLSSignature()) + vte.SetSignature(ts.RandBLSSignature()) - err := v.BasicCheck() + err := vte.BasicCheck() assert.NoError(t, err) - assert.Equal(t, int16(1), v.CPRound()) - assert.Equal(t, vote.CPValueAbstain, v.CPValue()) - assert.NotNil(t, v.CPJust()) + assert.Equal(t, int16(1), vte.CPRound()) + assert.Equal(t, vote.CPValueAbstain, vte.CPValue()) + assert.NotNil(t, vte.CPJust()) }) } @@ -452,28 +453,28 @@ func TestSignBytes(t *testing.T) { cpRound := int16(10) just := &vote.JustInitNo{} - v1 := vote.NewPrepareVote(blockHash, height, round, signer) - v2 := vote.NewPrecommitVote(blockHash, height, round, signer) - v3 := vote.NewCPPreVote(blockHash, height, round, cpRound, vote.CPValueNo, just, signer) - v4 := vote.NewCPMainVote(blockHash, height, round, cpRound, vote.CPValueAbstain, just, signer) - v5 := vote.NewCPDecidedVote(blockHash, height, round, cpRound, vote.CPValueYes, just, signer) - - sb1 := v1.SignBytes() - sb2 := v2.SignBytes() - sb3 := v3.SignBytes() - sb4 := v4.SignBytes() - sb5 := v5.SignBytes() - - assert.Equal(t, 45, len(sb1)) - assert.Equal(t, 38, len(sb2)) - assert.Equal(t, 49, len(sb3)) - assert.Equal(t, 50, len(sb4)) - assert.Equal(t, 48, len(sb5)) - - assert.Contains(t, string(sb1), "PREPARE") - assert.Contains(t, string(sb3), "PRE-VOTE") - assert.Contains(t, string(sb4), "MAIN-VOTE") - assert.Contains(t, string(sb5), "DECIDED") + vote1 := vote.NewPrepareVote(blockHash, height, round, signer) + vote2 := vote.NewPrecommitVote(blockHash, height, round, signer) + vote3 := vote.NewCPPreVote(blockHash, height, round, cpRound, vote.CPValueNo, just, signer) + vote4 := vote.NewCPMainVote(blockHash, height, round, cpRound, vote.CPValueAbstain, just, signer) + vote5 := vote.NewCPDecidedVote(blockHash, height, round, cpRound, vote.CPValueYes, just, signer) + + sby1 := vote1.SignBytes() + sby2 := vote2.SignBytes() + sby3 := vote3.SignBytes() + sby4 := vote4.SignBytes() + sby5 := vote5.SignBytes() + + assert.Equal(t, 45, len(sby1)) + assert.Equal(t, 38, len(sby2)) + assert.Equal(t, 49, len(sby3)) + assert.Equal(t, 50, len(sby4)) + assert.Equal(t, 48, len(sby5)) + + assert.Contains(t, string(sby1), "PREPARE") + assert.Contains(t, string(sby3), "PRE-VOTE") + assert.Contains(t, string(sby4), "MAIN-VOTE") + assert.Contains(t, string(sby5), "DECIDED") } func TestLog(t *testing.T) { diff --git a/util/bech32m/bech32m.go b/util/bech32m/bech32m.go index a1dda826e..60adc83e4 100644 --- a/util/bech32m/bech32m.go +++ b/util/bech32m/bech32m.go @@ -173,15 +173,15 @@ func DecodeNoLimit(bech string) (string, []byte, error) { // Only ASCII characters between 33 and 126 are allowed. var hasLower, hasUpper bool - for i := 0; i < len(bech); i++ { - if bech[i] < 33 || bech[i] > 126 { - return "", nil, InvalidCharacterError(bech[i]) + for index := 0; index < len(bech); index++ { + if bech[index] < 33 || bech[index] > 126 { + return "", nil, InvalidCharacterError(bech[index]) } // The characters must be either all lowercase or all uppercase. Testing // directly with ascii codes is safe here, given the previous test. - hasLower = hasLower || (bech[i] >= 97 && bech[i] <= 122) - hasUpper = hasUpper || (bech[i] >= 65 && bech[i] <= 90) + hasLower = hasLower || (bech[index] >= 97 && bech[index] <= 122) + hasUpper = hasUpper || (bech[index] >= 65 && bech[index] <= 90) if hasLower && hasUpper { return "", nil, MixedCaseError{} } @@ -303,9 +303,9 @@ func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) nextByte := byte(0) filledBits := uint8(0) - for _, b := range data { + for _, byt := range data { // Discard unused bits. - b <<= (8 - fromBits) + byt <<= (8 - fromBits) // How many bits remaining to extract from the input data. remFromBits := fromBits @@ -322,11 +322,11 @@ func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) // Add the next bits to nextByte, shifting the already // added bits to the left. - nextByte = (nextByte << toExtract) | (b >> (8 - toExtract)) + nextByte = (nextByte << toExtract) | (byt >> (8 - toExtract)) // Discard the bits we just extracted and get ready for // next iteration. - b <<= toExtract + byt <<= toExtract remFromBits -= toExtract filledBits += toExtract diff --git a/util/bech32m/bech32m_test.go b/util/bech32m/bech32m_test.go index 0478b0d4a..cd5a88586 100644 --- a/util/bech32m/bech32m_test.go +++ b/util/bech32m/bech32m_test.go @@ -55,12 +55,12 @@ func TestBech32M(t *testing.T) { {"\x801eym55h", InvalidCharacterError(0x80)}, } - for i, test := range tests { - str := test.str + for no, tt := range tests { + str := tt.str hrp, decoded, err := Decode(str) - if !errors.Is(err, test.expectedError) { + if !errors.Is(err, tt.expectedError) { t.Errorf("%d: (%v) expected decoding error %v "+ - "instead got %v", i, str, test.expectedError, + "instead got %v", no, str, tt.expectedError, err) continue @@ -128,60 +128,60 @@ func TestMixedCaseEncode(t *testing.T) { encoded: "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lwusvrv", }} - for _, test := range tests { + for _, tt := range tests { // Convert the text hex to bytes, convert those bytes from base256 to // base32, then ensure the encoded result with the HRP provided in the // test data is as expected. - data, err := hex.DecodeString(test.data) + data, err := hex.DecodeString(tt.data) if err != nil { - t.Errorf("%q: invalid hex %q: %v", test.name, test.data, err) + t.Errorf("%q: invalid hex %q: %v", tt.name, tt.data, err) continue } convertedData, err := ConvertBits(data, 8, 5, true) if err != nil { - t.Errorf("%q: unexpected convert bits error: %v", test.name, + t.Errorf("%q: unexpected convert bits error: %v", tt.name, err) continue } - gotEncoded, err := Encode(test.hrp, convertedData) + gotEncoded, err := Encode(tt.hrp, convertedData) if err != nil { - t.Errorf("%q: unexpected encode error: %v", test.name, err) + t.Errorf("%q: unexpected encode error: %v", tt.name, err) continue } - if gotEncoded != test.encoded { - t.Errorf("%q: mismatched encoding -- got %q, want %q", test.name, - gotEncoded, test.encoded) + if gotEncoded != tt.encoded { + t.Errorf("%q: mismatched encoding -- got %q, want %q", tt.name, + gotEncoded, tt.encoded) continue } // Ensure the decoding the expected lowercase encoding converted to all // uppercase produces the lowercase HRP and original data. - gotHRP, gotData, err := Decode(strings.ToUpper(test.encoded)) + gotHRP, gotData, err := Decode(strings.ToUpper(tt.encoded)) if err != nil { - t.Errorf("%q: unexpected decode error: %v", test.name, err) + t.Errorf("%q: unexpected decode error: %v", tt.name, err) continue } - wantHRP := strings.ToLower(test.hrp) + wantHRP := strings.ToLower(tt.hrp) if gotHRP != wantHRP { - t.Errorf("%q: mismatched decoded HRP -- got %q, want %q", test.name, + t.Errorf("%q: mismatched decoded HRP -- got %q, want %q", tt.name, gotHRP, wantHRP) continue } convertedGotData, err := ConvertBits(gotData, 5, 8, false) if err != nil { - t.Errorf("%q: unexpected convert bits error: %v", test.name, + t.Errorf("%q: unexpected convert bits error: %v", tt.name, err) continue } if !bytes.Equal(convertedGotData, data) { - t.Errorf("%q: mismatched data -- got %x, want %x", test.name, + t.Errorf("%q: mismatched data -- got %x, want %x", tt.name, convertedGotData, data) continue @@ -296,13 +296,13 @@ func TestBech32Base256(t *testing.T) { err: MixedCaseError{}, }} - for _, test := range tests { + for _, tt := range tests { // Ensure the decode either produces an error or not as expected. - str := test.encoded + str := tt.encoded gotHRP, gotData, err := DecodeToBase256(str) - if !errors.Is(test.err, err) { + if !errors.Is(tt.err, err) { t.Errorf("%q: unexpected decode error -- got %v, want %v", - test.name, err, test.err) + tt.name, err, tt.err) continue } @@ -312,20 +312,20 @@ func TestBech32Base256(t *testing.T) { } // Ensure the expected HRP and original data are as expected. - if gotHRP != test.hrp { - t.Errorf("%q: mismatched decoded HRP -- got %q, want %q", test.name, - gotHRP, test.hrp) + if gotHRP != tt.hrp { + t.Errorf("%q: mismatched decoded HRP -- got %q, want %q", tt.name, + gotHRP, tt.hrp) continue } - data, err := hex.DecodeString(test.data) + data, err := hex.DecodeString(tt.data) if err != nil { - t.Errorf("%q: invalid hex %q: %v", test.name, test.data, err) + t.Errorf("%q: invalid hex %q: %v", tt.name, tt.data, err) continue } if !bytes.Equal(gotData, data) { - t.Errorf("%q: mismatched data -- got %x, want %x", test.name, + t.Errorf("%q: mismatched data -- got %x, want %x", tt.name, gotData, data) continue @@ -334,27 +334,27 @@ func TestBech32Base256(t *testing.T) { // Encode the same data with the HRP converted to all uppercase and // ensure the result is the lowercase version of the original encoded // bech32 string. - gotEncoded, err := EncodeFromBase256(strings.ToUpper(test.hrp), data) + gotEncoded, err := EncodeFromBase256(strings.ToUpper(tt.hrp), data) if err != nil { - t.Errorf("%q: unexpected uppercase HRP encode error: %v", test.name, + t.Errorf("%q: unexpected uppercase HRP encode error: %v", tt.name, err) } wantEncoded := strings.ToLower(str) if gotEncoded != wantEncoded { - t.Errorf("%q: mismatched encoding -- got %q, want %q", test.name, + t.Errorf("%q: mismatched encoding -- got %q, want %q", tt.name, gotEncoded, wantEncoded) } // Encode the same data with the HRP converted to all lowercase and // ensure the result is the lowercase version of the original encoded // bech32 string. - gotEncoded, err = EncodeFromBase256(strings.ToLower(test.hrp), data) + gotEncoded, err = EncodeFromBase256(strings.ToLower(tt.hrp), data) if err != nil { - t.Errorf("%q: unexpected lowercase HRP encode error: %v", test.name, + t.Errorf("%q: unexpected lowercase HRP encode error: %v", tt.name, err) } if gotEncoded != wantEncoded { - t.Errorf("%q: mismatched encoding -- got %q, want %q", test.name, + t.Errorf("%q: mismatched encoding -- got %q, want %q", tt.name, gotEncoded, wantEncoded) } @@ -362,26 +362,26 @@ func TestBech32Base256(t *testing.T) { // lowercase and ensure the result is the lowercase version of the // original encoded bech32 string. var mixedHRPBuilder strings.Builder - for i, r := range test.hrp { - if i%2 == 0 { - mixedHRPBuilder.WriteString(strings.ToUpper(string(r))) + for index, chr := range tt.hrp { + if index%2 == 0 { + mixedHRPBuilder.WriteString(strings.ToUpper(string(chr))) continue } - mixedHRPBuilder.WriteRune(r) + mixedHRPBuilder.WriteRune(chr) } gotEncoded, err = EncodeFromBase256(mixedHRPBuilder.String(), data) if err != nil { - t.Errorf("%q: unexpected lowercase HRP encode error: %v", test.name, + t.Errorf("%q: unexpected lowercase HRP encode error: %v", tt.name, err) } if gotEncoded != wantEncoded { - t.Errorf("%q: mismatched encoding -- got %q, want %q", test.name, + t.Errorf("%q: mismatched encoding -- got %q, want %q", tt.name, gotEncoded, wantEncoded) } // Ensure a bit flip in the string is caught. - pos := strings.LastIndexAny(test.encoded, "1") + pos := strings.LastIndexAny(tt.encoded, "1") flipped := str[:pos+1] + string((str[pos+1] ^ 1)) + str[pos+2:] _, _, err = DecodeToBase256(flipped) if err == nil { @@ -488,25 +488,25 @@ func TestConvertBits(t *testing.T) { }, } - for i, tc := range tests { - input, err := hex.DecodeString(tc.input) + for no, tt := range tests { + input, err := hex.DecodeString(tt.input) if err != nil { t.Fatalf("invalid test input data: %v", err) } - expected, err := hex.DecodeString(tc.output) + expected, err := hex.DecodeString(tt.output) if err != nil { t.Fatalf("invalid test output data: %v", err) } - actual, err := ConvertBits(input, tc.fromBits, tc.toBits, tc.pad) + actual, err := ConvertBits(input, tt.fromBits, tt.toBits, tt.pad) if err != nil { - t.Fatalf("test case %d failed: %v", i, err) + t.Fatalf("test case %d failed: %v", no, err) } if !bytes.Equal(actual, expected) { t.Fatalf("test case %d has wrong output; expected=%x actual=%x", - i, expected, actual) + no, expected, actual) } } } @@ -532,16 +532,16 @@ func TestConvertBitsFailures(t *testing.T) { {"", 5, 10, false, InvalidBitGroupsError{}}, } - for i, tc := range tests { - input, err := hex.DecodeString(tc.input) + for no, tt := range tests { + input, err := hex.DecodeString(tt.input) if err != nil { t.Fatalf("invalid test input data: %v", err) } - _, err = ConvertBits(input, tc.fromBits, tc.toBits, tc.pad) - if !errors.Is(err, tc.err) { - t.Fatalf("test case %d failure: expected '%v' got '%v'", i, - tc.err, err) + _, err = ConvertBits(input, tt.fromBits, tt.toBits, tt.pad) + if !errors.Is(err, tt.err) { + t.Fatalf("test case %d failure: expected '%v' got '%v'", no, + tt.err, err) } } } @@ -609,20 +609,20 @@ func TestEncodeFromBase256WithType(t *testing.T) { {"", 32, "1", "", InvalidDataByteError(32)}, } - for i, tc := range tests { - data, _ := hex.DecodeString(tc.input) - enc, err := EncodeFromBase256WithType(tc.hrp, tc.typ, data) - if !errors.Is(err, tc.expectedError) { + for no, tt := range tests { + data, _ := hex.DecodeString(tt.input) + enc, err := EncodeFromBase256WithType(tt.hrp, tt.typ, data) + if !errors.Is(err, tt.expectedError) { t.Errorf("%d: (%v) expected encoding error "+ - "instead got %v", i, tc.expectedError, + "instead got %v", no, tt.expectedError, err) continue } - if enc != tc.expectedBech { - t.Errorf("%d: mismatched encoding -- got %q, want %q", i, - enc, tc.expectedBech) + if enc != tt.expectedBech { + t.Errorf("%d: mismatched encoding -- got %q, want %q", no, + enc, tt.expectedBech) } } } @@ -643,30 +643,30 @@ func TestDecodeToBase256WithTypeNoLimit(t *testing.T) { {"a1lqfn3a", "", 0, "", InvalidLengthError(0)}, } - for i, tc := range tests { - hrp, typ, data, err := DecodeToBase256WithTypeNoLimit(tc.bech) - if !errors.Is(err, tc.expectedError) { + for no, tt := range tests { + hrp, typ, data, err := DecodeToBase256WithTypeNoLimit(tt.bech) + if !errors.Is(err, tt.expectedError) { t.Errorf("%d: (%v) expected encoding error "+ - "instead got %v", i, tc.expectedError, + "instead got %v", no, tt.expectedError, err) continue } - if hrp != tc.expectedHRP { - t.Errorf("%d: mismatched HRP -- got %q, want %q", i, - hrp, tc.expectedHRP) + if hrp != tt.expectedHRP { + t.Errorf("%d: mismatched HRP -- got %q, want %q", no, + hrp, tt.expectedHRP) } - if typ != tc.expectedTyp { - t.Errorf("%d: mismatched Type -- got %q, want %q", i, - typ, tc.expectedTyp) + if typ != tt.expectedTyp { + t.Errorf("%d: mismatched Type -- got %q, want %q", no, + typ, tt.expectedTyp) } - expectedData, _ := hex.DecodeString(tc.expectedData) + expectedData, _ := hex.DecodeString(tt.expectedData) if !bytes.Equal(expectedData, data) { - t.Errorf("%d: mismatched HRP -- got \"%x\", want %q", i, - data, tc.expectedData) + t.Errorf("%d: mismatched HRP -- got \"%x\", want %q", no, + data, tt.expectedData) } } } diff --git a/util/downloader/downloader.go b/util/downloader/downloader.go index 06e2d2567..11d116a40 100644 --- a/util/downloader/downloader.go +++ b/util/downloader/downloader.go @@ -107,7 +107,7 @@ func (d *Downloader) download(ctx context.Context) { d.statsCh <- stats var wg sync.WaitGroup - for _, c := range d.chunks { + for _, chuck := range d.chunks { wg.Add(1) go func(c *chunk) { defer wg.Done() @@ -117,7 +117,7 @@ func (d *Downloader) download(ctx context.Context) { return } - }(c) + }(chuck) } wg.Wait() @@ -167,13 +167,13 @@ func (d *Downloader) createDir() error { return nil } -func (d *Downloader) downloadChunkWithContext(ctx context.Context, out *os.File, c *chunk, totalSize int64) error { +func (d *Downloader) downloadChunkWithContext(ctx context.Context, out *os.File, chuck *chunk, totalSize int64) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.url, http.NoBody) if err != nil { return &Error{Message: "failed to create new request for download chunk", Reason: err} } - req.Header.Set("Range", c.rangeHeader()) + req.Header.Set("Range", chuck.rangeHeader()) resp, err := d.client.Do(req) if err != nil { return &Error{Message: "failed to do request download chunk", Reason: err} @@ -191,22 +191,22 @@ func (d *Downloader) downloadChunkWithContext(ctx context.Context, out *os.File, } buf := make([]byte, 32*1024) // 32KB buffer for reading the response body - offset := c.start + offset := chuck.start for { - n, err := resp.Body.Read(buf) - if n > 0 { + count, err := resp.Body.Read(buf) + if count > 0 { d.mu.Lock() - for written := 0; written < n; { - w, err := out.WriteAt(buf[written:n], offset+int64(written)) + for written := 0; written < count; { + numBytes, err := out.WriteAt(buf[written:count], offset+int64(written)) if err != nil { d.mu.Unlock() return &Error{Message: "failed write data into file", Reason: err} } - written += w + written += numBytes } - offset += int64(n) - d.downloaded += int64(n) + offset += int64(count) + d.downloaded += int64(count) d.updateStats(d.downloaded, totalSize) d.mu.Unlock() } diff --git a/util/downloader/downloader_test.go b/util/downloader/downloader_test.go index 881584885..fd4d33c73 100644 --- a/util/downloader/downloader_test.go +++ b/util/downloader/downloader_test.go @@ -37,27 +37,26 @@ func TestDownloader(t *testing.T) { assert.NoError(t, os.RemoveAll("./testdata")) }() - dl := New(server.URL+fileURL, filePath, expectedSHA256Hex, WithCustomClient(server.Client())) + downloader := New(server.URL+fileURL, filePath, expectedSHA256Hex, WithCustomClient(server.Client())) - assrt := assert.New(t) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() go func() { - dl.Start(ctx) + downloader.Start(ctx) }() done := make(chan bool) go func() { - for stat := range dl.Stats() { + for stat := range downloader.Stats() { log.Printf("Downloaded: %d / %d (%.2f%%)\n", stat.Downloaded, stat.TotalSize, stat.Percent) - assrt.True(stat.Downloaded <= stat.TotalSize, "Downloaded size should not exceed total size") - assrt.True(stat.Percent <= 100, "Download percentage should not exceed 100") + assert.True(t, stat.Downloaded <= stat.TotalSize, "Downloaded size should not exceed total size") + assert.True(t, stat.Percent <= 100, "Download percentage should not exceed 100") if stat.Completed { log.Println("Download completed successfully") - assrt.Equal(float64(100), stat.Percent, "Download should be 100% complete") + assert.Equal(t, float64(100), stat.Percent, "Download should be 100% complete") done <- true return @@ -66,8 +65,8 @@ func TestDownloader(t *testing.T) { }() go func() { - for err := range dl.Errors() { - assrt.Fail("Download encountered an error", err) + for err := range downloader.Errors() { + assert.Fail(t, "Download encountered an error", err) done <- true return @@ -78,13 +77,13 @@ func TestDownloader(t *testing.T) { case <-done: case <-time.After(2 * time.Minute): cancel() - assrt.Fail("Download test timed out") + assert.Fail(t, "Download test timed out") } - t.Log(dl.FileName()) - t.Log(dl.FileType()) + t.Log(downloader.FileName()) + t.Log(downloader.FileType()) downloadedContent, err := os.ReadFile(filePath) - assrt.NoError(err, "Failed to read the downloaded file") - assrt.Equal(fileContent, downloadedContent, "Downloaded file content does not match expected content") + assert.NoError(t, err, "Failed to read the downloaded file") + assert.Equal(t, fileContent, downloadedContent, "Downloaded file content does not match expected content") } diff --git a/util/encoding/encoding.go b/util/encoding/encoding.go index 5eeb513cc..67fcb56bb 100644 --- a/util/encoding/encoding.go +++ b/util/encoding/encoding.go @@ -178,49 +178,49 @@ var binarySerializer binaryFreeList = make(chan []byte, binaryFreeListMaxItems) // ReadElement reads the next sequence of bytes from r using little endian // depending on the concrete type of element pointed to. -func ReadElement(r io.Reader, element any) error { +func ReadElement(r io.Reader, elm any) error { // Attempt to read the element based on the concrete type via fast // type assertions first. var err error - switch e := element.(type) { + switch elm := elm.(type) { case *bool: - rv := uint8(0) - err = binarySerializer.Uint8(r, &rv) - if rv == 0x00 { - *e = false + val := uint8(0) + err = binarySerializer.Uint8(r, &val) + if val == 0x00 { + *elm = false } else { - *e = true + *elm = true } case *int8: - rv := uint8(0) - err = binarySerializer.Uint8(r, &rv) - *e = int8(rv) + val := uint8(0) + err = binarySerializer.Uint8(r, &val) + *elm = int8(val) case *uint8: - err = binarySerializer.Uint8(r, e) + err = binarySerializer.Uint8(r, elm) case *int16: - rv := uint16(0) - err = binarySerializer.Uint16(r, &rv) - *e = int16(rv) + val := uint16(0) + err = binarySerializer.Uint16(r, &val) + *elm = int16(val) case *uint16: - err = binarySerializer.Uint16(r, e) + err = binarySerializer.Uint16(r, elm) case *int32: rv := uint32(0) err = binarySerializer.Uint32(r, &rv) - *e = int32(rv) + *elm = int32(rv) case *uint32: - err = binarySerializer.Uint32(r, e) + err = binarySerializer.Uint32(r, elm) case *int64: - rv := uint64(0) - err = binarySerializer.Uint64(r, &rv) - *e = int64(rv) + val := uint64(0) + err = binarySerializer.Uint64(r, &val) + *elm = int64(val) case *uint64: - err = binarySerializer.Uint64(r, e) + err = binarySerializer.Uint64(r, elm) case *hash.Hash: - _, err = io.ReadFull(r, e[:]) + _, err = io.ReadFull(r, elm[:]) default: // Fall back to the slower binary.Read if a fast path was not available // above. - err = binary.Read(r, binary.LittleEndian, element) + err = binary.Read(r, binary.LittleEndian, elm) } return err @@ -228,8 +228,8 @@ func ReadElement(r io.Reader, element any) error { // ReadElements reads multiple items from r. It is equivalent to multiple // calls to readElement. -func ReadElements(r io.Reader, elements ...any) error { - for _, element := range elements { +func ReadElements(r io.Reader, elms ...any) error { + for _, element := range elms { err := ReadElement(r, element) if err != nil { return err @@ -240,39 +240,39 @@ func ReadElements(r io.Reader, elements ...any) error { } // WriteElement writes the little endian representation of element to w. -func WriteElement(w io.Writer, element any) error { +func WriteElement(w io.Writer, elm any) error { // Attempt to write the element based on the concrete type via fast // type assertions first. var err error - switch e := element.(type) { + switch elm := elm.(type) { case bool: - if e { + if elm { err = binarySerializer.PutUint8(w, 0x01) } else { err = binarySerializer.PutUint8(w, 0x00) } case int8: - err = binarySerializer.PutUint8(w, uint8(e)) + err = binarySerializer.PutUint8(w, uint8(elm)) case uint8: - err = binarySerializer.PutUint8(w, e) + err = binarySerializer.PutUint8(w, elm) case int16: - err = binarySerializer.PutUint16(w, uint16(e)) + err = binarySerializer.PutUint16(w, uint16(elm)) case uint16: - err = binarySerializer.PutUint16(w, e) + err = binarySerializer.PutUint16(w, elm) case int32: - err = binarySerializer.PutUint32(w, uint32(e)) + err = binarySerializer.PutUint32(w, uint32(elm)) case uint32: - err = binarySerializer.PutUint32(w, e) + err = binarySerializer.PutUint32(w, elm) case int64: - err = binarySerializer.PutUint64(w, uint64(e)) + err = binarySerializer.PutUint64(w, uint64(elm)) case uint64: - err = binarySerializer.PutUint64(w, e) + err = binarySerializer.PutUint64(w, elm) case *hash.Hash: - _, err = w.Write(e[:]) + _, err = w.Write(elm[:]) default: // Fall back to the slower binary.Write if a fast path was not available // above. - err = binary.Write(w, binary.LittleEndian, element) + err = binary.Write(w, binary.LittleEndian, elm) } return err @@ -296,22 +296,22 @@ func ReadVarInt(r io.Reader) (uint64, error) { bits := 64 write := uint64(0) for shift := 0; ; shift += 7 { - b := uint8(0) - err := binarySerializer.Uint8(r, &b) + byt := uint8(0) + err := binarySerializer.Uint8(r, &byt) if err != nil { return 0, err } - if shift+7 >= bits && b >= 1<<(bits-shift) { + if shift+7 >= bits && byt >= 1<<(bits-shift) { return uint64(0), ErrOverflow } - if b == 0 && shift != 0 { + if byt == 0 && shift != 0 { return uint64(0), ErrNonCanonical } - write |= uint64(b&0x7f) << shift // Does the actually placing into write, stripping the first bit + write |= uint64(byt&0x7f) << shift // Does the actually placing into write, stripping the first bit // If there is no next - if (b & 0x80) == 0 { + if (byt & 0x80) == 0 { break } } @@ -435,13 +435,13 @@ func ReadVarBytes(r io.Reader) ([]byte, error) { "[count %d, max %d]", count, MaxPayloadSize) } - b := make([]byte, count) - _, err = io.ReadFull(r, b) + buf := make([]byte, count) + _, err = io.ReadFull(r, buf) if err != nil { return nil, err } - return b, nil + return buf, nil } // WriteVarBytes serializes a variable length byte array to w as a varInt diff --git a/util/encoding/encoding_test.go b/util/encoding/encoding_test.go index ff25b3493..ddab228e8 100644 --- a/util/encoding/encoding_test.go +++ b/util/encoding/encoding_test.go @@ -67,25 +67,25 @@ func TestElementEncoding(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { + for no, tt := range tests { var buf bytes.Buffer - err := WriteElement(&buf, test.in) - assert.NoError(t, err, "writeElement #%d", i) - assert.Equal(t, buf.Bytes(), test.buf, "writeElement #%d", i) - - rbuf := bytes.NewReader(test.buf) - val := test.in - if reflect.ValueOf(test.in).Kind() != reflect.Ptr { - val = reflect.New(reflect.TypeOf(test.in)).Interface() + err := WriteElement(&buf, tt.in) + assert.NoError(t, err, "writeElement #%d", no) + assert.Equal(t, buf.Bytes(), tt.buf, "writeElement #%d", no) + + rbuf := bytes.NewReader(tt.buf) + val := tt.in + if reflect.ValueOf(tt.in).Kind() != reflect.Ptr { + val = reflect.New(reflect.TypeOf(tt.in)).Interface() } err = ReadElement(rbuf, val) - assert.NoError(t, err, "readElement #%d", i) + assert.NoError(t, err, "readElement #%d", no) ival := val - if reflect.ValueOf(test.in).Kind() != reflect.Ptr { + if reflect.ValueOf(tt.in).Kind() != reflect.Ptr { ival = reflect.Indirect(reflect.ValueOf(val)).Interface() } - assert.Equal(t, ival, test.in, "readElement #%d", i) + assert.Equal(t, ival, tt.in, "readElement #%d", no) } } @@ -120,18 +120,18 @@ func TestElementEncodingErrors(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - w := util.NewFixedWriter(test.max) - err := WriteElement(w, test.in) - assert.ErrorIs(t, err, test.writeErr, "writeElement #%d", i) - - r := util.NewFixedReader(test.max, nil) - val := test.in - if reflect.ValueOf(test.in).Kind() != reflect.Ptr { - val = reflect.New(reflect.TypeOf(test.in)).Interface() + for no, tt := range tests { + w := util.NewFixedWriter(tt.max) + err := WriteElement(w, tt.in) + assert.ErrorIs(t, err, tt.writeErr, "writeElement #%d", no) + + r := util.NewFixedReader(tt.max, nil) + val := tt.in + if reflect.ValueOf(tt.in).Kind() != reflect.Ptr { + val = reflect.New(reflect.TypeOf(tt.in)).Interface() } err = ReadElement(r, val) - assert.ErrorIs(t, err, test.readErr, "readElement #%d", i) + assert.ErrorIs(t, err, tt.readErr, "readElement #%d", no) } } @@ -155,17 +155,17 @@ func TestVarStringEncoding(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { + for no, tt := range tests { var buf bytes.Buffer - err := WriteVarString(&buf, test.in) - assert.NoError(t, err, "WriteVarString #%d ", i) - assert.Equal(t, buf.Bytes(), test.buf, "WriteVarString #%d", i) + err := WriteVarString(&buf, tt.in) + assert.NoError(t, err, "WriteVarString #%d ", no) + assert.Equal(t, buf.Bytes(), tt.buf, "WriteVarString #%d", no) - rbuf := bytes.NewReader(test.buf) + rbuf := bytes.NewReader(tt.buf) val, err := ReadVarString(rbuf) - assert.NoError(t, err, "ReadVarString #%d", i) - assert.Equal(t, val, test.out, "ReadVarString #%d", i) - assert.Equal(t, VarStringSerializeSize(test.in), len(test.buf)) + assert.NoError(t, err, "ReadVarString #%d", no) + assert.Equal(t, val, tt.out, "ReadVarString #%d", no) + assert.Equal(t, VarStringSerializeSize(tt.in), len(tt.buf)) } } @@ -192,14 +192,14 @@ func TestVarStringEncodingErrors(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - w := util.NewFixedWriter(test.max) - err := WriteVarString(w, test.in) - assert.ErrorIs(t, err, test.writeErr, "WriteVarString #%d", i) + for no, tt := range tests { + w := util.NewFixedWriter(tt.max) + err := WriteVarString(w, tt.in) + assert.ErrorIs(t, err, tt.writeErr, "WriteVarString #%d", no) - r := util.NewFixedReader(test.max, test.buf) + r := util.NewFixedReader(tt.max, tt.buf) _, err = ReadVarString(r) - assert.ErrorIs(t, err, test.readErr, "ReadVarString #%d wrong", i) + assert.ErrorIs(t, err, tt.readErr, "ReadVarString #%d wrong", no) } } @@ -216,10 +216,10 @@ func TestVarStringOverflowErrors(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - rbuf := bytes.NewReader(test.buf) + for no, tt := range tests { + rbuf := bytes.NewReader(tt.buf) _, err := ReadVarString(rbuf) - assert.Contains(t, err.Error(), "variable length string is too long", "ReadVarString #%d", i) + assert.Contains(t, err.Error(), "variable length string is too long", "ReadVarString #%d", no) } } @@ -242,18 +242,18 @@ func TestVarBytesEncoding(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { + for no, tt := range tests { var buf bytes.Buffer - err := WriteVarBytes(&buf, test.in) - assert.NoError(t, err, "WriteVarBytes #%d", i) - assert.Equal(t, buf.Bytes(), test.buf, "WriteVarBytes #%d", i) + err := WriteVarBytes(&buf, tt.in) + assert.NoError(t, err, "WriteVarBytes #%d", no) + assert.Equal(t, buf.Bytes(), tt.buf, "WriteVarBytes #%d", no) - rbuf := bytes.NewReader(test.buf) + rbuf := bytes.NewReader(tt.buf) val, err := ReadVarBytes(rbuf) - assert.NoError(t, err, "ReadVarBytes #%d", i) - assert.Equal(t, buf.Bytes(), test.buf, "ReadVarBytes #%d", i) - assert.Equal(t, val, test.in, "ReadVarBytes #%d", i) - assert.Equal(t, VarBytesSerializeSize(test.in), len(test.buf)) + assert.NoError(t, err, "ReadVarBytes #%d", no) + assert.Equal(t, buf.Bytes(), tt.buf, "ReadVarBytes #%d", no) + assert.Equal(t, val, tt.in, "ReadVarBytes #%d", no) + assert.Equal(t, VarBytesSerializeSize(tt.in), len(tt.buf)) } } @@ -280,14 +280,14 @@ func TestVarBytesEncodingErrors(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - w := util.NewFixedWriter(test.max) - err := WriteVarBytes(w, test.in) - assert.ErrorIs(t, err, test.writeErr, "WriteVarBytes #%d", i) + for no, tt := range tests { + w := util.NewFixedWriter(tt.max) + err := WriteVarBytes(w, tt.in) + assert.ErrorIs(t, err, tt.writeErr, "WriteVarBytes #%d", no) - r := util.NewFixedReader(test.max, test.buf) + r := util.NewFixedReader(tt.max, tt.buf) _, err = ReadVarBytes(r) - assert.ErrorIs(t, err, test.readErr, "ReadVarBytes #%d", i) + assert.ErrorIs(t, err, tt.readErr, "ReadVarBytes #%d", no) } } @@ -304,10 +304,10 @@ func TestVarBytesOverflowErrors(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - rbuf := bytes.NewReader(test.buf) + for no, tt := range tests { + rbuf := bytes.NewReader(tt.buf) _, err := ReadVarBytes(rbuf) - assert.Contains(t, err.Error(), "variable length byte array is too long", "ReadVarString #%d", i) + assert.Contains(t, err.Error(), "variable length byte array is too long", "ReadVarString #%d", no) } } @@ -337,16 +337,16 @@ func TestVarInt(t *testing.T) { {uint64(0x7ffffffff), []byte{0xff, 0xff, 0xff, 0xff, 0x7f}}, {uint64(0x800000000), []byte{0x80, 0x80, 0x80, 0x80, 0x80, 0x1}}, } - for i, test := range tests { + for no, tt := range tests { var buf bytes.Buffer - err := WriteVarInt(&buf, test.in) - assert.NoError(t, err, "WriteVarInt #%d", i) - assert.Equal(t, buf.Bytes(), test.buf, "WriteVarInt #%d", i) + err := WriteVarInt(&buf, tt.in) + assert.NoError(t, err, "WriteVarInt #%d", no) + assert.Equal(t, buf.Bytes(), tt.buf, "WriteVarInt #%d", no) val, err := ReadVarInt(&buf) - assert.NoError(t, err, "ReadVarInt #%d", i) - assert.Equal(t, val, test.in, "ReadVarInt #%d", i) - assert.Equal(t, VarIntSerializeSize(test.in), len(test.buf)) + assert.NoError(t, err, "ReadVarInt #%d", no) + assert.Equal(t, val, tt.in, "ReadVarInt #%d", no) + assert.Equal(t, VarIntSerializeSize(tt.in), len(tt.buf)) } } @@ -378,11 +378,11 @@ func TestVarIntError(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - rbuf := bytes.NewReader(test.in) + for no, tt := range tests { + rbuf := bytes.NewReader(tt.in) val, err := ReadVarInt(rbuf) - assert.ErrorIs(t, err, test.readErr, "ReadVarInt #%d", i) - assert.Zero(t, val, "ReadVarInt #%d", i) + assert.ErrorIs(t, err, tt.readErr, "ReadVarInt #%d", no) + assert.Zero(t, val, "ReadVarInt #%d", no) } } diff --git a/util/io.go b/util/io.go index 41e273541..235492c95 100644 --- a/util/io.go +++ b/util/io.go @@ -10,20 +10,20 @@ import ( "strings" ) -func IsAbsPath(p string) bool { - return filepath.IsAbs(p) +func IsAbsPath(path string) bool { + return filepath.IsAbs(path) } -func MakeAbs(p string) string { - if IsAbsPath(p) { - return p +func MakeAbs(path string) string { + if IsAbsPath(path) { + return path } wd, err := os.Getwd() if err != nil { panic(err) } - return filepath.Clean(filepath.Join(wd, p)) + return filepath.Clean(filepath.Join(wd, path)) } func ReadFile(filename string) ([]byte, error) { @@ -42,17 +42,17 @@ func WriteFile(filename string, data []byte) error { return nil } -func Mkdir(dir string) error { +func Mkdir(path string) error { // create the directory - if err := os.MkdirAll(dir, 0o750); err != nil { - return fmt.Errorf("could not create directory %s", dir) + if err := os.MkdirAll(path, 0o750); err != nil { + return fmt.Errorf("could not create directory %s", path) } return nil } -func PathExists(p string) bool { - _, err := os.Stat(p) +func PathExists(path string) bool { + _, err := os.Stat(path) if os.IsNotExist(err) { return false } @@ -61,12 +61,12 @@ func PathExists(p string) bool { } func TempDirPath() string { - p, err := os.MkdirTemp("", "pactus*") + path, err := os.MkdirTemp("", "pactus*") if err != nil { panic(err) } - return p + return path } func TempFilePath() string { @@ -74,39 +74,39 @@ func TempFilePath() string { } // IsDirEmpty checks if a directory is empty. -func IsDirEmpty(name string) bool { - f, err := os.Open(name) +func IsDirEmpty(path string) bool { + file, err := os.Open(path) if err != nil { panic(err) } defer func() { - _ = f.Close() + _ = file.Close() }() // read in ONLY one file - _, err = f.Readdir(1) + _, err = file.Readdir(1) // and if the file is EOF... well, the dir is empty. return errors.Is(err, io.EOF) } // IsDirNotExistsOrEmpty checks if the path exists and, if so, whether the directory is empty. -func IsDirNotExistsOrEmpty(name string) bool { - if !PathExists(name) { +func IsDirNotExistsOrEmpty(path string) bool { + if !PathExists(path) { return true } - return IsDirEmpty(name) + return IsDirEmpty(path) } -func IsValidDirPath(fp string) bool { - fi, err := os.Stat(fp) +func IsValidDirPath(path string) bool { + fi, err := os.Stat(path) if err == nil { if fi.IsDir() { - if err := os.WriteFile(fp+"/test", []byte{}, 0o600); err != nil { + if err := os.WriteFile(path+"/test", []byte{}, 0o600); err != nil { return false } - _ = os.Remove(fp + "/test") + _ = os.Remove(path + "/test") return true } @@ -114,10 +114,10 @@ func IsValidDirPath(fp string) bool { return false } - if err := Mkdir(fp); err != nil { + if err := Mkdir(path); err != nil { return false } - _ = os.Remove(fp) + _ = os.Remove(path) return true } @@ -136,14 +136,14 @@ type FixedWriter struct { // io.ErrShortWrite is returned and the writer is left unchanged. // // This satisfies the io.Writer interface. -func (w *FixedWriter) Write(p []byte) (int, error) { - lenp := len(p) +func (w *FixedWriter) Write(data []byte) (int, error) { + lenp := len(data) if w.pos+lenp > cap(w.b) { return 0, io.ErrShortWrite } - w.pos += copy(w.b[w.pos:], p) + w.pos += copy(w.b[w.pos:], data) return lenp, nil } @@ -176,26 +176,26 @@ type FixedReader struct { // // This satisfies the io.Reader interface. func (fr *FixedReader) Read(p []byte) (int, error) { - n, err := fr.iobuf.Read(p) + count, err := fr.iobuf.Read(p) if err != nil { return 0, err } - fr.pos += n + fr.pos += count - return n, nil + return count, nil } // NewFixedReader returns a new io.Reader that will error once more bytes than // the specified max have been read. -func NewFixedReader(max int, buf []byte) *FixedReader { - b := make([]byte, max) - if buf != nil { - copy(b, buf) +func NewFixedReader(max int, data []byte) *FixedReader { + buf := make([]byte, max) + if data != nil { + copy(buf, data) } - iobuf := bytes.NewBuffer(b) - fr := FixedReader{b, 0, iobuf} + iobuf := bytes.NewBuffer(buf) + fr := FixedReader{buf, 0, iobuf} return &fr } diff --git a/util/linkedlist/linkedlist.go b/util/linkedlist/linkedlist.go index 335184a30..47f7fdc3c 100644 --- a/util/linkedlist/linkedlist.go +++ b/util/linkedlist/linkedlist.go @@ -29,138 +29,136 @@ func New[T any]() *LinkedList[T] { } } -// InsertAtHead inserts a new node at the head of the list. -func (l *LinkedList[T]) InsertAtHead(data T) *Element[T] { - newNode := NewElement(data) - - if l.Head == nil { +// InsertAtHead inserts a new element at the head of the list. +func (ll *LinkedList[T]) InsertAtHead(data T) *Element[T] { + elm := NewElement(data) + if ll.Head == nil { // Empty list case - l.Head = newNode - l.Tail = newNode + ll.Head = elm + ll.Tail = elm } else { - newNode.Next = l.Head - l.Head.Prev = newNode - l.Head = newNode + elm.Next = ll.Head + ll.Head.Prev = elm + ll.Head = elm } - l.length++ + ll.length++ - return newNode + return elm } -// InsertAtTail appends a new node at the tail of the list. -func (l *LinkedList[T]) InsertAtTail(data T) *Element[T] { - newNode := NewElement(data) - - if l.Head == nil { +// InsertAtTail appends a new element at the tail of the list. +func (ll *LinkedList[T]) InsertAtTail(data T) *Element[T] { + elm := NewElement(data) + if ll.Head == nil { // Empty list case - l.Head = newNode - l.Tail = newNode + ll.Head = elm + ll.Tail = elm } else { - newNode.Prev = l.Tail - l.Tail.Next = newNode - l.Tail = newNode + elm.Prev = ll.Tail + ll.Tail.Next = elm + ll.Tail = elm } - l.length++ + ll.length++ - return newNode + return elm } -func (l *LinkedList[T]) InsertBefore(data T, at *Element[T]) *Element[T] { - e := NewElement[T](data) - if at == l.Head { - l.Head = e - e.Next = at - e.Next.Prev = e +func (ll *LinkedList[T]) InsertBefore(data T, pos *Element[T]) *Element[T] { + elm := NewElement[T](data) + if pos == ll.Head { + ll.Head = elm + elm.Next = pos + elm.Next.Prev = elm } else { - e.Prev = at.Prev - e.Next = at - e.Next.Prev = e - e.Prev.Next = e + elm.Prev = pos.Prev + elm.Next = pos + elm.Next.Prev = elm + elm.Prev.Next = elm } - l.length++ + ll.length++ - return e + return elm } -func (l *LinkedList[T]) InsertAfter(data T, at *Element[T]) *Element[T] { - e := NewElement[T](data) - if at == l.Tail { - l.Tail = e - e.Prev = at - e.Prev.Next = e +func (ll *LinkedList[T]) InsertAfter(data T, pos *Element[T]) *Element[T] { + elm := NewElement[T](data) + if pos == ll.Tail { + ll.Tail = elm + elm.Prev = pos + elm.Prev.Next = elm } else { - e.Prev = at - e.Next = at.Next - e.Prev.Next = e - e.Next.Prev = e + elm.Prev = pos + elm.Next = pos.Next + elm.Prev.Next = elm + elm.Next.Prev = elm } - l.length++ + ll.length++ - return e + return elm } -// DeleteAtHead deletes the node at the head of the list. -func (l *LinkedList[T]) DeleteAtHead() { - if l.Head == nil { +// DeleteAtHead deletes the element at the head of the list. +func (ll *LinkedList[T]) DeleteAtHead() { + if ll.Head == nil { // Empty list case return } - l.Head = l.Head.Next - if l.Head != nil { - l.Head.Prev = nil + ll.Head = ll.Head.Next + if ll.Head != nil { + ll.Head.Prev = nil } else { - l.Tail = nil + ll.Tail = nil } - l.length-- + ll.length-- } -// DeleteAtTail deletes the node at the tail of the list. -func (l *LinkedList[T]) DeleteAtTail() { - if l.Tail == nil { +// DeleteAtTail deletes the element at the tail of the list. +func (ll *LinkedList[T]) DeleteAtTail() { + if ll.Tail == nil { // Empty list case return } - l.Tail = l.Tail.Prev - if l.Tail != nil { - l.Tail.Next = nil + ll.Tail = ll.Tail.Prev + if ll.Tail != nil { + ll.Tail.Next = nil } else { - l.Head = nil + ll.Head = nil } - l.length-- + ll.length-- } -// Delete removes a specific node from the list. -func (l *LinkedList[T]) Delete(ln *Element[T]) { - if ln.Prev != nil { - ln.Prev.Next = ln.Next +// Delete removes a specific element from the list. +func (ll *LinkedList[T]) Delete(elm *Element[T]) { + if elm.Prev != nil { + elm.Prev.Next = elm.Next } else { - l.Head = ln.Next + ll.Head = elm.Next } - if ln.Next != nil { - ln.Next.Prev = ln.Prev + if elm.Next != nil { + elm.Next.Prev = elm.Prev } else { - l.Tail = ln.Prev + ll.Tail = elm.Prev } - l.length-- + ll.length-- } -// Length returns the number of nodes in the list. -func (l *LinkedList[T]) Length() int { - return l.length +// Length returns the number of elements in the list. +func (ll *LinkedList[T]) Length() int { + return ll.length } // Values returns a slice of values in the list. -func (l *LinkedList[T]) Values() []T { +func (ll *LinkedList[T]) Values() []T { values := []T{} - cur := l.Head + cur := ll.Head for cur != nil { values = append(values, cur.Data) cur = cur.Next @@ -169,9 +167,9 @@ func (l *LinkedList[T]) Values() []T { return values } -// Clear removes all nodes from the list, making it empty. -func (l *LinkedList[T]) Clear() { - l.Head = nil - l.Tail = nil - l.length = 0 +// Clear removes all elements from the list, making it empty. +func (ll *LinkedList[T]) Clear() { + ll.Head = nil + ll.Tail = nil + ll.length = 0 } diff --git a/util/linkedlist/linkedlist_test.go b/util/linkedlist/linkedlist_test.go index e0feec4ce..6df30a86a 100644 --- a/util/linkedlist/linkedlist_test.go +++ b/util/linkedlist/linkedlist_test.go @@ -3,135 +3,135 @@ package linkedlist_test import ( "testing" - ll "github.com/pactus-project/pactus/util/linkedlist" + "github.com/pactus-project/pactus/util/linkedlist" "github.com/stretchr/testify/assert" ) func TestDoublyLink_InsertAtHead(t *testing.T) { - link := ll.New[int]() - link.InsertAtHead(1) - link.InsertAtHead(2) - link.InsertAtHead(3) - link.InsertAtHead(4) - - assert.Equal(t, []int{4, 3, 2, 1}, link.Values()) - assert.Equal(t, 4, link.Length()) - assert.Equal(t, 4, link.Head.Data) - assert.Equal(t, 1, link.Tail.Data) + list := linkedlist.New[int]() + list.InsertAtHead(1) + list.InsertAtHead(2) + list.InsertAtHead(3) + list.InsertAtHead(4) + + assert.Equal(t, []int{4, 3, 2, 1}, list.Values()) + assert.Equal(t, 4, list.Length()) + assert.Equal(t, 4, list.Head.Data) + assert.Equal(t, 1, list.Tail.Data) } func TestSinglyLink_InsertAtTail(t *testing.T) { - link := ll.New[int]() - link.InsertAtTail(1) - link.InsertAtTail(2) - link.InsertAtTail(3) - link.InsertAtTail(4) - - assert.Equal(t, []int{1, 2, 3, 4}, link.Values()) - assert.Equal(t, 4, link.Length()) - assert.Equal(t, 1, link.Head.Data) - assert.Equal(t, 4, link.Tail.Data) + list := linkedlist.New[int]() + list.InsertAtTail(1) + list.InsertAtTail(2) + list.InsertAtTail(3) + list.InsertAtTail(4) + + assert.Equal(t, []int{1, 2, 3, 4}, list.Values()) + assert.Equal(t, 4, list.Length()) + assert.Equal(t, 1, list.Head.Data) + assert.Equal(t, 4, list.Tail.Data) } func TestDeleteAtHead(t *testing.T) { - link := ll.New[int]() - link.InsertAtTail(1) - link.InsertAtTail(2) - link.InsertAtTail(3) - - link.DeleteAtHead() - assert.Equal(t, []int{2, 3}, link.Values()) - assert.Equal(t, 2, link.Length()) - - link.DeleteAtHead() - assert.Equal(t, []int{3}, link.Values()) - assert.Equal(t, 1, link.Length()) - - link.DeleteAtHead() - assert.Equal(t, []int{}, link.Values()) - assert.Equal(t, 0, link.Length()) - - link.DeleteAtHead() - assert.Equal(t, []int{}, link.Values()) - assert.Equal(t, 0, link.Length()) + list := linkedlist.New[int]() + list.InsertAtTail(1) + list.InsertAtTail(2) + list.InsertAtTail(3) + + list.DeleteAtHead() + assert.Equal(t, []int{2, 3}, list.Values()) + assert.Equal(t, 2, list.Length()) + + list.DeleteAtHead() + assert.Equal(t, []int{3}, list.Values()) + assert.Equal(t, 1, list.Length()) + + list.DeleteAtHead() + assert.Equal(t, []int{}, list.Values()) + assert.Equal(t, 0, list.Length()) + + list.DeleteAtHead() + assert.Equal(t, []int{}, list.Values()) + assert.Equal(t, 0, list.Length()) } func TestDeleteAtTail(t *testing.T) { - link := ll.New[int]() - link.InsertAtTail(1) - link.InsertAtTail(2) - link.InsertAtTail(3) - - link.DeleteAtTail() - assert.Equal(t, []int{1, 2}, link.Values()) - assert.Equal(t, 2, link.Length()) - - link.DeleteAtTail() - assert.Equal(t, []int{1}, link.Values()) - assert.Equal(t, 1, link.Length()) - - link.DeleteAtTail() - assert.Equal(t, []int{}, link.Values()) - assert.Equal(t, 0, link.Length()) - - link.DeleteAtTail() - assert.Equal(t, []int{}, link.Values()) - assert.Equal(t, 0, link.Length()) + list := linkedlist.New[int]() + list.InsertAtTail(1) + list.InsertAtTail(2) + list.InsertAtTail(3) + + list.DeleteAtTail() + assert.Equal(t, []int{1, 2}, list.Values()) + assert.Equal(t, 2, list.Length()) + + list.DeleteAtTail() + assert.Equal(t, []int{1}, list.Values()) + assert.Equal(t, 1, list.Length()) + + list.DeleteAtTail() + assert.Equal(t, []int{}, list.Values()) + assert.Equal(t, 0, list.Length()) + + list.DeleteAtTail() + assert.Equal(t, []int{}, list.Values()) + assert.Equal(t, 0, list.Length()) } func TestDelete(t *testing.T) { - link := ll.New[int]() - n1 := link.InsertAtTail(1) - n2 := link.InsertAtTail(2) - n3 := link.InsertAtTail(3) - n4 := link.InsertAtTail(4) - - link.Delete(n1) - assert.Equal(t, []int{2, 3, 4}, link.Values()) - assert.Equal(t, 3, link.Length()) - - link.Delete(n4) - assert.Equal(t, []int{2, 3}, link.Values()) - assert.Equal(t, 2, link.Length()) - - link.Delete(n2) - assert.Equal(t, []int{3}, link.Values()) - assert.Equal(t, 1, link.Length()) - - link.Delete(n3) - assert.Equal(t, []int{}, link.Values()) - assert.Equal(t, 0, link.Length()) + list := linkedlist.New[int]() + elm1 := list.InsertAtTail(1) + elm2 := list.InsertAtTail(2) + elm3 := list.InsertAtTail(3) + elm4 := list.InsertAtTail(4) + + list.Delete(elm1) + assert.Equal(t, []int{2, 3, 4}, list.Values()) + assert.Equal(t, 3, list.Length()) + + list.Delete(elm4) + assert.Equal(t, []int{2, 3}, list.Values()) + assert.Equal(t, 2, list.Length()) + + list.Delete(elm2) + assert.Equal(t, []int{3}, list.Values()) + assert.Equal(t, 1, list.Length()) + + list.Delete(elm3) + assert.Equal(t, []int{}, list.Values()) + assert.Equal(t, 0, list.Length()) } func TestClear(t *testing.T) { - link := ll.New[int]() - link.InsertAtTail(1) - link.InsertAtTail(2) - link.InsertAtTail(3) - - link.Clear() - assert.Equal(t, []int{}, link.Values()) - assert.Equal(t, 0, link.Length()) + list := linkedlist.New[int]() + list.InsertAtTail(1) + list.InsertAtTail(2) + list.InsertAtTail(3) + + list.Clear() + assert.Equal(t, []int{}, list.Values()) + assert.Equal(t, 0, list.Length()) } func TestInsertAfter(t *testing.T) { - link := ll.New[int]() - e1 := link.InsertAtHead(1) - e2 := link.InsertAfter(2, e1) - link.InsertAfter(3, e2) - link.InsertAfter(4, link.Head) - link.InsertAfter(5, link.Tail) - - assert.Equal(t, []int{1, 4, 2, 3, 5}, link.Values()) + list := linkedlist.New[int]() + elm1 := list.InsertAtHead(1) + elm2 := list.InsertAfter(2, elm1) + list.InsertAfter(3, elm2) + list.InsertAfter(4, list.Head) + list.InsertAfter(5, list.Tail) + + assert.Equal(t, []int{1, 4, 2, 3, 5}, list.Values()) } func TestInsertBefore(t *testing.T) { - link := ll.New[int]() - e1 := link.InsertAtHead(1) - e2 := link.InsertBefore(2, e1) - link.InsertBefore(3, e2) - link.InsertBefore(4, link.Head) - link.InsertBefore(5, link.Tail) - - assert.Equal(t, []int{4, 3, 2, 5, 1}, link.Values()) + list := linkedlist.New[int]() + elm1 := list.InsertAtHead(1) + elm2 := list.InsertBefore(2, elm1) + list.InsertBefore(3, elm2) + list.InsertBefore(4, list.Head) + list.InsertBefore(5, list.Tail) + + assert.Equal(t, []int{4, 3, 2, 5, 1}, list.Values()) } diff --git a/util/linkedmap/linkedmap.go b/util/linkedmap/linkedmap.go index 66e235ddc..e21f1af5b 100644 --- a/util/linkedmap/linkedmap.go +++ b/util/linkedmap/linkedmap.go @@ -1,7 +1,7 @@ package linkedmap import ( - ll "github.com/pactus-project/pactus/util/linkedlist" + "github.com/pactus-project/pactus/util/linkedlist" ) type Pair[K comparable, V any] struct { @@ -10,16 +10,16 @@ type Pair[K comparable, V any] struct { } type LinkedMap[K comparable, V any] struct { - list *ll.LinkedList[Pair[K, V]] - hashmap map[K]*ll.Element[Pair[K, V]] + list *linkedlist.LinkedList[Pair[K, V]] + hashmap map[K]*linkedlist.Element[Pair[K, V]] capacity int } // New creates a new LinkedMap with the specified capacity. func New[K comparable, V any](capacity int) *LinkedMap[K, V] { return &LinkedMap[K, V]{ - list: ll.New[Pair[K, V]](), - hashmap: make(map[K]*ll.Element[Pair[K, V]]), + list: linkedlist.New[Pair[K, V]](), + hashmap: make(map[K]*linkedlist.Element[Pair[K, V]]), capacity: capacity, } } @@ -40,70 +40,70 @@ func (lm *LinkedMap[K, V]) Has(key K) bool { // PushBack adds a new key-value pair to the end of the LinkedMap. func (lm *LinkedMap[K, V]) PushBack(key K, value V) { - ln, found := lm.hashmap[key] + node, found := lm.hashmap[key] if found { // Update the value if the key already exists - ln.Data.Value = value + node.Data.Value = value return } p := Pair[K, V]{Key: key, Value: value} - ln = lm.list.InsertAtTail(p) - lm.hashmap[key] = ln + node = lm.list.InsertAtTail(p) + lm.hashmap[key] = node lm.prune() } // PushFront adds a new key-value pair to the beginning of the LinkedMap. func (lm *LinkedMap[K, V]) PushFront(key K, value V) { - ln, found := lm.hashmap[key] + node, found := lm.hashmap[key] if found { // Update the value if the key already exists - ln.Data.Value = value + node.Data.Value = value return } p := Pair[K, V]{Key: key, Value: value} - ln = lm.list.InsertAtHead(p) - lm.hashmap[key] = ln + node = lm.list.InsertAtHead(p) + lm.hashmap[key] = node lm.prune() } -// GetNode returns the LinkNode corresponding to the specified key. -func (lm *LinkedMap[K, V]) GetNode(key K) *ll.Element[Pair[K, V]] { - ln, found := lm.hashmap[key] +// GetNode returns the Element corresponding to the specified key. +func (lm *LinkedMap[K, V]) GetNode(key K) *linkedlist.Element[Pair[K, V]] { + node, found := lm.hashmap[key] if found { - return ln + return node } return nil } -// TailNode returns the LinkNode at the end (tail) of the LinkedMap. -func (lm *LinkedMap[K, V]) TailNode() *ll.Element[Pair[K, V]] { - ln := lm.list.Tail - if ln == nil { +// TailNode returns the Element at the end (tail) of the LinkedMap. +func (lm *LinkedMap[K, V]) TailNode() *linkedlist.Element[Pair[K, V]] { + node := lm.list.Tail + if node == nil { return nil } - return ln + return node } func (lm *LinkedMap[K, V]) RemoveTail() { lm.remove(lm.list.Tail) } -// HeadNode returns the LinkNode at the beginning (head) of the LinkedMap. -func (lm *LinkedMap[K, V]) HeadNode() *ll.Element[Pair[K, V]] { - ln := lm.list.Head - if ln == nil { +// HeadNode returns the Element at the beginning (head) of the LinkedMap. +func (lm *LinkedMap[K, V]) HeadNode() *linkedlist.Element[Pair[K, V]] { + node := lm.list.Head + if node == nil { return nil } - return ln + return node } func (lm *LinkedMap[K, V]) RemoveHead() { @@ -122,7 +122,7 @@ func (lm *LinkedMap[K, V]) Remove(key K) bool { } // remove removes the specified element pair from the LinkedMap. -func (lm *LinkedMap[K, V]) remove(element *ll.Element[Pair[K, V]]) { +func (lm *LinkedMap[K, V]) remove(element *linkedlist.Element[Pair[K, V]]) { lm.list.Delete(element) delete(lm.hashmap, element.Data.Key) } @@ -150,7 +150,7 @@ func (lm *LinkedMap[K, V]) Full() bool { // Clear removes all key-value pairs from the LinkedMap, making it empty. func (lm *LinkedMap[K, V]) Clear() { lm.list.Clear() - lm.hashmap = make(map[K]*ll.Element[Pair[K, V]]) + lm.hashmap = make(map[K]*linkedlist.Element[Pair[K, V]]) } // prune removes excess elements from the LinkedMap if its size exceeds the capacity. diff --git a/util/linkedmap/linkedmap_test.go b/util/linkedmap/linkedmap_test.go index 887d002c6..7619924a8 100644 --- a/util/linkedmap/linkedmap_test.go +++ b/util/linkedmap/linkedmap_test.go @@ -8,396 +8,396 @@ import ( func TestLinkedMap(t *testing.T) { t.Run("Test FirstNode", func(t *testing.T) { - lm := New[int, string](4) - assert.Nil(t, lm.HeadNode()) + lmp := New[int, string](4) + assert.Nil(t, lmp.HeadNode()) - lm.PushFront(3, "c") - lm.PushFront(2, "b") - lm.PushFront(1, "a") + lmp.PushFront(3, "c") + lmp.PushFront(2, "b") + lmp.PushFront(1, "a") - assert.Equal(t, lm.HeadNode().Data.Key, 1) - assert.Equal(t, lm.HeadNode().Data.Value, "a") + assert.Equal(t, lmp.HeadNode().Data.Key, 1) + assert.Equal(t, lmp.HeadNode().Data.Value, "a") }) t.Run("Test LastNode", func(t *testing.T) { - lm := New[int, string](4) - assert.Nil(t, lm.TailNode()) + lmp := New[int, string](4) + assert.Nil(t, lmp.TailNode()) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") - assert.Equal(t, lm.TailNode().Data.Key, 3) - assert.Equal(t, lm.TailNode().Data.Value, "c") + assert.Equal(t, lmp.TailNode().Data.Key, 3) + assert.Equal(t, lmp.TailNode().Data.Value, "c") }) t.Run("Test Get", func(t *testing.T) { - lm := New[int, string](4) + lmp := New[int, string](4) - lm.PushBack(2, "b") - lm.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(1, "a") - n := lm.GetNode(2) - assert.Equal(t, n.Data.Key, 2) - assert.Equal(t, n.Data.Value, "b") + node := lmp.GetNode(2) + assert.Equal(t, node.Data.Key, 2) + assert.Equal(t, node.Data.Value, "b") - n = lm.GetNode(5) - assert.Nil(t, n) + node = lmp.GetNode(5) + assert.Nil(t, node) }) t.Run("Test Remove", func(t *testing.T) { - lm := New[int, string](4) + lmp := New[int, string](4) - lm.PushBack(0, "-") - lm.PushBack(2, "b") - lm.PushBack(1, "a") - assert.True(t, lm.Remove(2)) - assert.False(t, lm.Remove(2)) + lmp.PushBack(0, "-") + lmp.PushBack(2, "b") + lmp.PushBack(1, "a") + assert.True(t, lmp.Remove(2)) + assert.False(t, lmp.Remove(2)) }) t.Run("Test RemoveTail", func(t *testing.T) { - lm := New[int, string](4) - lm.PushBack(0, "-") - lm.PushBack(1, "a") - lm.PushBack(2, "b") - - lm.RemoveTail() - assert.Equal(t, lm.TailNode().Data.Value, "a") - assert.NotEqual(t, lm.TailNode().Data.Value, "b") + lmp := New[int, string](4) + lmp.PushBack(0, "-") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + + lmp.RemoveTail() + assert.Equal(t, lmp.TailNode().Data.Value, "a") + assert.NotEqual(t, lmp.TailNode().Data.Value, "b") }) t.Run("Test RemoveHead", func(t *testing.T) { - lm := New[int, string](4) - lm.PushBack(0, "-") - lm.PushBack(1, "a") - lm.PushBack(2, "b") - - lm.RemoveHead() - assert.Equal(t, lm.HeadNode().Data.Value, "a") - assert.NotEqual(t, lm.HeadNode().Data.Value, "-") + lmp := New[int, string](4) + lmp.PushBack(0, "-") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + + lmp.RemoveHead() + assert.Equal(t, lmp.HeadNode().Data.Value, "a") + assert.NotEqual(t, lmp.HeadNode().Data.Value, "-") }) t.Run("Should updates v", func(t *testing.T) { - lm := New[int, string](4) - lm.PushBack(1, "a") - - lm.PushBack(1, "b") - n := lm.GetNode(1) - assert.Equal(t, n.Data.Key, 1) - assert.Equal(t, n.Data.Value, "b") - - lm.PushFront(1, "c") - n = lm.GetNode(1) - assert.Equal(t, n.Data.Key, 1) - assert.Equal(t, n.Data.Value, "c") + lmp := New[int, string](4) + lmp.PushBack(1, "a") + + lmp.PushBack(1, "b") + node := lmp.GetNode(1) + assert.Equal(t, node.Data.Key, 1) + assert.Equal(t, node.Data.Value, "b") + + lmp.PushFront(1, "c") + node = lmp.GetNode(1) + assert.Equal(t, node.Data.Key, 1) + assert.Equal(t, node.Data.Value, "c") }) t.Run("Should prunes oldest item", func(t *testing.T) { - lm := New[int, string](4) + lmp := New[int, string](4) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") - lm.PushBack(4, "d") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") + lmp.PushBack(4, "d") - n := lm.GetNode(1) - assert.Equal(t, n.Data.Key, 1) - assert.Equal(t, n.Data.Value, "a") + node := lmp.GetNode(1) + assert.Equal(t, node.Data.Key, 1) + assert.Equal(t, node.Data.Value, "a") - lm.PushBack(5, "e") + lmp.PushBack(5, "e") - n = lm.GetNode(1) - assert.Nil(t, n) + node = lmp.GetNode(1) + assert.Nil(t, node) }) t.Run("Should prunes by changing capacity", func(t *testing.T) { - lm := New[int, string](4) + lmp := New[int, string](4) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") - lm.PushBack(4, "d") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") + lmp.PushBack(4, "d") - lm.SetCapacity(6) + lmp.SetCapacity(6) - n := lm.GetNode(2) - assert.Equal(t, n.Data.Key, 2) - assert.Equal(t, n.Data.Value, "b") + node := lmp.GetNode(2) + assert.Equal(t, node.Data.Key, 2) + assert.Equal(t, node.Data.Value, "b") - lm.SetCapacity(2) - assert.True(t, lm.Full()) + lmp.SetCapacity(2) + assert.True(t, lmp.Full()) - n = lm.GetNode(2) - assert.Nil(t, n) + node = lmp.GetNode(2) + assert.Nil(t, node) }) t.Run("Test PushBack and prune", func(t *testing.T) { - lm := New[int, string](3) + lmp := New[int, string](3) - lm.PushBack(1, "a") // This item should be pruned - lm.PushBack(2, "b") - lm.PushBack(3, "c") - lm.PushBack(4, "d") + lmp.PushBack(1, "a") // This item should be pruned + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") + lmp.PushBack(4, "d") - n := lm.HeadNode() - assert.Equal(t, n.Data.Key, 2) - assert.Equal(t, n.Data.Value, "b") + node := lmp.HeadNode() + assert.Equal(t, node.Data.Key, 2) + assert.Equal(t, node.Data.Value, "b") }) t.Run("Test PushFront and prune", func(t *testing.T) { - lm := New[int, string](3) + lmp := New[int, string](3) - lm.PushFront(1, "a") - lm.PushFront(2, "b") - lm.PushFront(3, "c") - lm.PushFront(4, "d") // This item should be pruned + lmp.PushFront(1, "a") + lmp.PushFront(2, "b") + lmp.PushFront(3, "c") + lmp.PushFront(4, "d") // This item should be pruned - n := lm.TailNode() - assert.Equal(t, n.Data.Key, 1) - assert.Equal(t, n.Data.Value, "a") + node := lmp.TailNode() + assert.Equal(t, node.Data.Key, 1) + assert.Equal(t, node.Data.Value, "a") }) t.Run("Delete first ", func(t *testing.T) { - lm := New[int, string](3) + lmp := New[int, string](3) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") - lm.Remove(1) + lmp.Remove(1) - assert.Equal(t, lm.HeadNode().Data.Key, 2) - assert.Equal(t, lm.HeadNode().Data.Value, "b") + assert.Equal(t, lmp.HeadNode().Data.Key, 2) + assert.Equal(t, lmp.HeadNode().Data.Value, "b") }) t.Run("Delete last", func(t *testing.T) { - lm := New[int, string](3) + lmp := New[int, string](3) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") - lm.Remove(3) + lmp.Remove(3) - assert.Equal(t, lm.TailNode().Data.Key, 2) - assert.Equal(t, lm.TailNode().Data.Value, "b") + assert.Equal(t, lmp.TailNode().Data.Key, 2) + assert.Equal(t, lmp.TailNode().Data.Value, "b") }) t.Run("Test Has function", func(t *testing.T) { - lm := New[int, string](2) + lmp := New[int, string](2) - lm.PushBack(1, "a") + lmp.PushBack(1, "a") - assert.True(t, lm.Has(1)) - assert.False(t, lm.Has(2)) + assert.True(t, lmp.Has(1)) + assert.False(t, lmp.Has(2)) }) t.Run("Test Clear", func(t *testing.T) { - lm := New[int, string](2) + lmp := New[int, string](2) - lm.PushBack(1, "a") - lm.Clear() - assert.True(t, lm.Empty()) + lmp.PushBack(1, "a") + lmp.Clear() + assert.True(t, lmp.Empty()) }) } func TestCapacity(t *testing.T) { t.Run("Check Capacity", func(t *testing.T) { capacity := 100 - lm := New[int, string](capacity) - assert.Equal(t, lm.Capacity(), capacity) + lmp := New[int, string](capacity) + assert.Equal(t, lmp.Capacity(), capacity) }) t.Run("Test FirstNode with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) - assert.Nil(t, lm.HeadNode()) + lmp := New[int, string](0) + assert.Nil(t, lmp.HeadNode()) - lm.PushFront(3, "c") - lm.PushFront(2, "b") - lm.PushFront(1, "a") + lmp.PushFront(3, "c") + lmp.PushFront(2, "b") + lmp.PushFront(1, "a") - assert.Equal(t, lm.HeadNode().Data.Key, 1) - assert.Equal(t, lm.HeadNode().Data.Value, "a") + assert.Equal(t, lmp.HeadNode().Data.Key, 1) + assert.Equal(t, lmp.HeadNode().Data.Value, "a") }) t.Run("Test LastNode with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) - assert.Nil(t, lm.TailNode()) + lmp := New[int, string](0) + assert.Nil(t, lmp.TailNode()) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") - assert.Equal(t, lm.TailNode().Data.Key, 3) - assert.Equal(t, lm.TailNode().Data.Value, "c") + assert.Equal(t, lmp.TailNode().Data.Key, 3) + assert.Equal(t, lmp.TailNode().Data.Value, "c") }) t.Run("Test Get with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(2, "b") - lm.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(1, "a") - n := lm.GetNode(2) - assert.Equal(t, n.Data.Key, 2) - assert.Equal(t, n.Data.Value, "b") + node := lmp.GetNode(2) + assert.Equal(t, node.Data.Key, 2) + assert.Equal(t, node.Data.Value, "b") - n = lm.GetNode(5) - assert.Nil(t, n) + node = lmp.GetNode(5) + assert.Nil(t, node) }) t.Run("Test Remove with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(0, "-") - lm.PushBack(2, "b") - lm.PushBack(1, "a") - assert.True(t, lm.Remove(2)) - assert.False(t, lm.Remove(2)) + lmp.PushBack(0, "-") + lmp.PushBack(2, "b") + lmp.PushBack(1, "a") + assert.True(t, lmp.Remove(2)) + assert.False(t, lmp.Remove(2)) }) t.Run("Test RemoveTail with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) - lm.PushBack(0, "-") - lm.PushBack(1, "a") - lm.PushBack(2, "b") - - lm.RemoveTail() - assert.Equal(t, lm.TailNode().Data.Value, "a") - assert.NotEqual(t, lm.TailNode().Data.Value, "b") + lmp := New[int, string](0) + lmp.PushBack(0, "-") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + + lmp.RemoveTail() + assert.Equal(t, lmp.TailNode().Data.Value, "a") + assert.NotEqual(t, lmp.TailNode().Data.Value, "b") }) t.Run("Test RemoveHead with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) - lm.PushBack(0, "-") - lm.PushBack(1, "a") - lm.PushBack(2, "b") - - lm.RemoveHead() - assert.Equal(t, lm.HeadNode().Data.Value, "a") - assert.NotEqual(t, lm.HeadNode().Data.Value, "-") + lmp := New[int, string](0) + lmp.PushBack(0, "-") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + + lmp.RemoveHead() + assert.Equal(t, lmp.HeadNode().Data.Value, "a") + assert.NotEqual(t, lmp.HeadNode().Data.Value, "-") }) t.Run("Should updates v with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) - lm.PushBack(1, "a") - - lm.PushBack(1, "b") - n := lm.GetNode(1) - assert.Equal(t, n.Data.Key, 1) - assert.Equal(t, n.Data.Value, "b") - - lm.PushFront(1, "c") - n = lm.GetNode(1) - assert.Equal(t, n.Data.Key, 1) - assert.Equal(t, n.Data.Value, "c") + lmp := New[int, string](0) + lmp.PushBack(1, "a") + + lmp.PushBack(1, "b") + node := lmp.GetNode(1) + assert.Equal(t, node.Data.Key, 1) + assert.Equal(t, node.Data.Value, "b") + + lmp.PushFront(1, "c") + node = lmp.GetNode(1) + assert.Equal(t, node.Data.Key, 1) + assert.Equal(t, node.Data.Value, "c") }) t.Run("Should not prunes oldest item with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") - lm.PushBack(4, "d") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") + lmp.PushBack(4, "d") - n := lm.GetNode(1) - assert.Equal(t, n.Data.Key, 1) - assert.Equal(t, n.Data.Value, "a") + node := lmp.GetNode(1) + assert.Equal(t, node.Data.Key, 1) + assert.Equal(t, node.Data.Value, "a") - lm.PushBack(5, "e") + lmp.PushBack(5, "e") - n = lm.GetNode(1) - assert.NotNil(t, n) + node = lmp.GetNode(1) + assert.NotNil(t, node) }) t.Run("Should prunes by changing capacity with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") - lm.PushBack(4, "d") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") + lmp.PushBack(4, "d") - lm.SetCapacity(6) + lmp.SetCapacity(6) - n := lm.GetNode(2) - assert.Equal(t, n.Data.Key, 2) - assert.Equal(t, n.Data.Value, "b") + node := lmp.GetNode(2) + assert.Equal(t, node.Data.Key, 2) + assert.Equal(t, node.Data.Value, "b") - lm.SetCapacity(2) - assert.True(t, lm.Full()) + lmp.SetCapacity(2) + assert.True(t, lmp.Full()) - n = lm.GetNode(2) - assert.Nil(t, n) + node = lmp.GetNode(2) + assert.Nil(t, node) }) t.Run("Test PushBack and should not prune with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(1, "a") // This item should be pruned - lm.PushBack(2, "b") - lm.PushBack(3, "c") - lm.PushBack(4, "d") + lmp.PushBack(1, "a") // This item should be pruned + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") + lmp.PushBack(4, "d") - n := lm.TailNode() - assert.Equal(t, n.Data.Key, 4) - assert.Equal(t, n.Data.Value, "d") + node := lmp.TailNode() + assert.Equal(t, node.Data.Key, 4) + assert.Equal(t, node.Data.Value, "d") }) t.Run("Test PushFront and prune with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushFront(1, "a") - lm.PushFront(2, "b") - lm.PushFront(3, "c") - lm.PushFront(4, "d") // This item should be pruned + lmp.PushFront(1, "a") + lmp.PushFront(2, "b") + lmp.PushFront(3, "c") + lmp.PushFront(4, "d") // This item should be pruned - n := lm.TailNode() + n := lmp.TailNode() assert.Equal(t, n.Data.Key, 1) assert.Equal(t, n.Data.Value, "a") }) t.Run("Delete first with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") - lm.Remove(1) + lmp.Remove(1) - assert.Equal(t, lm.HeadNode().Data.Key, 2) - assert.Equal(t, lm.HeadNode().Data.Value, "b") + assert.Equal(t, lmp.HeadNode().Data.Key, 2) + assert.Equal(t, lmp.HeadNode().Data.Value, "b") }) t.Run("Delete last with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(1, "a") - lm.PushBack(2, "b") - lm.PushBack(3, "c") + lmp.PushBack(1, "a") + lmp.PushBack(2, "b") + lmp.PushBack(3, "c") - lm.Remove(3) + lmp.Remove(3) - assert.Equal(t, lm.TailNode().Data.Key, 2) - assert.Equal(t, lm.TailNode().Data.Value, "b") + assert.Equal(t, lmp.TailNode().Data.Key, 2) + assert.Equal(t, lmp.TailNode().Data.Value, "b") }) t.Run("Test Has function with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(1, "a") + lmp.PushBack(1, "a") - assert.True(t, lm.Has(1)) - assert.False(t, lm.Has(2)) + assert.True(t, lmp.Has(1)) + assert.False(t, lmp.Has(2)) }) t.Run("Test Clear with Zero Capacity", func(t *testing.T) { - lm := New[int, string](0) + lmp := New[int, string](0) - lm.PushBack(1, "a") - lm.Clear() - assert.True(t, lm.Empty()) + lmp.PushBack(1, "a") + lmp.Clear() + assert.True(t, lmp.Empty()) }) } diff --git a/util/logger/logger.go b/util/logger/logger.go index d55bccf92..03fd0b5a1 100644 --- a/util/logger/logger.go +++ b/util/logger/logger.go @@ -73,21 +73,24 @@ func InitGlobalLogger(conf *Config) { writers := []io.Writer{} if slices.Contains(conf.Targets, "file") { - // file writer - fw := &lumberjack.Logger{ + fileWriter := &lumberjack.Logger{ Filename: LogFilename, MaxSize: MaxLogSize, MaxBackups: conf.MaxBackups, Compress: conf.Compress, MaxAge: conf.RotateLogAfterDays, } - writers = append(writers, fw) + writers = append(writers, fileWriter) } if slices.Contains(conf.Targets, "console") { // console writer if conf.Colorful { - writers = append(writers, zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: "15:04:05"}) + consoleWriter := &zerolog.ConsoleWriter{ + Out: os.Stderr, + TimeFormat: "15:04:05", + } + writers = append(writers, consoleWriter) } else { writers = append(writers, os.Stderr) } @@ -111,32 +114,32 @@ func addFields(event *zerolog.Event, keyvals ...any) *zerolog.Event { if len(keyvals)%2 != 0 { keyvals = append(keyvals, "!MISSING-VALUE!") } - for i := 0; i < len(keyvals); i += 2 { - key, ok := keyvals[i].(string) + for index := 0; index < len(keyvals); index += 2 { + key, ok := keyvals[index].(string) if !ok { key = "!INVALID-KEY!" } - value := keyvals[i+1] - switch v := value.(type) { + value := keyvals[index+1] + switch typ := value.(type) { case fmt.Stringer: - if isNil(v) { - event.Any(key, v) + if isNil(typ) { + event.Any(key, typ) } else { - event.Stringer(key, v) + event.Stringer(key, typ) } case ShortStringer: - if isNil(v) { - event.Any(key, v) + if isNil(typ) { + event.Any(key, typ) } else { - event.Str(key, v.ShortString()) + event.Str(key, typ.ShortString()) } case error: - event.AnErr(key, v) + event.AnErr(key, typ) case []byte: - event.Str(key, hex.EncodeToString(v)) + event.Str(key, hex.EncodeToString(typ)) default: - event.Any(key, v) + event.Any(key, typ) } } @@ -145,7 +148,7 @@ func addFields(event *zerolog.Event, keyvals ...any) *zerolog.Event { func NewSubLogger(name string, obj fmt.Stringer) *SubLogger { inst := getLoggersInst() - sl := &SubLogger{ + sub := &SubLogger{ logger: zerolog.New(inst.writer).With().Timestamp().Logger(), name: name, obj: obj, @@ -160,11 +163,11 @@ func NewSubLogger(name string, obj fmt.Stringer) *SubLogger { if err != nil { Warn("invalid log level", "error", err, "name", name) } - sl.logger = sl.logger.Level(lvl) + sub.logger = sub.logger.Level(lvl) - inst.subs[name] = sl + inst.subs[name] = sub - return sl + return sub } func (sl *SubLogger) logObj(event *zerolog.Event, msg string, keyvals ...any) { diff --git a/util/logger/logger_test.go b/util/logger/logger_test.go index 62a7d24bc..72f4ddbd5 100644 --- a/util/logger/logger_test.go +++ b/util/logger/logger_test.go @@ -38,15 +38,15 @@ func TestObjLogger(t *testing.T) { InitGlobalLogger(c) globalInst.config.Levels["test"] = "warn" - l := NewSubLogger("test", Foo{}) + subLogger := NewSubLogger("test", Foo{}) var buf bytes.Buffer - l.logger = l.logger.Output(&buf) + subLogger.logger = subLogger.logger.Output(&buf) - l.Trace("msg") - l.Debug("msg") - l.Info("msg") - l.Warn("msg") - l.Error("msg") + subLogger.Trace("msg") + subLogger.Debug("msg") + subLogger.Info("msg") + subLogger.Warn("msg") + subLogger.Error("msg") out := buf.String() diff --git a/util/pairslice/pairslice_test.go b/util/pairslice/pairslice_test.go index 94820dce1..2e94602ff 100644 --- a/util/pairslice/pairslice_test.go +++ b/util/pairslice/pairslice_test.go @@ -7,124 +7,124 @@ import ( ) func TestNew(t *testing.T) { - ps := New[int, string](10) + slice := New[int, string](10) - assert.NotNil(t, ps) - assert.Equal(t, 10, cap(ps.pairs)) - assert.Equal(t, 0, len(ps.pairs)) + assert.NotNil(t, slice) + assert.Equal(t, 10, cap(slice.pairs)) + assert.Equal(t, 0, len(slice.pairs)) } func TestPairSlice(t *testing.T) { t.Run("Test Append", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(2, "b") - ps.Append(3, "c") + slice.Append(1, "a") + slice.Append(2, "b") + slice.Append(3, "c") - assert.Equal(t, 3, ps.Len()) - assert.Equal(t, ps.pairs[2].First, 3) - assert.Equal(t, ps.pairs[2].Second, "c") + assert.Equal(t, 3, slice.Len()) + assert.Equal(t, slice.pairs[2].First, 3) + assert.Equal(t, slice.pairs[2].Second, "c") }) t.Run("Test RemoveFirst", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(2, "b") - ps.Append(3, "c") + slice.Append(1, "a") + slice.Append(2, "b") + slice.Append(3, "c") - ps.RemoveFirst() + slice.RemoveFirst() - assert.Equal(t, ps.pairs[0].First, 2) - assert.Equal(t, ps.pairs[0].Second, "b") + assert.Equal(t, slice.pairs[0].First, 2) + assert.Equal(t, slice.pairs[0].Second, "b") }) t.Run("Test RemoveLast", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(2, "b") - ps.Append(3, "c") - ps.Append(4, "d") + slice.Append(1, "a") + slice.Append(2, "b") + slice.Append(3, "c") + slice.Append(4, "d") - ps.RemoveLast() + slice.RemoveLast() - assert.Equal(t, ps.pairs[2].First, 3) - assert.Equal(t, ps.pairs[2].Second, "c") + assert.Equal(t, slice.pairs[2].First, 3) + assert.Equal(t, slice.pairs[2].Second, "c") }) t.Run("Test Len", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(2, "b") + slice.Append(1, "a") + slice.Append(2, "b") - assert.Equal(t, 2, ps.Len()) + assert.Equal(t, 2, slice.Len()) }) t.Run("Test Remove", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(2, "b") - ps.Append(3, "c") - ps.Append(4, "d") + slice.Append(1, "a") + slice.Append(2, "b") + slice.Append(3, "c") + slice.Append(4, "d") - ps.remove(1) + slice.remove(1) - assert.Equal(t, ps.pairs[1].First, 3) - assert.Equal(t, ps.pairs[1].Second, "c") + assert.Equal(t, slice.pairs[1].First, 3) + assert.Equal(t, slice.pairs[1].Second, "c") }) t.Run("Test Get", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(2, "b") - ps.Append(3, "c") - ps.Append(4, "d") + slice.Append(1, "a") + slice.Append(2, "b") + slice.Append(3, "c") + slice.Append(4, "d") - first, second, _ := ps.Get(2) - assert.Equal(t, ps.pairs[2].First, first) - assert.Equal(t, ps.pairs[2].Second, second) + first, second, _ := slice.Get(2) + assert.Equal(t, slice.pairs[2].First, first) + assert.Equal(t, slice.pairs[2].Second, second) }) t.Run("Test Get negative index or bigger than len", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(4, "d") + slice.Append(1, "a") + slice.Append(4, "d") - _, _, result1 := ps.Get(-1) - _, _, result2 := ps.Get(10) + _, _, result1 := slice.Get(-1) + _, _, result2 := slice.Get(10) assert.False(t, result1) assert.False(t, result2) }) t.Run("Test First", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(2, "b") - ps.Append(3, "c") - ps.Append(4, "d") + slice.Append(1, "a") + slice.Append(2, "b") + slice.Append(3, "c") + slice.Append(4, "d") - first, second, _ := ps.First() - assert.Equal(t, ps.pairs[0].First, first) - assert.Equal(t, ps.pairs[0].Second, second) + first, second, _ := slice.First() + assert.Equal(t, slice.pairs[0].First, first) + assert.Equal(t, slice.pairs[0].Second, second) }) t.Run("Test Last", func(t *testing.T) { - ps := New[int, string](4) + slice := New[int, string](4) - ps.Append(1, "a") - ps.Append(2, "b") - ps.Append(3, "c") - ps.Append(4, "d") + slice.Append(1, "a") + slice.Append(2, "b") + slice.Append(3, "c") + slice.Append(4, "d") - first, second, _ := ps.Last() - assert.Equal(t, ps.pairs[3].First, first) - assert.Equal(t, ps.pairs[3].Second, second) + first, second, _ := slice.Last() + assert.Equal(t, slice.pairs[3].First, first) + assert.Equal(t, slice.pairs[3].Second, second) }) } diff --git a/util/persistentmerkle/merkle.go b/util/persistentmerkle/merkle.go index e905bf86e..3021f8744 100644 --- a/util/persistentmerkle/merkle.go +++ b/util/persistentmerkle/merkle.go @@ -98,15 +98,15 @@ func (t *Tree) Root() hash.Hash { } func (t *Tree) nodeHash(width, height int) hash.Hash { - n := t.getNode(width, height) - if n == nil { - n = t.getNode(width-1, height) - if n == nil { + node := t.getNode(width, height) + if node == nil { + node = t.getNode(width-1, height) + if node == nil { panic("invalid merkle tree") } } - if n.hash != nil { - return *n.hash + if node.hash != nil { + return *node.hash } left := t.nodeHash(width*2, height-1) @@ -117,7 +117,7 @@ func (t *Tree) nodeHash(width, height int) hash.Hash { copy(data[hash.HashSize:], right.Bytes()) h := hash.CalcHash(data) - n.hash = &h + node.hash = &h return h } diff --git a/util/ratelimit/ratelimit_test.go b/util/ratelimit/ratelimit_test.go index e101e3604..9eee724b5 100644 --- a/util/ratelimit/ratelimit_test.go +++ b/util/ratelimit/ratelimit_test.go @@ -10,38 +10,38 @@ import ( func TestRateLimit(t *testing.T) { threshold := 5 window := 100 * time.Millisecond - r := NewRateLimit(threshold, window) + rateLimit := NewRateLimit(threshold, window) t.Run("InitialState", func(t *testing.T) { - assert.Equal(t, 0, r.counter) + assert.Equal(t, 0, rateLimit.counter) }) t.Run("AllowRequestWithinThreshold", func(t *testing.T) { for i := 0; i < threshold; i++ { - assert.True(t, r.AllowRequest()) + assert.True(t, rateLimit.AllowRequest()) } - assert.Equal(t, threshold, r.counter) + assert.Equal(t, threshold, rateLimit.counter) }) t.Run("ExceedThreshold", func(t *testing.T) { - assert.False(t, r.AllowRequest()) + assert.False(t, rateLimit.AllowRequest()) }) t.Run("ResetAfterWindow", func(t *testing.T) { time.Sleep(window + 10*time.Millisecond) - assert.True(t, r.AllowRequest()) - assert.Equal(t, 1, r.counter) + assert.True(t, rateLimit.AllowRequest()) + assert.Equal(t, 1, rateLimit.counter) }) t.Run("ResetMethod", func(t *testing.T) { - r.reset() - assert.Equal(t, 0, r.counter) - assert.True(t, r.AllowRequest()) - assert.Equal(t, 1, r.counter) + rateLimit.reset() + assert.Equal(t, 0, rateLimit.counter) + assert.True(t, rateLimit.AllowRequest()) + assert.Equal(t, 1, rateLimit.counter) }) t.Run("DiffMethod", func(t *testing.T) { - assert.LessOrEqual(t, r.diff(), window) + assert.LessOrEqual(t, rateLimit.diff(), window) }) } diff --git a/util/shell/shell.go b/util/shell/shell.go index a94c44aeb..67b0f7c37 100644 --- a/util/shell/shell.go +++ b/util/shell/shell.go @@ -23,7 +23,7 @@ type lexer struct { // New creates a Cobra CLI command named "shell" which runs an interactive shell prompt for the root command. func New(root *cobra.Command, refresh func() *cobra.Command, opts ...prompt.Option) *cobra.Command { - sh := &lexer{ + lexer := &lexer{ root: root, refresh: refresh, cache: make(map[string][]prompt.Suggest), @@ -36,12 +36,12 @@ func New(root *cobra.Command, refresh func() *cobra.Command, opts ...prompt.Opti Use: "shell", Short: "Start an interactive shell.", Run: func(cmd *cobra.Command, _ []string) { - sh.saveStdin() + lexer.saveStdin() - sh.editCommandTree(cmd) - prompt.New(sh.executor, sh.completer, opts...).Run() + lexer.editCommandTree(cmd) + prompt.New(lexer.executor, lexer.completer, opts...).Run() - sh.restoreStdin() + lexer.restoreStdin() }, } } @@ -110,8 +110,8 @@ func (s *lexer) restoreStdin() { } } -func (s *lexer) completer(d prompt.Document) []prompt.Suggest { - args, err := buildCompletionArgs(d.CurrentLine()) +func (s *lexer) completer(doc prompt.Document) []prompt.Suggest { + args, err := buildCompletionArgs(doc.CurrentLine()) if err != nil { return nil } @@ -132,7 +132,7 @@ func (s *lexer) completer(d prompt.Document) []prompt.Suggest { s.cache[key] = suggestions } - return prompt.FilterHasPrefix(suggestions, d.GetWordBeforeCursor(), true) + return prompt.FilterHasPrefix(suggestions, doc.GetWordBeforeCursor(), true) } func buildCompletionArgs(input string) ([]string, error) { @@ -164,19 +164,19 @@ func readCommandOutput(cmd *cobra.Command, args []string) (string, error) { } func execute(cmd *cobra.Command, args []string) error { - if c, _, err := cmd.Find(args); err == nil { + if cobraCmd, _, err := cmd.Find(args); err == nil { // Reset flag values between runs due to a limitation in Cobra - c.Flags().VisitAll(func(flag *pflag.Flag) { + cobraCmd.Flags().VisitAll(func(flag *pflag.Flag) { if val, ok := flag.Value.(pflag.SliceValue); ok { _ = val.Replace([]string{}) } else { _ = flag.Value.Set(flag.DefValue) } - _ = c.Flags().SetAnnotation(flag.Name, cobra.BashCompOneRequiredFlag, []string{"false"}) + _ = cobraCmd.Flags().SetAnnotation(flag.Name, cobra.BashCompOneRequiredFlag, []string{"false"}) }) - c.InitDefaultHelpFlag() + cobraCmd.InitDefaultHelpFlag() } cmd.SetArgs(args) @@ -193,37 +193,37 @@ func parseSuggestions(out string) []prompt.Suggest { } for _, line := range x[:len(x)-2] { - l := strings.SplitN(line, "\t", 2) + tokens := strings.SplitN(line, "\t", 2) - if isShorthandFlag(l[0]) { + if isShorthandFlag(tokens[0]) { continue } - suggestion := prompt.Suggest{Text: escapeSpecialCharacters(l[0])} - if len(l) > 1 { - suggestion.Description = l[1] + suggestion := prompt.Suggest{Text: escapeSpecialCharacters(tokens[0])} + if len(tokens) > 1 { + suggestion.Description = tokens[1] } suggestions = append(suggestions, suggestion) } sort.Slice(suggestions, func(i, j int) bool { - it := suggestions[i].Text - jt := suggestions[j].Text + iText := suggestions[i].Text + jText := suggestions[j].Text - if isFlag(it) && isFlag(jt) { - return it < jt + if isFlag(iText) && isFlag(jText) { + return iText < jText } - if isFlag(it) { + if isFlag(iText) { return false } - if isFlag(jt) { + if isFlag(jText) { return true } - return it < jt + return iText < jText }) return suggestions diff --git a/util/simplemerkle/merkle.go b/util/simplemerkle/merkle.go index 692e9f482..4423f02bb 100644 --- a/util/simplemerkle/merkle.go +++ b/util/simplemerkle/merkle.go @@ -22,17 +22,16 @@ type Tree struct { merkles []*hash.Hash } -// nextPowerOfTwo returns the next highest power of two from a given number if -// it is not already a power of two. This is a helper function used during the -// calculation of a merkle tree. -func nextPowerOfTwo(n int) int { +// nextPowerOfTwo returns the smallest power of two that is greater than or equal to +// the given number. If the number is already a power of two, it returns the number itself. +func nextPowerOfTwo(num int) int { // Return the number if it's already a power of 2. - if n&(n-1) == 0 { - return n + if num&(num-1) == 0 { + return num } // Figure out and return the next power of two. - exponent := uint(math.Log2(float64(n))) + 1 + exponent := uint(math.Log2(float64(num))) + 1 return 1 << exponent // 2^exponent } @@ -77,22 +76,22 @@ func NewTreeFromHashes(hashes []hash.Hash) *Tree { // Start the array offset after the last transaction and adjusted to the // next power of two. offset := nextPoT - for i := 0; i < arraySize-1; i += 2 { + for index := 0; index < arraySize-1; index += 2 { switch { // When there is no left child node, the parent is nil too. - case merkles[i] == nil: + case merkles[index] == nil: merkles[offset] = nil // When there is no right child, the parent is generated by // hashing the concatenation of the left child with itself. - case merkles[i+1] == nil: - newHash := HashMerkleBranches(merkles[i], merkles[i]) + case merkles[index+1] == nil: + newHash := HashMerkleBranches(merkles[index], merkles[index]) merkles[offset] = newHash // The normal case sets the parent node to the double sha256 // of the concatenation of the left and right children. default: - newHash := HashMerkleBranches(merkles[i], merkles[i+1]) + newHash := HashMerkleBranches(merkles[index], merkles[index+1]) merkles[offset] = newHash } offset++ diff --git a/util/simplemerkle/merkle_test.go b/util/simplemerkle/merkle_test.go index dafec9507..db37ee637 100644 --- a/util/simplemerkle/merkle_test.go +++ b/util/simplemerkle/merkle_test.go @@ -64,23 +64,17 @@ func TestMerkleTree_Bitcoin_Block100000(t *testing.T) { } // Block 100000 in bitcoin - wantMerkle, _ := hex.DecodeString("6657A9252AACD5C0B2940996ECFF952228C3067CC38D4885EFB5A4AC4247E9F3") - id1, _ := hex.DecodeString("876DD0A3EF4A2816FFD1C12AB649825A958B0FF3BB3D6F3E1250F13DDBF0148C") - id2, _ := hex.DecodeString("C40297F730DD7B5A99567EB8D27B78758F607507C52292D02D4031895B52F2FF") - id3, _ := hex.DecodeString("C46E239AB7D28E2C019B6D66AD8FAE98A56EF1F21AEECB94D1B1718186F05963") - id4, _ := hex.DecodeString("1D0CB83721529A062D9675B98D6E5C587E4A770FC84ED00ABC5A5DE04568A6E9") - - root, _ := hash.FromBytes(wantMerkle) - h1, _ := hash.FromBytes(id1) - h2, _ := hash.FromBytes(id2) - h3, _ := hash.FromBytes(id3) - h4, _ := hash.FromBytes(id4) + root, _ := hash.FromString("6657A9252AACD5C0B2940996ECFF952228C3067CC38D4885EFB5A4AC4247E9F3") + hash1, _ := hash.FromString("876DD0A3EF4A2816FFD1C12AB649825A958B0FF3BB3D6F3E1250F13DDBF0148C") + hash2, _ := hash.FromString("C40297F730DD7B5A99567EB8D27B78758F607507C52292D02D4031895B52F2FF") + hash3, _ := hash.FromString("C46E239AB7D28E2C019B6D66AD8FAE98A56EF1F21AEECB94D1B1718186F05963") + hash4, _ := hash.FromString("1D0CB83721529A062D9675B98D6E5C587E4A770FC84ED00ABC5A5DE04568A6E9") hashes := []hash.Hash{ - h1, - h2, - h3, - h4, + hash1, + hash2, + hash3, + hash4, } tree := NewTreeFromHashes(hashes) @@ -99,24 +93,24 @@ func TestMerkleTree_Bitcoin_Block153342(t *testing.T) { // Block 153342 in bitcoin wantMerkle, _ := hex.DecodeString("dd8ee246e19ec5c77ddd46c1138e8af6a272da4dbb6500ea74a79c0bf89e2c07") - h1, _ := hash.FromString("216404816ca6261f9206d471d0403ba49bda4264719d879819fbda9849781e62") - h2, _ := hash.FromString("56f2602c15cb0b8e0b38e54b2961a2e541a7febbe852516cd425aa5fb72c5578") - h3, _ := hash.FromString("0d065da59871386321c2c9b2e4b6482426bcce88600ab7f55f0d27b9916a9e0c") - h4, _ := hash.FromString("1129038c38783f4c4241e54d9d702965b305b8d1e54c091fdd9f9df21240586e") - h5, _ := hash.FromString("81461f9e0e093dad14d0c5fb3978431a321bf61de33512d6cc344edb86f359f3") - h6, _ := hash.FromString("22140f4b15d76ff27d657a731fdc3040487c22ee3577c6522239d9cfbe0292ad") - h7, _ := hash.FromString("0fa273bce5137a0dbffac068ebb6f1ebe64e6be2b00cdae5a967edeb0cd96b93") - h8, _ := hash.FromString("cab481631e7f2f7d864a65d23c34bd357f46ecba60bb8117f55ed43232aa75e5") - h9, _ := hash.FromString("dffea4c267fa6949111fed23b15977d5e2efa82fefd9cd5ac81e38518d2c2bef") - h10, _ := hash.FromString("ed9f4ee5e07a47a7026725173de32efa7372243117be1aa7f60a650aef075475") - h11, _ := hash.FromString("8822c80afa3eb84bc3603509b8b6deeee37cf771ca7b49d3dd73294e05f7b29f") - h12, _ := hash.FromString("23ad44934167cc712b358f2a097b7316ca2b3c2f34472017273969e7c7e5cdb4") - h13, _ := hash.FromString("c1dc3762c6a57757a9aa895b8229613d96f272f79d14c9854132b980eaa2a2c4") + hash1, _ := hash.FromString("216404816ca6261f9206d471d0403ba49bda4264719d879819fbda9849781e62") + hash2, _ := hash.FromString("56f2602c15cb0b8e0b38e54b2961a2e541a7febbe852516cd425aa5fb72c5578") + hash3, _ := hash.FromString("0d065da59871386321c2c9b2e4b6482426bcce88600ab7f55f0d27b9916a9e0c") + hash4, _ := hash.FromString("1129038c38783f4c4241e54d9d702965b305b8d1e54c091fdd9f9df21240586e") + hash5, _ := hash.FromString("81461f9e0e093dad14d0c5fb3978431a321bf61de33512d6cc344edb86f359f3") + hash6, _ := hash.FromString("22140f4b15d76ff27d657a731fdc3040487c22ee3577c6522239d9cfbe0292ad") + hash7, _ := hash.FromString("0fa273bce5137a0dbffac068ebb6f1ebe64e6be2b00cdae5a967edeb0cd96b93") + hash8, _ := hash.FromString("cab481631e7f2f7d864a65d23c34bd357f46ecba60bb8117f55ed43232aa75e5") + hash9, _ := hash.FromString("dffea4c267fa6949111fed23b15977d5e2efa82fefd9cd5ac81e38518d2c2bef") + hash10, _ := hash.FromString("ed9f4ee5e07a47a7026725173de32efa7372243117be1aa7f60a650aef075475") + hash11, _ := hash.FromString("8822c80afa3eb84bc3603509b8b6deeee37cf771ca7b49d3dd73294e05f7b29f") + hash12, _ := hash.FromString("23ad44934167cc712b358f2a097b7316ca2b3c2f34472017273969e7c7e5cdb4") + hash13, _ := hash.FromString("c1dc3762c6a57757a9aa895b8229613d96f272f79d14c9854132b980eaa2a2c4") root, _ := hash.FromBytes(wantMerkle) hashes := []hash.Hash{ - h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13, + hash1, hash2, hash3, hash4, hash5, hash6, hash7, hash8, hash9, hash10, hash11, hash12, hash13, } tree := NewTreeFromHashes(hashes) diff --git a/util/slice.go b/util/slice.go index 2f11a3b1c..476a8a477 100644 --- a/util/slice.go +++ b/util/slice.go @@ -5,7 +5,6 @@ import ( "compress/gzip" "crypto/subtle" "encoding/binary" - "io" "math/rand" ) @@ -73,29 +72,28 @@ func StringToBytes(s string) []byte { return []byte(s) } -func CompressBuffer(s []byte) ([]byte, error) { - var b bytes.Buffer - gz := gzip.NewWriter(&b) - if _, err := gz.Write(s); err != nil { +func CompressBuffer(data []byte) ([]byte, error) { + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + if _, err := gz.Write(data); err != nil { return nil, err } if err := gz.Close(); err != nil { return nil, err } - return b.Bytes(), nil + return buf.Bytes(), nil } func DecompressBuffer(s []byte) ([]byte, error) { - b := bytes.NewBuffer(s) - var r io.Reader - r, err := gzip.NewReader(b) + buf := bytes.NewBuffer(s) + reader, err := gzip.NewReader(buf) if err != nil { return nil, err } var res bytes.Buffer - if _, err = res.ReadFrom(r); err != nil { + if _, err = res.ReadFrom(reader); err != nil { return nil, err } @@ -117,17 +115,17 @@ func Subtracts(slice1, slice2 []int32) []int32 { return slice1 } - for _, s1 := range slice1 { + for _, num1 := range slice1 { found := false - for _, s2 := range slice2 { - if s1 == s2 { + for _, num2 := range slice2 { + if num1 == num2 { found = true break } } if !found { - sub = append(sub, s1) + sub = append(sub, num1) } } @@ -163,8 +161,8 @@ func Equal[T comparable](a, b []T) bool { // SafeCmp compares two slices with constant time. // Note that we are using the subtle.ConstantTimeCompare() function for this // to help prevent timing attacks. -func SafeCmp(s1, s2 []byte) bool { - return subtle.ConstantTimeCompare(s1, s2) == 1 +func SafeCmp(left, right []byte) bool { + return subtle.ConstantTimeCompare(left, right) == 1 } // Merge accepts multiple slices and returns a single merged slice. @@ -189,20 +187,20 @@ func Merge[T any](slices ...[]T) []T { // Reverse replace the contents of a slice with the same elements but in // reverse order. -func Reverse[S ~[]E, E any](s S) { - for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { - s[i], s[j] = s[j], s[i] +func Reverse[S ~[]E, E any](slice S) { + for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 { + slice[i], slice[j] = slice[j], slice[i] } } -// Extend extends the slice 's' to length 'n' by appending zero-valued elements. -func Extend[T any](s []T, n int) []T { - if len(s) < n { - pad := make([]T, n-len(s), n+len(s)) - s = append(pad, s...) +// Extend extends the slice to the given length by appending zero-valued elements. +func Extend[T any](slice []T, length int) []T { + if len(slice) < length { + pad := make([]T, length-len(slice), length+len(slice)) + slice = append(pad, slice...) } - return s + return slice } // IsSubset checks if subSet is a subset of parentSet. @@ -227,24 +225,24 @@ func IsSubset[T comparable](parentSet, subSet []T) bool { return true } -// RemoveFirstOccurrenceOf removes the first occurrence of element e from slice s. +// RemoveFirstOccurrenceOf removes the first occurrence of element from slice. // It returns the modified slice and a boolean indicating whether an element was removed. -func RemoveFirstOccurrenceOf[T comparable](s []T, e T) ([]T, bool) { - for i, v := range s { - if v == e { - return append(s[:i], s[i+1:]...), true +func RemoveFirstOccurrenceOf[T comparable](slice []T, element T) ([]T, bool) { + for i, v := range slice { + if v == element { + return append(slice[:i], slice[i+1:]...), true } } - return s, false + return slice, false } -func Trim[T any](s []T, newLength int) []T { - if newLength <= len(s) { - return s[:newLength] +func Trim[T any](slice []T, newLength int) []T { + if newLength <= len(slice) { + return slice[:newLength] } - return s + return slice } // Shuffle shuffles a slice of any type. diff --git a/util/slice_test.go b/util/slice_test.go index 616aeba78..8747efc75 100644 --- a/util/slice_test.go +++ b/util/slice_test.go @@ -21,16 +21,16 @@ func TestSliceToInt16(t *testing.T) { {MaxInt16, []byte{0xff, 0x7f}}, } - for _, test := range tests { - s1 := Uint16ToSlice(uint16(test.in)) - s2 := Int16ToSlice(test.in) + for _, tt := range tests { + s1 := Uint16ToSlice(uint16(tt.in)) + s2 := Int16ToSlice(tt.in) assert.Equal(t, s1, s2) - assert.Equal(t, test.slice, s1) + assert.Equal(t, tt.slice, s1) - v1 := SliceToInt16(test.slice) - v2 := SliceToUint16(test.slice) + v1 := SliceToInt16(tt.slice) + v2 := SliceToUint16(tt.slice) assert.Equal(t, int16(v2), v1) - assert.Equal(t, test.in, v1) + assert.Equal(t, tt.in, v1) } } @@ -48,16 +48,16 @@ func TestSliceToInt32(t *testing.T) { {MaxInt32, []byte{0xff, 0xff, 0xff, 0x7f}}, } - for _, test := range tests { - s1 := Uint32ToSlice(uint32(test.in)) - s2 := Int32ToSlice(test.in) + for _, tt := range tests { + s1 := Uint32ToSlice(uint32(tt.in)) + s2 := Int32ToSlice(tt.in) assert.Equal(t, s1, s2) - assert.Equal(t, test.slice, s1) + assert.Equal(t, tt.slice, s1) - v1 := SliceToInt32(test.slice) - v2 := SliceToUint32(test.slice) + v1 := SliceToInt32(tt.slice) + v2 := SliceToUint32(tt.slice) assert.Equal(t, int32(v2), v1) - assert.Equal(t, test.in, v1) + assert.Equal(t, tt.in, v1) } } @@ -75,16 +75,16 @@ func TestSliceToInt64(t *testing.T) { {MaxInt64, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}}, } - for _, test := range tests { - s1 := Uint64ToSlice(uint64(test.in)) - s2 := Int64ToSlice(test.in) + for _, tt := range tests { + s1 := Uint64ToSlice(uint64(tt.in)) + s2 := Int64ToSlice(tt.in) assert.Equal(t, s1, s2) - assert.Equal(t, test.slice, s1) + assert.Equal(t, tt.slice, s1) - v1 := SliceToInt64(test.slice) - v2 := SliceToUint64(test.slice) + v1 := SliceToInt64(tt.slice) + v2 := SliceToUint64(tt.slice) assert.Equal(t, int64(v2), v1) - assert.Equal(t, test.in, v1) + assert.Equal(t, tt.in, v1) } } @@ -98,14 +98,14 @@ func TestCompress(t *testing.T) { } func TestDecompress(t *testing.T) { - d, _ := hex.DecodeString( + data, _ := hex.DecodeString( "1f8b08000000000000ff5accb8929191492afefe9620e60805060280254221ac2238cb57f8d6da3ecfc47b617bd47bf80fbe503b11b7aef3" + "85a6c0ba159a2142ac110a1d8f2e447cd46a3f3d71d6fc5c9eac45377ec4efffa0b76c33bb1377fead15f5cdf7d9085bc44e58094784c216" + "9fcd92c947ee35a43a49ff5d57b563eeaad9415b8ed6d685bd72aaf9afd3b5898b334455a26edf71fd634957941ead7f15ad5fe0e96517ce" + "f48d79216323616702020000ffffa63359ef1b010000") - _, err := DecompressBuffer(d[1:]) + _, err := DecompressBuffer(data[1:]) assert.Error(t, err) - _, err = DecompressBuffer(d) + _, err = DecompressBuffer(data) assert.NoError(t, err) } @@ -199,9 +199,9 @@ func TestMerge(t *testing.T) { {[][]byte{{0}, {1}, {2}}, []byte{0, 1, 2}}, } - for _, test := range tests { - merged := Merge(test.slices...) - assert.Equal(t, test.merged, merged) + for _, tt := range tests { + merged := Merge(tt.slices...) + assert.Equal(t, tt.merged, merged) } } @@ -216,14 +216,14 @@ func TestReverse(t *testing.T) { {[]byte{1, 2}, []byte{2, 1}}, } - for _, test := range tests { - Reverse(test.slice) - assert.Equal(t, test.slice, test.reversed) + for _, tt := range tests { + Reverse(tt.slice) + assert.Equal(t, tt.slice, tt.reversed) } } func TestExtendSlice(t *testing.T) { - cases := []struct { + tests := []struct { in []int size int want []int @@ -234,10 +234,10 @@ func TestExtendSlice(t *testing.T) { {[]int{}, 5, []int{0, 0, 0, 0, 0}}, } - for _, c := range cases { - inCopy := c.in - inCopy = Extend(inCopy, c.size) - assert.Equal(t, c.want, inCopy, "ExtendSlice(%v, %v) == %v, want %v", c.in, c.size, c.in, c.want) + for _, tt := range tests { + inCopy := tt.in + inCopy = Extend(inCopy, tt.size) + assert.Equal(t, tt.want, inCopy, "ExtendSlice(%v, %v) == %v, want %v", tt.in, tt.size, tt.in, tt.want) } } @@ -273,9 +273,9 @@ func TestStringToBytes(t *testing.T) { {"", []byte("")}, } - for _, test := range tests { - got := StringToBytes(test.input) - assert.Equal(t, test.output, got, "StringToBytes('%s') = %v, want %v", test.input, got, test.output) + for _, tt := range tests { + got := StringToBytes(tt.input) + assert.Equal(t, tt.output, got, "StringToBytes('%s') = %v, want %v", tt.input, got, tt.output) } } diff --git a/util/testsuite/testsuite.go b/util/testsuite/testsuite.go index 7adf16dc9..5028564d9 100644 --- a/util/testsuite/testsuite.go +++ b/util/testsuite/testsuite.go @@ -350,7 +350,7 @@ type BlockMaker struct { PrevCert *certificate.BlockCertificate } -// NewBlockMaker creates a new BlockMaker instance with default values. +// NewBlockMaker creates a new BlockMaker instance. func (ts *TestSuite) NewBlockMaker() *BlockMaker { txs := block.NewTxs() tx1 := ts.GenerateTestTransferTx() @@ -436,20 +436,20 @@ func BlockWithTransactions(txs block.Txs) func(bm *BlockMaker) { func (ts *TestSuite) GenerateTestBlock(height uint32, options ...func(bm *BlockMaker)) ( *block.Block, *certificate.BlockCertificate, ) { - bm := ts.NewBlockMaker() - bm.PrevCert = ts.GenerateTestBlockCertificate(height - 1) + bmk := ts.NewBlockMaker() + bmk.PrevCert = ts.GenerateTestBlockCertificate(height - 1) if height == 1 { - bm.PrevCert = nil - bm.PrevHash = hash.UndefHash + bmk.PrevCert = nil + bmk.PrevHash = hash.UndefHash } for _, opt := range options { - opt(bm) + opt(bmk) } - header := block.NewHeader(bm.Version, bm.Time, bm.PrevHash, bm.PrevHash, bm.Seed, bm.Proposer) - blk := block.NewBlock(header, bm.PrevCert, bm.Txs) + header := block.NewHeader(bmk.Version, bmk.Time, bmk.PrevHash, bmk.PrevHash, bmk.Seed, bmk.Proposer) + blk := block.NewBlock(header, bmk.PrevCert, bmk.Txs) blockCert := ts.GenerateTestBlockCertificate(height) @@ -487,14 +487,39 @@ func (ts *TestSuite) GenerateTestPrepareCertificate(height uint32) *certificate. return cert } +type ProposalMaker struct { + ProposerKey *bls.ValidatorKey +} + +// NewProposalMaker creates a new NewProposalMaker instance. +func (ts *TestSuite) NewProposalMaker() *ProposalMaker { + return &ProposalMaker{ + ProposerKey: ts.RandValKey(), + } +} + +// WithProposerKey sets the private key of the proposer. +func WithProposerKey(key *bls.ValidatorKey) func(pm *ProposalMaker) { + return func(pm *ProposalMaker) { + pm.ProposerKey = key + } +} + // GenerateTestProposal generates a proposal for testing purposes. -func (ts *TestSuite) GenerateTestProposal(height uint32, round int16) (*proposal.Proposal, *bls.ValidatorKey) { - valKey := ts.RandValKey() - blk, _ := ts.GenerateTestBlock(height, BlockWithProposer(valKey.Address())) +func (ts *TestSuite) GenerateTestProposal(height uint32, round int16, + options ...func(pmk *ProposalMaker), +) *proposal.Proposal { + pmk := ts.NewProposalMaker() + + for _, opt := range options { + opt(pmk) + } + + blk, _ := ts.GenerateTestBlock(height, BlockWithProposer(pmk.ProposerKey.Address())) prop := proposal.NewProposal(height, round, blk) - ts.HelperSignProposal(valKey, prop) + ts.HelperSignProposal(pmk.ProposerKey, prop) - return prop, valKey + return prop } type TransactionMaker struct { @@ -520,7 +545,7 @@ func (tm *TransactionMaker) SignerValidatorAddress() crypto.Address { return blsPub.ValidatorAddress() } -// NewTransactionMaker creates a new TransactionMaker instance with default values. +// NewTransactionMaker creates a new TransactionMaker instance. func (ts *TestSuite) NewTransactionMaker() *TransactionMaker { return &TransactionMaker{ LockTime: ts.RandHeight(), @@ -567,113 +592,113 @@ func TransactionWithEd25519Signer(signer *ed25519.PrivateKey) func(tm *Transacti // GenerateTestTransferTx generates a transfer transaction for testing purposes. func (ts *TestSuite) GenerateTestTransferTx(options ...func(tm *TransactionMaker)) *tx.Tx { - tm := ts.NewTransactionMaker() + tmk := ts.NewTransactionMaker() for _, opt := range options { - opt(tm) + opt(tmk) } - if tm.Signer == nil { + if tmk.Signer == nil { useBLSSigner := ts.RandBool() if useBLSSigner { _, prv := ts.RandBLSKeyPair() - tm.Signer = prv + tmk.Signer = prv } else { _, prv := ts.RandEd25519KeyPair() - tm.Signer = prv + tmk.Signer = prv } } - sender := tm.SignerAccountAddress() - trx := tx.NewTransferTx(tm.LockTime, sender, ts.RandAccAddress(), tm.Amount, tm.Fee) - ts.HelperSignTransaction(tm.Signer, trx) + sender := tmk.SignerAccountAddress() + trx := tx.NewTransferTx(tmk.LockTime, sender, ts.RandAccAddress(), tmk.Amount, tmk.Fee) + ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestBondTx generates a bond transaction for testing purposes. func (ts *TestSuite) GenerateTestBondTx(options ...func(tm *TransactionMaker)) *tx.Tx { - tm := ts.NewTransactionMaker() + tmk := ts.NewTransactionMaker() for _, opt := range options { - opt(tm) + opt(tmk) } - if tm.Signer == nil { + if tmk.Signer == nil { useBLSSigner := ts.RandBool() if useBLSSigner { _, prv := ts.RandBLSKeyPair() - tm.Signer = prv + tmk.Signer = prv } else { _, prv := ts.RandEd25519KeyPair() - tm.Signer = prv + tmk.Signer = prv } } - sender := tm.SignerAccountAddress() - trx := tx.NewBondTx(tm.LockTime, sender, ts.RandValAddress(), nil, tm.Amount, tm.Fee) - ts.HelperSignTransaction(tm.Signer, trx) + sender := tmk.SignerAccountAddress() + trx := tx.NewBondTx(tmk.LockTime, sender, ts.RandValAddress(), nil, tmk.Amount, tmk.Fee) + ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestSortitionTx generates a sortition transaction for testing purposes. func (ts *TestSuite) GenerateTestSortitionTx(options ...func(tm *TransactionMaker)) *tx.Tx { - tm := ts.NewTransactionMaker() + tmk := ts.NewTransactionMaker() for _, opt := range options { - opt(tm) + opt(tmk) } - if tm.Signer == nil { + if tmk.Signer == nil { _, prv := ts.RandBLSKeyPair() - tm.Signer = prv + tmk.Signer = prv } proof := ts.RandProof() - sender := tm.SignerValidatorAddress() - trx := tx.NewSortitionTx(tm.LockTime, sender, proof) - ts.HelperSignTransaction(tm.Signer, trx) + sender := tmk.SignerValidatorAddress() + trx := tx.NewSortitionTx(tmk.LockTime, sender, proof) + ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestUnbondTx generates an unbond transaction for testing purposes. func (ts *TestSuite) GenerateTestUnbondTx(options ...func(tm *TransactionMaker)) *tx.Tx { - tm := ts.NewTransactionMaker() + tmk := ts.NewTransactionMaker() for _, opt := range options { - opt(tm) + opt(tmk) } - if tm.Signer == nil { + if tmk.Signer == nil { _, prv := ts.RandBLSKeyPair() - tm.Signer = prv + tmk.Signer = prv } - sender := tm.SignerValidatorAddress() - trx := tx.NewUnbondTx(tm.LockTime, sender) - ts.HelperSignTransaction(tm.Signer, trx) + sender := tmk.SignerValidatorAddress() + trx := tx.NewUnbondTx(tmk.LockTime, sender) + ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestWithdrawTx generates a withdraw transaction for testing purposes. func (ts *TestSuite) GenerateTestWithdrawTx(options ...func(tm *TransactionMaker)) *tx.Tx { - tm := ts.NewTransactionMaker() + tmk := ts.NewTransactionMaker() for _, opt := range options { - opt(tm) + opt(tmk) } - if tm.Signer == nil { + if tmk.Signer == nil { _, prv := ts.RandBLSKeyPair() - tm.Signer = prv + tmk.Signer = prv } - sender := tm.SignerValidatorAddress() - trx := tx.NewWithdrawTx(tm.LockTime, sender, ts.RandAccAddress(), tm.Amount, tm.Fee) - ts.HelperSignTransaction(tm.Signer, trx) + sender := tmk.SignerValidatorAddress() + trx := tx.NewWithdrawTx(tmk.LockTime, sender, ts.RandAccAddress(), tmk.Amount, tmk.Fee) + ts.HelperSignTransaction(tmk.Signer, trx) return trx } @@ -681,25 +706,25 @@ func (ts *TestSuite) GenerateTestWithdrawTx(options ...func(tm *TransactionMaker // GenerateTestPrecommitVote generates a precommit vote for testing purposes. func (ts *TestSuite) GenerateTestPrecommitVote(height uint32, round int16) (*vote.Vote, *bls.ValidatorKey) { valKey := ts.RandValKey() - v := vote.NewPrecommitVote( + vote := vote.NewPrecommitVote( ts.RandHash(), height, round, valKey.Address()) - ts.HelperSignVote(valKey, v) + ts.HelperSignVote(valKey, vote) - return v, valKey + return vote, valKey } // GenerateTestPrepareVote generates a prepare vote for testing purposes. func (ts *TestSuite) GenerateTestPrepareVote(height uint32, round int16) (*vote.Vote, *bls.ValidatorKey) { valKey := ts.RandValKey() - v := vote.NewPrepareVote( + vote := vote.NewPrepareVote( ts.RandHash(), height, round, valKey.Address()) - ts.HelperSignVote(valKey, v) + ts.HelperSignVote(valKey, vote) - return v, valKey + return vote, valKey } // GenerateTestCommittee generates a committee for testing purposes. @@ -710,13 +735,13 @@ func (ts *TestSuite) GenerateTestCommittee(num int) (committee.Committee, []*bls } valKeys := make([]*bls.ValidatorKey, num) vals := make([]*validator.Validator, num) - for i := int32(0); i < int32(num); i++ { - val, s := ts.GenerateTestValidator(i) - valKeys[i] = s - vals[i] = val + for index := int32(0); index < int32(num); index++ { + val, s := ts.GenerateTestValidator(index) + valKeys[index] = s + vals[index] = val - val.UpdateLastBondingHeight(1 + uint32(i)) - val.UpdateLastSortitionHeight(1 + uint32(i)) + val.UpdateLastBondingHeight(1 + uint32(index)) + val.UpdateLastSortitionHeight(1 + uint32(index)) val.SubtractFromStake(val.Stake()) val.AddToStake(10e9) } diff --git a/util/time_test.go b/util/time_test.go index 13cea5418..1d4115a69 100644 --- a/util/time_test.go +++ b/util/time_test.go @@ -8,39 +8,37 @@ import ( ) func TestRoundNow(t *testing.T) { - c1 := time.Now() - c2 := RoundNow(1) - c3 := RoundNow(5) - - assert.NotEqual(t, c1, c2) - assert.Equal(t, c1.Second(), c2.Second()) - assert.Equal(t, int64(0), c2.UnixMicro()%1000000) - assert.Equal(t, int64(0), c2.UnixMilli()%1000) - assert.Equal(t, 0, c3.Nanosecond()) - assert.Equal(t, 0, c3.Second()%5) + time1 := time.Now() + time2 := RoundNow(1) + time3 := RoundNow(5) + + assert.NotEqual(t, time1, time2) + assert.Equal(t, time1.Second(), time2.Second()) + assert.Equal(t, int64(0), time2.UnixMicro()%1000000) + assert.Equal(t, int64(0), time2.UnixMilli()%1000) + assert.Equal(t, 0, time3.Nanosecond()) + assert.Equal(t, 0, time3.Second()%5) } func TestRoundingTime(t *testing.T) { - t1, _ := time.Parse(time.RFC3339Nano, "2006-01-02T15:04:11.111111111Z") - t2, _ := time.Parse(time.RFC3339Nano, "2006-01-02T15:04:24.333333333Z") - t3, _ := time.Parse(time.RFC3339Nano, "2006-01-02T15:04:35.555555555Z") - t4, _ := time.Parse(time.RFC3339Nano, "2006-01-02T15:04:48.777777777Z") - t5, _ := time.Parse(time.RFC3339Nano, "2006-01-02T15:04:59.999999999Z") - c1 := roundDownTime(t1, 10) - c2 := roundDownTime(t2, 10) - c3 := roundDownTime(t3, 10) - c4 := roundDownTime(t4, 10) - c5 := roundDownTime(t5, 10) - - assert.Equal(t, 0, c1.Nanosecond()) - assert.Equal(t, 0, c2.Nanosecond()) - assert.Equal(t, 0, c3.Nanosecond()) - assert.Equal(t, 0, c4.Nanosecond()) - assert.Equal(t, 0, c5.Nanosecond()) - - assert.Equal(t, 10, c1.Second()) - assert.Equal(t, 20, c2.Second()) - assert.Equal(t, 30, c3.Second()) - assert.Equal(t, 40, c4.Second()) - assert.Equal(t, 50, c5.Second()) + tests := []struct { + input string + expected int + }{ + {"2006-01-02T15:04:11.111111111Z", 10}, + {"2006-01-02T15:04:24.333333333Z", 20}, + {"2006-01-02T15:04:35.555555555Z", 30}, + {"2006-01-02T15:04:48.777777777Z", 40}, + {"2006-01-02T15:04:59.999999999Z", 50}, + } + + for _, tt := range tests { + parsedTime, err := time.Parse(time.RFC3339Nano, tt.input) + assert.NoError(t, err, "Failed to parse time") + + roundedTime := roundDownTime(parsedTime, 10) + + assert.Equal(t, 0, roundedTime.Nanosecond(), "Nanoseconds should be rounded to 0") + assert.Equal(t, tt.expected, roundedTime.Second(), "Seconds should match the expected rounded value") + } } diff --git a/util/utils.go b/util/utils.go index 94ec20bd1..ba58dc8b4 100644 --- a/util/utils.go +++ b/util/utils.go @@ -115,13 +115,13 @@ func OS2IP(x []byte) *big.Int { // I2OSP converts a nonnegative integer to an octet string of a specified length. // https://datatracker.ietf.org/doc/html/rfc8017#section-4.1 -func I2OSP(x *big.Int, xLen int) []byte { - if x.Sign() == -1 { +func I2OSP(num *big.Int, len int) []byte { + if num.Sign() == -1 { return nil } - buf := make([]byte, xLen) + buf := make([]byte, len) - return x.FillBytes(buf) + return num.FillBytes(buf) } // LogScale computes 2^⌈log₂(val)⌉, where ⌈x⌉ represents the ceiling of x. @@ -134,28 +134,28 @@ func LogScale(val int) int { func FormatBytesToHumanReadable(bytes uint64) string { const ( - _ = iota - KB = 1 << (10 * iota) - MB - GB - TB + _ = iota + KiloBYte = 1 << (10 * iota) + MegaBYte + GigaByte + TeraByte ) unit := "Bytes" value := float64(bytes) switch { - case bytes >= TB: + case bytes >= TeraByte: unit = "TB" - value /= TB - case bytes >= GB: + value /= TeraByte + case bytes >= GigaByte: unit = "GB" - value /= GB - case bytes >= MB: + value /= GigaByte + case bytes >= MegaBYte: unit = "MB" - value /= MB - case bytes >= KB: + value /= MegaBYte + case bytes >= KiloBYte: unit = "KB" - value /= KB + value /= KiloBYte } return fmt.Sprintf("%.2f %s", value, unit) diff --git a/util/utils_test.go b/util/utils_test.go index db4169e94..7def6e3e0 100644 --- a/util/utils_test.go +++ b/util/utils_test.go @@ -102,7 +102,7 @@ func TestIS2OP(t *testing.T) { } func TestLogScale(t *testing.T) { - testCases := []struct { + tests := []struct { input int expected int }{ @@ -113,9 +113,9 @@ func TestLogScale(t *testing.T) { {8, 8}, } - for _, testCase := range testCases { - result := LogScale(testCase.input) - assert.Equal(t, testCase.expected, result, "LogScale(%d) failed", testCase.input) + for _, tt := range tests { + result := LogScale(tt.input) + assert.Equal(t, tt.expected, result, "LogScale(%d) failed", tt.input) } } @@ -132,10 +132,10 @@ func TestFormatBytesToHumanReadable(t *testing.T) { {1_099_511_627_776, "1.00 TB"}, } - for _, test := range tests { - result := FormatBytesToHumanReadable(test.bytes) - if result != test.expected { - t.Errorf("FormatBytesToHumanReadable(%d) returned %s, expected %s", test.bytes, result, test.expected) + for _, tt := range tests { + result := FormatBytesToHumanReadable(tt.bytes) + if result != tt.expected { + t.Errorf("FormatBytesToHumanReadable(%d) returned %s, expected %s", tt.bytes, result, tt.expected) } } } diff --git a/version/version.go b/version/version.go index e7393684f..f2602c9e1 100644 --- a/version/version.go +++ b/version/version.go @@ -34,7 +34,7 @@ type Version struct { // The format should be "Major.Minor.Patch-Meta", where Meta is optional. // Returns the parsed Version struct and an error if parsing fails. func ParseVersion(versionStr string) (Version, error) { - var v Version + var ver Version if versionStr[0] == 'v' { versionStr = versionStr[1:] @@ -42,40 +42,40 @@ func ParseVersion(versionStr string) (Version, error) { // Split the version string into parts parts := strings.Split(versionStr, ".") if len(parts) != 3 { - return v, errors.New("invalid version format") + return ver, errors.New("invalid version format") } // Parse Major version major, err := strconv.ParseUint(parts[0], 10, 64) if err != nil { - return v, fmt.Errorf("failed to parse Major version: %w", err) + return ver, fmt.Errorf("failed to parse Major version: %w", err) } - v.Major = uint(major) + ver.Major = uint(major) // Parse Minor version minor, err := strconv.ParseUint(parts[1], 10, 64) if err != nil { - return v, fmt.Errorf("failed to parse Minor version: %w", err) + return ver, fmt.Errorf("failed to parse Minor version: %w", err) } - v.Minor = uint(minor) + ver.Minor = uint(minor) // Parse Patch version and Meta (if present) patchMeta := strings.Split(parts[2], "-") if len(patchMeta) > 2 { - return v, errors.New("invalid Patch and Meta format") + return ver, errors.New("invalid Patch and Meta format") } patch, err := strconv.ParseUint(patchMeta[0], 10, 64) if err != nil { - return v, fmt.Errorf("failed to parse Patch version: %w", err) + return ver, fmt.Errorf("failed to parse Patch version: %w", err) } - v.Patch = uint(patch) + ver.Patch = uint(patch) if len(patchMeta) == 2 { - v.Meta = patchMeta[1] + ver.Meta = patchMeta[1] } - return v, nil + return ver, nil } // StringWithAlias returns a string representation of the Version object with the alias. diff --git a/version/version_test.go b/version/version_test.go index dc0e2a60b..3c7a42535 100644 --- a/version/version_test.go +++ b/version/version_test.go @@ -94,13 +94,13 @@ func TestParseVersion(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - v, err := version.ParseVersion(tt.input) + ver, err := version.ParseVersion(tt.input) if tt.expectedErr { assert.Error(t, err) } else { assert.NoError(t, err) - assert.Equal(t, tt.expected, v) + assert.Equal(t, tt.expected, ver) } }) } @@ -153,14 +153,14 @@ func TestVersionComparison(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - v1, err := version.ParseVersion(tt.v1Input) + ver1, err := version.ParseVersion(tt.v1Input) assert.NoError(t, err) - v2, err := version.ParseVersion(tt.v2Input) + ver2, err := version.ParseVersion(tt.v2Input) assert.NoError(t, err) expectedSign := tt.expectedSign - actualSign := v1.Compare(v2) + actualSign := ver1.Compare(ver2) assert.Equal(t, expectedSign, actualSign, fmt.Sprintf("Comparison result mismatch for %s vs %s", tt.v1Input, tt.v2Input)) diff --git a/wallet/addresspath/path_test.go b/wallet/addresspath/path_test.go index 8d3632a67..26f25e5f6 100644 --- a/wallet/addresspath/path_test.go +++ b/wallet/addresspath/path_test.go @@ -21,8 +21,8 @@ func TestPathToString(t *testing.T) { {NewPath(h, h+1), "m/0'/1'"}, {NewPath(h, h+1, h+1000000000), "m/0'/1'/1000000000'"}, } - for i, test := range tests { - assert.Equal(t, test.wantStr, test.path.String(), "case %d failed", i) + for no, tt := range tests { + assert.Equal(t, tt.wantStr, tt.path.String(), "case %d failed", no) } } @@ -44,10 +44,10 @@ func TestStringToPath(t *testing.T) { {"m/'", nil, strconv.ErrSyntax}, {"m/abc'", nil, strconv.ErrSyntax}, } - for i, test := range tests { - path, err := FromString(test.str) - assert.Equal(t, test.wantPath, path, "case %d failed", i) - assert.ErrorIsf(t, err, test.wantErr, "case %d failed", i) + for no, tt := range tests { + path, err := FromString(tt.str) + assert.Equal(t, tt.wantPath, path, "case %d failed", no) + assert.ErrorIsf(t, err, tt.wantErr, "case %d failed", no) } } diff --git a/wallet/client.go b/wallet/client.go index 9ec400414..4b4f3c715 100644 --- a/wallet/client.go +++ b/wallet/client.go @@ -143,14 +143,14 @@ func (c *grpcClient) sendTx(trx *tx.Tx) (tx.ID, error) { } // TODO: check the return value type. -func (c *grpcClient) getTransaction(id tx.ID) (*pactus.GetTransactionResponse, error) { +func (c *grpcClient) getTransaction(txID tx.ID) (*pactus.GetTransactionResponse, error) { if err := c.connect(); err != nil { return nil, err } res, err := c.transactionClient.GetTransaction(c.ctx, &pactus.GetTransactionRequest{ - Id: id.String(), + Id: txID.String(), Verbosity: pactus.TransactionVerbosity_TRANSACTION_INFO, }) if err != nil { diff --git a/wallet/encrypter/encrypter.go b/wallet/encrypter/encrypter.go index 2bc380f2e..00c802c6b 100644 --- a/wallet/encrypter/encrypter.go +++ b/wallet/encrypter/encrypter.go @@ -155,7 +155,7 @@ func (e *Encrypter) Encrypt(message, password string) (string, error) { case nameFuncAES256CTR: // Using salt for Initialization Vector (IV) iv := salt - ct := aesCrypt([]byte(message), iv, cipherKey) + cipher := aesCrypt([]byte(message), iv, cipherKey) // MAC method switch funcs[2] { @@ -163,10 +163,10 @@ func (e *Encrypter) Encrypt(message, password string) (string, error) { // Calculate the MAC // We use the MAC to check if the password is correct // https: //en.wikipedia.org/wiki/Authenticated_encryption#Encrypt-then-MAC_(EtM) - mac := calcMACv1(cipherKey[16:32], ct) + mac := calcMACv1(cipherKey[16:32], cipher) data = append(data, salt...) - data = append(data, ct...) + data = append(data, cipher...) data = append(data, mac...) default: @@ -251,13 +251,13 @@ func (e *Encrypter) Decrypt(cipherText, password string) (string, error) { // aesCrypt encrypts/decrypts a message using AES-256-CTR and // returns the encoded/decoded bytes. -func aesCrypt(message, iv, cipherKey []byte) []byte { +func aesCrypt(message, initVec, cipherKey []byte) []byte { // Generate the cipher message cipherMsg := make([]byte, len(message)) aesCipher, err := aes.NewCipher(cipherKey) exitOnErr(err) - stream := cipher.NewCTR(aesCipher, iv) + stream := cipher.NewCTR(aesCipher, initVec) stream.XORKeyStream(cipherMsg, message) return cipherMsg @@ -265,13 +265,13 @@ func aesCrypt(message, iv, cipherKey []byte) []byte { // calcMACv1 calculates the 4 bytes MAC of the given slices base on SHA-256. func calcMACv1(data ...[]byte) []byte { - h := sha256.New() + hasher := sha256.New() for _, d := range data { - _, err := h.Write(d) + _, err := hasher.Write(d) exitOnErr(err) } - return h.Sum(nil)[:4] + return hasher.Sum(nil)[:4] } // exitOnErr exit the software immediately if an error happens. diff --git a/wallet/encrypter/encrypter_test.go b/wallet/encrypter/encrypter_test.go index 363c8a081..585f6f872 100644 --- a/wallet/encrypter/encrypter_test.go +++ b/wallet/encrypter/encrypter_test.go @@ -7,23 +7,23 @@ import ( ) func TestNopeEncrypter(t *testing.T) { - e := NopeEncrypter() - assert.Equal(t, "", e.Method) - assert.Nil(t, e.Params) - assert.False(t, e.IsEncrypted()) + enc := NopeEncrypter() + assert.Equal(t, "", enc.Method) + assert.Nil(t, enc.Params) + assert.False(t, enc.IsEncrypted()) msg := "foo" - _, err := e.Encrypt(msg, "password") + _, err := enc.Encrypt(msg, "password") assert.ErrorIs(t, err, ErrInvalidPassword) - enc, err := e.Encrypt(msg, "") + cipher, err := enc.Encrypt(msg, "") assert.NoError(t, err) - assert.Equal(t, msg, enc) + assert.Equal(t, msg, cipher) - _, err = e.Decrypt(enc, "password") + _, err = enc.Decrypt(cipher, "password") assert.ErrorIs(t, err, ErrInvalidPassword) - dec, err := e.Decrypt(enc, "") + decipher, err := enc.Decrypt(cipher, "") assert.NoError(t, err) - assert.Equal(t, msg, dec) + assert.Equal(t, msg, decipher) } func TestDefaultEncrypter(t *testing.T) { @@ -32,16 +32,16 @@ func TestDefaultEncrypter(t *testing.T) { OptionMemory(4), OptionParallelism(5), } - e := DefaultEncrypter(opts...) - assert.Equal(t, "ARGON2ID-AES_256_CTR-MACV1", e.Method) - assert.Equal(t, "3", e.Params["iterations"]) - assert.Equal(t, "4", e.Params["memory"]) - assert.Equal(t, "5", e.Params["parallelism"]) - assert.True(t, e.IsEncrypted()) + enc := DefaultEncrypter(opts...) + assert.Equal(t, "ARGON2ID-AES_256_CTR-MACV1", enc.Method) + assert.Equal(t, "3", enc.Params["iterations"]) + assert.Equal(t, "4", enc.Params["memory"]) + assert.Equal(t, "5", enc.Params["parallelism"]) + assert.True(t, enc.IsEncrypted()) } func TestEncrypter(t *testing.T) { - e := &Encrypter{ + enc := &Encrypter{ Method: "ARGON2ID-AES_256_CTR-MACV1", Params: params{ nameParamIterations: "1", @@ -50,18 +50,19 @@ func TestEncrypter(t *testing.T) { }, } - password := "cowboy" msg := "foo" - enc, err := e.Encrypt(msg, password) + + _, err := enc.Encrypt(msg, "") + assert.ErrorIs(t, err, ErrInvalidPassword) + + password := "cowboy" + cipher, err := enc.Encrypt(msg, password) assert.NoError(t, err) - dec, err := e.Decrypt(enc, password) + dec, err := enc.Decrypt(cipher, password) assert.NoError(t, err) assert.Equal(t, msg, dec) - _, err = e.Decrypt(enc, "invalid-password") - assert.ErrorIs(t, err, ErrInvalidPassword) - - _, err = e.Encrypt(enc, "") + _, err = enc.Decrypt(cipher, "invalid-password") assert.ErrorIs(t, err, ErrInvalidPassword) } diff --git a/wallet/encrypter/params_test.go b/wallet/encrypter/params_test.go index e3b1ab70a..4feebbe9b 100644 --- a/wallet/encrypter/params_test.go +++ b/wallet/encrypter/params_test.go @@ -16,9 +16,9 @@ func TestParamsUint8(t *testing.T) { } p := params{} - for _, test := range tests { - p.SetUint8(test.key, test.val) - assert.Equal(t, test.val, p.GetUint8(test.key)) + for _, tt := range tests { + p.SetUint8(tt.key, tt.val) + assert.Equal(t, tt.val, p.GetUint8(tt.key)) } } @@ -32,9 +32,9 @@ func TestParamsUint32(t *testing.T) { } p := params{} - for _, test := range tests { - p.SetUint32(test.key, test.val) - assert.Equal(t, test.val, p.GetUint32(test.key)) + for _, tt := range tests { + p.SetUint32(tt.key, tt.val) + assert.Equal(t, tt.val, p.GetUint32(tt.key)) } } @@ -48,9 +48,9 @@ func TestParamsUint64(t *testing.T) { } p := params{} - for _, test := range tests { - p.SetUint64(test.key, test.val) - assert.Equal(t, test.val, p.GetUint64(test.key)) + for _, tt := range tests { + p.SetUint64(tt.key, tt.val) + assert.Equal(t, tt.val, p.GetUint64(tt.key)) } } @@ -65,9 +65,9 @@ func TestParamsBytes(t *testing.T) { } p := params{} - for _, test := range tests { - p.SetBytes(test.key, test.val) - assert.Equal(t, test.val, p.GetBytes(test.key)) + for _, tt := range tests { + p.SetBytes(tt.key, tt.val) + assert.Equal(t, tt.val, p.GetBytes(tt.key)) } } @@ -82,8 +82,8 @@ func TestParamsString(t *testing.T) { } p := params{} - for _, test := range tests { - p.SetString(test.key, test.val) - assert.Equal(t, test.val, p.GetString(test.key)) + for _, tt := range tests { + p.SetString(tt.key, tt.val) + assert.Equal(t, tt.val, p.GetString(tt.key)) } } diff --git a/wallet/manager.go b/wallet/manager.go index 3466120e8..4b2070905 100644 --- a/wallet/manager.go +++ b/wallet/manager.go @@ -263,15 +263,15 @@ func (wm *Manager) ListWallet() ([]string, error) { return nil, err } - for _, f := range files { - _, err = Open(f, true) + for _, file := range files { + _, err = Open(file, true) if err != nil { - logger.Warn(fmt.Sprintf("file %s is not wallet", f)) + logger.Warn(fmt.Sprintf("file %s is not wallet", file)) continue } - wallets = append(wallets, filepath.Base(f)) + wallets = append(wallets, filepath.Base(file)) } return wallets, nil diff --git a/wallet/vault/utils_test.go b/wallet/vault/utils_test.go index 64b08d8ae..025f09171 100644 --- a/wallet/vault/utils_test.go +++ b/wallet/vault/utils_test.go @@ -46,10 +46,10 @@ func TestValidateMnemonic(t *testing.T) { "", }, } - for i, test := range tests { - err := CheckMnemonic(test.mnenomic) + for no, tt := range tests { + err := CheckMnemonic(tt.mnenomic) if err != nil { - assert.Equal(t, test.errStr, err.Error(), "test %v failed", i) + assert.Equal(t, tt.errStr, err.Error(), "test %v failed", no) } } } diff --git a/wallet/vault/vault.go b/wallet/vault/vault.go index 81ee3e5ed..e874550e6 100644 --- a/wallet/vault/vault.go +++ b/wallet/vault/vault.go @@ -134,14 +134,14 @@ func CreateVaultFromMnemonic(mnemonic string, coinType uint32) (*Vault, error) { return nil, err } - ks := keyStore{ + store := keyStore{ MasterNode: masterNode{ Mnemonic: mnemonic, }, ImportedKeys: make([]string, 0), } - keyStoreDate, err := json.Marshal(ks) + storeDate, err := json.Marshal(store) if err != nil { return nil, err } @@ -151,7 +151,7 @@ func CreateVaultFromMnemonic(mnemonic string, coinType uint32) (*Vault, error) { CoinType: coinType, Encrypter: enc, Addresses: make(map[string]AddressInfo), - KeyStore: string(keyStoreDate), + KeyStore: string(storeDate), Purposes: purposes{ PurposeBLS: purposeBLS{ XPubValidator: xPubValidator.Neuter().String(), diff --git a/wallet/vault/vault_test.go b/wallet/vault/vault_test.go index a2e7e01e4..b34c206c8 100644 --- a/wallet/vault/vault_test.go +++ b/wallet/vault/vault_test.go @@ -310,16 +310,16 @@ func TestGetPrivateKeys(t *testing.T) { for _, info := range td.vault.AddressInfos() { prv, err := td.vault.PrivateKeys(tPassword, []string{info.Address}) assert.NoError(t, err) - i := td.vault.AddressInfo(info.Address) + addrInfo := td.vault.AddressInfo(info.Address) path, _ := addresspath.FromString(info.Path) switch path.AddressType() - addresspath.HardenedKeyStart { case uint32(crypto.AddressTypeBLSAccount), uint32(crypto.AddressTypeValidator): - pub, _ := bls.PublicKeyFromString(i.PublicKey) + pub, _ := bls.PublicKeyFromString(addrInfo.PublicKey) require.True(t, prv[0].PublicKey().EqualsTo(pub)) case uint32(crypto.AddressTypeEd25519Account): - pub, _ := ed25519.PublicKeyFromString(i.PublicKey) + pub, _ := ed25519.PublicKeyFromString(addrInfo.PublicKey) require.True(t, prv[0].PublicKey().EqualsTo(pub)) default: assert.Fail(t, "not supported") diff --git a/wallet/wallet.go b/wallet/wallet.go index 318f297f6..dfa65dcea 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -148,7 +148,7 @@ func newWallet(walletPath string, store *Store, offline bool, option *walletOpt) client := newGrpcClient(option.timeout, option.servers) - w := &Wallet{ + wlt := &Wallet{ store: store, path: walletPath, grpcClient: client, @@ -162,7 +162,7 @@ func newWallet(walletPath string, store *Store, offline bool, option *walletOpt) } var netServers []string - switch w.store.Network { + switch wlt.store.Network { case genesis.Mainnet: netServers = serversInfo["mainnet"] @@ -183,7 +183,7 @@ func newWallet(walletPath string, store *Store, offline bool, option *walletOpt) } } - return w, nil + return wlt, nil } func (w *Wallet) Name() string { @@ -365,15 +365,15 @@ func (w *Wallet) SignTransaction(password string, trx *tx.Tx) error { } func (w *Wallet) BroadcastTransaction(trx *tx.Tx) (string, error) { - id, err := w.grpcClient.sendTx(trx) + txID, err := w.grpcClient.sendTx(trx) if err != nil { return "", err } - d, _ := trx.Bytes() - w.store.History.addPending(trx.Payload().Signer().String(), trx.Payload().Value(), id, d) + data, _ := trx.Bytes() + w.store.History.addPending(trx.Payload().Signer().String(), trx.Payload().Value(), txID, data) - return id.String(), nil + return txID.String(), nil } func (w *Wallet) CalculateFee(amt amount.Amount, payloadType payload.Type) (amount.Amount, error) { @@ -467,13 +467,13 @@ func (w *Wallet) SetLabel(addr, label string) error { return w.store.Vault.SetLabel(addr, label) } -func (w *Wallet) AddTransaction(id tx.ID) error { - idStr := id.String() +func (w *Wallet) AddTransaction(txID tx.ID) error { + idStr := txID.String() if w.store.History.hasTransaction(idStr) { return ErrHistoryExists } - trxRes, err := w.grpcClient.getTransaction(id) + trxRes, err := w.grpcClient.getTransaction(txID) if err != nil { return err } diff --git a/www/grpc/basicauth/basicauth_test.go b/www/grpc/basicauth/basicauth_test.go index 613e551fc..714497e03 100644 --- a/www/grpc/basicauth/basicauth_test.go +++ b/www/grpc/basicauth/basicauth_test.go @@ -8,7 +8,7 @@ import ( ) func TestMakeCredentials(t *testing.T) { - testCases := []struct { + tests := []struct { username string password string expected string @@ -20,13 +20,13 @@ func TestMakeCredentials(t *testing.T) { } // Iterate over test cases - for _, tc := range testCases { - t.Run(fmt.Sprintf("Username: %s, Password: %s", tc.username, tc.password), func(t *testing.T) { + for _, tt := range tests { + t.Run(fmt.Sprintf("Username: %s, Password: %s", tt.username, tt.password), func(t *testing.T) { // Call basicAuth function - result := EncodeBasicAuth(tc.username, tc.password) + result := EncodeBasicAuth(tt.username, tt.password) // Check if the result matches the expected output - assert.Equal(t, tc.expected, result) + assert.Equal(t, tt.expected, result) }) } } diff --git a/www/grpc/blockchain.go b/www/grpc/blockchain.go index 3945c4e5d..9c799ca5e 100644 --- a/www/grpc/blockchain.go +++ b/www/grpc/blockchain.go @@ -28,9 +28,9 @@ func (s *blockchainServer) GetBlockchainInfo(_ context.Context, _ *pactus.GetBlockchainInfoRequest, ) (*pactus.GetBlockchainInfoResponse, error) { vals := s.state.CommitteeValidators() - cv := make([]*pactus.ValidatorInfo, 0, len(vals)) - for _, v := range vals { - cv = append(cv, s.validatorToProto(v)) + valInfos := make([]*pactus.ValidatorInfo, 0, len(vals)) + for _, val := range vals { + valInfos = append(valInfos, s.validatorToProto(val)) } return &pactus.GetBlockchainInfoResponse{ @@ -43,7 +43,7 @@ func (s *blockchainServer) GetBlockchainInfo(_ context.Context, IsPruned: s.state.IsPruned(), PruningHeight: s.state.PruningHeight(), LastBlockTime: s.state.LastBlockTime().Unix(), - CommitteeValidators: cv, + CommitteeValidators: valInfos, }, nil } @@ -318,19 +318,19 @@ func (*blockchainServer) accountToProto(addr crypto.Address, acc *account.Accoun } } -func (*blockchainServer) voteToProto(v *vote.Vote) *pactus.VoteInfo { +func (*blockchainServer) voteToProto(vte *vote.Vote) *pactus.VoteInfo { cpRound := int32(0) cpValue := int32(0) - if v.IsCPVote() { - cpRound = int32(v.CPRound()) - cpValue = int32(v.CPValue()) + if vte.IsCPVote() { + cpRound = int32(vte.CPRound()) + cpValue = int32(vte.CPValue()) } return &pactus.VoteInfo{ - Type: pactus.VoteType(v.Type()), - Voter: v.Signer().String(), - BlockHash: v.BlockHash().String(), - Round: int32(v.Round()), + Type: pactus.VoteType(vte.Type()), + Voter: vte.Signer().String(), + BlockHash: vte.BlockHash().String(), + Round: int32(vte.Round()), CpRound: cpRound, CpValue: cpValue, } diff --git a/www/grpc/blockchain_test.go b/www/grpc/blockchain_test.go index a565bedbf..fdf4582a1 100644 --- a/www/grpc/blockchain_test.go +++ b/www/grpc/blockchain_test.go @@ -14,8 +14,8 @@ func TestGetBlock(t *testing.T) { conn, client := td.blockchainClient(t) height := uint32(100) - b := td.mockState.TestStore.AddTestBlock(height) - data, _ := b.Bytes() + blk := td.mockState.TestStore.AddTestBlock(height) + data, _ := blk.Bytes() t.Run("Should return nil for non existing block ", func(t *testing.T) { res, err := client.GetBlock(context.Background(), @@ -34,7 +34,7 @@ func TestGetBlock(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, height, res.Height) - assert.Equal(t, b.Hash().String(), res.Hash) + assert.Equal(t, blk.Hash().String(), res.Hash) assert.Equal(t, hex.EncodeToString(data), res.Data) assert.Empty(t, res.Header) assert.Empty(t, res.Txs) @@ -47,17 +47,17 @@ func TestGetBlock(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, height, res.Height) - assert.Equal(t, b.Hash().String(), res.Hash) + assert.Equal(t, blk.Hash().String(), res.Hash) assert.Empty(t, res.Data) assert.NotEmpty(t, res.Header) - assert.Equal(t, b.PrevCertificate().Committers(), res.PrevCert.Committers) - assert.Equal(t, b.PrevCertificate().Absentees(), res.PrevCert.Absentees) + assert.Equal(t, blk.PrevCertificate().Committers(), res.PrevCert.Committers) + assert.Equal(t, blk.PrevCertificate().Absentees(), res.PrevCert.Absentees) for i, trx := range res.Txs { - blockTrx := b.Transactions()[i] - b, err := blockTrx.Bytes() + blockTrx := blk.Transactions()[i] + blk, err := blockTrx.Bytes() assert.NoError(t, err) assert.Equal(t, trx.Id, blockTrx.ID().String()) - assert.Equal(t, trx.Data, hex.EncodeToString(b)) + assert.Equal(t, trx.Data, hex.EncodeToString(blk)) assert.Zero(t, trx.LockTime) assert.Empty(t, trx.Signature) assert.Empty(t, trx.PublicKey) @@ -71,12 +71,12 @@ func TestGetBlock(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, height, res.Height) - assert.Equal(t, b.Hash().String(), res.Hash) + assert.Equal(t, blk.Hash().String(), res.Hash) assert.Empty(t, res.Data) assert.NotEmpty(t, res.Header) assert.NotEmpty(t, res.Txs) for i, trx := range res.Txs { - blockTrx := b.Transactions()[i] + blockTrx := blk.Transactions()[i] assert.Equal(t, trx.Id, blockTrx.ID().String()) assert.Empty(t, trx.Data) @@ -94,7 +94,8 @@ func TestGetBlockHash(t *testing.T) { td := setup(t, nil) conn, client := td.blockchainClient(t) - b := td.mockState.TestStore.AddTestBlock(100) + height := td.RandHeight() + blk := td.mockState.TestStore.AddTestBlock(height) t.Run("Should return error for non existing block", func(t *testing.T) { res, err := client.GetBlockHash(context.Background(), @@ -106,10 +107,10 @@ func TestGetBlockHash(t *testing.T) { t.Run("Should return height of existing block", func(t *testing.T) { res, err := client.GetBlockHash(context.Background(), - &pactus.GetBlockHashRequest{Height: 100}) + &pactus.GetBlockHashRequest{Height: height}) assert.NoError(t, err) - assert.Equal(t, b.Hash().String(), res.Hash) + assert.Equal(t, blk.Hash().String(), res.Hash) }) assert.Nil(t, conn.Close(), "Error closing connection") @@ -120,7 +121,8 @@ func TestGetBlockHeight(t *testing.T) { td := setup(t, nil) conn, client := td.blockchainClient(t) - b := td.mockState.TestStore.AddTestBlock(100) + height := td.RandHeight() + blk := td.mockState.TestStore.AddTestBlock(height) t.Run("Should return error for invalid hash", func(t *testing.T) { res, err := client.GetBlockHeight(context.Background(), @@ -140,10 +142,10 @@ func TestGetBlockHeight(t *testing.T) { t.Run("Should return height of existing block", func(t *testing.T) { res, err := client.GetBlockHeight(context.Background(), - &pactus.GetBlockHeightRequest{Hash: b.Hash().String()}) + &pactus.GetBlockHeightRequest{Hash: blk.Hash().String()}) assert.NoError(t, err) - assert.Equal(t, uint32(100), res.Height) + assert.Equal(t, height, res.Height) }) assert.Nil(t, conn.Close(), "Error closing connection") @@ -339,7 +341,7 @@ func TestConsensusInfo(t *testing.T) { consRound := td.RandRound() vote1, _ := td.GenerateTestPrepareVote(consHeight, consRound) vote2, _ := td.GenerateTestPrecommitVote(consHeight, consRound) - prop, _ := td.GenerateTestProposal(consHeight, consRound) + prop := td.GenerateTestProposal(consHeight, consRound) td.consMocks[0].Active = true td.consMocks[0].Height = consHeight diff --git a/www/grpc/gateway.go b/www/grpc/gateway.go index 842d416a0..59f89dd9f 100644 --- a/www/grpc/gateway.go +++ b/www/grpc/gateway.go @@ -73,7 +73,7 @@ func (s *Server) startGateway(grpcAddr string) error { return err } - oa, err := s.getOpenAPIHandler() + handler, err := s.getOpenAPIHandler() if err != nil { return err } @@ -87,7 +87,7 @@ func (s *Server) startGateway(grpcAddr string) error { return } - oa.ServeHTTP(w, r) + handler.ServeHTTP(w, r) }), } @@ -123,7 +123,7 @@ func preflightHandler(w http.ResponseWriter) { // allowCORS allows Cross Origin Resource Sharing from any origin. // Don't do this without consideration in production systems. -func allowCORS(h http.Handler) http.Handler { +func allowCORS(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", origin) @@ -133,6 +133,6 @@ func allowCORS(h http.Handler) http.Handler { return } } - h.ServeHTTP(w, r) + handler.ServeHTTP(w, r) }) } diff --git a/www/grpc/network.go b/www/grpc/network.go index c82b7efb2..484ff8dad 100644 --- a/www/grpc/network.go +++ b/www/grpc/network.go @@ -24,7 +24,7 @@ func newNetworkServer(server *Server) *networkServer { func (s *networkServer) GetNodeInfo(_ context.Context, _ *pactus.GetNodeInfoRequest, ) (*pactus.GetNodeInfoResponse, error) { - ps := s.sync.PeerSet() + peerSet := s.sync.PeerSet() clockOffset, err := s.sync.ClockOffset() if err != nil { @@ -37,7 +37,7 @@ func (s *networkServer) GetNodeInfo(_ context.Context, PeerId: hex.EncodeToString([]byte(s.sync.SelfID())), Reachability: s.net.ReachabilityStatus(), LocalAddrs: s.net.HostAddrs(), - StartedAt: uint64(ps.StartedAt().Unix()), + StartedAt: uint64(peerSet.StartedAt().Unix()), Protocols: s.net.Protocols(), Services: int32(s.sync.Services()), ServicesNames: s.sync.Services().String(), @@ -53,44 +53,44 @@ func (s *networkServer) GetNodeInfo(_ context.Context, func (s *networkServer) GetNetworkInfo(_ context.Context, req *pactus.GetNetworkInfoRequest, ) (*pactus.GetNetworkInfoResponse, error) { - ps := s.sync.PeerSet() - peerInfos := make([]*pactus.PeerInfo, 0, ps.Len()) + peerSet := s.sync.PeerSet() + peerInfos := make([]*pactus.PeerInfo, 0, peerSet.Len()) - ps.IteratePeers(func(peer *peer.Peer) bool { + peerSet.IteratePeers(func(peer *peer.Peer) bool { if req.OnlyConnected && !peer.Status.IsConnectedOrKnown() { return false } - p := new(pactus.PeerInfo) - peerInfos = append(peerInfos, p) + peerInfo := new(pactus.PeerInfo) + peerInfos = append(peerInfos, peerInfo) - bs, err := cbor.Marshal(peer.Agent) + data, err := cbor.Marshal(peer.Agent) if err != nil { s.logger.Error("couldn't marshal agent", "error", err) return false } - p.Agent = string(bs) - - p.PeerId = hex.EncodeToString([]byte(peer.PeerID)) - p.Moniker = peer.Moniker - p.Agent = peer.Agent - p.Address = peer.Address - p.Direction = peer.Direction - p.Services = uint32(peer.Services) - p.Height = peer.Height - p.Protocols = peer.Protocols - p.Status = int32(peer.Status) - p.LastSent = peer.LastSent.Unix() - p.LastReceived = peer.LastReceived.Unix() - p.LastBlockHash = peer.LastBlockHash.String() - p.TotalSessions = int32(peer.TotalSessions) - p.CompletedSessions = int32(peer.CompletedSessions) - p.MetricInfo = metricToProto(peer.Metric) + peerInfo.Agent = string(data) + + peerInfo.PeerId = hex.EncodeToString([]byte(peer.PeerID)) + peerInfo.Moniker = peer.Moniker + peerInfo.Agent = peer.Agent + peerInfo.Address = peer.Address + peerInfo.Direction = peer.Direction + peerInfo.Services = uint32(peer.Services) + peerInfo.Height = peer.Height + peerInfo.Protocols = peer.Protocols + peerInfo.Status = int32(peer.Status) + peerInfo.LastSent = peer.LastSent.Unix() + peerInfo.LastReceived = peer.LastReceived.Unix() + peerInfo.LastBlockHash = peer.LastBlockHash.String() + peerInfo.TotalSessions = int32(peer.TotalSessions) + peerInfo.CompletedSessions = int32(peer.CompletedSessions) + peerInfo.MetricInfo = metricToProto(peer.Metric) for _, key := range peer.ConsensusKeys { - p.ConsensusKeys = append(p.ConsensusKeys, key.String()) - p.ConsensusAddresses = append(p.ConsensusAddresses, key.ValidatorAddress().String()) + peerInfo.ConsensusKeys = append(peerInfo.ConsensusKeys, key.String()) + peerInfo.ConsensusAddresses = append(peerInfo.ConsensusAddresses, key.ValidatorAddress().String()) } return false @@ -100,30 +100,30 @@ func (s *networkServer) GetNetworkInfo(_ context.Context, NetworkName: s.net.Name(), ConnectedPeersCount: uint32(len(peerInfos)), ConnectedPeers: peerInfos, - MetricInfo: metricToProto(ps.Metric()), + MetricInfo: metricToProto(peerSet.Metric()), }, nil } -func metricToProto(m metric.Metric) *pactus.MetricInfo { +func metricToProto(metric metric.Metric) *pactus.MetricInfo { metricInfo := &pactus.MetricInfo{ TotalInvalid: &pactus.CounterInfo{ - Bytes: uint64(m.TotalInvalid.Bytes), - Bundles: uint64(m.TotalInvalid.Bundles), + Bytes: uint64(metric.TotalInvalid.Bytes), + Bundles: uint64(metric.TotalInvalid.Bundles), }, TotalSent: &pactus.CounterInfo{ - Bytes: uint64(m.TotalSent.Bytes), - Bundles: uint64(m.TotalSent.Bundles), + Bytes: uint64(metric.TotalSent.Bytes), + Bundles: uint64(metric.TotalSent.Bundles), }, TotalReceived: &pactus.CounterInfo{ - Bytes: uint64(m.TotalReceived.Bytes), - Bundles: uint64(m.TotalReceived.Bundles), + Bytes: uint64(metric.TotalReceived.Bytes), + Bundles: uint64(metric.TotalReceived.Bundles), }, } metricInfo.MessageSent = make(map[int32]*pactus.CounterInfo) - for msgType, counter := range m.MessageSent { + for msgType, counter := range metric.MessageSent { metricInfo.MessageSent[int32(msgType)] = &pactus.CounterInfo{ Bytes: uint64(counter.Bytes), Bundles: uint64(counter.Bundles), @@ -131,7 +131,7 @@ func metricToProto(m metric.Metric) *pactus.MetricInfo { } metricInfo.MessageReceived = make(map[int32]*pactus.CounterInfo) - for msgType, counter := range m.MessageReceived { + for msgType, counter := range metric.MessageReceived { metricInfo.MessageReceived[int32(msgType)] = &pactus.CounterInfo{ Bytes: uint64(counter.Bytes), Bundles: uint64(counter.Bundles), diff --git a/www/grpc/network_test.go b/www/grpc/network_test.go index ccd18b804..e707db042 100644 --- a/www/grpc/network_test.go +++ b/www/grpc/network_test.go @@ -29,18 +29,18 @@ func TestGetNetworkInfo(t *testing.T) { assert.NoError(t, err) assert.Nil(t, err) assert.Equal(t, 2, len(res.ConnectedPeers)) - for _, p := range res.ConnectedPeers { - assert.NotEmpty(t, p.PeerId) - b, err := hex.DecodeString(p.PeerId) + for _, peer := range res.ConnectedPeers { + assert.NotEmpty(t, peer.PeerId) + b, err := hex.DecodeString(peer.PeerId) assert.NoError(t, err) pid, _ := lp2ppeer.IDFromBytes(b) pp := td.mockSync.PeerSet().GetPeer(pid) - assert.Equal(t, p.Agent, pp.Agent) - assert.Equal(t, p.Moniker, pp.Moniker) - assert.Equal(t, p.Height, pp.Height) + assert.Equal(t, peer.Agent, pp.Agent) + assert.Equal(t, peer.Moniker, pp.Moniker) + assert.Equal(t, peer.Height, pp.Height) assert.NotEmpty(t, pp.ConsensusKeys) for _, key := range pp.ConsensusKeys { - assert.Contains(t, p.ConsensusKeys, key.String()) + assert.Contains(t, peer.ConsensusKeys, key.String()) } } }) diff --git a/www/grpc/server.go b/www/grpc/server.go index b43ab3301..76f709f1c 100644 --- a/www/grpc/server.go +++ b/www/grpc/server.go @@ -29,8 +29,8 @@ type Server struct { logger *logger.SubLogger } -func NewServer(conf *Config, st state.Facade, syn sync.Synchronizer, - n network.Network, consMgr consensus.ManagerReader, +func NewServer(conf *Config, state state.Facade, sync sync.Synchronizer, + network network.Network, consMgr consensus.ManagerReader, walletMgr *wallet.Manager, ) *Server { ctx, cancel := context.WithCancel(context.Background()) @@ -39,9 +39,9 @@ func NewServer(conf *Config, st state.Facade, syn sync.Synchronizer, ctx: ctx, cancel: cancel, config: conf, - state: st, - sync: syn, - net: n, + state: state, + sync: sync, + net: network, consMgr: consMgr, walletMgr: walletMgr, logger: logger.NewSubLogger("_grpc", nil), diff --git a/www/grpc/wallet.go b/www/grpc/wallet.go index 3c4280b83..de3d018db 100644 --- a/www/grpc/wallet.go +++ b/www/grpc/wallet.go @@ -25,15 +25,15 @@ func newWalletServer(server *Server, manager *wallet.Manager) *walletServer { } } -func (*walletServer) mapHistoryInfo(hi []wallet.HistoryInfo) []*pactus.HistoryInfo { +func (*walletServer) mapHistoryInfo(his []wallet.HistoryInfo) []*pactus.HistoryInfo { historyInfo := make([]*pactus.HistoryInfo, 0) - for _, hi := range hi { + for _, info := range his { historyInfo = append(historyInfo, &pactus.HistoryInfo{ - TransactionId: hi.TxID, + TransactionId: info.TxID, // Time: uint32(hi.Time.Unix()), // TODO: Fix me - PayloadType: hi.PayloadType, - Description: hi.Desc, - Amount: hi.Amount.ToNanoPAC(), + PayloadType: info.PayloadType, + Description: info.Desc, + Amount: info.Amount.ToNanoPAC(), }) } @@ -139,7 +139,7 @@ func (s *walletServer) SignRawTransaction(_ context.Context, return nil, err } - id, data, err := s.walletManager.SignRawTransaction( + txID, data, err := s.walletManager.SignRawTransaction( req.WalletName, req.Password, rawBytes, ) if err != nil { @@ -147,7 +147,7 @@ func (s *walletServer) SignRawTransaction(_ context.Context, } return &pactus.SignRawTransactionResponse{ - TransactionId: hex.EncodeToString(id), + TransactionId: hex.EncodeToString(txID), SignedRawTransaction: hex.EncodeToString(data), }, nil } diff --git a/www/grpc/wallet_test.go b/www/grpc/wallet_test.go index eea1270c3..12bc2ad63 100644 --- a/www/grpc/wallet_test.go +++ b/www/grpc/wallet_test.go @@ -164,13 +164,13 @@ func TestLoadWallet(t *testing.T) { bondTx := tx.NewBondTx(td.RandHeight(), wltAddr, td.RandValAddress(), nil, td.RandAmount(), td.RandAmount()) - b, err := bondTx.Bytes() + data, err := bondTx.Bytes() assert.NoError(t, err) res, err := client.SignRawTransaction(context.Background(), &pactus.SignRawTransactionRequest{ WalletName: wltName, - RawTransaction: hex.EncodeToString(b), + RawTransaction: hex.EncodeToString(data), Password: "", }) assert.NoError(t, err) @@ -187,13 +187,13 @@ func TestLoadWallet(t *testing.T) { bondTx := tx.NewBondTx(td.RandHeight(), wltAddr, td.RandValAddress(), nil, td.RandAmount(), td.RandAmount()) - b, err := bondTx.Bytes() + data, err := bondTx.Bytes() assert.NoError(t, err) res, err := client.SignRawTransaction(context.Background(), &pactus.SignRawTransactionRequest{ WalletName: "not-loaded-wallet", - RawTransaction: hex.EncodeToString(b), + RawTransaction: hex.EncodeToString(data), Password: "", }) assert.Error(t, err) diff --git a/www/http/blockchain.go b/www/http/blockchain.go index 4f5be45b8..fec1d30bd 100644 --- a/www/http/blockchain.go +++ b/www/http/blockchain.go @@ -25,21 +25,21 @@ func (s *Server) BlockchainHandler(w http.ResponseWriter, r *http.Request) { return } - tm := newTableMaker() - tm.addRowBlockHash("Last Block Hash", res.LastBlockHash) - tm.addRowInt("Last Block Height", int(res.LastBlockHeight)) - tm.addRowBool("Is Pruned", res.IsPruned) - tm.addRowInt("Pruning Height", int(res.PruningHeight)) - tm.addRowString("--- Committee", "---") - tm.addRowPower("Total Power", res.TotalPower) - tm.addRowPower("Committee Power", res.CommitteePower) + tmk := newTableMaker() + tmk.addRowBlockHash("Last Block Hash", res.LastBlockHash) + tmk.addRowInt("Last Block Height", int(res.LastBlockHeight)) + tmk.addRowBool("Is Pruned", res.IsPruned) + tmk.addRowInt("Pruning Height", int(res.PruningHeight)) + tmk.addRowString("--- Committee", "---") + tmk.addRowPower("Total Power", res.TotalPower) + tmk.addRowPower("Committee Power", res.CommitteePower) for i, val := range res.CommitteeValidators { - tm.addRowInt("--- Validator", i+1) + tmk.addRowInt("--- Validator", i+1) tmVal := s.writeValidatorTable(val) - tm.addRowString("", tmVal.html()) + tmk.addRowString("", tmVal.html()) } - s.writeHTML(w, tm.html()) + s.writeHTML(w, tmk.html()) } func (s *Server) GetBlockByHeightHandler(w http.ResponseWriter, r *http.Request) { @@ -90,35 +90,35 @@ func (s *Server) blockByHeight(ctx context.Context, w http.ResponseWriter, block return } - tm := newTableMaker() - tm.addRowString("Time", time.Unix(int64(res.BlockTime), 0).String()) - tm.addRowInt("Height", int(res.Height)) - tm.addRowString("Hash", res.Hash) - tm.addRowString("Data", res.Data) + tmk := newTableMaker() + tmk.addRowString("Time", time.Unix(int64(res.BlockTime), 0).String()) + tmk.addRowInt("Height", int(res.Height)) + tmk.addRowString("Hash", res.Hash) + tmk.addRowString("Data", res.Data) if res.Header != nil { - tm.addRowString("--- Header", "---") - tm.addRowInt("Version", int(res.Header.Version)) - tm.addRowInt("UnixTime", int(res.BlockTime)) - tm.addRowBlockHash("PrevBlockHash", res.Header.PrevBlockHash) - tm.addRowString("StateRoot", res.Header.StateRoot) - tm.addRowString("SortitionSeed", res.Header.SortitionSeed) - tm.addRowValAddress("ProposerAddress", res.Header.ProposerAddress) + tmk.addRowString("--- Header", "---") + tmk.addRowInt("Version", int(res.Header.Version)) + tmk.addRowInt("UnixTime", int(res.BlockTime)) + tmk.addRowBlockHash("PrevBlockHash", res.Header.PrevBlockHash) + tmk.addRowString("StateRoot", res.Header.StateRoot) + tmk.addRowString("SortitionSeed", res.Header.SortitionSeed) + tmk.addRowValAddress("ProposerAddress", res.Header.ProposerAddress) } if res.PrevCert != nil { - tm.addRowString("--- PrevCertificate", "---") - tm.addRowString("Hash", res.PrevCert.Hash) - tm.addRowInt("Round", int(res.PrevCert.Round)) - tm.addRowInts("Committers", res.PrevCert.Committers) - tm.addRowInts("Absentees", res.PrevCert.Absentees) - tm.addRowString("Signature", res.PrevCert.Signature) + tmk.addRowString("--- PrevCertificate", "---") + tmk.addRowString("Hash", res.PrevCert.Hash) + tmk.addRowInt("Round", int(res.PrevCert.Round)) + tmk.addRowInts("Committers", res.PrevCert.Committers) + tmk.addRowInts("Absentees", res.PrevCert.Absentees) + tmk.addRowString("Signature", res.PrevCert.Signature) } - tm.addRowString("--- Transactions", "---") + tmk.addRowString("--- Transactions", "---") for i, trx := range res.Txs { - tm.addRowInt("Transaction #", i+1) - txToTable(tm, trx) + tmk.addRowInt("Transaction #", i+1) + txToTable(tmk, trx) } - s.writeHTML(w, tm.html()) + s.writeHTML(w, tmk.html()) } // GetAccountHandler returns a handler to get account by address. @@ -135,13 +135,13 @@ func (s *Server) GetAccountHandler(w http.ResponseWriter, r *http.Request) { } acc := res.Account - tm := newTableMaker() - tm.addRowAccAddress("Address", acc.Address) - tm.addRowInt("Number", int(acc.Number)) - tm.addRowAmount("Balance", amount.Amount(acc.Balance)) - tm.addRowString("Hash", acc.Hash) + tmk := newTableMaker() + tmk.addRowAccAddress("Address", acc.Address) + tmk.addRowInt("Number", int(acc.Number)) + tmk.addRowAmount("Balance", amount.Amount(acc.Balance)) + tmk.addRowString("Hash", acc.Hash) - s.writeHTML(w, tm.html()) + s.writeHTML(w, tmk.html()) } // GetValidatorHandler returns a handler to get validator by address. @@ -207,18 +207,18 @@ func (s *Server) GetTxPoolContentHandler(w http.ResponseWriter, r *http.Request) } func (*Server) writeValidatorTable(val *pactus.ValidatorInfo) *tableMaker { - tm := newTableMaker() - tm.addRowString("Public Key", val.PublicKey) - tm.addRowValAddress("Address", val.Address) - tm.addRowInt("Number", int(val.Number)) - tm.addRowAmount("Stake", amount.Amount(val.Stake)) - tm.addRowInt("LastBondingHeight", int(val.LastBondingHeight)) - tm.addRowInt("LastSortitionHeight", int(val.LastSortitionHeight)) - tm.addRowInt("UnbondingHeight", int(val.UnbondingHeight)) - tm.addRowDouble("AvailabilityScore", val.AvailabilityScore) - tm.addRowString("Hash", val.Hash) - - return tm + tmk := newTableMaker() + tmk.addRowString("Public Key", val.PublicKey) + tmk.addRowValAddress("Address", val.Address) + tmk.addRowInt("Number", int(val.Number)) + tmk.addRowAmount("Stake", amount.Amount(val.Stake)) + tmk.addRowInt("LastBondingHeight", int(val.LastBondingHeight)) + tmk.addRowInt("LastSortitionHeight", int(val.LastSortitionHeight)) + tmk.addRowInt("UnbondingHeight", int(val.UnbondingHeight)) + tmk.addRowDouble("AvailabilityScore", val.AvailabilityScore) + tmk.addRowString("Hash", val.Hash) + + return tmk } func (s *Server) ConsensusHandler(w http.ResponseWriter, r *http.Request) { @@ -232,33 +232,33 @@ func (s *Server) ConsensusHandler(w http.ResponseWriter, r *http.Request) { return } - tm := newTableMaker() + tmk := newTableMaker() - tm.addRowString("== Proposal", "") + tmk.addRowString("== Proposal", "") if res.Proposal != nil { - tm.addRowInt("Height", int(res.Proposal.Height)) - tm.addRowInt("Round", int(res.Proposal.Round)) - tm.addRowString("BlockData", res.Proposal.BlockData) - tm.addRowString("Signature", res.Proposal.Signature) + tmk.addRowInt("Height", int(res.Proposal.Height)) + tmk.addRowInt("Round", int(res.Proposal.Round)) + tmk.addRowString("BlockData", res.Proposal.BlockData) + tmk.addRowString("Signature", res.Proposal.Signature) } for i, cons := range res.Instances { - tm.addRowInt("== Validator", i+1) - tm.addRowValAddress("Address", cons.Address) - tm.addRowBool("Active", cons.Active) - tm.addRowInt("Height", int(cons.Height)) - tm.addRowInt("Round", int(cons.Round)) - tm.addRowString("Votes", "---") - for i, v := range cons.Votes { - tm.addRowInt("-- Vote #", i+1) - tm.addRowBlockHash("BlockHash", v.BlockHash) - tm.addRowString("Type", vote.Type(v.Type).String()) - tm.addRowString("Voter", v.Voter) - tm.addRowInt("Round", int(v.Round)) - tm.addRowInt("CPRound", int(v.CpRound)) - tm.addRowInt("CPValue", int(v.CpValue)) + tmk.addRowInt("== Validator", i+1) + tmk.addRowValAddress("Address", cons.Address) + tmk.addRowBool("Active", cons.Active) + tmk.addRowInt("Height", int(cons.Height)) + tmk.addRowInt("Round", int(cons.Round)) + tmk.addRowString("Votes", "---") + for index, vte := range cons.Votes { + tmk.addRowInt("-- Vote #", index+1) + tmk.addRowBlockHash("BlockHash", vte.BlockHash) + tmk.addRowString("Type", vote.Type(vte.Type).String()) + tmk.addRowString("Voter", vte.Voter) + tmk.addRowInt("Round", int(vte.Round)) + tmk.addRowInt("CPRound", int(vte.CpRound)) + tmk.addRowInt("CPValue", int(vte.CpValue)) } } - s.writeHTML(w, tm.html()) + s.writeHTML(w, tmk.html()) } diff --git a/www/http/blockchain_test.go b/www/http/blockchain_test.go index 913238480..67ae4ae9b 100644 --- a/www/http/blockchain_test.go +++ b/www/http/blockchain_test.go @@ -30,22 +30,23 @@ func TestBlockchainInfo(t *testing.T) { func TestBlock(t *testing.T) { td := setup(t) - b := td.mockState.TestStore.AddTestBlock(100) + height := td.RandHeight() + blk := td.mockState.TestStore.AddTestBlock(height) t.Run("Shall return a block", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) - r = mux.SetURLVars(r, map[string]string{"hash": b.Hash().String()}) + r = mux.SetURLVars(r, map[string]string{"hash": blk.Hash().String()}) td.httpServer.GetBlockByHashHandler(w, r) assert.Equal(t, 200, w.Code) - assert.Contains(t, w.Body.String(), b.Hash().String()) + assert.Contains(t, w.Body.String(), blk.Hash().String()) }) t.Run("Shall return a block", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) - r = mux.SetURLVars(r, map[string]string{"height": "100"}) + r = mux.SetURLVars(r, map[string]string{"height": fmt.Sprintf("%d", height)}) td.httpServer.GetBlockByHeightHandler(w, r) assert.Equal(t, 200, w.Code) @@ -280,14 +281,14 @@ func TestValidatorByNumber(t *testing.T) { func TestConsensusInfo(t *testing.T) { td := setup(t) - h, _ := td.mockConsMgr.HeightRound() - v1, _ := td.GenerateTestPrepareVote(h, 1) - v2, _ := td.GenerateTestPrecommitVote(h, 2) - p, _ := td.GenerateTestProposal(h, 2) + height, _ := td.mockConsMgr.HeightRound() + vote1, _ := td.GenerateTestPrepareVote(height, 1) + vote2, _ := td.GenerateTestPrecommitVote(height, 2) + prop := td.GenerateTestProposal(height, 2) - td.mockConsMgr.AddVote(v1) - td.mockConsMgr.AddVote(v2) - td.mockConsMgr.SetProposal(p) + td.mockConsMgr.AddVote(vote1) + td.mockConsMgr.AddVote(vote2) + td.mockConsMgr.SetProposal(prop) w := httptest.NewRecorder() r := new(http.Request) @@ -296,8 +297,8 @@ func TestConsensusInfo(t *testing.T) { assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "2") - assert.Contains(t, w.Body.String(), v2.Signer().String()) - assert.Contains(t, w.Body.String(), p.Signature().String()) + assert.Contains(t, w.Body.String(), vote2.Signer().String()) + assert.Contains(t, w.Body.String(), prop.Signature().String()) td.StopServers() } diff --git a/www/http/middleware_test.go b/www/http/middleware_test.go index 550ac73b6..5bb00aa93 100644 --- a/www/http/middleware_test.go +++ b/www/http/middleware_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/grpc/metadata" ) @@ -20,35 +21,33 @@ func TestBasicAuthMiddleware(t *testing.T) { t.Run("NoAuth", func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", http.NoBody) - rr := httptest.NewRecorder() + rec := httptest.NewRecorder() - handler.ServeHTTP(rr, req) + handler.ServeHTTP(rec, req) - assert.Equal(t, http.StatusUnauthorized, rr.Code) - assert.Equal(t, `Basic realm="restricted", charset="UTF-8"`, rr.Header().Get("WWW-Authenticate")) + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.Equal(t, `Basic realm="restricted", charset="UTF-8"`, rec.Header().Get("WWW-Authenticate")) }) t.Run("WithAuth", func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", http.NoBody) req.SetBasicAuth("username", "password") - rr := httptest.NewRecorder() + rec := httptest.NewRecorder() - handler.ServeHTTP(rr, req) + handler.ServeHTTP(rec, req) - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "authorized", rr.Body.String()) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "authorized", rec.Body.String()) }) t.Run("CheckMetadata", func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", http.NoBody) req.SetBasicAuth("username", "password") - rr := httptest.NewRecorder() + rec := httptest.NewRecorder() checkMetadataHandler := basicAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { md, ok := metadata.FromOutgoingContext(r.Context()) - if !ok { - t.Errorf("No metadata in context") - } + require.True(t, ok, "No metadata in context") auth := md["authorization"][0] @@ -65,8 +64,8 @@ func TestBasicAuthMiddleware(t *testing.T) { w.WriteHeader(http.StatusOK) })) - checkMetadataHandler.ServeHTTP(rr, req) + checkMetadataHandler.ServeHTTP(rec, req) - assert.Equal(t, http.StatusOK, rr.Code) + assert.Equal(t, http.StatusOK, rec.Code) }) } diff --git a/www/http/network.go b/www/http/network.go index 301be57c5..ca80c1264 100644 --- a/www/http/network.go +++ b/www/http/network.go @@ -36,45 +36,45 @@ func (s *Server) NetworkHandler(w http.ResponseWriter, r *http.Request) { return } - tm := newTableMaker() - tm.addRowString("Network Name", res.NetworkName) - tm.addRowInt("Connected Peers Count", int(res.ConnectedPeersCount)) - metricToTable(tm, res.MetricInfo) + tmk := newTableMaker() + tmk.addRowString("Network Name", res.NetworkName) + tmk.addRowInt("Connected Peers Count", int(res.ConnectedPeersCount)) + metricToTable(tmk, res.MetricInfo) - tm.addRowString("Peers", "---") + tmk.addRowString("Peers", "---") sort.Slice(res.ConnectedPeers, func(i, j int) bool { return res.ConnectedPeers[i].MetricInfo.TotalReceived.Bundles > res.ConnectedPeers[j].MetricInfo.TotalReceived.Bundles }) - for i, p := range res.ConnectedPeers { - id, _ := hex.DecodeString(p.PeerId) + for index, peer := range res.ConnectedPeers { + id, _ := hex.DecodeString(peer.PeerId) pid, _ := lp2ppeer.IDFromBytes(id) - tm.addRowInt("-- Peer #", i+1) - tm.addRowString("Status", status.Status(p.Status).String()) - tm.addRowString("PeerID", pid.String()) - tm.addRowString("Services", service.Services(p.Services).String()) - tm.addRowString("Agent", p.Agent) - tm.addRowString("Moniker", p.Moniker) - tm.addRowString("Remote Address", p.Address) - tm.addRowString("Direction", p.Direction) - tm.addRowStrings("Protocols", p.Protocols) - tm.addRowString("LastSent", time.Unix(p.LastSent, 0).String()) - tm.addRowString("LastReceived", time.Unix(p.LastReceived, 0).String()) - tm.addRowBlockHash("Last block Hash", p.LastBlockHash) - tm.addRowInt("Height", int(p.Height)) - tm.addRowInt("TotalSessions", int(p.TotalSessions)) - tm.addRowInt("CompletedSessions", int(p.CompletedSessions)) - metricToTable(tm, p.MetricInfo) - - for _, key := range p.ConsensusKeys { + tmk.addRowInt("-- Peer #", index+1) + tmk.addRowString("Status", status.Status(peer.Status).String()) + tmk.addRowString("PeerID", pid.String()) + tmk.addRowString("Services", service.Services(peer.Services).String()) + tmk.addRowString("Agent", peer.Agent) + tmk.addRowString("Moniker", peer.Moniker) + tmk.addRowString("Remote Address", peer.Address) + tmk.addRowString("Direction", peer.Direction) + tmk.addRowStrings("Protocols", peer.Protocols) + tmk.addRowString("LastSent", time.Unix(peer.LastSent, 0).String()) + tmk.addRowString("LastReceived", time.Unix(peer.LastReceived, 0).String()) + tmk.addRowBlockHash("Last block Hash", peer.LastBlockHash) + tmk.addRowInt("Height", int(peer.Height)) + tmk.addRowInt("TotalSessions", int(peer.TotalSessions)) + tmk.addRowInt("CompletedSessions", int(peer.CompletedSessions)) + metricToTable(tmk, peer.MetricInfo) + + for _, key := range peer.ConsensusKeys { pub, _ := bls.PublicKeyFromString(key) - tm.addRowString("-- PublicKey", pub.String()) - tm.addRowValAddress("-- Address", pub.ValidatorAddress().String()) + tmk.addRowString("-- PublicKey", pub.String()) + tmk.addRowValAddress("-- Address", pub.ValidatorAddress().String()) } } - s.writeHTML(w, tm.html()) + s.writeHTML(w, tmk.html()) } func (s *Server) NodeHandler(w http.ResponseWriter, r *http.Request) { @@ -87,43 +87,43 @@ func (s *Server) NodeHandler(w http.ResponseWriter, r *http.Request) { return } - id, _ := hex.DecodeString(res.PeerId) - sid, _ := lp2ppeer.IDFromBytes(id) - tm := newTableMaker() - tm.addRowString("Peer ID", sid.String()) - tm.addRowString("Agent", res.Agent) - tm.addRowString("Moniker", res.Moniker) - tm.addRowTime("Started at", int64(res.StartedAt)) - tm.addRowString("Reachability", res.Reachability) - tm.addRowFloat64("Clock Offset", res.ClockOffset) - tm.addRowInt("Services", int(res.Services)) - tm.addRowString("Services Names", res.ServicesNames) - - tm.addRowString("Connection Info", "---") - tm.addRowInt("-- Total connections", int(res.ConnectionInfo.Connections)) - tm.addRowInt("-- Inbound connections", int(res.ConnectionInfo.InboundConnections)) - tm.addRowInt("-- Outbound connections", int(res.ConnectionInfo.OutboundConnections)) - - tm.addRowString("Protocols", "---") + pid, _ := hex.DecodeString(res.PeerId) + sid, _ := lp2ppeer.IDFromBytes(pid) + tmk := newTableMaker() + tmk.addRowString("Peer ID", sid.String()) + tmk.addRowString("Agent", res.Agent) + tmk.addRowString("Moniker", res.Moniker) + tmk.addRowTime("Started at", int64(res.StartedAt)) + tmk.addRowString("Reachability", res.Reachability) + tmk.addRowFloat64("Clock Offset", res.ClockOffset) + tmk.addRowInt("Services", int(res.Services)) + tmk.addRowString("Services Names", res.ServicesNames) + + tmk.addRowString("Connection Info", "---") + tmk.addRowInt("-- Total connections", int(res.ConnectionInfo.Connections)) + tmk.addRowInt("-- Inbound connections", int(res.ConnectionInfo.InboundConnections)) + tmk.addRowInt("-- Outbound connections", int(res.ConnectionInfo.OutboundConnections)) + + tmk.addRowString("Protocols", "---") for i, p := range res.Protocols { - tm.addRowString(fmt.Sprint(i), p) + tmk.addRowString(fmt.Sprint(i), p) } - tm.addRowString("Local Addresses", "---") + tmk.addRowString("Local Addresses", "---") for i, la := range res.LocalAddrs { - tm.addRowString(fmt.Sprint(i), la) + tmk.addRowString(fmt.Sprint(i), la) } - s.writeHTML(w, tm.html()) + s.writeHTML(w, tmk.html()) } -func metricToTable(tm *tableMaker, mi *pactus.MetricInfo) { - printCounter := func(tm *tableMaker, name string, c *pactus.CounterInfo) { - tm.addRowString(name, - fmt.Sprintf("[%d, %s]", c.Bundles, util.FormatBytesToHumanReadable(c.Bytes))) +func metricToTable(tmk *tableMaker, metricInfo *pactus.MetricInfo) { + printCounter := func(tmk *tableMaker, name string, counterInfo *pactus.CounterInfo) { + tmk.addRowString(name, + fmt.Sprintf("[%d, %s]", counterInfo.Bundles, util.FormatBytesToHumanReadable(counterInfo.Bytes))) } - printSortedMap := func(tm *tableMaker, msgCounter map[int32]*pactus.CounterInfo) { + printSortedMap := func(tmk *tableMaker, msgCounter map[int32]*pactus.CounterInfo) { keys := make([]int32, 0, len(msgCounter)) for k := range msgCounter { keys = append(keys, k) @@ -134,17 +134,17 @@ func metricToTable(tm *tableMaker, mi *pactus.MetricInfo) { }) for _, key := range keys { - printCounter(tm, message.Type(key).String(), msgCounter[key]) + printCounter(tmk, message.Type(key).String(), msgCounter[key]) } } - printCounter(tm, "Total Invalid", mi.TotalInvalid) + printCounter(tmk, "Total Invalid", metricInfo.TotalInvalid) - tm.addRowString("Sent Metric", "---") - printCounter(tm, "Total Sent", mi.TotalSent) - printSortedMap(tm, mi.MessageSent) + tmk.addRowString("Sent Metric", "---") + printCounter(tmk, "Total Sent", metricInfo.TotalSent) + printSortedMap(tmk, metricInfo.MessageSent) - tm.addRowString("Received Metric", "---") - printCounter(tm, "Total Received", mi.TotalReceived) - printSortedMap(tm, mi.MessageReceived) + tmk.addRowString("Received Metric", "---") + printCounter(tmk, "Total Received", metricInfo.TotalReceived) + printSortedMap(tmk, metricInfo.MessageReceived) } diff --git a/www/http/transaction.go b/www/http/transaction.go index e98d6f9d6..3c28cbf73 100644 --- a/www/http/transaction.go +++ b/www/http/transaction.go @@ -30,52 +30,52 @@ func (s *Server) GetTransactionHandler(w http.ResponseWriter, r *http.Request) { s.writeHTML(w, tm.html()) } -func txToTable(tm *tableMaker, trx *pactus.TransactionInfo) { +func txToTable(tmk *tableMaker, trx *pactus.TransactionInfo) { if trx == nil { return } - tm.addRowTxID("ID", trx.Id) - tm.addRowInt("Version", int(trx.Version)) - tm.addRowInt("LockTime", int(trx.LockTime)) - tm.addRowAmount("Fee", amount.Amount(trx.Fee)) - tm.addRowString("Memo", trx.Memo) - tm.addRowString("Payload type", trx.PayloadType.String()) + tmk.addRowTxID("ID", trx.Id) + tmk.addRowInt("Version", int(trx.Version)) + tmk.addRowInt("LockTime", int(trx.LockTime)) + tmk.addRowAmount("Fee", amount.Amount(trx.Fee)) + tmk.addRowString("Memo", trx.Memo) + tmk.addRowString("Payload type", trx.PayloadType.String()) switch trx.PayloadType { case pactus.PayloadType_TRANSFER_PAYLOAD: pld := trx.Payload.(*pactus.TransactionInfo_Transfer).Transfer - tm.addRowAccAddress("Sender", pld.Sender) - tm.addRowAccAddress("Receiver", pld.Receiver) - tm.addRowAmount("Amount", amount.Amount(pld.Amount)) + tmk.addRowAccAddress("Sender", pld.Sender) + tmk.addRowAccAddress("Receiver", pld.Receiver) + tmk.addRowAmount("Amount", amount.Amount(pld.Amount)) case pactus.PayloadType_BOND_PAYLOAD: pld := trx.Payload.(*pactus.TransactionInfo_Bond).Bond - tm.addRowAccAddress("Sender", pld.Sender) - tm.addRowValAddress("Receiver", pld.Receiver) - tm.addRowAmount("Stake", amount.Amount(pld.Stake)) + tmk.addRowAccAddress("Sender", pld.Sender) + tmk.addRowValAddress("Receiver", pld.Receiver) + tmk.addRowAmount("Stake", amount.Amount(pld.Stake)) case pactus.PayloadType_SORTITION_PAYLOAD: pld := trx.Payload.(*pactus.TransactionInfo_Sortition).Sortition - tm.addRowValAddress("Address", pld.Address) - tm.addRowString("Proof", pld.Proof) + tmk.addRowValAddress("Address", pld.Address) + tmk.addRowString("Proof", pld.Proof) case pactus.PayloadType_UNBOND_PAYLOAD: pld := trx.Payload.(*pactus.TransactionInfo_Unbond).Unbond - tm.addRowValAddress("Validator", pld.Validator) + tmk.addRowValAddress("Validator", pld.Validator) case pactus.PayloadType_WITHDRAW_PAYLOAD: pld := trx.Payload.(*pactus.TransactionInfo_Withdraw).Withdraw - tm.addRowValAddress("Sender", pld.ValidatorAddress) - tm.addRowAccAddress("Receiver", pld.AccountAddress) - tm.addRowAmount("Amount", amount.Amount(pld.Amount)) + tmk.addRowValAddress("Sender", pld.ValidatorAddress) + tmk.addRowAccAddress("Receiver", pld.AccountAddress) + tmk.addRowAmount("Amount", amount.Amount(pld.Amount)) case pactus.PayloadType_UNKNOWN: - tm.addRowValAddress("error", "unknown payload type") + tmk.addRowValAddress("error", "unknown payload type") } if trx.PublicKey != "" { - tm.addRowString("PublicKey", trx.PublicKey) + tmk.addRowString("PublicKey", trx.PublicKey) } if trx.Signature != "" { - tm.addRowString("Signature", trx.Signature) + tmk.addRowString("Signature", trx.Signature) } } diff --git a/www/nanomsg/event/event.go b/www/nanomsg/event/event.go index ec50db9b8..45ee601cb 100644 --- a/www/nanomsg/event/event.go +++ b/www/nanomsg/event/event.go @@ -22,40 +22,37 @@ type Event []byte // The block event structure is like : // . func CreateBlockEvent(blockHash hash.Hash, height uint32) Event { - buf := make([]byte, 0, 42) - w := bytes.NewBuffer(buf) - err := encoding.WriteElements(w, TopicBlock, blockHash, height) + buf := bytes.NewBuffer(make([]byte, 0, 42)) + err := encoding.WriteElements(buf, TopicBlock, blockHash, height) if err != nil { logger.Error("error on encoding event in new block", "error", err) } - return w.Bytes() + return buf.Bytes() } // CreateTransactionEvent creates an event when a new transaction sent. // The new transaction event structure is like : // . func CreateTransactionEvent(txHash tx.ID, height uint32) Event { - buf := make([]byte, 0, 42) - w := bytes.NewBuffer(buf) - err := encoding.WriteElements(w, TopicTransaction, txHash, height) + buf := bytes.NewBuffer(make([]byte, 0, 42)) + err := encoding.WriteElements(buf, TopicTransaction, txHash, height) if err != nil { logger.Error("error on encoding event in new transaction", "error", err) } - return w.Bytes() + return buf.Bytes() } // CreateAccountChangeEvent creates an event when the new account is created. // The account event structure is like : // . func CreateAccountChangeEvent(accountAddr crypto.Address, height uint32) Event { - buf := make([]byte, 0, 42) - w := bytes.NewBuffer(buf) - err := encoding.WriteElements(w, TopicAccountChange, accountAddr, height) + buf := bytes.NewBuffer(make([]byte, 0, 42)) + err := encoding.WriteElements(buf, TopicAccountChange, accountAddr, height) if err != nil { logger.Error("error on encoding event in new account", "error", err) } - return w.Bytes() + return buf.Bytes() } diff --git a/www/nanomsg/server.go b/www/nanomsg/server.go index 0c099241b..da3e82629 100644 --- a/www/nanomsg/server.go +++ b/www/nanomsg/server.go @@ -79,14 +79,14 @@ func (s *Server) eventLoop() { return case e := <-s.eventCh: - w := bytes.NewBuffer(e) - err := encoding.WriteElement(w, s.seqNum) + writer := bytes.NewBuffer(e) + err := encoding.WriteElement(writer, s.seqNum) if err != nil { s.logger.Error("error on encoding event", "error", err) return } - err = s.publisher.Send(w.Bytes()) + err = s.publisher.Send(writer.Bytes()) if err != nil { s.logger.Error("error on emitting event", "error", err)