Skip to content

Commit

Permalink
refactoring and add linter config
Browse files Browse the repository at this point in the history
  • Loading branch information
semyon-dev committed Sep 11, 2024
1 parent 7c750b2 commit dad208e
Show file tree
Hide file tree
Showing 33 changed files with 285 additions and 260 deletions.
52 changes: 52 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# This file configures github.com/golangci/golangci-lint.

run:
concurrency: 4
timeout: 5m
tests: false
issues-exit-code: 3
modules-download-mode: readonly
allow-parallel-runners: true

linters:
disable-all: true
enable:
- gosimple
- govet
- ineffassign
- misspell
- unconvert
- typecheck
# - unused
- staticcheck
- bidichk
- durationcheck
- exportloopref
- whitespace
- revive # only certain checks enabled

linters-settings:
gofmt:
simplify: true
revive:
enable-all-rules: false
# here we enable specific useful rules
# see https://golangci-lint.run/usage/linters/#revive for supported rules
rules:
- name: receiver-naming
severity: warning
disabled: false
exclude: [ "" ]

issues:
exclude-dirs-use-default: true
exclude-dirs:
- bin
- build
- \.git
exclude-files:
- ".pb"
exclude-rules:
- linters:
- lll
source: "^//go:generate "
4 changes: 2 additions & 2 deletions authutils/auth_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package authutils
import (
"math/big"
"testing"
"time"

"github.com/singnet/snet-daemon/config"
"github.com/stretchr/testify/assert"
Expand All @@ -28,9 +29,8 @@ func TestCheckAllowedBlockDifferenceForToken(t *testing.T) {
currentBlockNum, _ := CurrentBlock()
err := CheckIfTokenHasExpired(currentBlockNum.Sub(currentBlockNum, big.NewInt(20000)))
assert.Equal(t, err.Error(), "authentication failed as the Free Call Token passed has expired")

time.Sleep(250 * time.Millisecond) // because of HTTP 429 Too Many Requests
currentBlockNum, _ = CurrentBlock()
err = CheckIfTokenHasExpired(currentBlockNum.Add(currentBlockNum, big.NewInt(20)))
assert.Equal(t, nil, err)

}
34 changes: 21 additions & 13 deletions blockchain/ethereum_test_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package blockchain
import (
"crypto/ecdsa"
"fmt"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient/simulated"
"math/big"

"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/crypto"
)

Expand All @@ -19,7 +19,7 @@ type SimulatedEthereumEnvironment struct {
ClientPrivateKey *ecdsa.PrivateKey
ServerWallet *bind.TransactOpts
ServerPrivateKey *ecdsa.PrivateKey
Backend *backends.SimulatedBackend
Backend *simulated.Backend
SingularityNetToken *SingularityNetToken
MultiPartyEscrowAddress common.Address
MultiPartyEscrow *MultiPartyEscrow
Expand Down Expand Up @@ -63,40 +63,48 @@ func (env *SimulatedEthereumEnvironment) Commit() *SimulatedEthereumEnvironment
}

func GetSimulatedEthereumEnvironment() (env SimulatedEthereumEnvironment) {
env.SingnetPrivateKey, env.SingnetWallet = getTestWallet()
env.ClientPrivateKey, env.ClientWallet = getTestWallet()
env.ServerPrivateKey, env.ServerWallet = getTestWallet()
var chainID = big.NewInt(11155111)
env.SingnetPrivateKey, env.SingnetWallet, _ = getTestWallet(chainID)
env.ClientPrivateKey, env.ClientWallet, _ = getTestWallet(chainID)
env.ServerPrivateKey, env.ServerWallet, _ = getTestWallet(chainID)

alloc := map[common.Address]core.GenesisAccount{
alloc := map[common.Address]types.Account{
env.SingnetWallet.From: {Balance: big.NewInt(1000000000000)},
env.ClientWallet.From: {Balance: big.NewInt(1000000000000)},
env.ServerWallet.From: {Balance: big.NewInt(10000000)},
}

env.Backend = backends.NewSimulatedBackend(alloc, 0)
b := simulated.NewBackend(alloc, simulated.WithBlockGasLimit(0))

env.Backend = b
deployContracts(&env)

return
}

func getTestWallet() (privateKey *ecdsa.PrivateKey, wallet *bind.TransactOpts) {
privateKey, err := crypto.GenerateKey()
func getTestWallet(chainID *big.Int) (privateKey *ecdsa.PrivateKey, wallet *bind.TransactOpts, err error) {
privateKey, err = crypto.GenerateKey()
if err != nil {
panic(fmt.Sprintf("Unable to generate private key, error: %v", err))
}

return privateKey, bind.NewKeyedTransactor(privateKey)
wallet, err = bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
return nil, nil, err
}

return privateKey, wallet, err
}

func deployContracts(env *SimulatedEthereumEnvironment) {
tokenAddress, _, token, err := DeploySingularityNetToken(EstimateGas(env.SingnetWallet), env.Backend, "SingularityNet Token", "AGI")
tokenAddress, _, token, err := DeploySingularityNetToken(EstimateGas(env.SingnetWallet), env.Backend.Client(), "SingularityNet Token", "AGI")
if err != nil {
panic(fmt.Sprintf("Unable to deploy SingularityNetToken contract, error: %v", err))
}
env.Backend.Commit()
env.SingularityNetToken = token

mpeAddress, _, mpe, err := DeployMultiPartyEscrow(EstimateGas(env.SingnetWallet), env.Backend, tokenAddress)
mpeAddress, _, mpe, err := DeployMultiPartyEscrow(EstimateGas(env.SingnetWallet), env.Backend.Client(), tokenAddress)
if err != nil {
panic(fmt.Sprintf("Unable to deploy MultiPartyEscrow contract, error: %v", err))
}
Expand Down
5 changes: 2 additions & 3 deletions blockchain/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,12 @@ func HexToBytes(str string) []byte {

// HexToAddress converts hex string to Ethreum address.
func HexToAddress(str string) common.Address {
return common.Address(common.BytesToAddress(HexToBytes(str)))
return common.BytesToAddress(HexToBytes(str))
}

func StringToBytes32(str string) [32]byte {

var byte32 [32]byte
copy(byte32[:], []byte(str))
copy(byte32[:], str)
return byte32
}

Expand Down
4 changes: 1 addition & 3 deletions config/blockchain_network_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ func GetRegistryAddress() string {

// Read the Registry address from JSON file passed
func setRegistryAddress() (err error) {

//if address is already set in the config file and has been initialized , then skip the setting process
//if the address is already set in the config file and has been initialized, then skip the setting process
if len(networkSelected.RegistryAddressKey) > 0 {
return
}
Expand Down Expand Up @@ -125,7 +124,6 @@ func ReadFromFile(filename string) ([]byte, error) {
}
}
return file, nil

}

// Read from the blockchain network config json
Expand Down
4 changes: 2 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,11 +406,11 @@ func ValidateEmail(email string) bool {
}

func ValidateEndpoints(daemonEndpoint string, passthroughEndpoint string) error {

passthroughURL, err := url.Parse(passthroughEndpoint)
if err != nil || passthroughURL.Host == "" {
return errors.New("passthrough_endpoint is the endpoint of your AI service in the daemon config and needs to be a valid url.")
}

daemonHost, daemonPort, err := net.SplitHostPort(daemonEndpoint)
if err != nil {
return errors.New("couldn't split host:post of daemon endpoint")
Expand Down Expand Up @@ -443,7 +443,7 @@ func IsAllowedUser(address *common.Address) bool {
// Set the list of allowed users
func SetAllowedUsers() (err error) {
users := vip.GetStringSlice(AllowedUserAddresses)
if users == nil || len(users) == 0 {
if len(users) == 0 {
return fmt.Errorf("a valid Address needs to be specified for the config %v to ensure that, only these users can make calls", AllowedUserAddresses)
}
userAddress = make([]common.Address, len(users))
Expand Down
1 change: 0 additions & 1 deletion config/configuration_schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ func GetConfigurationSchema() ([]ConfigurationDetails, error) {
_ = json.Unmarshal(configurationDetailsJSON, configDetails)
allConfigurations = append(allConfigurations, *configDetails)
}

}
return allConfigurations, nil
}
Expand Down
3 changes: 1 addition & 2 deletions config/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package config

import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -39,7 +38,7 @@ func CheckVersionOfDaemon() (message string, err error) {
latestVersionFromGit, err = GetLatestDaemonVersion()
if len(versionTag) > 0 && err == nil {
if strings.Compare(latestVersionFromGit, versionTag) != 0 {
err = errors.New(fmt.Sprintf("There is a newer version of the Daemon %v available. You are currently on %v, please consider upgrading.", latestVersionFromGit, versionTag))
err = fmt.Errorf("there is a newer version of the Daemon %v available. You are currently on %v, please consider upgrading", latestVersionFromGit, versionTag)
}
}
return message, err
Expand Down
11 changes: 5 additions & 6 deletions configuration_service/broadcast_message.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type MessageBroadcaster struct {
trigger chan int
quit chan int
subscribers []chan int
//This will be used to make sure , we dont interfere with other threads
//This will be used to make sure, we don't interfere with other threads
mutex sync.Mutex
}

Expand All @@ -35,17 +35,16 @@ func (broadcast *MessageBroadcaster) NewSubscriber() chan int {
return ch
}

// Once a message is received, pass it down to all the subscribers
// Publish - Once a message is received, pass it down to all the subscribers
func (broadcast *MessageBroadcaster) Publish() {
for {
//Wait for the message to trigger the broadcast
// Wait for the message to trigger the broadcast
msg := <-broadcast.trigger
broadcast.mutex.Lock()
defer broadcast.mutex.Unlock()
for _, subscriber := range broadcast.subscribers {
//Now broad the message to all the subscribers.
// Now broad the message to all the subscribers.
subscriber <- msg
}

broadcast.mutex.Unlock()
}
}
8 changes: 4 additions & 4 deletions configuration_service/configuration_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,15 @@ const (
func getAuthenticationAddress() []common.Address {
users := config.Vip().GetStringSlice(config.AuthenticationAddresses)
userAddress := make([]common.Address, 0)
if users == nil || len(users) == 0 {
if len(users) == 0 {
return userAddress
}
for _, user := range users {
if !common.IsHexAddress(user) {
fmt.Errorf("%v is not a valid hex address", user)
} else {
userAddress = append(userAddress, common.BytesToAddress(common.FromHex(user)))
zap.L().Warn("not a valid hex address in config."+config.AuthenticationAddresses, zap.String("address", user))
continue
}
userAddress = append(userAddress, common.BytesToAddress(common.FromHex(user)))
}
return userAddress
}
Expand Down
6 changes: 1 addition & 5 deletions escrow/control_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@ If an error is encountered , then we return back whatever was successful and sto
and return the error that was encountered.
*/
func (service *ProviderControlService) StartClaimForMultipleChannels(ctx context.Context, request *StartMultipleClaimRequest) (reply *PaymentsListReply, err error) {

if err := service.checkMpeAddress(request.GetMpeAddress()); err != nil {
return nil, err
}
Expand Down Expand Up @@ -148,13 +147,10 @@ func (service *ProviderControlService) verifySignerForStartClaimForMultipleChann

func getBytesOfChannelIds(request *StartMultipleClaimRequest) []byte {
channelIds := make([]uint64, 0)
for _, channelId := range request.GetChannelIds() {
channelIds = append(channelIds, channelId)
}
channelIds = append(channelIds, request.GetChannelIds()...)
//sort the channel Ids
Uint64s(channelIds)
channelIdInBytes := make([]byte, 0)

for index, channelId := range channelIds {
if index == 0 {
channelIdInBytes = bytes.Join([][]byte{
Expand Down
4 changes: 2 additions & 2 deletions escrow/escrow.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ func (h *lockingPaymentChannelService) PaymentChannel(key *PaymentChannelKey) (c
blockchainChannel, blockchainOk, err := h.blockchainReader.GetChannelStateFromBlockchain(key)

if !storageOk {
// Group ID check is only done for the first time , when the channel is added to storage from the block chain ,
//if the channel is already present in the storage the group ID check is skipped.
// Group ID check is only done for the first time, when the channel is added to storage from the blockchain,
// if the channel is already present in the storage the group ID check is skipped.
if blockchainChannel != nil {
blockChainGroupID, err := h.replicaGroupID()
if err = h.verifyGroupId(blockChainGroupID, blockchainChannel.GroupID); err != nil {
Expand Down
4 changes: 2 additions & 2 deletions escrow/free_call.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ func (transaction *freeCallTransaction) Commit() error {
return nil
}

func (payment *freeCallTransaction) Rollback() error {
func (transaction *freeCallTransaction) Rollback() error {
defer func(payment *freeCallTransaction) {
err := payment.lock.Unlock()
if err != nil {
Expand All @@ -159,6 +159,6 @@ func (payment *freeCallTransaction) Rollback() error {
} else {
zap.L().Debug("Free call Payment rolled back, free call user unlocked")
}
}(payment)
}(transaction)
return nil
}
3 changes: 1 addition & 2 deletions escrow/payment_channel_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ func serialize(value any) (slice string, err error) {
return
}

slice = string(b.Bytes())
return
return b.String(), err
}

func deserialize(slice string, value any) (err error) {
Expand Down
2 changes: 1 addition & 1 deletion escrow/prepaid_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ type PrePaidPaymentHandler struct {

func (validator *PrePaidPaymentValidator) Validate(payment *PrePaidPayment) (err error) {
//Validate the token
return validator.tokenManager.VerifyToken(string(payment.AuthToken), payment.ChannelID)
return validator.tokenManager.VerifyToken(payment.AuthToken, payment.ChannelID)
}

// NewPaymentHandler returns new MultiPartyEscrow contract payment handler.
Expand Down
2 changes: 1 addition & 1 deletion escrow/token_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,5 @@ func (service *TokenService) GetToken(ctx context.Context, request *TokenRequest
}
tokenGenerated, err := service.tokenManager.CreateToken(channelID)
return &TokenReply{ChannelId: request.ChannelId, Token: fmt.Sprintf("%v", tokenGenerated), PlannedAmount: plannedAmount.Amount.Uint64(),
UsedAmount: usageAmount.Uint64()}, nil
UsedAmount: usageAmount.Uint64()}, err
}
Loading

0 comments on commit dad208e

Please sign in to comment.