Skip to content

Commit

Permalink
all: minor type tweaks
Browse files Browse the repository at this point in the history
fmt alreacy calls String methods with the %s verb,
so we don't need to call them directly.

It's easier for a func to take a duration parameter
rather than a seconds integer which then needs to be converted.

Use path.Join and net/url rather than fmt.Sprintf to join with slashes.
  • Loading branch information
mvdan authored and p4u committed Oct 17, 2023
1 parent c75912c commit c04218e
Show file tree
Hide file tree
Showing 19 changed files with 41 additions and 40 deletions.
5 changes: 3 additions & 2 deletions api/faucet/faucet.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package faucet
import (
"encoding/json"
"fmt"
"path"

"github.com/ethereum/go-ethereum/common"
"go.vocdoni.io/dvote/api"
Expand Down Expand Up @@ -36,7 +37,7 @@ func AttachFaucetAPI(signingKey *ethereum.SignKeys, networks map[string]uint64,
networks: networks,
}
return api.RegisterMethod(
fmt.Sprintf("%s/{network}/{to}", pathPrefix),
path.Join(pathPrefix, "{network}/{to}"),
"GET",
apirest.MethodAccessTypePublic,
f.faucetHandler,
Expand All @@ -58,7 +59,7 @@ func (f *FaucetAPI) faucetHandler(_ *apirest.APIdata, ctx *httprouter.HTTPContex
to := common.HexToAddress(toStr)

// generate faucet package
log.Debugf("faucet request from %s for network %s", to.String(), network)
log.Debugf("faucet request from %s for network %s", to, network)
fpackage, err := vochain.GenerateFaucetPackage(f.signingKey, to, amount)
if err != nil {
return api.ErrCantGenerateFaucetPkg.WithErr(err)
Expand Down
2 changes: 1 addition & 1 deletion apiclient/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ func (c *HTTPclient) TransactionSetCensus(electionID types.HexBytes, census api.
// get the own account details
acc, err := c.Account("")
if err != nil {
return nil, fmt.Errorf("could not fetch account info: %s", acc.Address.String())
return nil, fmt.Errorf("could not fetch account info: %s", acc.Address)
}

tx := &models.SetProcessTx{
Expand Down
2 changes: 1 addition & 1 deletion apiclient/election.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ func (c *HTTPclient) SetElectionStatus(electionID types.HexBytes, status string)
// get the own account details
acc, err := c.Account("")
if err != nil {
return nil, fmt.Errorf("could not fetch account info: %s", acc.Address.String())
return nil, fmt.Errorf("could not fetch account info: %s", acc.Address)
}

// build the set process transaction
Expand Down
2 changes: 1 addition & 1 deletion apiclient/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func (c *HTTPclient) WaitUntilElectionStatus(ctx context.Context,
// WaitUntilElectionResults waits until the given election has published final results.
func (c *HTTPclient) WaitUntilElectionResults(ctx context.Context,
electionID types.HexBytes) (*api.ElectionResults, error) {
log.Infof("waiting for election %s to publish final results", electionID.String())
log.Infof("waiting for election %s to publish final results", electionID)
startTime := time.Now()
for {
election, err := c.ElectionResults(electionID)
Expand Down
2 changes: 1 addition & 1 deletion cmd/vochaininspector/inspector.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func main() {
vnode := newVochain(chain, dataDir)
vi := vochaininfo.NewVochainInfo(vnode)
go vi.Start(10)
go service.VochainPrintInfo(20, vi)
go service.VochainPrintInfo(20*time.Second, vi)

defer func() {
vnode.NodeClient.Stop()
Expand Down
4 changes: 2 additions & 2 deletions crypto/zk/circuit/circuit.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func (circuit *ZkCircuit) LoadRemote(ctx context.Context) error {
if err != nil {
return err
}
remotePath := fmt.Sprintf("%s/%s", baseUri.String(), circuit.Config.CircuitPath)
remoteUri := baseUri.JoinPath(circuit.Config.CircuitPath)
localPath := filepath.Join(BaseDir, circuit.Config.CircuitPath)
if err := os.MkdirAll(localPath, os.ModePerm); err != nil {
return err
Expand All @@ -129,7 +129,7 @@ func (circuit *ZkCircuit) LoadRemote(ctx context.Context) error {
}
for filename := range files {
// Compose the artifact uri and download it
file, err := downloadFile(ctx, fmt.Sprintf("%s/%s", remotePath, filename))
file, err := downloadFile(ctx, remoteUri.JoinPath(filename).String())
if err != nil {
return fmt.Errorf("error downloading '%s' artifact: %w", filename, err)
}
Expand Down
2 changes: 1 addition & 1 deletion data/ipfs/ipfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ func (i *Handler) Unpin(ctx context.Context, path string) error {
if err := cpath.IsValid(); err != nil {
return fmt.Errorf("invalid path %s: %w", path, err)
}
log.Debugf("removing pin %s", cpath.String())
log.Debugf("removing pin %s", cpath)
return i.CoreAPI.Pin().Rm(ctx, cpath, options.Pin.RmRecursive(true))
}

Expand Down
6 changes: 3 additions & 3 deletions service/vochain.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func (vs *VocdoniService) Start() error {
}
log.Infow("vochain fastsync completed", "height", vs.Stats.Height(), "time", time.Since(timeSyncCounter))
}
go VochainPrintInfo(20, vs.Stats)
go VochainPrintInfo(20*time.Second, vs.Stats)

if vs.Config.LogLevel == "debug" {
go vochainPrintPeers(20*time.Second, vs.Stats)
Expand All @@ -170,7 +170,7 @@ func (vs *VocdoniService) Start() error {
}

// VochainPrintInfo initializes the Vochain statistics recollection.
func VochainPrintInfo(sleepSecs int64, vi *vochaininfo.VochainInfo) {
func VochainPrintInfo(interval time.Duration, vi *vochaininfo.VochainInfo) {
var a *[5]int32
var h int64
var p, v uint64
Expand Down Expand Up @@ -210,7 +210,7 @@ func VochainPrintInfo(sleepSecs int64, vi *vochaininfo.VochainInfo) {
"blockTime": b.String(),
})

time.Sleep(time.Duration(sleepSecs) * time.Second)
time.Sleep(interval)
}
}

Expand Down
2 changes: 1 addition & 1 deletion test/testcommon/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (d *APIserver) Start(t testing.TB, apis ...string) {
addr, err := url.Parse("http://" + router.Address().String() + "/")
qt.Assert(t, err, qt.IsNil)
d.ListenAddr = addr
t.Logf("address: %s", addr.String())
t.Logf("address: %s", addr)
api, err := api.NewAPI(&router, "/", t.TempDir(), db.TypePebble)
qt.Assert(t, err, qt.IsNil)

Expand Down
2 changes: 1 addition & 1 deletion vochain/cometbft.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func (app *BaseApplication) InitChain(_ context.Context,
crypto256k1.KeyType,
))
}
myValidator, err := app.State.Validator(ethcommon.Address(app.NodeAddress), false)
myValidator, err := app.State.Validator(app.NodeAddress, false)
if err != nil {
return nil, fmt.Errorf("cannot get node validator: %w", err)
}
Expand Down
14 changes: 7 additions & 7 deletions vochain/state/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (a *Account) IsDelegate(addr common.Address) bool {
// AddDelegate adds an address to the list of delegates for an account
func (a *Account) AddDelegate(addr common.Address) error {
if a.IsDelegate(addr) {
return fmt.Errorf("address %s is already a delegate", addr.String())
return fmt.Errorf("address %s is already a delegate", addr)
}
a.DelegateAddrs = append(a.DelegateAddrs, addr.Bytes())
return nil
Expand All @@ -74,7 +74,7 @@ func (a *Account) AddDelegate(addr common.Address) error {
func (a *Account) DelDelegate(addr common.Address) error {
for i, d := range a.DelegateAddrs {
if !a.IsDelegate(addr) {
return fmt.Errorf("address %s is not a delegate", addr.String())
return fmt.Errorf("address %s is not a delegate", addr)
}
if bytes.Equal(addr.Bytes(), d) {
a.DelegateAddrs[i] = a.DelegateAddrs[len(a.DelegateAddrs)-1]
Expand Down Expand Up @@ -152,7 +152,7 @@ func (v *State) SetAccountInfoURI(accountAddress common.Address, infoURI string)
return fmt.Errorf("invalid infoURI")
}
acc.InfoURI = infoURI
log.Debugf("setting account %s infoURI %s", accountAddress.String(), infoURI)
log.Debugf("setting account %s infoURI %s", accountAddress, infoURI)
return v.SetAccount(accountAddress, acc)
}

Expand All @@ -170,7 +170,7 @@ func (v *State) IncrementAccountProcessIndex(accountAddress common.Address) erro
acc.ProcessIndex = 0
}
acc.ProcessIndex++
log.Debugf("setting account %s process index to %d", accountAddress.String(), acc.ProcessIndex)
log.Debugf("setting account %s process index to %d", accountAddress, acc.ProcessIndex)
return v.SetAccount(accountAddress, acc)
}

Expand Down Expand Up @@ -255,7 +255,7 @@ func (v *State) BurnTxCostIncrementNonce(accountAddress common.Address, txType m
if err := acc.Transfer(burnAcc, cost); err != nil {
return fmt.Errorf("burnTxCostIncrementNonce: %w", err)
}
log.Debugf("burning fee for tx %s with cost %d from account %s", txType.String(), cost, accountAddress.String())
log.Debugf("burning fee for tx %s with cost %d from account %s", txType, cost, accountAddress)
if err := v.SetAccount(BurnAddress, burnAcc); err != nil {
return fmt.Errorf("burnTxCostIncrementNonce: %w", err)
}
Expand Down Expand Up @@ -286,15 +286,15 @@ func (v *State) SetAccountDelegate(accountAddr common.Address,
}
switch txType {
case models.TxType_ADD_DELEGATE_FOR_ACCOUNT:
log.Debugf("adding delegates %+v for account %s", delegateAddrs, accountAddr.String())
log.Debugf("adding delegates %+v for account %s", delegateAddrs, accountAddr)
for _, delegate := range delegateAddrs {
if err := acc.AddDelegate(common.BytesToAddress(delegate)); err != nil {
return fmt.Errorf("cannot add delegate, AddDelegate: %w", err)
}
}
return v.SetAccount(accountAddr, acc)
case models.TxType_DEL_DELEGATE_FOR_ACCOUNT:
log.Debugf("deleting delegates %+v for account %s", delegateAddrs, accountAddr.String())
log.Debugf("deleting delegates %+v for account %s", delegateAddrs, accountAddr)
for _, delegate := range delegateAddrs {
if err := acc.DelDelegate(common.BytesToAddress(delegate)); err != nil {
return fmt.Errorf("cannot delete delegate, DelDelegate: %w", err)
Expand Down
6 changes: 3 additions & 3 deletions vochain/state/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ func (v *State) SetTxBaseCost(txType models.TxType, cost uint64) error {
}
v.tx.Lock()
defer v.tx.Unlock()
log.Debugf("setting tx cost %d for tx %s", cost, txType.String())
log.Debugf("setting tx cost %d for tx %s", cost, txType)
costBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(costBytes, cost)
return v.tx.DeepSet([]byte(key), costBytes, StateTreeCfg(TreeExtra))
Expand Down Expand Up @@ -286,7 +286,7 @@ func (v *State) MintBalance(tx *vochaintx.TokenTransfer) error {
"to", fmt.Sprintf("%x", tx.ToAddress),
"amount", fmt.Sprintf("%d", tx.Amount),
)
log.Debugf("minting %d tokens to account %s", tx.Amount, tx.ToAddress.String())
log.Debugf("minting %d tokens to account %s", tx.Amount, tx.ToAddress)
if err := v.SetAccount(tx.ToAddress, acc); err != nil {
return err
}
Expand Down Expand Up @@ -316,7 +316,7 @@ func (v *State) InitChainMintBalance(to common.Address, amount uint64) error {
return ErrBalanceOverflow
}
acc.Balance += amount
log.Debugf("minting %d tokens to account %s", amount, to.String())
log.Debugf("minting %d tokens to account %s", amount, to)
return v.SetAccount(to, acc)
}

Expand Down
10 changes: 5 additions & 5 deletions vochain/state/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ func (v *State) SetProcessStatus(pid []byte, newstatus models.ProcessStatus, com
switch newstatus {
case models.ProcessStatus_READY:
if currentStatus != models.ProcessStatus_PAUSED {
return fmt.Errorf("cannot set process status from %s to ready", currentStatus.String())
return fmt.Errorf("cannot set process status from %s to ready", currentStatus)
}
if currentStatus == models.ProcessStatus_READY {
return fmt.Errorf("process %x already in ready state", pid)
Expand Down Expand Up @@ -234,7 +234,7 @@ func (v *State) SetProcessStatus(pid []byte, newstatus models.ProcessStatus, com
}
case models.ProcessStatus_PAUSED:
if currentStatus != models.ProcessStatus_READY {
return fmt.Errorf("cannot set process status from %s to paused", currentStatus.String())
return fmt.Errorf("cannot set process status from %s to paused", currentStatus)
}
if currentStatus == models.ProcessStatus_PAUSED {
return fmt.Errorf("process %x already in paused state", pid)
Expand All @@ -247,15 +247,15 @@ func (v *State) SetProcessStatus(pid []byte, newstatus models.ProcessStatus, com
return fmt.Errorf("process %x already in results state", pid)
}
if currentStatus != models.ProcessStatus_ENDED && currentStatus != models.ProcessStatus_READY {
return fmt.Errorf("cannot set state to results from %s", currentStatus.String())
return fmt.Errorf("cannot set state to results from %s", currentStatus)
}
if currentStatus == models.ProcessStatus_READY &&
process.StartBlock+process.BlockCount < v.CurrentHeight() {
return fmt.Errorf("cannot set state to results from %s, process is still alive",
currentStatus.String())
}
default:
return fmt.Errorf("process status %s unknown", newstatus.String())
return fmt.Errorf("process status %s unknown", newstatus)
}

if commit {
Expand Down Expand Up @@ -327,7 +327,7 @@ func (v *State) SetProcessCensus(pid, censusRoot []byte, censusURI string, commi
// census origin
if !CensusOrigins[process.CensusOrigin].AllowCensusUpdate {
return fmt.Errorf(
"cannot update census, invalid census origin: %s", process.CensusOrigin.String())
"cannot update census, invalid census origin: %s", process.CensusOrigin)
}
// status
if !(process.Status == models.ProcessStatus_READY) &&
Expand Down
6 changes: 3 additions & 3 deletions vochain/transaction/account_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func (t *TransactionHandler) CreateAccountTxCheck(vtx *vochaintx.Tx) error {
return fmt.Errorf("cannot get faucet issuer address account: %w", err)
}
if issuerAcc == nil {
return fmt.Errorf("the account signing the faucet payload does not exist (%s)", issuerAddress.String())
return fmt.Errorf("the account signing the faucet payload does not exist (%s)", issuerAddress)
}
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, faucetPayload.Identifier)
Expand Down Expand Up @@ -144,15 +144,15 @@ func (t *TransactionHandler) SetAccountDelegateTxCheck(vtx *vochaintx.Tx) error
for _, delegate := range tx.Delegates {
delegateAddress := common.BytesToAddress(delegate)
if txSenderAccount.IsDelegate(delegateAddress) {
return fmt.Errorf("delegate %s already exists", delegateAddress.String())
return fmt.Errorf("delegate %s already exists", delegateAddress)
}
}
return nil
case models.TxType_DEL_DELEGATE_FOR_ACCOUNT:
for _, delegate := range tx.Delegates {
delegateAddress := common.BytesToAddress(delegate)
if !txSenderAccount.IsDelegate(delegateAddress) {
return fmt.Errorf("delegate %s does not exist", delegateAddress.String())
return fmt.Errorf("delegate %s does not exist", delegateAddress)
}
}
return nil
Expand Down
2 changes: 1 addition & 1 deletion vochain/transaction/admin_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (t *TransactionHandler) AdminTxCheck(vtx *vochaintx.Tx) (ethereum.Address,
// endblock is always greater than start block so that case is also included here
if height > process.StartBlock {
return ethereum.Address{}, fmt.Errorf(
"cannot add keys to a process that has started or finished (%s)", process.Status.String())
"cannot add keys to a process that has started or finished (%s)", process.Status)
}
// process is not canceled
if process.Status == models.ProcessStatus_CANCELED ||
Expand Down
2 changes: 1 addition & 1 deletion vochain/transaction/election_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func (t *TransactionHandler) SetProcessTxCheck(vtx *vochaintx.Tx) (ethereum.Addr
// get tx cost
cost, err := t.state.TxBaseCost(tx.Txtype, false)
if err != nil {
return ethereum.Address{}, fmt.Errorf("cannot get %s transaction cost: %w", tx.Txtype.String(), err)
return ethereum.Address{}, fmt.Errorf("cannot get %s transaction cost: %w", tx.Txtype, err)
}
addr, acc, err := t.state.AccountFromSignature(vtx.SignedBody, vtx.Signature)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion vochain/transaction/proof.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ func VerifyProofOffChainCSP(_ *models.Process, proof *models.Proof,
processID, rootPub.Bytes(), cspbundleDec.ProcessId, cspbundleDec.Address, signature.Bytes())
}
default:
return false, nil, fmt.Errorf("CSP proof %s type not supported", p.Type.String())
return false, nil, fmt.Errorf("CSP proof %s type not supported", p.Type)
}
return true, bigOne, nil
}
Expand Down
4 changes: 2 additions & 2 deletions vochain/transaction/tokens_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func (t *TransactionHandler) SetTransactionCostsTxCheck(vtx *vochaintx.Tx) (uint
}
// check vtx.Signature recovered address
if common.BytesToAddress(treasurer.Address) != sigAddress {
return 0, fmt.Errorf("address recovered not treasurer: expected %s got %s", common.BytesToAddress(treasurer.Address), sigAddress.String())
return 0, fmt.Errorf("address recovered not treasurer: expected %s got %s", common.BytesToAddress(treasurer.Address), sigAddress)
}
return tx.Value, nil
}
Expand Down Expand Up @@ -197,7 +197,7 @@ func (t *TransactionHandler) CollectFaucetTxCheck(vtx *vochaintx.Tx) error {
}
txSenderAccount, err := t.state.GetAccount(txSenderAddress, false)
if err != nil {
return fmt.Errorf("cannot check if account %s exists: %w", txSenderAddress.String(), err)
return fmt.Errorf("cannot check if account %s exists: %w", txSenderAddress, err)
}
if txSenderAccount == nil {
return vstate.ErrAccountNotExist
Expand Down
6 changes: 3 additions & 3 deletions vocone/vocone.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ func (vc *Vocone) EnableAPI(host string, port int, URLpath string) (*api.API, er
// Start starts the Vocone node. This function is blocking.
func (vc *Vocone) Start() {
vc.lastBlockTime = time.Now()
go vochainPrintInfo(10, vc.Stats)
go vochainPrintInfo(10*time.Second, vc.Stats)
if vc.App.Height() == 0 {
log.Infof("initializing new blockchain")
genesisAppData, err := json.Marshal(&genesis.AppState{
Expand Down Expand Up @@ -471,7 +471,7 @@ func (vc *Vocone) getTxWithHash(height uint32, txIndex int32) (*models.SignedTx,
}

// VochainPrintInfo initializes the Vochain statistics recollection
func vochainPrintInfo(sleepSecs int64, vi *vochaininfo.VochainInfo) {
func vochainPrintInfo(interval time.Duration, vi *vochaininfo.VochainInfo) {
var a *[5]int32
var h int64
var p, v uint64
Expand Down Expand Up @@ -508,7 +508,7 @@ func vochainPrintInfo(sleepSecs int64, vi *vochaininfo.VochainInfo) {
"voteCache": vc,
"blockTime": b.String(),
})
time.Sleep(time.Duration(sleepSecs) * time.Second)
time.Sleep(interval)
}
}

Expand Down

0 comments on commit c04218e

Please sign in to comment.