diff --git a/.golangci.yml b/.golangci.yml index b206a601f..83ae89e21 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -28,8 +28,6 @@ linters: - funlen # Consider to enable it - forbidigo # Consider to enable it - gci # Consider to enable it (add it to make fmt) - - gofumpt # Consider to enable it (add it to make fmt) - - godot # Consider to enable it - godox # Consider to enable it (only show warning) - gocritic # Consider to enable it - wsl # Consider to enable it diff --git a/Makefile b/Makefile index 5799e53ee..66bc21b5d 100644 --- a/Makefile +++ b/Makefile @@ -21,6 +21,7 @@ devtools: go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2 go install github.com/bufbuild/buf/cmd/buf@v1.25.0 + go install mvdan.cc/gofumpt@latest go install github.com/rakyll/statik@v0.1 ######################################## @@ -60,6 +61,7 @@ proto: ### Formatting, linting, and vetting fmt: gofmt -s -w . + gofumpt -l -w . check: golangci-lint run --build-tags "${BUILD_TAG}" --timeout=20m0s diff --git a/cmd/cmd.go b/cmd/cmd.go index 9dc360977..d9cffab44 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -257,7 +257,8 @@ func TrapSignal(cleanupFunc func()) { func CreateNode(numValidators int, chain genesis.ChainType, workingDir string, mnemonic string, walletPassword string) ( - validatorAddrs []string, rewardAddrs []string, err error) { + validatorAddrs []string, rewardAddrs []string, err error, +) { // To make process faster, we update the password after creating the addresses walletPath := PactusDefaultWalletPath(workingDir) wallet, err := wallet.Create(walletPath, mnemonic, "", chain) @@ -323,7 +324,8 @@ func CreateNode(numValidators int, chain genesis.ChainType, workingDir string, } func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string, bool)) ( - *node.Node, *wallet.Wallet, error) { + *node.Node, *wallet.Wallet, error, +) { gen, err := genesis.LoadFromFile(PactusGenesisPath(workingDir)) if err != nil { return nil, nil, err @@ -415,8 +417,7 @@ func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string, return nil, nil, fmt.Errorf("not enough addresses in wallet") } for i := 0; i < conf.Node.NumValidators; i++ { - rewardAddrs[i], _ = - crypto.AddressFromString(addrLabels[conf.Node.NumValidators+i].Address) + rewardAddrs[i], _ = crypto.AddressFromString(addrLabels[conf.Node.NumValidators+i].Address) } } @@ -439,7 +440,8 @@ func makeLocalGenesis(w wallet.Wallet) *genesis.Genesis { acc := account.NewAccount(0) acc.AddToBalance(21 * 1e14) accs := map[crypto.Address]*account.Account{ - crypto.TreasuryAddress: acc} + crypto.TreasuryAddress: acc, + } vals := make([]*validator.Validator, 4) for i := 0; i < 4; i++ { diff --git a/cmd/daemon/init.go b/cmd/daemon/init.go index f004004ca..11bc183f9 100644 --- a/cmd/daemon/init.go +++ b/cmd/daemon/init.go @@ -12,7 +12,7 @@ import ( // BuildInitCmd builds the init command for the Pactus blockchain. func buildInitCmd(parentCmd *cobra.Command) { - var initCmd = &cobra.Command{ + initCmd := &cobra.Command{ Use: "init", Short: "Initialize the Pactus blockchain", } diff --git a/cmd/daemon/main.go b/cmd/daemon/main.go index 6f35e01a4..2acb870ed 100644 --- a/cmd/daemon/main.go +++ b/cmd/daemon/main.go @@ -7,7 +7,7 @@ import ( ) func main() { - var rootCmd = &cobra.Command{ + rootCmd := &cobra.Command{ Use: "pactus-daemon", Short: "Pactus daemon", Run: func(cmd *cobra.Command, args []string) { diff --git a/cmd/daemon/start.go b/cmd/daemon/start.go index c65632b6a..d0ae1431a 100644 --- a/cmd/daemon/start.go +++ b/cmd/daemon/start.go @@ -14,7 +14,7 @@ import ( // Start starts the pactus node. func buildStartCmd(parentCmd *cobra.Command) { - var startCmd = &cobra.Command{ + startCmd := &cobra.Command{ Use: "start", Short: "Start the Pactus blockchain", } diff --git a/cmd/daemon/version.go b/cmd/daemon/version.go index cbb9f8fe1..003a15d2b 100644 --- a/cmd/daemon/version.go +++ b/cmd/daemon/version.go @@ -7,7 +7,7 @@ import ( // Version prints the version of the Pactus node. func buildVersionCmd(parentCmd *cobra.Command) { - var versionCmd = &cobra.Command{ + versionCmd := &cobra.Command{ Use: "version", Short: "Print the Pactus version", } diff --git a/cmd/gtk/model_wallet.go b/cmd/gtk/model_wallet.go index 1ea4a85f6..e4b515644 100644 --- a/cmd/gtk/model_wallet.go +++ b/cmd/gtk/model_wallet.go @@ -67,7 +67,8 @@ func (model *walletModel) rebuildModel() { IDAddressesColumnAddress, IDAddressesColumnLabel, IDAddressesColumnBalance, - IDAddressesColumnStake}, + IDAddressesColumnStake, + }, []interface{}{ d[0], d[1], @@ -97,7 +98,8 @@ func (model *walletModel) createAddress() error { IDAddressesColumnAddress, IDAddressesColumnLabel, IDAddressesColumnBalance, - IDAddressesColumnStake}, + IDAddressesColumnStake, + }, []interface{}{ fmt.Sprintf("%v", model.wallet.AddressCount()+1), address, diff --git a/cmd/gtk/startup_assistant.go b/cmd/gtk/startup_assistant.go index 4c34e383e..81a9d3f9d 100644 --- a/cmd/gtk/startup_assistant.go +++ b/cmd/gtk/startup_assistant.go @@ -347,7 +347,8 @@ func pageSeedRestore(assistant *gtk.Assistant, assistFunc assistantFunc) (*gtk.W } func pageSeedConfirm(assistant *gtk.Assistant, assistFunc assistantFunc, - textViewSeed *gtk.TextView) (*gtk.Widget, string) { + textViewSeed *gtk.TextView, +) (*gtk.Widget, string) { pageWidget := new(gtk.Widget) textViewConfirmSeed, err := gtk.TextViewNew() fatalErrorCheck(err) @@ -464,7 +465,8 @@ func pagePassword(assistant *gtk.Assistant, assistFunc assistantFunc) (*gtk.Widg } func pageNumValidators(assistant *gtk.Assistant, - assistFunc assistantFunc) (*gtk.Widget, *gtk.ListStore, *gtk.ComboBox, string) { + assistFunc assistantFunc, +) (*gtk.Widget, *gtk.ListStore, *gtk.ComboBox, string) { var pageWidget *gtk.Widget lsNumValidators, err := gtk.ListStoreNew(glib.TYPE_INT) fatalErrorCheck(err) diff --git a/cmd/gtk/utils.go b/cmd/gtk/utils.go index 0b57a587e..6e9a1afa2 100644 --- a/cmd/gtk/utils.go +++ b/cmd/gtk/utils.go @@ -162,6 +162,7 @@ func updateValidatorHint(lbl *gtk.Label, addr string, w *wallet.Wallet) { updateHintLabel(lbl, hint) } } + func updateAccountHint(lbl *gtk.Label, addr string, w *wallet.Wallet) { balance, err := w.Balance(addr) if err != nil { @@ -223,7 +224,7 @@ func signAndBroadcastTransaction(parent *gtk.Dialog, msg string, w *wallet.Walle } } -// openURLInBrowser open specific url in browser base on os +// openURLInBrowser open specific url in browser base on os. func openURLInBrowser(address string) error { cmd := "" args := make([]string, 0) diff --git a/cmd/wallet/create.go b/cmd/wallet/create.go index 41a37d5d6..891d11445 100644 --- a/cmd/wallet/create.go +++ b/cmd/wallet/create.go @@ -42,7 +42,7 @@ func buildGenerateCmd(parentCmd *cobra.Command) { // ChangePassword updates the wallet password. func buildChangePasswordCmd(parentCmd *cobra.Command) { - var changePasswordCmd = &cobra.Command{ + changePasswordCmd := &cobra.Command{ Use: "password", Short: "Change wallet password", } diff --git a/cmd/wallet/history.go b/cmd/wallet/history.go index 061c92b72..5b23f9cb1 100644 --- a/cmd/wallet/history.go +++ b/cmd/wallet/history.go @@ -20,7 +20,7 @@ func buildAllHistoryCmd(parentCmd *cobra.Command) { } func buildAddToHistoryCmd(parentCmd *cobra.Command) { - var addToHistoryCmd = &cobra.Command{ + addToHistoryCmd := &cobra.Command{ Use: "add", Short: "Add a transaction to the wallet history", } diff --git a/cmd/wallet/main.go b/cmd/wallet/main.go index 43c6b87a5..cc1fdd855 100644 --- a/cmd/wallet/main.go +++ b/cmd/wallet/main.go @@ -7,9 +7,11 @@ import ( "github.com/spf13/cobra" ) -var pathArg *string -var offlineOpt *bool -var serverAddrOpt *string +var ( + pathArg *string + offlineOpt *bool + serverAddrOpt *string +) func addPasswordOption(c *cobra.Command) *string { return c.Flags().StringP("password", "p", diff --git a/committee/committee.go b/committee/committee.go index e0e57a123..5787a9fca 100644 --- a/committee/committee.go +++ b/committee/committee.go @@ -25,7 +25,8 @@ func cloneValidator(val *validator.Validator) *validator.Validator { } func NewCommittee(validators []*validator.Validator, committeeSize int, - proposerAddress crypto.Address) (Committee, error) { + proposerAddress crypto.Address, +) (Committee, error) { validatorList := list.New() var proposerPos *list.Element diff --git a/config/config.go b/config/config.go index f485e9011..a4bbf876b 100644 --- a/config/config.go +++ b/config/config.go @@ -103,7 +103,8 @@ func SaveTestnetConfig(path string, numValidators int) error { "/ip4/172.104.46.145/tcp/21777/p2p/12D3KooWNYD4bB82YZRXv6oNyYPwc5ozabx2epv75ATV3D8VD3Mq", "/ip4/163.172.178.141/tcp/21777/p2p/12D3KooWDF8a4goNCHriP1y922y4jagaPwHdX4eSrG5WtQpjzS6k", "/ip4/13.230.117.134/tcp/21777/p2p/12D3KooWBGNEH8NqdK1UddSnPV1yRHGLYpaQUcnujC24s7YNWPiq", - "/ip6/2400:8901::f03c:93ff:fe1c:c3ec/tcp/21777/p2p/12D3KooWNYD4bB82YZRXv6oNyYPwc5ozabx2epv75ATV3D8VD3Mq"} + "/ip6/2400:8901::f03c:93ff:fe1c:c3ec/tcp/21777/p2p/12D3KooWNYD4bB82YZRXv6oNyYPwc5ozabx2epv75ATV3D8VD3Mq", + } conf.Network.Bootstrap.MinThreshold = 4 conf.Network.Bootstrap.MaxThreshold = 8 conf.Network.EnableRelay = true diff --git a/config/config_test.go b/config/config_test.go index f84dd202f..80b74bff8 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -97,7 +97,8 @@ func TestNodeConfigSanityCheck(t *testing.T) { t.Run("invalid number of reward addresses", func(t *testing.T) { conf := DefaultNodeConfig() conf.RewardAddresses = []string{ - ts.RandomAddress().String()} + ts.RandomAddress().String(), + } assert.Error(t, conf.SanityCheck()) }) @@ -107,7 +108,8 @@ func TestNodeConfigSanityCheck(t *testing.T) { conf.NumValidators = 2 conf.RewardAddresses = []string{ ts.RandomAddress().String(), - "abcd"} + "abcd", + } assert.Error(t, conf.SanityCheck()) }) @@ -117,7 +119,8 @@ func TestNodeConfigSanityCheck(t *testing.T) { conf.NumValidators = 2 conf.RewardAddresses = []string{ ts.RandomAddress().String(), - ts.RandomAddress().String()} + ts.RandomAddress().String(), + } assert.NoError(t, conf.SanityCheck()) }) diff --git a/consensus/consensus.go b/consensus/consensus.go index 1ae507294..6be3cfabc 100644 --- a/consensus/consensus.go +++ b/consensus/consensus.go @@ -47,7 +47,8 @@ func NewConsensus( signer crypto.Signer, rewardAddr crypto.Address, broadcastCh chan message.Message, - mediator mediator) Consensus { + mediator mediator, +) Consensus { cs := &consensus{ config: conf, state: state, diff --git a/consensus/consensus_test.go b/consensus/consensus_test.go index e5e701db8..822df5c6d 100644 --- a/consensus/consensus_test.go +++ b/consensus/consensus_test.go @@ -159,12 +159,14 @@ func (td *testData) shouldPublishBlockAnnounce(t *testing.T, cons *consensus, ha } func (td *testData) shouldPublishProposal(t *testing.T, cons *consensus, - height uint32, round int16) *proposal.Proposal { + height uint32, round int16, +) *proposal.Proposal { return shouldPublishProposal(t, cons, height, round) } func shouldPublishProposal(t *testing.T, cons *consensus, - height uint32, round int16) *proposal.Proposal { + height uint32, round int16, +) *proposal.Proposal { timeout := time.NewTimer(1 * time.Second) for { @@ -254,7 +256,8 @@ func (td *testData) checkHeightRoundWait(t *testing.T, cons *consensus, height u } func (td *testData) addVote(cons *consensus, voteType vote.Type, height uint32, round int16, - blockHash hash.Hash, valID int) *vote.Vote { + blockHash hash.Hash, valID int, +) *vote.Vote { v := vote.NewVote(voteType, height, round, blockHash, td.signers[valID].Address()) td.signers[valID].SignMsg(v) diff --git a/consensus/height_test.go b/consensus/height_test.go index 761d2b1c5..900b24546 100644 --- a/consensus/height_test.go +++ b/consensus/height_test.go @@ -35,6 +35,7 @@ func TestNewHeightEntry(t *testing.T) { assert.True(t, td.consX.active) assert.NotEqual(t, td.consX.currentState.name(), "new-height") } + func TestUpdateCertificate(t *testing.T) { td := setup(t) diff --git a/consensus/manager.go b/consensus/manager.go index 89e1ac021..fc59318db 100644 --- a/consensus/manager.go +++ b/consensus/manager.go @@ -19,7 +19,8 @@ func NewManager( state state.Facade, signers []crypto.Signer, rewardAddrs []crypto.Address, - broadcastCh chan message.Message) Manager { + broadcastCh chan message.Message, +) Manager { mgr := &manager{ instances: make([]Consensus, len(signers)), } diff --git a/consensus/mediator.go b/consensus/mediator.go index 0af64a3a5..c626ec4ba 100644 --- a/consensus/mediator.go +++ b/consensus/mediator.go @@ -14,7 +14,7 @@ type mediator interface { Register(cons Consensus) } -// ConcreteMediator struct +// ConcreteMediator struct. type ConcreteMediator struct { instances []Consensus } @@ -47,7 +47,7 @@ func (m *ConcreteMediator) OnBlockAnnounce(from Consensus) { } } -// Register a new Consensus instance to the mediator +// Register a new Consensus instance to the mediator. func (m *ConcreteMediator) Register(cons Consensus) { m.instances = append(m.instances, cons) } diff --git a/consensus/mock.go b/consensus/mock.go index 202a5fc44..d7316388b 100644 --- a/consensus/mock.go +++ b/consensus/mock.go @@ -45,15 +45,18 @@ func MockingConsensus(ts *testsuite.TestSuite, signer crypto.Signer) *MockConsen Signer: signer, } } + func (m *MockConsensus) SignerKey() crypto.PublicKey { return m.Signer.PublicKey() } + func (m *MockConsensus) MoveToNewHeight() { m.lk.Lock() defer m.lk.Unlock() m.Height++ } + func (m *MockConsensus) Start() error { return nil } @@ -65,18 +68,21 @@ func (m *MockConsensus) AddVote(v *vote.Vote) { m.Votes = append(m.Votes, v) } + func (m *MockConsensus) AllVotes() []*vote.Vote { m.lk.Lock() defer m.lk.Unlock() return m.Votes } + func (m *MockConsensus) SetProposal(p *proposal.Proposal) { m.lk.Lock() defer m.lk.Unlock() m.Proposal = p } + func (m *MockConsensus) HasVote(hash hash.Hash) bool { m.lk.Lock() defer m.lk.Unlock() @@ -88,6 +94,7 @@ func (m *MockConsensus) HasVote(hash hash.Hash) bool { } return false } + func (m *MockConsensus) RoundProposal(round int16) *proposal.Proposal { m.lk.Lock() defer m.lk.Unlock() @@ -97,15 +104,18 @@ func (m *MockConsensus) RoundProposal(round int16) *proposal.Proposal { } return m.Proposal } + func (m *MockConsensus) HeightRound() (uint32, int16) { m.lk.Lock() defer m.lk.Unlock() return m.Height, m.Round } + func (m *MockConsensus) String() string { return "" } + func (m *MockConsensus) PickRandomVote(_ int16) *vote.Vote { m.lk.Lock() defer m.lk.Unlock() @@ -116,6 +126,7 @@ func (m *MockConsensus) PickRandomVote(_ int16) *vote.Vote { r := m.ts.RandInt32(int32(len(m.Votes))) return m.Votes[r] } + func (m *MockConsensus) IsActive() bool { m.lk.Lock() defer m.lk.Unlock() diff --git a/consensus/propose.go b/consensus/propose.go index 044479aab..be192f34f 100644 --- a/consensus/propose.go +++ b/consensus/propose.go @@ -56,6 +56,7 @@ func (s *proposeState) onSetProposal(_ *proposal.Proposal) { func (s *proposeState) onTimeout(_ *ticker) { panic("Unreachable") } + func (s *proposeState) name() string { return "propose" } diff --git a/consensus/voteset/voteset.go b/consensus/voteset/voteset.go index b66f43344..5f3f81fd9 100644 --- a/consensus/voteset/voteset.go +++ b/consensus/voteset/voteset.go @@ -123,6 +123,7 @@ func (vs *VoteSet) AddVote(v *vote.Vote) error { return nil } + func (vs *VoteSet) hasTwoThirdOfTotalPower(power int64) bool { return power > (vs.totalPower * 2 / 3) } diff --git a/crypto/address_test.go b/crypto/address_test.go index 2aef10602..b75787629 100644 --- a/crypto/address_test.go +++ b/crypto/address_test.go @@ -95,15 +95,19 @@ func TestToString(t *testing.T) { "", "PC1P0HRCT7EFLRPW4CCRTTXZS4QUD2AXEX4DCDZDFR", // UPPERCASE true, - &crypto.Address{0x1, 0x7d, 0xc7, 0x85, 0xfb, 0x29, 0xf8, 0xc2, 0xea, 0xe3, - 0x3, 0x5a, 0xcc, 0x28, 0x54, 0x1c, 0x6a, 0xba, 0x6c, 0x9a, 0xad}, + &crypto.Address{ + 0x1, 0x7d, 0xc7, 0x85, 0xfb, 0x29, 0xf8, 0xc2, 0xea, 0xe3, + 0x3, 0x5a, 0xcc, 0x28, 0x54, 0x1c, 0x6a, 0xba, 0x6c, 0x9a, 0xad, + }, }, { "", "pc1p0hrct7eflrpw4ccrttxzs4qud2axex4dcdzdfr", true, - &crypto.Address{0x1, 0x7d, 0xc7, 0x85, 0xfb, 0x29, 0xf8, 0xc2, 0xea, 0xe3, - 0x3, 0x5a, 0xcc, 0x28, 0x54, 0x1c, 0x6a, 0xba, 0x6c, 0x9a, 0xad}, + &crypto.Address{ + 0x1, 0x7d, 0xc7, 0x85, 0xfb, 0x29, 0xf8, 0xc2, 0xea, 0xe3, + 0x3, 0x5a, 0xcc, 0x28, 0x54, 0x1c, 0x6a, 0xba, 0x6c, 0x9a, 0xad, + }, }, } for no, test := range tests { diff --git a/crypto/bls/hdkeychain/error.go b/crypto/bls/hdkeychain/error.go index a6fbdf2c8..29c0ec5b7 100644 --- a/crypto/bls/hdkeychain/error.go +++ b/crypto/bls/hdkeychain/error.go @@ -31,6 +31,6 @@ var ( // not valid. ErrInvalidKeyData = errors.New("key data is invalid") - // ErrInvalidPath describes an error in which the key path is invalid + // ErrInvalidPath describes an error in which the key path is invalid. ErrInvalidPath = errors.New("the key path is invalid") ) diff --git a/crypto/bls/hdkeychain/extendedkey.go b/crypto/bls/hdkeychain/extendedkey.go index 72b31f464..15d19fd3c 100644 --- a/crypto/bls/hdkeychain/extendedkey.go +++ b/crypto/bls/hdkeychain/extendedkey.go @@ -436,7 +436,7 @@ func NewMaster(seed []byte, pubOnG1 bool) (*ExtendedKey, error) { // masterKey is the master key used along with a random seed used to generate // the master node in the hierarchical tree. - var masterKey = []byte("BLS12381-HD-KEYCHAIN") + masterKey := []byte("BLS12381-HD-KEYCHAIN") // First take the HMAC-SHA512 of the master key and the seed data: // I = HMAC-SHA512(Key = "BLS12381-HD-KEYCHAIN", Data = S) diff --git a/crypto/bls/hdkeychain/extendedkey_test.go b/crypto/bls/hdkeychain/extendedkey_test.go index 58c499055..a4deab6ca 100644 --- a/crypto/bls/hdkeychain/extendedkey_test.go +++ b/crypto/bls/hdkeychain/extendedkey_test.go @@ -350,7 +350,7 @@ func TestDerivation(t *testing.T) { } } -// TestInvalidDerivation tests Derive function for invalid data +// TestInvalidDerivation tests Derive function for invalid data. func TestInvalidDerivation(t *testing.T) { t.Run("Private key is 31 bytes. It should be 32 bytes", func(t *testing.T) { key := [31]byte{0} diff --git a/crypto/bls/private_key.go b/crypto/bls/private_key.go index fbd6e6df4..53a4075d8 100644 --- a/crypto/bls/private_key.go +++ b/crypto/bls/private_key.go @@ -121,7 +121,7 @@ func (prv *PrivateKey) Bytes() []byte { } // Sign calculates the signature from the private key and given message. -// It's defined in section 2.6 of the spec: CoreSign +// It's defined in section 2.6 of the spec: CoreSign. func (prv *PrivateKey) Sign(msg []byte) crypto.Signature { g1 := bls12381.NewG1() diff --git a/crypto/bls/private_key_test.go b/crypto/bls/private_key_test.go index c9d774920..7f652a7fe 100644 --- a/crypto/bls/private_key_test.go +++ b/crypto/bls/private_key_test.go @@ -79,15 +79,19 @@ func TestPrivateKeyToString(t *testing.T) { "", "secret1pdrwtlp5px0fahdx39gxzjp7fkzfalml0d5u9tt9kvqhduc99cmgqqjvk67", // lowercase true, - []byte{0x68, 0xdc, 0xbf, 0x86, 0x81, 0x33, 0xd3, 0xdb, 0xb4, 0xd1, 0x2a, 0xc, 0x29, 0x7, 0xc9, 0xb0, - 0x93, 0xdf, 0xef, 0xef, 0x6d, 0x38, 0x55, 0xac, 0xb6, 0x60, 0x2e, 0xde, 0x60, 0xa5, 0xc6, 0xd0}, + []byte{ + 0x68, 0xdc, 0xbf, 0x86, 0x81, 0x33, 0xd3, 0xdb, 0xb4, 0xd1, 0x2a, 0xc, 0x29, 0x7, 0xc9, 0xb0, + 0x93, 0xdf, 0xef, 0xef, 0x6d, 0x38, 0x55, 0xac, 0xb6, 0x60, 0x2e, 0xde, 0x60, 0xa5, 0xc6, 0xd0, + }, }, { "", "SECRET1PDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CMGQQJVK67", true, - []byte{0x68, 0xdc, 0xbf, 0x86, 0x81, 0x33, 0xd3, 0xdb, 0xb4, 0xd1, 0x2a, 0xc, 0x29, 0x7, 0xc9, 0xb0, - 0x93, 0xdf, 0xef, 0xef, 0x6d, 0x38, 0x55, 0xac, 0xb6, 0x60, 0x2e, 0xde, 0x60, 0xa5, 0xc6, 0xd0}, + []byte{ + 0x68, 0xdc, 0xbf, 0x86, 0x81, 0x33, 0xd3, 0xdb, 0xb4, 0xd1, 0x2a, 0xc, 0x29, 0x7, 0xc9, 0xb0, + 0x93, 0xdf, 0xef, 0xef, 0x6d, 0x38, 0x55, 0xac, 0xb6, 0x60, 0x2e, 0xde, 0x60, 0xa5, 0xc6, 0xd0, + }, }, } for no, test := range tests { diff --git a/crypto/bls/public_key.go b/crypto/bls/public_key.go index fd358a77f..2bf2fb815 100644 --- a/crypto/bls/public_key.go +++ b/crypto/bls/public_key.go @@ -109,7 +109,7 @@ func (pub *PublicKey) Decode(r io.Reader) error { } // The Verify checks that a signature is valid for the given message and public key. -// It's defined in section 2.6 of the spec: CoreVerify +// It's defined in section 2.6 of the spec: CoreVerify. func (pub *PublicKey) Verify(msg []byte, sig crypto.Signature) error { if sig == nil { return errors.Error(errors.ErrInvalidSignature) diff --git a/crypto/bls/public_key_test.go b/crypto/bls/public_key_test.go index 1ccd94464..4214b22c2 100644 --- a/crypto/bls/public_key_test.go +++ b/crypto/bls/public_key_test.go @@ -114,47 +114,56 @@ func TestPublicKeyBytes(t *testing.T) { "public134jkgz", false, nil, }, - {"compression flag must be set", + { + "compression flag must be set", "public1pqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqjzu9w8", false, nil, }, - {"input string must be zero when infinity flag is set", + { + "input string must be zero when infinity flag is set", "public1pllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll" + "llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllluhpuzyf", false, nil, }, - {"public key is zero", + { + "public key is zero", "public1pcqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqglnhh9", false, nil, }, - {"invalid hrp: xxx", + { + "invalid hrp: xxx", "xxx1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjrvqc" + "vf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg7v5evslaq", false, nil, }, - {"invalid checksum (expected jhx47a got jhx470)", + { + "invalid checksum (expected jhx47a got jhx470)", "public1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjr" + "vqcvf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg7v5jhx470", false, nil, }, - {"public key should be 96 bytes, but it is 95 bytes", + { + "public key should be 96 bytes, but it is 95 bytes", "public1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjr" + "vqcvf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg73y98kl", false, nil, }, - {"", + { + "", "public1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjr" + "vqcvf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg7v5jhx47a", true, - []byte{0xaf, 0x0f, 0x74, 0x91, 0x7f, 0x50, 0x65, 0xaf, 0x94, 0x72, 0x7a, 0xe9, 0x54, 0x1b, 0x0d, 0xdc, + []byte{ + 0xaf, 0x0f, 0x74, 0x91, 0x7f, 0x50, 0x65, 0xaf, 0x94, 0x72, 0x7a, 0xe9, 0x54, 0x1b, 0x0d, 0xdc, 0xfb, 0x5b, 0x82, 0x8a, 0x9e, 0x01, 0x6b, 0x02, 0x49, 0x8f, 0x47, 0x7e, 0xd3, 0x7f, 0xb4, 0x4d, 0x5d, 0x88, 0x24, 0x95, 0xaf, 0xb6, 0xfd, 0x4f, 0x97, 0x73, 0xe4, 0xea, 0x9d, 0xee, 0xe4, 0x36, 0x03, 0x0c, 0x4d, 0x61, 0xc6, 0xe3, 0xa1, 0x15, 0x15, 0x85, 0xe1, 0xd8, 0x38, 0xca, 0xe1, 0x44, 0x4a, 0x43, 0x8d, 0x08, 0x9c, 0xe7, 0x7e, 0x10, 0xc4, 0x92, 0xa5, 0x5f, 0x69, 0x08, 0x12, 0x5c, 0x5b, 0xe9, 0xb2, 0x36, - 0xa2, 0x46, 0xe4, 0x08, 0x2d, 0x08, 0xde, 0x56, 0x4e, 0x11, 0x1e, 0x65}, + 0xa2, 0x46, 0xe4, 0x08, 0x2d, 0x08, 0xde, 0x56, 0x4e, 0x11, 0x1e, 0x65, + }, }, } diff --git a/crypto/bls/signature_test.go b/crypto/bls/signature_test.go index 032d1fcf8..96adf9e4c 100644 --- a/crypto/bls/signature_test.go +++ b/crypto/bls/signature_test.go @@ -127,9 +127,11 @@ func TestSignatureBytes(t *testing.T) { "", "ad0f88cec815e9b8af3f0136297cb242ed8b6369af723fbdac077fa927f5780db7df47c77fb53f3a22324673f000c792", true, - []byte{0xad, 0x0f, 0x88, 0xce, 0xc8, 0x15, 0xe9, 0xb8, 0xaf, 0x3f, 0x01, 0x36, 0x29, 0x7c, 0xb2, 0x42, + []byte{ + 0xad, 0x0f, 0x88, 0xce, 0xc8, 0x15, 0xe9, 0xb8, 0xaf, 0x3f, 0x01, 0x36, 0x29, 0x7c, 0xb2, 0x42, 0xed, 0x8b, 0x63, 0x69, 0xaf, 0x72, 0x3f, 0xbd, 0xac, 0x07, 0x7f, 0xa9, 0x27, 0xf5, 0x78, 0x0d, - 0xb7, 0xdf, 0x47, 0xc7, 0x7f, 0xb5, 0x3f, 0x3a, 0x22, 0x32, 0x46, 0x73, 0xf0, 0x00, 0xc7, 0x92}, + 0xb7, 0xdf, 0x47, 0xc7, 0x7f, 0xb5, 0x3f, 0x3a, 0x22, 0x32, 0x46, 0x73, 0xf0, 0x00, 0xc7, 0x92, + }, }, } diff --git a/crypto/bls/signer_test.go b/crypto/bls/signer_test.go index ea5d8c15e..92091b86f 100644 --- a/crypto/bls/signer_test.go +++ b/crypto/bls/signer_test.go @@ -17,9 +17,11 @@ type testSignableMsg struct { func (t *testSignableMsg) SignBytes() []byte { return []byte("zarb") } + func (t *testSignableMsg) SetSignature(sig crypto.Signature) { t.sig = sig.(*bls.Signature) } + func (t *testSignableMsg) SetPublicKey(pub crypto.PublicKey) { t.pub = pub.(*bls.PublicKey) } diff --git a/crypto/crypto.go b/crypto/crypto.go index 4fc4ed2be..53ece8420 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -1,14 +1,14 @@ package crypto var ( - // Human Readable Part (HRP) for address + // Human Readable Part (HRP) for address. AddressHRP = "pc" - // Human Readable Part (HRP) for public key + // Human Readable Part (HRP) for public key. PublicKeyHRP = "public" - // Human Readable Part (HRP) for private key + // Human Readable Part (HRP) for private key. PrivateKeyHRP = "secret" - // Human Readable Part (HRP) for extended public key + // Human Readable Part (HRP) for extended public key. XPublicKeyHRP = "xpublic" - // Human Readable Part (HRP) for extended private key + // Human Readable Part (HRP) for extended private key. XPrivateKeyHRP = "xsecret" ) diff --git a/crypto/hash/hash_test.go b/crypto/hash/hash_test.go index b16bd6745..4ba1ecb76 100644 --- a/crypto/hash/hash_test.go +++ b/crypto/hash/hash_test.go @@ -41,7 +41,7 @@ func TestHashEmpty(t *testing.T) { } func TestHash256(t *testing.T) { - var data = []byte("zarb") + data := []byte("zarb") h1 := hash.Hash256(data) expected, _ := hex.DecodeString("12b38977f2d67f06f0c0cd54aaf7324cf4fee184398ea33d295e8d1543c2ee1a") assert.Equal(t, h1, expected) @@ -52,7 +52,7 @@ func TestHash256(t *testing.T) { } func TestHash160(t *testing.T) { - var data = []byte("zarb") + data := []byte("zarb") h := hash.Hash160(data) expected, _ := hex.DecodeString("e93efc0c83176034cb828e39435eeecc07a29298") assert.Equal(t, h, expected) diff --git a/execution/execution.go b/execution/execution.go index 902952cf3..26a1184eb 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -33,6 +33,7 @@ func newExecution(strict bool) *Execution { strict: strict, } } + func NewExecutor() *Execution { return newExecution(true) } diff --git a/execution/executor/sortition.go b/execution/executor/sortition.go index 3137e206e..be2ec9ec7 100644 --- a/execution/executor/sortition.go +++ b/execution/executor/sortition.go @@ -78,7 +78,8 @@ func (e *SortitionExecutor) Fee() int64 { } func (e *SortitionExecutor) joinCommittee(sb sandbox.Sandbox, - val *validator.Validator) error { + val *validator.Validator, +) error { joiningNum := 0 joiningPower := int64(0) committee := sb.Committee() diff --git a/genesis/genesis.go b/genesis/genesis.go index cea4fa83f..b5d03071a 100644 --- a/genesis/genesis.go +++ b/genesis/genesis.go @@ -123,7 +123,8 @@ func makeGenesisValidator(val *validator.Validator) genValidator { } func MakeGenesis(genesisTime time.Time, accounts map[crypto.Address]*account.Account, - validators []*validator.Validator, params param.Params) *Genesis { + validators []*validator.Validator, params param.Params, +) *Genesis { genAccs := make([]genAccount, len(accounts)) for addr, acc := range accounts { genAcc := makeGenesisAccount(addr, acc) diff --git a/network/bootstrap.go b/network/bootstrap.go index 59b6b6865..82d1e275f 100644 --- a/network/bootstrap.go +++ b/network/bootstrap.go @@ -34,7 +34,8 @@ type bootstrap struct { // newBootstrap returns a new Bootstrap that will attempt to keep connected // to the network by connecting to the given bootstrap peers. func newBootstrap(ctx context.Context, h lp2phost.Host, d lp2pnet.Dialer, r lp2prouting.Routing, - conf *BootstrapConfig, logger *logger.SubLogger) *bootstrap { + conf *BootstrapConfig, logger *logger.SubLogger, +) *bootstrap { b := &bootstrap{ ctx: ctx, config: conf, @@ -79,7 +80,6 @@ func (b *bootstrap) Start() { // Stop stops the Bootstrap. func (b *bootstrap) Stop() { - } // checkConnectivity does the actual work. If the number of connected peers diff --git a/network/dht.go b/network/dht.go index 1d2a2a95e..34ddea039 100644 --- a/network/dht.go +++ b/network/dht.go @@ -18,7 +18,8 @@ type dhtService struct { } func newDHTService(ctx context.Context, host lp2phost.Host, protocolID lp2pcore.ProtocolID, - conf *BootstrapConfig, logger *logger.SubLogger) *dhtService { + conf *BootstrapConfig, logger *logger.SubLogger, +) *dhtService { opts := []lp2pdht.Option{ lp2pdht.Mode(lp2pdht.ModeAuto), lp2pdht.ProtocolPrefix(protocolID), diff --git a/network/gossip.go b/network/gossip.go index 5b05669ad..5f74f476f 100644 --- a/network/gossip.go +++ b/network/gossip.go @@ -22,7 +22,8 @@ type gossipService struct { } func newGossipService(ctx context.Context, host lp2phost.Host, eventCh chan Event, - logger *logger.SubLogger) *gossipService { + logger *logger.SubLogger, +) *gossipService { pubsub, err := lp2pps.NewGossipSub(ctx, host) if err != nil { logger.Panic("unable to start Gossip service", "err", err) diff --git a/network/mock.go b/network/mock.go index f27d2bda4..d1c5d9f9a 100644 --- a/network/mock.go +++ b/network/mock.go @@ -35,24 +35,30 @@ func MockingNetwork(ts *testsuite.TestSuite, id peer.ID) *MockNetwork { ID: id, } } + func (mock *MockNetwork) Start() error { return nil } + func (mock *MockNetwork) Stop() { } func (mock *MockNetwork) EventChannel() <-chan Event { return mock.EventCh } + func (mock *MockNetwork) JoinGeneralTopic() error { return nil } + func (mock *MockNetwork) JoinConsensusTopic() error { return nil } + func (mock *MockNetwork) SelfID() peer.ID { return mock.ID } + func (mock *MockNetwork) SendTo(data []byte, pid lp2pcore.PeerID) error { if mock.SendError != nil { return mock.SendError @@ -63,6 +69,7 @@ func (mock *MockNetwork) SendTo(data []byte, pid lp2pcore.PeerID) error { } return nil } + func (mock *MockNetwork) Broadcast(data []byte, _ TopicID) error { mock.BroadcastCh <- BroadcastData{ Data: data, @@ -91,6 +98,7 @@ func (mock *MockNetwork) SendToOthers(data []byte, target *peer.ID) { } } } + func (mock *MockNetwork) CloseConnection(pid peer.ID) { for i, net := range mock.OtherNets { if net.ID == pid { @@ -98,6 +106,7 @@ func (mock *MockNetwork) CloseConnection(pid peer.ID) { } } } + func (mock *MockNetwork) IsClosed(pid peer.ID) bool { for _, net := range mock.OtherNets { if net.ID == pid { @@ -106,9 +115,11 @@ func (mock *MockNetwork) IsClosed(pid peer.ID) bool { } return true } + func (mock *MockNetwork) NumConnectedPeers() int { return len(mock.OtherNets) } + func (mock *MockNetwork) AddAnotherNetwork(net *MockNetwork) { mock.OtherNets = append(mock.OtherNets, net) } diff --git a/network/network.go b/network/network.go index 9e9cca045..1414857ee 100644 --- a/network/network.go +++ b/network/network.go @@ -98,7 +98,6 @@ func newNetwork(conf *Config, opts []lp2p.Option) (*network, error) { rcmgr.NewFixedLimiter(rcmgr.DefaultLimits.AutoScale()), rcmgr.WithTraceReporter(str), ) - if err != nil { return nil, errors.Errorf(errors.ErrNetwork, err.Error()) } diff --git a/network/stream.go b/network/stream.go index 381adea74..2f529b1b2 100644 --- a/network/stream.go +++ b/network/stream.go @@ -24,7 +24,8 @@ type streamService struct { func newStreamService(ctx context.Context, host lp2phost.Host, protocolID lp2pcore.ProtocolID, relayAddrs []ma.Multiaddr, - eventCh chan Event, logger *logger.SubLogger) *streamService { + eventCh chan Event, logger *logger.SubLogger, +) *streamService { s := &streamService{ ctx: ctx, host: host, @@ -40,6 +41,7 @@ func newStreamService(ctx context.Context, host lp2phost.Host, func (s *streamService) Start() { } + func (s *streamService) Stop() { } @@ -87,7 +89,7 @@ func (s *streamService) SendRequest(msg []byte, pid lp2peer.ID) error { if err != nil { return errors.Errorf(errors.ErrNetwork, err.Error()) } - //fmt.Println(circuitAddr) + // fmt.Println(circuitAddr) circuitAddrs[i] = circuitAddr } diff --git a/node/node.go b/node/node.go index 6e6891203..16c3d3262 100644 --- a/node/node.go +++ b/node/node.go @@ -38,7 +38,8 @@ type Node struct { } func NewNode(genDoc *genesis.Genesis, conf *config.Config, - signers []crypto.Signer, rewardAddrs []crypto.Address) (*Node, error) { + signers []crypto.Signer, rewardAddrs []crypto.Address, +) (*Node, error) { // Initialize the logger logger.InitGlobalLogger(conf.Logger) @@ -150,16 +151,19 @@ func (n *Node) Stop() { n.nanomsg.StopServer() } -// these methods are using by GUI +// these methods are using by GUI. func (n *Node) ConsManager() consensus.ManagerReader { return n.consMgr } + func (n *Node) Sync() sync.Synchronizer { return n.sync } + func (n *Node) State() state.Facade { return n.state } + func (n *Node) GRPC() *grpc.Server { return n.grpc } diff --git a/sandbox/mock.go b/sandbox/mock.go index ac3536739..7e846f80d 100644 --- a/sandbox/mock.go +++ b/sandbox/mock.go @@ -63,43 +63,55 @@ func (m *MockSandbox) Account(addr crypto.Address) *account.Account { acc, _ := m.TestStore.Account(addr) return acc } + func (m *MockSandbox) MakeNewAccount(_ crypto.Address) *account.Account { return account.NewAccount(m.TestStore.TotalAccounts()) } + func (m *MockSandbox) UpdateAccount(addr crypto.Address, acc *account.Account) { m.TestStore.UpdateAccount(addr, acc) } + func (m *MockSandbox) Validator(addr crypto.Address) *validator.Validator { val, _ := m.TestStore.Validator(addr) return val } + func (m *MockSandbox) JoinedToCommittee(addr crypto.Address) { m.TestJoinedValidators[addr] = true } + func (m *MockSandbox) IsJoinedCommittee(addr crypto.Address) bool { return m.TestJoinedValidators[addr] } + func (m *MockSandbox) MakeNewValidator(pub *bls.PublicKey) *validator.Validator { return validator.NewValidator(pub, m.TestStore.TotalValidators()) } + func (m *MockSandbox) UpdateValidator(val *validator.Validator) { m.TestStore.UpdateValidator(val) } + func (m *MockSandbox) CurrentHeight() uint32 { return m.TestStore.LastHeight + 1 } + func (m *MockSandbox) Params() param.Params { return m.TestParams } + func (m *MockSandbox) RecentBlockByStamp(stamp hash.Stamp) (uint32, *block.Block) { return m.TestStore.RecentBlockByStamp(stamp) } + func (m *MockSandbox) IterateAccounts(consumer func(crypto.Address, *account.Account, bool)) { m.TestStore.IterateAccounts(func(addr crypto.Address, acc *account.Account) bool { consumer(addr, acc, true) return false }) } + func (m *MockSandbox) IterateValidators(consumer func(*validator.Validator, bool, bool)) { m.TestStore.IterateValidators(func(val *validator.Validator) bool { consumer(val, true, m.TestJoinedValidators[val.Address()]) @@ -110,12 +122,15 @@ func (m *MockSandbox) IterateValidators(consumer func(*validator.Validator, bool func (m *MockSandbox) Committee() committee.Reader { return m.TestCommittee } + func (m *MockSandbox) UpdatePowerDelta(delta int64) { m.TestPowerDelta += delta } + func (m *MockSandbox) PowerDelta() int64 { return m.TestPowerDelta } + func (m *MockSandbox) VerifyProof(hash.Stamp, sortition.Proof, *validator.Validator) bool { return m.TestAcceptSortition } diff --git a/sandbox/sandbox.go b/sandbox/sandbox.go index bb7d8d973..d5db33dcc 100644 --- a/sandbox/sandbox.go +++ b/sandbox/sandbox.go @@ -44,7 +44,8 @@ type sandboxAccount struct { } func NewSandbox(store store.Reader, params param.Params, - committee committee.Reader, totalPower int64) Sandbox { + committee committee.Reader, totalPower int64, +) Sandbox { sb := &sandbox{ store: store, committee: committee, @@ -227,7 +228,8 @@ func (sb *sandbox) currentHeight() uint32 { } func (sb *sandbox) IterateAccounts( - consumer func(crypto.Address, *account.Account, bool)) { + consumer func(crypto.Address, *account.Account, bool), +) { sb.lk.RLock() defer sb.lk.RUnlock() @@ -237,7 +239,8 @@ func (sb *sandbox) IterateAccounts( } func (sb *sandbox) IterateValidators( - consumer func(*validator.Validator, bool, bool)) { + consumer func(*validator.Validator, bool, bool), +) { sb.lk.RLock() defer sb.lk.RUnlock() diff --git a/state/mock.go b/state/mock.go index 292e0f32f..a3ad0bec9 100644 --- a/state/mock.go +++ b/state/mock.go @@ -57,33 +57,40 @@ func (m *MockState) CommitTestBlocks(num int) { m.TestStore.SaveBlock(m.LastBlockHeight()+1, b, cert) } } + func (m *MockState) LastBlockHeight() uint32 { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.LastHeight } + func (m *MockState) Genesis() *genesis.Genesis { return m.TestGenesis } + func (m *MockState) LastBlockHash() hash.Hash { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.BlockHash(m.TestStore.LastHeight) } + func (m *MockState) LastBlockTime() time.Time { return util.Now() } + func (m *MockState) LastCertificate() *block.Certificate { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.LastCert } + func (m *MockState) BlockTime() time.Duration { return time.Second } + func (m *MockState) UpdateLastCertificate(cert *block.Certificate) error { m.TestStore.LastCert = cert return nil @@ -103,25 +110,32 @@ func (m *MockState) CommitBlock(h uint32, b *block.Block, cert *block.Certificat func (m *MockState) Close() error { return nil } + func (m *MockState) ProposeBlock(_ crypto.Signer, _ crypto.Address, _ int16) (*block.Block, error) { b := m.ts.GenerateTestBlock(nil, nil) return b, nil } + func (m *MockState) ValidateBlock(_ *block.Block) error { return nil } + func (m *MockState) CommitteeValidators() []*validator.Validator { return m.TestCommittee.Validators() } + func (m *MockState) IsInCommittee(addr crypto.Address) bool { return m.TestCommittee.Contains(addr) } + func (m *MockState) Proposer(round int16) *validator.Validator { return m.TestCommittee.Proposer(round) } + func (m *MockState) IsProposer(addr crypto.Address, round int16) bool { return m.TestCommittee.IsProposer(addr, round) } + func (m *MockState) IsValidator(addr crypto.Address) bool { return m.TestStore.HasValidator(addr) } @@ -142,9 +156,11 @@ func (m *MockState) TotalPower() int64 { }) return p } + func (m *MockState) CommitteePower() int64 { return m.TestCommittee.TotalPower() } + func (m *MockState) StoredBlock(height uint32) *store.StoredBlock { m.lk.RLock() defer m.lk.RUnlock() @@ -152,6 +168,7 @@ func (m *MockState) StoredBlock(height uint32) *store.StoredBlock { b, _ := m.TestStore.Block(height) return b } + func (m *MockState) StoredTx(id tx.ID) *store.StoredTx { m.lk.RLock() defer m.lk.RUnlock() @@ -159,52 +176,63 @@ func (m *MockState) StoredTx(id tx.ID) *store.StoredTx { trx, _ := m.TestStore.Transaction(id) return trx } + func (m *MockState) BlockHash(height uint32) hash.Hash { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.BlockHash(height) } + func (m *MockState) BlockHeight(hash hash.Hash) uint32 { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.BlockHeight(hash) } + func (m *MockState) AccountByAddress(addr crypto.Address) *account.Account { a, _ := m.TestStore.Account(addr) return a } + func (m *MockState) AccountByNumber(number int32) *account.Account { a, _ := m.TestStore.AccountByNumber(number) return a } + func (m *MockState) ValidatorAddresses() []crypto.Address { return m.TestStore.ValidatorAddresses() } + func (m *MockState) ValidatorByAddress(addr crypto.Address) *validator.Validator { v, _ := m.TestStore.Validator(addr) return v } + func (m *MockState) ValidatorByNumber(n int32) *validator.Validator { v, _ := m.TestStore.ValidatorByNumber(n) return v } + func (m *MockState) PendingTx(id tx.ID) *tx.Tx { return m.TestPool.PendingTx(id) } + func (m *MockState) AddPendingTx(trx *tx.Tx) error { if m.TestPool.HasTx(trx.ID()) { return errors.Error(errors.ErrGeneric) } return m.TestPool.AppendTx(trx) } + func (m *MockState) AddPendingTxAndBroadcast(trx *tx.Tx) error { if m.TestPool.HasTx(trx.ID()) { return errors.Error(errors.ErrGeneric) } return m.TestPool.AppendTxAndBroadcast(trx) } + func (m *MockState) Params() param.Params { return m.TestParams } diff --git a/state/state.go b/state/state.go index a764177d0..b9a9b18c3 100644 --- a/state/state.go +++ b/state/state.go @@ -50,7 +50,8 @@ func LoadOrNewState( genDoc *genesis.Genesis, signers []crypto.Signer, store store.Store, - txPool txpool.TxPool, eventCh chan event.Event) (Facade, error) { + txPool txpool.TxPool, eventCh chan event.Event, +) (Facade, error) { st := &state{ signers: signers, genDoc: genDoc, @@ -637,9 +638,11 @@ func (st *state) StoredTx(id tx.ID) *store.StoredTx { func (st *state) BlockHash(height uint32) hash.Hash { return st.store.BlockHash(height) } + func (st *state) BlockHeight(hash hash.Hash) uint32 { return st.store.BlockHeight(hash) } + func (st *state) AccountByAddress(addr crypto.Address) *account.Account { acc, err := st.store.Account(addr) if err != nil { @@ -676,20 +679,24 @@ 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) AddPendingTx(trx *tx.Tx) error { return st.txPool.AppendTx(trx) } + func (st *state) AddPendingTxAndBroadcast(trx *tx.Tx) error { return st.txPool.AppendTxAndBroadcast(trx) } + func (st *state) Params() param.Params { return st.params } -// publishEvents publishes block related events +// publishEvents publishes block related events. func (st *state) publishEvents(height uint32, block *block.Block) { if st.eventCh == nil { return diff --git a/state/state_test.go b/state/state_test.go index 9bdd6da91..b1f8fb9b6 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -104,7 +104,8 @@ func setup(t *testing.T) *testData { } func (td *testData) makeBlockAndCertificate(t *testing.T, round int16, - signers ...crypto.Signer) (*block.Block, *block.Certificate) { + signers ...crypto.Signer, +) (*block.Block, *block.Certificate) { var st *state if td.state1.committee.IsProposer(td.state1.signers[0].Address(), round) { st = td.state1 @@ -125,7 +126,8 @@ func (td *testData) makeBlockAndCertificate(t *testing.T, round int16, } func (td *testData) makeCertificateAndSign(t *testing.T, blockHash hash.Hash, round int16, - signers ...crypto.Signer) *block.Certificate { + signers ...crypto.Signer, +) *block.Certificate { assert.NotZero(t, len(signers)) sigs := make([]*bls.Signature, len(signers)) sb := block.CertificateSignBytes(blockHash, round) diff --git a/store/mock.go b/store/mock.go index ad413882c..2c9be551b 100644 --- a/store/mock.go +++ b/store/mock.go @@ -32,6 +32,7 @@ func MockingStore(ts *testsuite.TestSuite) *MockStore { Validators: make(map[crypto.Address]validator.Validator), } } + func (m *MockStore) Block(height uint32) (*StoredBlock, error) { b, ok := m.Blocks[height] if ok { @@ -44,6 +45,7 @@ func (m *MockStore) Block(height uint32) (*StoredBlock, error) { } return nil, fmt.Errorf("not found") } + func (m *MockStore) BlockHash(height uint32) hash.Hash { b, ok := m.Blocks[height] if ok { @@ -51,6 +53,7 @@ func (m *MockStore) BlockHash(height uint32) hash.Hash { } return hash.UndefHash } + func (m *MockStore) BlockHeight(hash hash.Hash) uint32 { for h, b := range m.Blocks { if b.Hash().EqualsTo(hash) { @@ -59,6 +62,7 @@ func (m *MockStore) BlockHeight(hash hash.Hash) uint32 { } return 0 } + func (m *MockStore) Transaction(id tx.ID) (*StoredTx, error) { for height, block := range m.Blocks { for _, trx := range block.Transactions() { @@ -75,10 +79,12 @@ func (m *MockStore) Transaction(id tx.ID) (*StoredTx, error) { } return nil, fmt.Errorf("not found") } + func (m *MockStore) HasAccount(addr crypto.Address) bool { _, ok := m.Accounts[addr] return ok } + func (m *MockStore) Account(addr crypto.Address) (*account.Account, error) { a, ok := m.Accounts[addr] if ok { @@ -103,10 +109,12 @@ func (m *MockStore) UpdateAccount(addr crypto.Address, acc *account.Account) { func (m *MockStore) TotalAccounts() int32 { return int32(len(m.Accounts)) } + func (m *MockStore) HasValidator(addr crypto.Address) bool { _, ok := m.Validators[addr] return ok } + func (m *MockStore) ValidatorAddresses() []crypto.Address { addrs := make([]crypto.Address, 0, len(m.Validators)) for addr := range m.Validators { @@ -114,6 +122,7 @@ func (m *MockStore) ValidatorAddresses() []crypto.Address { } return addrs } + func (m *MockStore) Validator(addr crypto.Address) (*validator.Validator, error) { v, ok := m.Validators[addr] if ok { @@ -121,6 +130,7 @@ func (m *MockStore) Validator(addr crypto.Address) (*validator.Validator, error) } return nil, fmt.Errorf("not found") } + func (m *MockStore) ValidatorByNumber(num int32) (*validator.Validator, error) { for _, v := range m.Validators { if v.Number() == num { @@ -129,18 +139,23 @@ func (m *MockStore) ValidatorByNumber(num int32) (*validator.Validator, error) { } return nil, fmt.Errorf("not found") } + func (m *MockStore) UpdateValidator(val *validator.Validator) { m.Validators[val.Address()] = *val } + func (m *MockStore) TotalValidators() int32 { return int32(len(m.Validators)) } + func (m *MockStore) Close() error { return nil } + func (m *MockStore) HasAnyBlock() bool { return len(m.Blocks) > 0 } + func (m *MockStore) IterateAccounts(consumer func(crypto.Address, *account.Account) (stop bool)) { for addr, acc := range m.Accounts { cloned := acc @@ -150,6 +165,7 @@ func (m *MockStore) IterateAccounts(consumer func(crypto.Address, *account.Accou } } } + func (m *MockStore) IterateValidators(consumer func(*validator.Validator) (stop bool)) { for _, val := range m.Validators { cloned := val @@ -159,6 +175,7 @@ func (m *MockStore) IterateValidators(consumer func(*validator.Validator) (stop } } } + func (m *MockStore) SaveBlock(height uint32, b *block.Block, cert *block.Certificate) { m.Blocks[height] = *b m.LastHeight = height @@ -171,6 +188,7 @@ func (m *MockStore) LastCertificate() (uint32, *block.Certificate) { } return m.LastHeight, m.LastCert } + func (m *MockStore) RecentBlockByStamp(stamp hash.Stamp) (uint32, *block.Block) { for h, b := range m.Blocks { if b.Stamp().EqualsTo(stamp) { @@ -180,6 +198,7 @@ func (m *MockStore) RecentBlockByStamp(stamp hash.Stamp) (uint32, *block.Block) return 0, nil } + func (m *MockStore) WriteBatch() error { return nil } @@ -202,6 +221,7 @@ func (m *MockStore) AddTestBlock(height uint32) *block.Block { m.SaveBlock(height, b, cert) return b } + func (m *MockStore) RandomTestAcc() (crypto.Address, *account.Account) { for addr, acc := range m.Accounts { // Do not return the Treasury address for tests, @@ -213,6 +233,7 @@ func (m *MockStore) RandomTestAcc() (crypto.Address, *account.Account) { } panic("no account in sandbox") } + func (m *MockStore) RandomTestVal() *validator.Validator { for _, val := range m.Validators { return &val diff --git a/store/store_test.go b/store/store_test.go index 44b3b589a..bda0a818d 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -81,6 +81,7 @@ func TestWriteAndClosePeacefully(t *testing.T) { assert.NoError(t, td.store.Close()) assert.Error(t, td.store.WriteBatch()) } + func TestRetrieveBlockAndTransactions(t *testing.T) { td := setup(t) diff --git a/sync/bundle/bundle_test.go b/sync/bundle/bundle_test.go index c238e3b40..d4f2ce5f3 100644 --- a/sync/bundle/bundle_test.go +++ b/sync/bundle/bundle_test.go @@ -30,10 +30,11 @@ func TestInvalidCBOR(t *testing.T) { _, err = m.Decode(bytes.NewReader(d2)) assert.Error(t, err) } + func TestMessageCompress(t *testing.T) { ts := testsuite.NewTestSuite(t) - var blocksData = [][]byte{} + blocksData := [][]byte{} for i := 0; i < 10; i++ { b := ts.GenerateTestBlock(nil, nil) d, _ := b.Bytes() diff --git a/sync/bundle/message/blocks_response.go b/sync/bundle/message/blocks_response.go index 3040877c6..a3a666501 100644 --- a/sync/bundle/message/blocks_response.go +++ b/sync/bundle/message/blocks_response.go @@ -7,8 +7,10 @@ import ( "github.com/pactus-project/pactus/util/errors" ) -const LatestBlocksResponseCodeOK = 0 -const LatestBlocksResponseCodeNoMoreBlock = 1 +const ( + LatestBlocksResponseCodeOK = 0 + LatestBlocksResponseCodeNoMoreBlock = 1 +) type BlocksResponseMessage struct { ResponseCode ResponseCode `cbor:"1,keyasint"` @@ -20,7 +22,8 @@ type BlocksResponseMessage struct { } func NewBlocksResponseMessage(code ResponseCode, reason string, sid int, from uint32, - blocksData [][]byte, lastCert *block.Certificate) *BlocksResponseMessage { + blocksData [][]byte, lastCert *block.Certificate, +) *BlocksResponseMessage { return &BlocksResponseMessage{ ResponseCode: code, SessionID: sid, @@ -30,6 +33,7 @@ func NewBlocksResponseMessage(code ResponseCode, reason string, sid int, from ui Reason: reason, } } + func (m *BlocksResponseMessage) SanityCheck() error { if m.From == 0 && len(m.BlocksData) != 0 { return errors.Errorf(errors.ErrInvalidHeight, "unexpected block for height zero") diff --git a/sync/bundle/message/hello.go b/sync/bundle/message/hello.go index 1ee8c0ce0..7048c9230 100644 --- a/sync/bundle/message/hello.go +++ b/sync/bundle/message/hello.go @@ -30,7 +30,8 @@ type HelloMessage struct { } func NewHelloMessage(pid peer.ID, moniker string, - height uint32, flags int, blockHash, genesisHash hash.Hash) *HelloMessage { + height uint32, flags int, blockHash, genesisHash hash.Hash, +) *HelloMessage { return &HelloMessage{ PeerID: pid, Agent: version.Agent(), diff --git a/sync/firewall/firewall.go b/sync/firewall/firewall.go index 29cec1095..d027a1832 100644 --- a/sync/firewall/firewall.go +++ b/sync/firewall/firewall.go @@ -25,7 +25,8 @@ type Firewall struct { } func NewFirewall(conf *Config, net network.Network, peerSet *peerset.PeerSet, state state.Facade, - logger *logger.SubLogger) *Firewall { + logger *logger.SubLogger, +) *Firewall { return &Firewall{ config: conf, network: net, diff --git a/sync/handler_blocks_response_test.go b/sync/handler_blocks_response_test.go index 75b2c7e69..41e7c4fac 100644 --- a/sync/handler_blocks_response_test.go +++ b/sync/handler_blocks_response_test.go @@ -115,7 +115,8 @@ func TestSyncing(t *testing.T) { // For better logging when testing overrideLogger := func(sync *synchronizer, name string) { sync.logger = logger.NewSubLogger("_sync", &OverrideStringer{ - name: fmt.Sprintf("%s - %s: ", name, t.Name()), sync: sync}) + name: fmt.Sprintf("%s - %s: ", name, t.Name()), sync: sync, + }) } overrideLogger(syncAlice, "Alice") diff --git a/sync/mock.go b/sync/mock.go index 4bf4febd8..776f13139 100644 --- a/sync/mock.go +++ b/sync/mock.go @@ -49,6 +49,7 @@ func MockingSync(ts *testsuite.TestSuite) *MockSync { func (m *MockSync) Start() error { return nil } + func (m *MockSync) Stop() { } @@ -59,6 +60,7 @@ func (m *MockSync) SelfID() peer.ID { func (m *MockSync) Moniker() string { return "test-moniker" } + func (m *MockSync) PeerSet() *peerset.PeerSet { return m.TestPeerSet } diff --git a/sync/peerset/peer_set.go b/sync/peerset/peer_set.go index febc685e3..5bd0452cb 100644 --- a/sync/peerset/peer_set.go +++ b/sync/peerset/peer_set.go @@ -244,7 +244,8 @@ func (ps *PeerSet) UpdatePeerInfo( moniker string, agent string, consKey *bls.PublicKey, - nodeNetwork bool) { + nodeNetwork bool, +) { ps.lk.Lock() defer ps.lk.Unlock() diff --git a/sync/sync.go b/sync/sync.go index 9c96421aa..dfbb20c65 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -52,7 +52,8 @@ func NewSynchronizer( state state.Facade, consMgr consensus.Manager, net network.Network, - broadcastCh <-chan message.Message) (Synchronizer, error) { + broadcastCh <-chan message.Message, +) (Synchronizer, error) { sync := &synchronizer{ ctx: context.Background(), // TODO, set proper context config: conf, @@ -198,6 +199,7 @@ func (sync *synchronizer) broadcastLoop() { } } } + func (sync *synchronizer) receiveLoop() { for { select { diff --git a/sync/sync_test.go b/sync/sync_test.go index 6db2abc83..6854ade42 100644 --- a/sync/sync_test.go +++ b/sync/sync_test.go @@ -153,7 +153,8 @@ func shouldPublishMessageWithThisType(t *testing.T, net *network.MockNetwork, ms } func (td *testData) shouldPublishMessageWithThisType(t *testing.T, net *network.MockNetwork, - msgType message.Type) *bundle.Bundle { + msgType message.Type, +) *bundle.Bundle { return shouldPublishMessageWithThisType(t, net, msgType) } diff --git a/tests/main_test.go b/tests/main_test.go index e727b54b2..87e4877b4 100644 --- a/tests/main_test.go +++ b/tests/main_test.go @@ -24,24 +24,28 @@ import ( "google.golang.org/grpc/credentials/insecure" ) -var tSigners [][]crypto.Signer -var tConfigs []*config.Config -var tNodes []*node.Node -var tGRPCAddress = "0.0.0.0:1337" -var tGenDoc *genesis.Genesis -var tGRPC *grpc.ClientConn -var tBlockchain pactus.BlockchainClient -var tTransaction pactus.TransactionClient -var tNetwork pactus.NetworkClient -var tCtx context.Context -var tSequences map[crypto.Address]int32 - -const tNodeIdx1 = 0 -const tNodeIdx2 = 1 -const tNodeIdx3 = 2 -const tNodeIdx4 = 3 -const tTotalNodes = 4 // each node has 3 validators -const tCommitteeSize = 7 +var ( + tSigners [][]crypto.Signer + tConfigs []*config.Config + tNodes []*node.Node + tGRPCAddress = "0.0.0.0:1337" + tGenDoc *genesis.Genesis + tGRPC *grpc.ClientConn + tBlockchain pactus.BlockchainClient + tTransaction pactus.TransactionClient + tNetwork pactus.NetworkClient + tCtx context.Context + tSequences map[crypto.Address]int32 +) + +const ( + tNodeIdx1 = 0 + tNodeIdx2 = 1 + tNodeIdx3 = 2 + tNodeIdx4 = 3 + tTotalNodes = 4 // each node has 3 validators + tCommitteeSize = 7 +) func incSequence(addr crypto.Address) { tSequences[addr] = tSequences[addr] + 1 @@ -132,7 +136,8 @@ func TestMain(m *testing.M) { []crypto.Address{ tSigners[i][0].Address(), tSigners[i][1].Address(), - tSigners[i][2].Address()}) + tSigners[i][2].Address(), + }) if err := tNodes[i].Start(); err != nil { panic(fmt.Sprintf("Error on starting the node: %v", err)) diff --git a/txpool/mock.go b/txpool/mock.go index 4664cf0f7..43c1f60f1 100644 --- a/txpool/mock.go +++ b/txpool/mock.go @@ -54,6 +54,7 @@ func (m *MockTxPool) AppendTx(trx *tx.Tx) error { m.Txs = append(m.Txs, trx) return nil } + func (m *MockTxPool) AppendTxAndBroadcast(trx *tx.Tx) error { m.Txs = append(m.Txs, trx) return nil @@ -61,7 +62,7 @@ func (m *MockTxPool) AppendTxAndBroadcast(trx *tx.Tx) error { func (m *MockTxPool) RemoveTx(_ hash.Hash) { // This test pools is shared between different test objects - //delete(m.Txs, id) + // delete(m.Txs, id) } func (m *MockTxPool) PrepareBlockTransactions() block.Txs { diff --git a/types/account/account.go b/types/account/account.go index 660e0a938..5117ab1ee 100644 --- a/types/account/account.go +++ b/types/account/account.go @@ -37,7 +37,6 @@ func FromBytes(data []byte) (*Account, error) { &acc.data.Number, &acc.data.Sequence, &acc.data.Balance) - if err != nil { return nil, err } diff --git a/types/block/block.go b/types/block/block.go index f3a60e33f..080857c9f 100644 --- a/types/block/block.go +++ b/types/block/block.go @@ -51,7 +51,8 @@ func FromBytes(data []byte) (*Block, error) { func MakeBlock(version uint8, timestamp time.Time, txs Txs, prevBlockHash, stateRoot hash.Hash, - prevCert *Certificate, sortitionSeed sortition.VerifiableSeed, proposer crypto.Address) *Block { + prevCert *Certificate, sortitionSeed sortition.VerifiableSeed, proposer crypto.Address, +) *Block { header := NewHeader(version, timestamp, stateRoot, prevBlockHash, sortitionSeed, proposer) diff --git a/types/block/header.go b/types/block/header.go index 43ba04c15..28791952c 100644 --- a/types/block/header.go +++ b/types/block/header.go @@ -24,43 +24,44 @@ type headerData struct { ProposerAddress crypto.Address } -// Version returns the block version +// Version returns the block version. func (h *Header) Version() uint8 { return h.data.Version } -// Time returns the block time +// Time returns the block time. func (h *Header) Time() time.Time { return time.Unix(int64(h.data.UnixTime), 0) } -// UnixTime returns the block time in Unix value +// UnixTime returns the block time in Unix value. func (h *Header) UnixTime() uint32 { return h.data.UnixTime } -// StateRoot returns the state root hash +// StateRoot returns the state root hash. func (h *Header) StateRoot() hash.Hash { return h.data.StateRoot } -// PrevBlockHash returns the previous block hash +// PrevBlockHash returns the previous block hash. func (h *Header) PrevBlockHash() hash.Hash { return h.data.PrevBlockHash } -// SortitionSeed returns the sortition seed +// SortitionSeed returns the sortition seed. func (h *Header) SortitionSeed() sortition.VerifiableSeed { return h.data.SortitionSeed } -// ProposerAddress returns the proposer address +// ProposerAddress returns the proposer address. func (h *Header) ProposerAddress() crypto.Address { return h.data.ProposerAddress } func NewHeader(version uint8, time time.Time, stateRoot, prevBlockHash hash.Hash, - sortitionSeed sortition.VerifiableSeed, proposerAddress crypto.Address) *Header { + sortitionSeed sortition.VerifiableSeed, proposerAddress crypto.Address, +) *Header { return &Header{ data: headerData{ Version: version, diff --git a/types/proposal/proposal.go b/types/proposal/proposal.go index 84046ae5d..171e0e22b 100644 --- a/types/proposal/proposal.go +++ b/types/proposal/proposal.go @@ -87,6 +87,7 @@ func (p *Proposal) Verify(pubKey crypto.PublicKey) error { } return pubKey.Verify(p.SignBytes(), p.data.Signature) } + func (p *Proposal) Hash() hash.Hash { return hash.CalcHash(p.SignBytes()) } diff --git a/types/tx/factory.go b/types/tx/factory.go index b32845647..79c617da7 100644 --- a/types/tx/factory.go +++ b/types/tx/factory.go @@ -9,7 +9,8 @@ import ( ) func NewSubsidyTx(stamp hash.Stamp, seq int32, - receiver crypto.Address, amount int64, memo string) *Tx { + receiver crypto.Address, amount int64, memo string, +) *Tx { return NewTransferTx( stamp, seq, @@ -22,7 +23,8 @@ func NewSubsidyTx(stamp hash.Stamp, seq int32, func NewTransferTx(stamp hash.Stamp, seq int32, sender, receiver crypto.Address, - amount, fee int64, memo string) *Tx { + amount, fee int64, memo string, +) *Tx { pld := &payload.TransferPayload{ Sender: sender, Receiver: receiver, @@ -34,7 +36,8 @@ func NewTransferTx(stamp hash.Stamp, seq int32, func NewBondTx(stamp hash.Stamp, seq int32, sender, receiver crypto.Address, pubKey *bls.PublicKey, - stake, fee int64, memo string) *Tx { + stake, fee int64, memo string, +) *Tx { pld := &payload.BondPayload{ Sender: sender, Receiver: receiver, @@ -46,7 +49,8 @@ func NewBondTx(stamp hash.Stamp, seq int32, func NewUnbondTx(stamp hash.Stamp, seq int32, val crypto.Address, - memo string) *Tx { + memo string, +) *Tx { pld := &payload.UnbondPayload{ Validator: val, } @@ -57,7 +61,8 @@ func NewWithdrawTx(stamp hash.Stamp, seq int32, val crypto.Address, acc crypto.Address, amount, fee int64, - memo string) *Tx { + memo string, +) *Tx { pld := &payload.WithdrawPayload{ From: val, To: acc, @@ -68,7 +73,8 @@ func NewWithdrawTx(stamp hash.Stamp, seq int32, func NewSortitionTx(stamp hash.Stamp, seq int32, addr crypto.Address, - proof sortition.Proof) *Tx { + proof sortition.Proof, +) *Tx { pld := &payload.SortitionPayload{ Address: addr, Proof: proof, diff --git a/types/tx/payload/sortition.go b/types/tx/payload/sortition.go index 8f4442a5f..0f4c77689 100644 --- a/types/tx/payload/sortition.go +++ b/types/tx/payload/sortition.go @@ -36,7 +36,7 @@ func (p *SortitionPayload) SanityCheck() error { } func (p *SortitionPayload) SerializeSize() int { - return 69 //48+21 + return 69 // 48+21 } func (p *SortitionPayload) Encode(w io.Writer) error { diff --git a/types/tx/payload/sortition_test.go b/types/tx/payload/sortition_test.go index bcb77cfe1..440d3f4d8 100644 --- a/types/tx/payload/sortition_test.go +++ b/types/tx/payload/sortition_test.go @@ -48,7 +48,7 @@ func TestSortitionDecoding(t *testing.T) { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, //proof + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, // proof }, value: 0, readErr: io.EOF, @@ -64,7 +64,7 @@ func TestSortitionDecoding(t *testing.T) { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, //proof + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // proof }, value: 0, readErr: nil, @@ -80,7 +80,7 @@ func TestSortitionDecoding(t *testing.T) { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, //proof + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // proof }, value: 0, readErr: nil, diff --git a/types/tx/payload/unbond.go b/types/tx/payload/unbond.go index d2df55c13..8c2b09f5b 100644 --- a/types/tx/payload/unbond.go +++ b/types/tx/payload/unbond.go @@ -25,7 +25,7 @@ func (p *UnbondPayload) Value() int64 { return 0 } -// TODO: write test for me +// TODO: write test for me. func (p *UnbondPayload) SanityCheck() error { if err := p.Validator.SanityCheck(); err != nil { return errors.Error(errors.ErrInvalidAddress) diff --git a/types/tx/payload/withdraw.go b/types/tx/payload/withdraw.go index ac8e6f443..e44730a55 100644 --- a/types/tx/payload/withdraw.go +++ b/types/tx/payload/withdraw.go @@ -27,7 +27,7 @@ func (p *WithdrawPayload) Value() int64 { return p.Amount } -// TODO: write test for me +// TODO: write test for me. func (p *WithdrawPayload) SanityCheck() error { if err := p.From.SanityCheck(); err != nil { return errors.Error(errors.ErrInvalidAddress) diff --git a/types/tx/tx.go b/types/tx/tx.go index f781931a9..0a1c851f8 100644 --- a/types/tx/tx.go +++ b/types/tx/tx.go @@ -14,8 +14,10 @@ import ( "github.com/pactus-project/pactus/util/errors" ) -const versionLatest = 0x01 -const flagLockTime = 0x80 +const ( + versionLatest = 0x01 + flagLockTime = 0x80 +) const maxMemoLength = 64 @@ -49,7 +51,8 @@ type txData struct { } func NewTx(stamp hash.Stamp, seq int32, pld payload.Payload, fee int64, - memo string) *Tx { + memo string, +) *Tx { trx := &Tx{ data: txData{ Stamp: stamp, @@ -65,7 +68,8 @@ func NewTx(stamp hash.Stamp, seq int32, pld payload.Payload, fee int64, } func NewLockTimeTx(lockTime uint32, seq int32, pld payload.Payload, fee int64, - memo string) *Tx { + memo string, +) *Tx { trx := &Tx{ data: txData{ LockTime: lockTime, @@ -356,6 +360,7 @@ func (tx *Tx) DecodeWithNoSignatory(r io.Reader) error { } return nil } + func (tx *Tx) Decode(r io.Reader) error { err := tx.DecodeWithNoSignatory(r) if err != nil { diff --git a/types/validator/validator.go b/types/validator/validator.go index fa8396618..60d77f857 100644 --- a/types/validator/validator.go +++ b/types/validator/validator.go @@ -55,7 +55,6 @@ func FromBytes(data []byte) (*Validator, error) { &acc.data.UnbondingHeight, &acc.data.LastSortitionHeight, ) - if err != nil { return nil, err } diff --git a/types/validator/validator_test.go b/types/validator/validator_test.go index 9fd08293e..708e5e616 100644 --- a/types/validator/validator_test.go +++ b/types/validator/validator_test.go @@ -79,6 +79,7 @@ func TestPower(t *testing.T) { assert.Equal(t, val.Stake(), int64(1)) assert.Equal(t, val.Power(), int64(0)) } + func TestAddToStake(t *testing.T) { ts := testsuite.NewTestSuite(t) diff --git a/util/bech32m/bech32m_test.go b/util/bech32m/bech32m_test.go index 80deb6328..e72b288c1 100644 --- a/util/bech32m/bech32m_test.go +++ b/util/bech32m/bech32m_test.go @@ -197,9 +197,8 @@ func TestCanDecodeUnlimtedBech32(t *testing.T) { t.Fatalf("Unexpected hrp: %v", hrp) } decodedHex := fmt.Sprintf("%x", data) - expected := - "00000000000000000000000000000000000000000000000000000000000000000000000000000000000" + - "00000000010000000000000000000000000000000000000000000000000000000000000000000000000" + expected := "00000000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000010000000000000000000000000000000000000000000000000000000000000000000000000" if decodedHex != expected { t.Fatalf("Unexpected decoded data: %s", decodedHex) } diff --git a/util/encoding/encoding_test.go b/util/encoding/encoding_test.go index c7a17d904..582a01c95 100644 --- a/util/encoding/encoding_test.go +++ b/util/encoding/encoding_test.go @@ -35,19 +35,21 @@ func TestElementEncoding(t *testing.T) { {int64(-65536), []byte{0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {int64(65536), []byte{0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}}, {uint64(4294967296), []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}}, - {&hash.Stamp{ - 0x01, 0x02, 0x03, 0x04, - }, + { + &hash.Stamp{ + 0x01, 0x02, 0x03, 0x04, + }, []byte{ 0x01, 0x02, 0x03, 0x04, }, }, - {&hash.Hash{ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - }, + { + &hash.Hash{ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, + }, []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, @@ -55,11 +57,12 @@ func TestElementEncoding(t *testing.T) { 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, }, }, - {&crypto.Address{ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, - 0x11, 0x12, 0x13, 0x14, 0x15, - }, + { + &crypto.Address{ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, + }, []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, @@ -115,19 +118,21 @@ func TestElementEncodingErrors(t *testing.T) { {int64(65536), 0, io.ErrShortWrite, io.EOF}, {uint64(4294967296), 0, io.ErrShortWrite, io.EOF}, {&hash.Stamp{0x01, 0x02, 0x03, 0x04}, 0, io.ErrShortWrite, io.EOF}, - {&hash.Hash{ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - }, + { + &hash.Hash{ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, + }, 0, io.ErrShortWrite, io.EOF, }, - {&crypto.Address{ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, - 0x11, 0x12, 0x13, 0x14, 0x15, - }, + { + &crypto.Address{ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, + }, 0, io.ErrShortWrite, io.EOF, }, } diff --git a/util/io.go b/util/io.go index a5ce353a2..186b11245 100644 --- a/util/io.go +++ b/util/io.go @@ -33,7 +33,7 @@ func WriteFile(filename string, data []byte) error { if err := Mkdir(filepath.Dir(filename)); err != nil { return err } - if err := os.WriteFile(filename, data, 0600); err != nil { + if err := os.WriteFile(filename, data, 0o600); err != nil { return fmt.Errorf("failed to write to %s: %v", filename, err) } return nil @@ -41,7 +41,7 @@ func WriteFile(filename string, data []byte) error { func Mkdir(dir string) error { // create the directory - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return fmt.Errorf("could not create directory %s", dir) } return nil @@ -93,7 +93,7 @@ func IsValidDirPath(fp string) bool { fi, err := os.Stat(fp) if err == nil { if fi.IsDir() { - if err := os.WriteFile(fp+"/test", []byte{}, 0600); err != nil { + if err := os.WriteFile(fp+"/test", []byte{}, 0o600); err != nil { return false } os.Remove(fp + "/test") diff --git a/util/io_test.go b/util/io_test.go index f185405f4..36e63e9f4 100644 --- a/util/io_test.go +++ b/util/io_test.go @@ -80,6 +80,7 @@ func isRoot() bool { } return i == 0 } + func TestIsValidPath(t *testing.T) { // To pass this tests inside docker if runtime.GOOS != "windows" && !isRoot() { diff --git a/util/linkedmap/doublylink.go b/util/linkedmap/doublylink.go index 6fd191a9c..86cb29cf1 100644 --- a/util/linkedmap/doublylink.go +++ b/util/linkedmap/doublylink.go @@ -14,7 +14,7 @@ func NewLinkNode[T any](data T) *LinkNode[T] { } } -// DoublyLinkedList represents a doubly linked list +// DoublyLinkedList represents a doubly linked list. type DoublyLinkedList[T any] struct { Head *LinkNode[T] Tail *LinkNode[T] @@ -29,7 +29,7 @@ func NewDoublyLinkedList[T any]() *DoublyLinkedList[T] { } } -// InsertAtHead inserts a new node at the head of the list +// InsertAtHead inserts a new node at the head of the list. func (l *DoublyLinkedList[T]) InsertAtHead(data T) *LinkNode[T] { newNode := NewLinkNode(data) @@ -48,7 +48,7 @@ func (l *DoublyLinkedList[T]) InsertAtHead(data T) *LinkNode[T] { return newNode } -// InsertAtTail appends a new node at the tail of the list +// InsertAtTail appends a new node at the tail of the list. func (l *DoublyLinkedList[T]) InsertAtTail(data T) *LinkNode[T] { newNode := NewLinkNode(data) @@ -67,7 +67,7 @@ func (l *DoublyLinkedList[T]) InsertAtTail(data T) *LinkNode[T] { return newNode } -// DeleteAtHead deletes the node at the head of the list +// DeleteAtHead deletes the node at the head of the list. func (l *DoublyLinkedList[T]) DeleteAtHead() { if l.Head == nil { // Empty list case @@ -84,7 +84,7 @@ func (l *DoublyLinkedList[T]) DeleteAtHead() { l.length-- } -// DeleteAtTail deletes the node at the tail of the list +// DeleteAtTail deletes the node at the tail of the list. func (l *DoublyLinkedList[T]) DeleteAtTail() { if l.Tail == nil { // Empty list case @@ -101,7 +101,7 @@ func (l *DoublyLinkedList[T]) DeleteAtTail() { l.length-- } -// Delete removes a specific node from the list +// Delete removes a specific node from the list. func (l *DoublyLinkedList[T]) Delete(ln *LinkNode[T]) { if ln.Prev != nil { ln.Prev.Next = ln.Next @@ -118,12 +118,12 @@ func (l *DoublyLinkedList[T]) Delete(ln *LinkNode[T]) { l.length-- } -// Length returns the number of nodes in the list +// Length returns the number of nodes in the list. func (l *DoublyLinkedList[T]) Length() int { return l.length } -// Values returns a slice of values in the list +// Values returns a slice of values in the list. func (l *DoublyLinkedList[T]) Values() []T { values := []T{} cur := l.Head @@ -134,7 +134,7 @@ func (l *DoublyLinkedList[T]) Values() []T { return values } -// Clear removes all nodes from the list, making it empty +// Clear removes all nodes from the list, making it empty. func (l *DoublyLinkedList[T]) Clear() { l.Head = nil l.Tail = nil diff --git a/util/logger/logger.go b/util/logger/logger.go index b5aaa5c8f..fe11771b5 100644 --- a/util/logger/logger.go +++ b/util/logger/logger.go @@ -14,9 +14,7 @@ type logger struct { subs map[string]*SubLogger } -var ( - globalInst *logger -) +var globalInst *logger type SubLogger struct { logger zerolog.Logger diff --git a/util/persistentmerkle/merkle_test.go b/util/persistentmerkle/merkle_test.go index 91c4c46c1..72d1e74da 100644 --- a/util/persistentmerkle/merkle_test.go +++ b/util/persistentmerkle/merkle_test.go @@ -47,7 +47,8 @@ func TestMerkleTree(t *testing.T) { data := []string{ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"} + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + } roots := []string{ "a3a0081351bb785d0758ddf68076a95ffd3f10b88bbc9911e9fea4d793c06414", "f8c780ed425c674e458b1e42abc894d144af4660476b63adc900e5ca72ef3a7d", diff --git a/util/slice_test.go b/util/slice_test.go index cc874318a..d953b6d45 100644 --- a/util/slice_test.go +++ b/util/slice_test.go @@ -33,6 +33,7 @@ func TestSliceToInt16(t *testing.T) { assert.Equal(t, v1, test.in) } } + func TestSliceToInt32(t *testing.T) { tests := []struct { in int32 diff --git a/util/utils.go b/util/utils.go index b64dd5b45..f93578735 100644 --- a/util/utils.go +++ b/util/utils.go @@ -10,20 +10,26 @@ import ( "golang.org/x/exp/constraints" ) -const MaxUint16 = ^uint16(0) -const MinUint16 = 0 -const MaxInt16 = int16(MaxUint16 >> 1) -const MinInt16 = -MaxInt16 - 1 - -const MaxUint32 = ^uint32(0) -const MinUint32 = 0 -const MaxInt32 = int32(MaxUint32 >> 1) -const MinInt32 = -MaxInt32 - 1 - -const MaxUint64 = ^uint64(0) -const MinUint64 = 0 -const MaxInt64 = int64(MaxUint64 >> 1) -const MinInt64 = -MaxInt64 - 1 +const ( + MaxUint16 = ^uint16(0) + MinUint16 = 0 + MaxInt16 = int16(MaxUint16 >> 1) + MinInt16 = -MaxInt16 - 1 +) + +const ( + MaxUint32 = ^uint32(0) + MinUint32 = 0 + MaxInt32 = int32(MaxUint32 >> 1) + MinInt32 = -MaxInt32 - 1 +) + +const ( + MaxUint64 = ^uint64(0) + MinUint64 = 0 + MaxInt64 = int64(MaxUint64 >> 1) + MinInt64 = -MaxInt64 - 1 +) // Max returns the biggest of two integer numbers. func Max[T constraints.Integer](a, b T) T { diff --git a/wallet/client.go b/wallet/client.go index 67684fdc8..06242a3c1 100644 --- a/wallet/client.go +++ b/wallet/client.go @@ -66,7 +66,6 @@ func (c *grpcClient) sendTx(tx *tx.Tx) (tx.ID, error) { res, err := c.transactionClient.SendRawTransaction(context.Background(), &pactus.SendRawTransactionRequest{ Data: data, }) - if err != nil { return hash.UndefHash, err } @@ -74,7 +73,7 @@ func (c *grpcClient) sendTx(tx *tx.Tx) (tx.ID, error) { return hash.FromBytes(res.Id) } -// TODO: check the return value type +// TODO: check the return value type. func (c *grpcClient) getTransaction(id tx.ID) (*pactus.GetTransactionResponse, error) { res, err := c.transactionClient.GetTransaction(context.Background(), &pactus.GetTransactionRequest{ Id: id.Bytes(), @@ -89,7 +88,8 @@ func (c *grpcClient) getTransaction(id tx.ID) (*pactus.GetTransactionResponse, e func (c *grpcClient) getFee(amount int64, payloadType payload.Type) (int64, error) { res, err := c.transactionClient.CalculateFee(context.Background(), &pactus.CalculateFeeRequest{ - Amount: amount, PayloadType: pactus.PayloadType(payloadType)}) + Amount: amount, PayloadType: pactus.PayloadType(payloadType), + }) if err != nil { return 0, err } diff --git a/wallet/client_test.go b/wallet/client_test.go index 4cead75e5..85561716c 100644 --- a/wallet/client_test.go +++ b/wallet/client_test.go @@ -12,37 +12,45 @@ type blockchainServer struct{} type transactionServer struct{} -var tBlockchainInfoResponse *pactus.GetBlockchainInfoResponse -var tAccountResponse *pactus.GetAccountResponse -var tValidatorResponse *pactus.GetValidatorResponse +var ( + tBlockchainInfoResponse *pactus.GetBlockchainInfoResponse + tAccountResponse *pactus.GetAccountResponse + tValidatorResponse *pactus.GetValidatorResponse +) func (s *blockchainServer) GetBlockchainInfo(_ context.Context, - _ *pactus.GetBlockchainInfoRequest) (*pactus.GetBlockchainInfoResponse, error) { + _ *pactus.GetBlockchainInfoRequest, +) (*pactus.GetBlockchainInfoResponse, error) { return tBlockchainInfoResponse, nil } func (s *blockchainServer) GetConsensusInfo(_ context.Context, - _ *pactus.GetConsensusInfoRequest) (*pactus.GetConsensusInfoResponse, error) { + _ *pactus.GetConsensusInfoRequest, +) (*pactus.GetConsensusInfoResponse, error) { return &pactus.GetConsensusInfoResponse{}, nil } func (s *blockchainServer) GetBlockHash(_ context.Context, - _ *pactus.GetBlockHashRequest) (*pactus.GetBlockHashResponse, error) { + _ *pactus.GetBlockHashRequest, +) (*pactus.GetBlockHashResponse, error) { return &pactus.GetBlockHashResponse{}, nil } func (s *blockchainServer) GetBlockHeight(_ context.Context, - _ *pactus.GetBlockHeightRequest) (*pactus.GetBlockHeightResponse, error) { + _ *pactus.GetBlockHeightRequest, +) (*pactus.GetBlockHeightResponse, error) { return &pactus.GetBlockHeightResponse{}, nil } func (s *blockchainServer) GetBlock(_ context.Context, - _ *pactus.GetBlockRequest) (*pactus.GetBlockResponse, error) { + _ *pactus.GetBlockRequest, +) (*pactus.GetBlockResponse, error) { return &pactus.GetBlockResponse{}, nil } func (s *blockchainServer) GetAccount(_ context.Context, - _ *pactus.GetAccountRequest) (*pactus.GetAccountResponse, error) { + _ *pactus.GetAccountRequest, +) (*pactus.GetAccountResponse, error) { if tAccountResponse != nil { return tAccountResponse, nil } @@ -50,22 +58,26 @@ func (s *blockchainServer) GetAccount(_ context.Context, } func (s *blockchainServer) GetValidatorAddresses(_ context.Context, - _ *pactus.GetValidatorAddressesRequest) (*pactus.GetValidatorAddressesResponse, error) { + _ *pactus.GetValidatorAddressesRequest, +) (*pactus.GetValidatorAddressesResponse, error) { return &pactus.GetValidatorAddressesResponse{}, nil } func (s *blockchainServer) GetAccountByNumber(_ context.Context, - _ *pactus.GetAccountByNumberRequest) (*pactus.GetAccountResponse, error) { + _ *pactus.GetAccountByNumberRequest, +) (*pactus.GetAccountResponse, error) { return &pactus.GetAccountResponse{}, nil } func (s *blockchainServer) GetValidatorByNumber(_ context.Context, - _ *pactus.GetValidatorByNumberRequest) (*pactus.GetValidatorResponse, error) { + _ *pactus.GetValidatorByNumberRequest, +) (*pactus.GetValidatorResponse, error) { return &pactus.GetValidatorResponse{}, nil } func (s *blockchainServer) GetValidator(_ context.Context, - _ *pactus.GetValidatorRequest) (*pactus.GetValidatorResponse, error) { + _ *pactus.GetValidatorRequest, +) (*pactus.GetValidatorResponse, error) { if tValidatorResponse != nil { return tValidatorResponse, nil } @@ -73,17 +85,20 @@ func (s *blockchainServer) GetValidator(_ context.Context, } func (s *transactionServer) GetTransaction(_ context.Context, - _ *pactus.GetTransactionRequest) (*pactus.GetTransactionResponse, error) { + _ *pactus.GetTransactionRequest, +) (*pactus.GetTransactionResponse, error) { return &pactus.GetTransactionResponse{}, nil } func (s *transactionServer) CalculateFee(_ context.Context, - _ *pactus.CalculateFeeRequest) (*pactus.CalculateFeeResponse, error) { + _ *pactus.CalculateFeeRequest, +) (*pactus.CalculateFeeResponse, error) { return &pactus.CalculateFeeResponse{Fee: 0}, nil } func (s *transactionServer) SendRawTransaction(_ context.Context, - req *pactus.SendRawTransactionRequest) (*pactus.SendRawTransactionResponse, error) { + req *pactus.SendRawTransactionRequest, +) (*pactus.SendRawTransactionResponse, error) { trx, _ := tx.FromBytes(req.Data) return &pactus.SendRawTransactionResponse{ Id: trx.ID().Bytes(), diff --git a/wallet/encrypter/encrypter.go b/wallet/encrypter/encrypter.go index 87c9578a3..7ca205ebe 100644 --- a/wallet/encrypter/encrypter.go +++ b/wallet/encrypter/encrypter.go @@ -53,11 +53,9 @@ const ( nameFuncMACv1 = "MACV1" ) -var ( - // ErrNotSupported describes an error in which the encrypted method is no - // known or supported. - ErrNotSupported = errors.New("encrypted method is not supported") -) +// ErrNotSupported describes an error in which the encrypted method is no +// known or supported. +var ErrNotSupported = errors.New("encrypted method is not supported") // encrypter keeps the method and parameters for the cipher algorithm. type Encrypter struct { @@ -110,7 +108,7 @@ func (e *Encrypter) IsEncrypted() bool { return e.Method != nameFuncNope } -// Encrypt encrypts the `message` using give `password` and returns the cipher message +// Encrypt encrypts the `message` using give `password` and returns the cipher message. func (e *Encrypter) Encrypt(message string, password string) (string, error) { if e.Method == nameFuncNope { if password != "" { @@ -188,7 +186,7 @@ func (e *Encrypter) Encrypt(message string, password string) (string, error) { return cipherText, nil } -// Decrypt decrypts the `cipher` using give `password` and returns the original message +// Decrypt decrypts the `cipher` using give `password` and returns the original message. func (e *Encrypter) Decrypt(cipher string, password string) (string, error) { if e.Method == nameFuncNope { if password != "" { diff --git a/wallet/encrypter/params.go b/wallet/encrypter/params.go index dfeb44545..cf6ff7a4b 100644 --- a/wallet/encrypter/params.go +++ b/wallet/encrypter/params.go @@ -12,6 +12,7 @@ type params map[string]string func newParams() params { return make(map[string]string) } + func (p params) SetUint8(key string, val uint8) { p.SetUint64(key, uint64(val)) } diff --git a/wallet/history_test.go b/wallet/history_test.go index 2bae56ed1..199760d60 100644 --- a/wallet/history_test.go +++ b/wallet/history_test.go @@ -15,19 +15,29 @@ func TestActivitiesSort(t *testing.T) { historyMock.addActivity("addr-1", 20, &pactus.GetTransactionResponse{ BlockTime: 2, Transaction: &pactus.TransactionInfo{ - Id: []byte{2}}}) + Id: []byte{2}, + }, + }) historyMock.addActivity("addr-1", 40, &pactus.GetTransactionResponse{ BlockTime: 4, Transaction: &pactus.TransactionInfo{ - Id: []byte{4}}}) + Id: []byte{4}, + }, + }) historyMock.addActivity("addr-1", 30, &pactus.GetTransactionResponse{ BlockTime: 3, Transaction: &pactus.TransactionInfo{ - Id: []byte{3}}}) + Id: []byte{3}, + }, + }) historyMock.addActivity("addr-1", 10, &pactus.GetTransactionResponse{ BlockTime: 1, Transaction: &pactus.TransactionInfo{ - Id: []byte{1}}}) + Id: []byte{1}, + }, + }) historyMock.addActivity("addr-2", 50, &pactus.GetTransactionResponse{ BlockTime: 5, Transaction: &pactus.TransactionInfo{ - Id: []byte{5}}}) + Id: []byte{5}, + }, + }) h := historyMock.getAddrHistory("addr-1") assert.Len(t, h, 4) diff --git a/wallet/tx_builder.go b/wallet/tx_builder.go index 2af6f90dc..f7e777006 100644 --- a/wallet/tx_builder.go +++ b/wallet/tx_builder.go @@ -22,6 +22,7 @@ func OptionStamp(stamp string) func(builder *txBuilder) error { return nil } } + func OptionSequence(seq int32) func(builder *txBuilder) error { return func(builder *txBuilder) error { builder.seq = seq @@ -77,6 +78,7 @@ func (m *txBuilder) setFromAddr(addr string) error { m.from = &from return nil } + func (m *txBuilder) setToAddress(addr string) error { to, err := crypto.AddressFromString(addr) if err != nil { diff --git a/wallet/vault/errors.go b/wallet/vault/errors.go index e99c3ca84..b9ab83afd 100644 --- a/wallet/vault/errors.go +++ b/wallet/vault/errors.go @@ -10,7 +10,7 @@ var ( // in wallet. ErrAddressExists = errors.New("address already exists") - // ErrInvalidPath describes an error in which the key path is invalid + // ErrInvalidPath describes an error in which the key path is invalid. ErrInvalidPath = errors.New("the key path is invalid") // ErrNeutered describes an error in which the wallet is neutered. diff --git a/wallet/vault/utils.go b/wallet/vault/utils.go index ed030ccbc..40e3da5f3 100644 --- a/wallet/vault/utils.go +++ b/wallet/vault/utils.go @@ -59,7 +59,7 @@ func GenerateMnemonic(bitSize int) string { return mnemonic } -// CheckMnemonic validates a mnemonic (seed phrase) based on BIP-39 +// CheckMnemonic validates a mnemonic (seed phrase) based on BIP-39. func CheckMnemonic(mnemonic string) error { _, err := bip39.EntropyFromMnemonic(mnemonic) return err diff --git a/wallet/vault/vault.go b/wallet/vault/vault.go index 349792ab7..9bcfcc976 100644 --- a/wallet/vault/vault.go +++ b/wallet/vault/vault.go @@ -79,8 +79,8 @@ func CreateVaultFromMnemonic(mnemonic string, coinType uint32) (*Vault, error) { purposeKey, err := masterKey.DerivePath([]uint32{ 12381 + hdkeychain.HardenedKeyStart, - coinType + hdkeychain.HardenedKeyStart}) - + coinType + hdkeychain.HardenedKeyStart, + }) if err != nil { return nil, err } diff --git a/wallet/vault/vault_test.go b/wallet/vault/vault_test.go index b1788301c..01a9c7268 100644 --- a/wallet/vault/vault_test.go +++ b/wallet/vault/vault_test.go @@ -22,7 +22,7 @@ type testData struct { importedPrv crypto.PrivateKey } -// setup return an instances of vault fo testing +// setup return an instances of vault fo testing. func setup(t *testing.T) *testData { ts := testsuite.NewTestSuite(t) @@ -295,7 +295,8 @@ func TestNeuter(t *testing.T) { assert.ErrorIs(t, err, ErrNeutered) _, err = neutered.PrivateKeys(tPassword, []string{ - td.RandomAddress().String()}) + td.RandomAddress().String(), + }) assert.ErrorIs(t, err, ErrNeutered) err = neutered.ImportPrivateKey("any", td.importedPrv) diff --git a/wallet/wallet.go b/wallet/wallet.go index df66c1baf..d0203e043 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -38,7 +38,7 @@ func GenerateMnemonic(entropy int) string { return vault.GenerateMnemonic(entropy) } -// CheckMnemonic is a wrapper for `vault.CheckMnemonic` +// CheckMnemonic is a wrapper for `vault.CheckMnemonic`. func CheckMnemonic(mnemonic string) error { return vault.CheckMnemonic(mnemonic) } @@ -75,8 +75,7 @@ func Create(path, mnemonic, password string, chain genesis.ChainType) (*Wallet, switch chain { case genesis.Mainnet: coinType = 21888 - case genesis.Testnet, - genesis.Localnet: + case genesis.Testnet, genesis.Localnet: coinType = 21777 default: return nil, ErrInvalidNetwork @@ -285,7 +284,8 @@ func (w *Wallet) ValidatorSequence(addrStr string) (int32, error) { // MakeTransferTx creates a new transfer transaction based on the given parameters. func (w *Wallet) MakeTransferTx(sender, receiver string, amount int64, - options ...TxOption) (*tx.Tx, error) { + options ...TxOption, +) (*tx.Tx, error) { maker, err := newTxBuilder(w.client, options...) if err != nil { return nil, err @@ -306,7 +306,8 @@ func (w *Wallet) MakeTransferTx(sender, receiver string, amount int64, // MakeBondTx creates a new bond transaction based on the given parameters. func (w *Wallet) MakeBondTx(sender, receiver, pubKey string, amount int64, - options ...TxOption) (*tx.Tx, error) { + options ...TxOption, +) (*tx.Tx, error) { maker, err := newTxBuilder(w.client, options...) if err != nil { return nil, err @@ -356,7 +357,8 @@ func (w *Wallet) MakeUnbondTx(addr string, opts ...TxOption) (*tx.Tx, error) { // MakeWithdrawTx creates a new withdraw transaction based on the given // parameters. func (w *Wallet) MakeWithdrawTx(sender, receiver string, amount int64, - options ...TxOption) (*tx.Tx, error) { + options ...TxOption, +) (*tx.Tx, error) { maker, err := newTxBuilder(w.client, options...) if err != nil { return nil, err diff --git a/wallet/wallet_test.go b/wallet/wallet_test.go index 3728c4b4f..ca39ae82e 100644 --- a/wallet/wallet_test.go +++ b/wallet/wallet_test.go @@ -166,6 +166,7 @@ func TestSaveWallet(t *testing.T) { assert.Error(t, td.wallet.Save()) }) } + func TestInvalidAddress(t *testing.T) { td := setup(t) diff --git a/www/grpc/blockchain.go b/www/grpc/blockchain.go index 0c18f038a..b434e1172 100644 --- a/www/grpc/blockchain.go +++ b/www/grpc/blockchain.go @@ -23,7 +23,8 @@ type blockchainServer struct { } func (s *blockchainServer) GetBlockchainInfo(_ context.Context, - _ *pactus.GetBlockchainInfoRequest) (*pactus.GetBlockchainInfoResponse, error) { + _ *pactus.GetBlockchainInfoRequest, +) (*pactus.GetBlockchainInfoResponse, error) { vals := s.state.CommitteeValidators() cv := make([]*pactus.ValidatorInfo, 0, len(vals)) for _, v := range vals { @@ -42,7 +43,8 @@ func (s *blockchainServer) GetBlockchainInfo(_ context.Context, } func (s *blockchainServer) GetConsensusInfo(_ context.Context, - _ *pactus.GetConsensusInfoRequest) (*pactus.GetConsensusInfoResponse, error) { + _ *pactus.GetConsensusInfoRequest, +) (*pactus.GetConsensusInfoResponse, error) { instances := make([]*pactus.ConsensusInfo, 0) for _, cons := range s.consMgr.Instances() { height, round := cons.HeightRound() @@ -66,7 +68,8 @@ func (s *blockchainServer) GetConsensusInfo(_ context.Context, } func (s *blockchainServer) GetBlockHash(_ context.Context, - req *pactus.GetBlockHashRequest) (*pactus.GetBlockHashResponse, error) { + req *pactus.GetBlockHashRequest, +) (*pactus.GetBlockHashResponse, error) { height := req.GetHeight() hash := s.state.BlockHash(height) if hash.IsUndef() { @@ -78,7 +81,8 @@ func (s *blockchainServer) GetBlockHash(_ context.Context, } func (s *blockchainServer) GetBlockHeight(_ context.Context, - req *pactus.GetBlockHeightRequest) (*pactus.GetBlockHeightResponse, error) { + req *pactus.GetBlockHeightRequest, +) (*pactus.GetBlockHeightResponse, error) { hash, err := hash.FromBytes(req.GetHash()) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid hash: %v", err) @@ -93,7 +97,8 @@ func (s *blockchainServer) GetBlockHeight(_ context.Context, } func (s *blockchainServer) GetBlock(_ context.Context, - req *pactus.GetBlockRequest) (*pactus.GetBlockResponse, error) { + req *pactus.GetBlockRequest, +) (*pactus.GetBlockResponse, error) { height := req.GetHeight() storedBlock := s.state.StoredBlock(height) if storedBlock == nil { @@ -156,7 +161,8 @@ func (s *blockchainServer) GetBlock(_ context.Context, } func (s *blockchainServer) GetAccount(_ context.Context, - req *pactus.GetAccountRequest) (*pactus.GetAccountResponse, error) { + req *pactus.GetAccountRequest, +) (*pactus.GetAccountResponse, error) { addr, err := crypto.AddressFromString(req.Address) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid address: %v", err) @@ -173,7 +179,8 @@ func (s *blockchainServer) GetAccount(_ context.Context, } func (s *blockchainServer) GetAccountByNumber(_ context.Context, - req *pactus.GetAccountByNumberRequest) (*pactus.GetAccountResponse, error) { + req *pactus.GetAccountByNumberRequest, +) (*pactus.GetAccountResponse, error) { acc := s.state.AccountByNumber(req.Number) if acc == nil { return nil, status.Errorf(codes.InvalidArgument, "account not found") @@ -185,7 +192,8 @@ func (s *blockchainServer) GetAccountByNumber(_ context.Context, } func (s *blockchainServer) GetValidatorByNumber(_ context.Context, - req *pactus.GetValidatorByNumberRequest) (*pactus.GetValidatorResponse, error) { + req *pactus.GetValidatorByNumberRequest, +) (*pactus.GetValidatorResponse, error) { val := s.state.ValidatorByNumber(req.Number) if val == nil { return nil, status.Errorf(codes.NotFound, "validator not found") @@ -197,7 +205,8 @@ func (s *blockchainServer) GetValidatorByNumber(_ context.Context, } func (s *blockchainServer) GetValidator(_ context.Context, - req *pactus.GetValidatorRequest) (*pactus.GetValidatorResponse, error) { + req *pactus.GetValidatorRequest, +) (*pactus.GetValidatorResponse, error) { addr, err := crypto.AddressFromString(req.Address) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid validator address: %v", err.Error()) @@ -213,7 +222,8 @@ func (s *blockchainServer) GetValidator(_ context.Context, } func (s *blockchainServer) GetValidatorAddresses(_ context.Context, - _ *pactus.GetValidatorAddressesRequest) (*pactus.GetValidatorAddressesResponse, error) { + _ *pactus.GetValidatorAddressesRequest, +) (*pactus.GetValidatorAddressesResponse, error) { addresses := s.state.ValidatorAddresses() addressesPB := make([]string, 0, len(addresses)) for _, address := range addresses { diff --git a/www/grpc/blockchain_test.go b/www/grpc/blockchain_test.go index 1f4c98596..ad78b6dca 100644 --- a/www/grpc/blockchain_test.go +++ b/www/grpc/blockchain_test.go @@ -17,7 +17,8 @@ func TestGetBlock(t *testing.T) { t.Run("Should return nil for non existing block ", func(t *testing.T) { res, err := client.GetBlock(tCtx, &pactus.GetBlockRequest{ - Height: height + 1, Verbosity: pactus.BlockVerbosity_BLOCK_DATA}) + Height: height + 1, Verbosity: pactus.BlockVerbosity_BLOCK_DATA, + }) assert.Error(t, err) assert.Nil(t, res) diff --git a/www/grpc/gateway.go b/www/grpc/gateway.go index cd5e07c2a..4f20b5a2d 100644 --- a/www/grpc/gateway.go +++ b/www/grpc/gateway.go @@ -13,7 +13,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - // Static files + // Static files. _ "github.com/pactus-project/pactus/www/grpc/statik" ) diff --git a/www/grpc/gen/go/blockchain.pb.gw.go b/www/grpc/gen/go/blockchain.pb.gw.go index 326b0cea1..549d65bc3 100644 --- a/www/grpc/gen/go/blockchain.pb.gw.go +++ b/www/grpc/gen/go/blockchain.pb.gw.go @@ -23,7 +23,7 @@ import ( "google.golang.org/protobuf/proto" ) -// Suppress "imported and not used" errors +// Suppress "imported and not used" errors. var _ codes.Code var _ io.Reader var _ status.Status diff --git a/www/grpc/gen/go/blockchain_grpc.pb.go b/www/grpc/gen/go/blockchain_grpc.pb.go index df0d601cc..a4b1e92fa 100644 --- a/www/grpc/gen/go/blockchain_grpc.pb.go +++ b/www/grpc/gen/go/blockchain_grpc.pb.go @@ -130,7 +130,7 @@ func (c *blockchainClient) GetValidatorAddresses(ctx context.Context, in *GetVal // BlockchainServer is the server API for Blockchain service. // All implementations should embed UnimplementedBlockchainServer -// for forward compatibility +// for forward compatibility. type BlockchainServer interface { GetBlock(context.Context, *GetBlockRequest) (*GetBlockResponse, error) GetBlockHash(context.Context, *GetBlockHashRequest) (*GetBlockHashResponse, error) @@ -372,7 +372,7 @@ func _Blockchain_GetValidatorAddresses_Handler(srv interface{}, ctx context.Cont // Blockchain_ServiceDesc is the grpc.ServiceDesc for Blockchain service. // It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) +// and not to be introspected or modified (even as a copy). var Blockchain_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Blockchain", HandlerType: (*BlockchainServer)(nil), diff --git a/www/grpc/gen/go/network.pb.gw.go b/www/grpc/gen/go/network.pb.gw.go index 95eb2f8f6..98436f950 100644 --- a/www/grpc/gen/go/network.pb.gw.go +++ b/www/grpc/gen/go/network.pb.gw.go @@ -23,7 +23,7 @@ import ( "google.golang.org/protobuf/proto" ) -// Suppress "imported and not used" errors +// Suppress "imported and not used" errors. var _ codes.Code var _ io.Reader var _ status.Status diff --git a/www/grpc/gen/go/network_grpc.pb.go b/www/grpc/gen/go/network_grpc.pb.go index 74f75af03..491b0649b 100644 --- a/www/grpc/gen/go/network_grpc.pb.go +++ b/www/grpc/gen/go/network_grpc.pb.go @@ -50,7 +50,7 @@ func (c *networkClient) GetNodeInfo(ctx context.Context, in *GetNodeInfoRequest, // NetworkServer is the server API for Network service. // All implementations should embed UnimplementedNetworkServer -// for forward compatibility +// for forward compatibility. type NetworkServer interface { GetNetworkInfo(context.Context, *GetNetworkInfoRequest) (*GetNetworkInfoResponse, error) GetNodeInfo(context.Context, *GetNodeInfoRequest) (*GetNodeInfoResponse, error) @@ -116,7 +116,7 @@ func _Network_GetNodeInfo_Handler(srv interface{}, ctx context.Context, dec func // Network_ServiceDesc is the grpc.ServiceDesc for Network service. // It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) +// and not to be introspected or modified (even as a copy). var Network_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Network", HandlerType: (*NetworkServer)(nil), diff --git a/www/grpc/gen/go/transaction.pb.gw.go b/www/grpc/gen/go/transaction.pb.gw.go index b35fcdbf8..7a666231b 100644 --- a/www/grpc/gen/go/transaction.pb.gw.go +++ b/www/grpc/gen/go/transaction.pb.gw.go @@ -23,7 +23,7 @@ import ( "google.golang.org/protobuf/proto" ) -// Suppress "imported and not used" errors +// Suppress "imported and not used" errors. var _ codes.Code var _ io.Reader var _ status.Status diff --git a/www/grpc/gen/go/transaction_grpc.pb.go b/www/grpc/gen/go/transaction_grpc.pb.go index 76efcef30..ff1725bfb 100644 --- a/www/grpc/gen/go/transaction_grpc.pb.go +++ b/www/grpc/gen/go/transaction_grpc.pb.go @@ -60,7 +60,7 @@ func (c *transactionClient) SendRawTransaction(ctx context.Context, in *SendRawT // TransactionServer is the server API for Transaction service. // All implementations should embed UnimplementedTransactionServer -// for forward compatibility +// for forward compatibility. type TransactionServer interface { GetTransaction(context.Context, *GetTransactionRequest) (*GetTransactionResponse, error) CalculateFee(context.Context, *CalculateFeeRequest) (*CalculateFeeResponse, error) @@ -148,7 +148,7 @@ func _Transaction_SendRawTransaction_Handler(srv interface{}, ctx context.Contex // Transaction_ServiceDesc is the grpc.ServiceDesc for Transaction service. // It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) +// and not to be introspected or modified (even as a copy). var Transaction_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Transaction", HandlerType: (*TransactionServer)(nil), diff --git a/www/grpc/gen/go/wallet.pb.gw.go b/www/grpc/gen/go/wallet.pb.gw.go index 214876303..4c1429245 100644 --- a/www/grpc/gen/go/wallet.pb.gw.go +++ b/www/grpc/gen/go/wallet.pb.gw.go @@ -23,7 +23,7 @@ import ( "google.golang.org/protobuf/proto" ) -// Suppress "imported and not used" errors +// Suppress "imported and not used" errors. var _ codes.Code var _ io.Reader var _ status.Status diff --git a/www/grpc/gen/go/wallet_grpc.pb.go b/www/grpc/gen/go/wallet_grpc.pb.go index 2607cf981..123b0febc 100644 --- a/www/grpc/gen/go/wallet_grpc.pb.go +++ b/www/grpc/gen/go/wallet_grpc.pb.go @@ -80,7 +80,7 @@ func (c *walletClient) UnlockWallet(ctx context.Context, in *UnlockWalletRequest // WalletServer is the server API for Wallet service. // All implementations should embed UnimplementedWalletServer -// for forward compatibility +// for forward compatibility. type WalletServer interface { CreateWallet(context.Context, *CreateWalletRequest) (*CreateWalletResponse, error) LoadWallet(context.Context, *LoadWalletRequest) (*LoadWalletResponse, error) @@ -212,7 +212,7 @@ func _Wallet_UnlockWallet_Handler(srv interface{}, ctx context.Context, dec func // Wallet_ServiceDesc is the grpc.ServiceDesc for Wallet service. // It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) +// and not to be introspected or modified (even as a copy). var Wallet_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Wallet", HandlerType: (*WalletServer)(nil), diff --git a/www/grpc/network.go b/www/grpc/network.go index 0c157cff4..de286abb1 100644 --- a/www/grpc/network.go +++ b/www/grpc/network.go @@ -17,7 +17,8 @@ type networkServer struct { } func (s *networkServer) GetNetworkInfo(_ context.Context, - _ *pactus.GetNetworkInfoRequest) (*pactus.GetNetworkInfoResponse, error) { + _ *pactus.GetNetworkInfoRequest, +) (*pactus.GetNetworkInfoResponse, error) { peerset := s.sync.PeerSet() peers := make([]*pactus.PeerInfo, peerset.Len()) @@ -66,7 +67,8 @@ func (s *networkServer) GetNetworkInfo(_ context.Context, } func (s *networkServer) GetNodeInfo(_ context.Context, - _ *pactus.GetNodeInfoRequest) (*pactus.GetNodeInfoResponse, error) { + _ *pactus.GetNodeInfoRequest, +) (*pactus.GetNodeInfoResponse, error) { return &pactus.GetNodeInfoResponse{ Moniker: s.sync.Moniker(), Agent: version.Agent(), diff --git a/www/grpc/server.go b/www/grpc/server.go index 93f005b01..80458e4b4 100644 --- a/www/grpc/server.go +++ b/www/grpc/server.go @@ -25,7 +25,8 @@ type Server struct { } func NewServer(conf *Config, state state.Facade, sync sync.Synchronizer, - consMgr consensus.ManagerReader) *Server { + consMgr consensus.ManagerReader, +) *Server { return &Server{ ctx: context.Background(), config: conf, diff --git a/www/grpc/server_test.go b/www/grpc/server_test.go index 2e880a38b..1484c1fe2 100644 --- a/www/grpc/server_test.go +++ b/www/grpc/server_test.go @@ -20,11 +20,13 @@ import ( "google.golang.org/grpc/test/bufconn" ) -var tMockState *state.MockState -var tConsMocks []*consensus.MockConsensus -var tMockSync *sync.MockSync -var tListener *bufconn.Listener -var tCtx context.Context +var ( + tMockState *state.MockState + tConsMocks []*consensus.MockConsensus + tMockSync *sync.MockSync + tListener *bufconn.Listener + tCtx context.Context +) func init() { ts := testsuite.NewTestSuiteForSeed(0x1234) diff --git a/www/grpc/transaction.go b/www/grpc/transaction.go index 700d00c58..19a42e28e 100644 --- a/www/grpc/transaction.go +++ b/www/grpc/transaction.go @@ -19,7 +19,8 @@ type transactionServer struct { } func (s *transactionServer) GetTransaction(_ context.Context, - req *pactus.GetTransactionRequest) (*pactus.GetTransactionResponse, error) { + req *pactus.GetTransactionRequest, +) (*pactus.GetTransactionResponse, error) { id, err := hash.FromBytes(req.Id) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid transaction ID: %v", err.Error()) @@ -43,7 +44,8 @@ func (s *transactionServer) GetTransaction(_ context.Context, } func (s *transactionServer) SendRawTransaction(_ context.Context, - req *pactus.SendRawTransactionRequest) (*pactus.SendRawTransactionResponse, error) { + req *pactus.SendRawTransactionRequest, +) (*pactus.SendRawTransactionResponse, error) { trx, err := tx.FromBytes(req.Data) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "couldn't decode transaction: %v", err.Error()) @@ -63,7 +65,8 @@ func (s *transactionServer) SendRawTransaction(_ context.Context, } func (s *transactionServer) CalculateFee(_ context.Context, - req *pactus.CalculateFeeRequest) (*pactus.CalculateFeeResponse, error) { + req *pactus.CalculateFeeRequest, +) (*pactus.CalculateFeeResponse, error) { fee, err := s.state.CalculateFee(req.Amount, payload.Type(req.PayloadType)) if err != nil { return nil, err diff --git a/www/grpc/transaction_test.go b/www/grpc/transaction_test.go index d095a5733..c31c72053 100644 --- a/www/grpc/transaction_test.go +++ b/www/grpc/transaction_test.go @@ -18,8 +18,10 @@ func TestGetTransaction(t *testing.T) { trx1 := testBlock.Transactions()[0] t.Run("Should return transaction", func(t *testing.T) { - res, err := client.GetTransaction(tCtx, &pactus.GetTransactionRequest{Id: trx1.ID().Bytes(), - Verbosity: pactus.TransactionVerbosity_TRANSACTION_INFO}) + res, err := client.GetTransaction(tCtx, &pactus.GetTransactionRequest{ + Id: trx1.ID().Bytes(), + Verbosity: pactus.TransactionVerbosity_TRANSACTION_INFO, + }) pld := res.Transaction.Payload.(*pactus.TransactionInfo_Transfer) assert.NoError(t, err) diff --git a/www/grpc/wallet.go b/www/grpc/wallet.go index c7aae33b2..14eabd375 100644 --- a/www/grpc/wallet.go +++ b/www/grpc/wallet.go @@ -29,7 +29,8 @@ func walletPath(name string) string { } func (s *walletServer) CreateWallet(_ context.Context, - req *pactus.CreateWalletRequest) (*pactus.CreateWalletResponse, error) { + req *pactus.CreateWalletRequest, +) (*pactus.CreateWalletResponse, error) { if req.Name == "" { return nil, fmt.Errorf("wallet name is required") } @@ -51,7 +52,8 @@ func (s *walletServer) CreateWallet(_ context.Context, } func (s *walletServer) LoadWallet(_ context.Context, - req *pactus.LoadWalletRequest) (*pactus.LoadWalletResponse, error) { + req *pactus.LoadWalletRequest, +) (*pactus.LoadWalletResponse, error) { _, ok := s.wallets[req.Name] if !ok { return nil, status.Errorf(codes.AlreadyExists, "wallet already loaded") @@ -71,7 +73,8 @@ func (s *walletServer) LoadWallet(_ context.Context, } func (s *walletServer) UnloadWallet(_ context.Context, - req *pactus.UnloadWalletRequest) (*pactus.UnloadWalletResponse, error) { + req *pactus.UnloadWalletRequest, +) (*pactus.UnloadWalletResponse, error) { _, ok := s.wallets[req.Name] if !ok { return nil, status.Errorf(codes.NotFound, "wallet is not loaded") @@ -85,11 +88,13 @@ func (s *walletServer) UnloadWallet(_ context.Context, } func (s *walletServer) LockWallet(_ context.Context, - _ *pactus.LockWalletRequest) (*pactus.LockWalletResponse, error) { + _ *pactus.LockWalletRequest, +) (*pactus.LockWalletResponse, error) { return &pactus.LockWalletResponse{}, nil } func (s *walletServer) UnlockWallet(_ context.Context, - _ *pactus.UnlockWalletRequest) (*pactus.UnlockWalletResponse, error) { + _ *pactus.UnlockWalletRequest, +) (*pactus.UnlockWalletResponse, error) { return &pactus.UnlockWalletResponse{}, nil } diff --git a/www/http/block_test.go b/www/http/block_test.go index 7542fce64..e90062036 100644 --- a/www/http/block_test.go +++ b/www/http/block_test.go @@ -32,7 +32,7 @@ func TestBlock(t *testing.T) { td.httpServer.GetBlockByHeightHandler(w, r) assert.Equal(t, w.Code, 200) - //fmt.Println(w.Body) + // fmt.Println(w.Body) }) t.Run("Shall return an error, invalid height", func(t *testing.T) { @@ -42,7 +42,7 @@ func TestBlock(t *testing.T) { td.httpServer.GetBlockByHeightHandler(w, r) assert.Equal(t, w.Code, 400) - //fmt.Println(w.Body) + // fmt.Println(w.Body) }) t.Run("Shall return an error, non exists", func(t *testing.T) { diff --git a/www/http/server.go b/www/http/server.go index 561f444f8..00c0e8779 100644 --- a/www/http/server.go +++ b/www/http/server.go @@ -127,7 +127,6 @@ func (s *Server) RootHandler(w http.ResponseWriter, _ *http.Request) { return nil }) - if err != nil { s.logger.Error("unable to walk through methods", "err", err) return @@ -168,31 +167,40 @@ func newTableMaker() *tableMaker { func (t *tableMaker) addRowBlockHash(key string, val []byte) { t.w.WriteString(fmt.Sprintf("%s%x", key, val, val)) } + func (t *tableMaker) addRowAccAddress(key, val string) { t.w.WriteString(fmt.Sprintf("%s%s", key, val, val)) } + func (t *tableMaker) addRowValAddress(key, val string) { t.w.WriteString(fmt.Sprintf("%s%s", key, val, val)) } + func (t *tableMaker) addRowTxID(key string, val []byte) { t.w.WriteString(fmt.Sprintf("%s%x", key, val, val)) } + func (t *tableMaker) addRowString(key, val string) { t.w.WriteString(fmt.Sprintf("%s%s", key, val)) } + func (t *tableMaker) addRowTime(key string, sec int64) { t.w.WriteString(fmt.Sprintf("%s%s", key, time.Unix(sec, 0).String())) } + func (t *tableMaker) addRowAmount(key string, change int64) { t.w.WriteString(fmt.Sprintf("%s%s", key, util.ChangeToString(change))) } + func (t *tableMaker) addRowInt(key string, val int) { t.w.WriteString(fmt.Sprintf("%s%d", key, val)) } + func (t *tableMaker) addRowBool(key string, val bool) { t.w.WriteString(fmt.Sprintf("%s%v", key, val)) } + func (t *tableMaker) addRowInts(key string, vals []int32) { t.w.WriteString(fmt.Sprintf("%s", key)) for _, n := range vals { @@ -200,9 +208,11 @@ func (t *tableMaker) addRowInts(key string, vals []int32) { } t.w.WriteString("") } + func (t *tableMaker) addRowBytes(key string, val []byte) { t.w.WriteString(fmt.Sprintf("%s%x", key, val)) } + func (t *tableMaker) html() string { t.w.WriteString("") return t.w.String() diff --git a/www/nanomsg/event/event.go b/www/nanomsg/event/event.go index 051eee01a..356015551 100644 --- a/www/nanomsg/event/event.go +++ b/www/nanomsg/event/event.go @@ -9,14 +9,16 @@ import ( "github.com/pactus-project/pactus/util/logger" ) -const TopicNewBlock = uint16(0x0101) -const TopicNewTransaction = uint16(0x0201) +const ( + TopicNewBlock = uint16(0x0101) + TopicNewTransaction = uint16(0x0201) +) type Event []byte // CreateBlockEvent creates an event when the new block is committed. // The block event structure is like : -// +// . func CreateBlockEvent(blockHash hash.Hash, height uint32) Event { buf := make([]byte, 0, 42) w := bytes.NewBuffer(buf) @@ -29,7 +31,7 @@ func CreateBlockEvent(blockHash hash.Hash, height uint32) Event { // CreateBlockEvent creates an event when the new block is committed. // The block event structure is like : -// +// . func CreateNewTransactionEvent(txHash tx.ID, height uint32) Event { buf := make([]byte, 0, 42) w := bytes.NewBuffer(buf) diff --git a/www/nanomsg/event/event_test.go b/www/nanomsg/event/event_test.go index 5a6342ff8..a1f234068 100644 --- a/www/nanomsg/event/event_test.go +++ b/www/nanomsg/event/event_test.go @@ -11,15 +11,20 @@ func TestCreateBlockEvent(t *testing.T) { hash, _ := hash.FromString("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") height := uint32(0x2134) e := CreateBlockEvent(hash, height) - assert.Equal(t, e, Event{0x1, 0x1, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, + assert.Equal(t, e, Event{ + 0x1, 0x1, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, - 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x34, 0x21, 0x0, 0x0}) + 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x34, 0x21, 0x0, 0x0, + }) } + func TestCreateNewTransactionEvent(t *testing.T) { hash, _ := hash.FromString("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") height := uint32(0x2134) e := CreateNewTransactionEvent(hash, height) - assert.Equal(t, e, Event{0x1, 0x2, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, + assert.Equal(t, e, Event{ + 0x1, 0x2, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, - 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x34, 0x21, 0x0, 0x0}) + 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x34, 0x21, 0x0, 0x0, + }) } diff --git a/www/nanomsg/server.go b/www/nanomsg/server.go index 0c5fddaee..97a7ae0ad 100644 --- a/www/nanomsg/server.go +++ b/www/nanomsg/server.go @@ -11,7 +11,7 @@ import ( mangos "go.nanomsg.org/mangos/v3" "go.nanomsg.org/mangos/v3/protocol/pub" - // register nano ports transports + // register nano ports transports. _ "go.nanomsg.org/mangos/v3/transport/all" )