Skip to content

Commit

Permalink
all: make use of some Go 1.22 std APIs
Browse files Browse the repository at this point in the history
Sorting with the slices package and int-based compare funcs,
and making use of slices.Clone and cmp.Or to simplify code.
  • Loading branch information
mvdan committed Feb 22, 2024
1 parent 23129ba commit c9d1170
Show file tree
Hide file tree
Showing 8 changed files with 29 additions and 46 deletions.
9 changes: 2 additions & 7 deletions cmd/cli/editor.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"cmp"
"os"
"os/exec"
"strings"
Expand All @@ -16,13 +17,7 @@ type PreferredEditorResolver func() string
// GetPreferredEditorFromEnvironment returns the user's editor as defined by the `$EDITOR` environment variable, or
// the `DefaultEditor` if it is not set.
func GetPreferredEditorFromEnvironment() string {
editor := os.Getenv("EDITOR")

if editor == "" {
return DefaultEditor
}

return editor
return cmp.Or(os.Getenv("EDITOR"), DefaultEditor)
}

func resolveEditorArguments(executable, filename string) []string {
Expand Down
7 changes: 2 additions & 5 deletions db/metadb/metadb.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package metadb

import (
"cmp"
"fmt"
"os"
"testing"
Expand Down Expand Up @@ -39,11 +40,7 @@ func New(typ, dir string) (db.Database, error) {
}

func ForTest() (typ string) {
dbType := os.Getenv("DVOTE_DB_TYPE")
if dbType == "" {
dbType = "pebble" // default to Pebble, just like vocdoninode
}
return dbType
return cmp.Or(os.Getenv("DVOTE_DB_TYPE"), "pebble") // default to Pebble, just like vocdoninode
}

func NewTest(tb testing.TB) db.Database {
Expand Down
7 changes: 2 additions & 5 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package log

import (
"bytes"
"cmp"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -33,11 +34,7 @@ func init() {
// environment variable can be set globally even when running tests.
// Always initializing the logger is also useful to avoid panics when
// logging if the logger is nil.
level := "error"
if s := os.Getenv("LOG_LEVEL"); s != "" {
level = s
}
Init(level, "stderr", nil)
Init(cmp.Or(os.Getenv("LOG_LEVEL"), "error"), "stderr", nil)
}

// Logger provides access to the global logger (zerolog).
Expand Down
22 changes: 7 additions & 15 deletions vochain/cometbft.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package vochain

import (
"bytes"
"cmp"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sort"
"slices"
"time"

cometabcitypes "github.com/cometbft/cometbft/abci/types"
Expand Down Expand Up @@ -349,7 +350,7 @@ func (app *BaseApplication) PrepareProposal(ctx context.Context,

type txInfo struct {
Data []byte
Addr *ethcommon.Address
Addr ethcommon.Address
Nonce uint32
DecodedTx *vochaintx.Tx
}
Expand Down Expand Up @@ -382,20 +383,11 @@ func (app *BaseApplication) PrepareProposal(ctx context.Context,
}

// Sort the transactions based on the sender's address and nonce
sort.Slice(validTxInfos, func(i, j int) bool {
if validTxInfos[i].Addr == nil && validTxInfos[j].Addr != nil {
return true
slices.SortFunc(validTxInfos, func(a, b txInfo) int {
if c := a.Addr.Cmp(b.Addr); c != 0 {
return c
}
if validTxInfos[i].Addr != nil && validTxInfos[j].Addr == nil {
return false
}
if validTxInfos[i].Addr != nil && validTxInfos[j].Addr != nil {
if bytes.Equal(validTxInfos[i].Addr.Bytes(), validTxInfos[j].Addr.Bytes()) {
return validTxInfos[i].Nonce < validTxInfos[j].Nonce
}
return bytes.Compare(validTxInfos[i].Addr.Bytes(), validTxInfos[j].Addr.Bytes()) == -1
}
return false
return cmp.Compare(a.Nonce, b.Nonce)
})

// Check the validity of the transactions
Expand Down
4 changes: 2 additions & 2 deletions vochain/indexer/indexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"math/big"
"os"
"path/filepath"
"sort"
"slices"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -384,7 +384,7 @@ func (idx *Indexer) Commit(height uint32) error {

// Update existing processes
updateProcs := maps.Keys(idx.blockUpdateProcs)
sort.Strings(updateProcs)
slices.Sort(updateProcs)

queries := idx.blockTxQueries()
ctx := context.TODO()
Expand Down
3 changes: 2 additions & 1 deletion vochain/state/sik.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"math/big"
"slices"

"github.com/ethereum/go-ethereum/common"
"go.vocdoni.io/dvote/db"
Expand Down Expand Up @@ -139,7 +140,7 @@ func (v *State) InvalidateSIK(address common.Address) error {
func (v *State) ValidSIKRoots() [][]byte {
v.mtxValidSIKRoots.Lock()
defer v.mtxValidSIKRoots.Unlock()
return append([][]byte{}, v.validSIKRoots...)
return slices.Clone(v.validSIKRoots)
}

// FetchValidSIKRoots updates the list of current valid SIK roots in the current
Expand Down
9 changes: 5 additions & 4 deletions vochain/state/votes.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"math/big"
"slices"

"go.vocdoni.io/dvote/crypto/ethereum"
"go.vocdoni.io/dvote/db"
Expand Down Expand Up @@ -82,11 +83,11 @@ func (v *Vote) Hash() []byte {
// DeepCopy returns a deep copy of the Vote struct.
func (v *Vote) DeepCopy() *Vote {
voteCopy := &Vote{
ProcessID: append([]byte{}, v.ProcessID...),
Nullifier: append([]byte{}, v.Nullifier...),
ProcessID: slices.Clone(v.ProcessID),
Nullifier: slices.Clone(v.Nullifier),
Height: v.Height,
VotePackage: append([]byte{}, v.VotePackage...),
EncryptionKeyIndexes: append([]uint32{}, v.EncryptionKeyIndexes...),
VotePackage: slices.Clone(v.VotePackage),
EncryptionKeyIndexes: slices.Clone(v.EncryptionKeyIndexes),
Weight: new(big.Int).Set(v.Weight),
VoterID: v.VoterID,
Overwrites: v.Overwrites,
Expand Down
14 changes: 7 additions & 7 deletions vochain/transaction/nonce.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
// The function uses the signature of the transaction to derive the sender's public key and subsequently
// the Ethereum address. The nonce is extracted based on the specific payload type of the transaction.
// If the transaction does not contain signature or nonce, it returns the default values (nil and 0).
func (t *TransactionHandler) ExtractNonceAndSender(vtx *vochaintx.Tx) (*common.Address, uint32, error) {
func (t *TransactionHandler) ExtractNonceAndSender(vtx *vochaintx.Tx) (common.Address, uint32, error) {
var ptx interface {
GetNonce() uint32
}
Expand All @@ -29,7 +29,7 @@ func (t *TransactionHandler) ExtractNonceAndSender(vtx *vochaintx.Tx) (*common.A
case *models.Tx_SetAccount:
if payload.SetAccount.Txtype == models.TxType_CREATE_ACCOUNT {
// create account tx is a special case where the nonce is not relevant
return nil, 0, nil
return common.Address{}, 0, nil
}
ptx = payload.SetAccount
case *models.Tx_CollectFaucet:
Expand All @@ -38,25 +38,25 @@ func (t *TransactionHandler) ExtractNonceAndSender(vtx *vochaintx.Tx) (*common.A
*models.Tx_SetTransactionCosts, *models.Tx_DelSIK, *models.Tx_RegisterKey, *models.Tx_SetSIK,
*models.Tx_RegisterSIK:
// these tx does not have incremental nonce
return nil, 0, nil
return common.Address{}, 0, nil
default:
log.Errorf("unknown payload type on extract nonce: %T", payload)
}

if ptx == nil {
return nil, 0, fmt.Errorf("payload is nil")
return common.Address{}, 0, fmt.Errorf("payload is nil")
}

pubKey, err := ethereum.PubKeyFromSignature(vtx.SignedBody, vtx.Signature)
if err != nil {
return nil, 0, fmt.Errorf("cannot extract public key from vtx.Signature: %w", err)
return common.Address{}, 0, fmt.Errorf("cannot extract public key from vtx.Signature: %w", err)
}
addr, err := ethereum.AddrFromPublicKey(pubKey)
if err != nil {
return nil, 0, fmt.Errorf("cannot extract address from public key: %w", err)
return common.Address{}, 0, fmt.Errorf("cannot extract address from public key: %w", err)
}

return &addr, ptx.GetNonce(), nil
return addr, ptx.GetNonce(), nil
}

// checkAccountNonce checks if the nonce of the given transaction matches the nonce of the sender account.
Expand Down

0 comments on commit c9d1170

Please sign in to comment.