Skip to content

Commit

Permalink
replace interface{} to any, fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
semyon-dev committed Jul 15, 2024
1 parent 34050c8 commit b72fa0f
Show file tree
Hide file tree
Showing 24 changed files with 121 additions and 112 deletions.
12 changes: 6 additions & 6 deletions config/blockchain_network_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,24 @@ var networkSelected = &NetworkSelected{}
var networkIdNameMapping string

func determineNetworkSelected(data []byte) (err error) {
dynamicBinding := map[string]interface{}{}
dynamicBinding := map[string]any{}
networkName := GetString(BlockChainNetworkSelected)
if err = json.Unmarshal(data, &dynamicBinding); err != nil {
return err
}
//Get the Network Name selected in config ( snetd.config.json) , Based on this retrieve the Registry address ,
//Ethereum End point and Network ID mapped to
networkSelected.NetworkName = networkName
networkSelected.RegistryAddressKey = getDetailsFromJsonOrConfig(dynamicBinding[networkName].(map[string]interface{})[RegistryAddressKey], RegistryAddressKey)
networkSelected.EthereumJSONRPCEndpoint = getDetailsFromJsonOrConfig(dynamicBinding[networkName].(map[string]interface{})[EthereumJsonRpcEndpointKey], EthereumJsonRpcEndpointKey)
networkSelected.NetworkId = fmt.Sprintf("%v", dynamicBinding[networkName].(map[string]interface{})[NetworkId])
networkSelected.RegistryAddressKey = getDetailsFromJsonOrConfig(dynamicBinding[networkName].(map[string]any)[RegistryAddressKey], RegistryAddressKey)
networkSelected.EthereumJSONRPCEndpoint = getDetailsFromJsonOrConfig(dynamicBinding[networkName].(map[string]any)[EthereumJsonRpcEndpointKey], EthereumJsonRpcEndpointKey)
networkSelected.NetworkId = fmt.Sprintf("%v", dynamicBinding[networkName].(map[string]any)[NetworkId])

return err
}

// Check if the value set in the config file, if yes, then we use it as is
// else we derive the value from the JSON parsed
func getDetailsFromJsonOrConfig(details interface{}, configName string) string {
func getDetailsFromJsonOrConfig(details any, configName string) string {
if len(GetString(configName)) > 0 {
return GetString(configName)
}
Expand Down Expand Up @@ -107,7 +107,7 @@ func deriveDatafromJSON(data []byte) (err error) {
return errors.New("cannot find registry address from JSON for the selected network")
}

networkSelected.RegistryAddressKey = fmt.Sprintf("%v", m[GetNetworkId()].(map[string]interface{})["address"])
networkSelected.RegistryAddressKey = fmt.Sprintf("%v", m[GetNetworkId()].(map[string]any)["address"])

zap.L().Info("Derive data from JSON", zap.String("Network", GetString(BlockChainNetworkSelected)),
zap.String("NetwrokId", GetNetworkId()),
Expand Down
4 changes: 2 additions & 2 deletions config/blockchain_network_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func Test_SetBlockChainNetworkDetails(t *testing.T) {

func Test_GetDetailsFromJsonOrConfig(t *testing.T) {

dynamicBinding := map[string]interface{}{}
dynamicBinding := map[string]any{}
data := []byte(defaultBlockChainNetworkConfig)
json.Unmarshal(data, &dynamicBinding)

Expand All @@ -97,7 +97,7 @@ func Test_GetDetailsFromJsonOrConfig(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := getDetailsFromJsonOrConfig(dynamicBinding[tt.network].(map[string]interface{})[tt.name], tt.name); got != tt.want {
if got := getDetailsFromJsonOrConfig(dynamicBinding[tt.network].(map[string]any)[tt.name], tt.name); got != tt.want {
t.Errorf("getDetailsFromJsonOrConfig() = %v, want %v", got, tt.want)
}
})
Expand Down
3 changes: 2 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,10 @@ func Validate() error {

// Check if the Daemon is on the latest version or not
if message, err := CheckVersionOfDaemon(); err != nil {
//In case of any error on version check, just log it
// In case of any error on version check, just log it
zap.L().Warn(err.Error())
} else {
// Print current version of daemon
zap.L().Info(message)
}

Expand Down
4 changes: 2 additions & 2 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ const jsonConfigString = `
}`

func assertConfigIsEqualToJsonConfigString(t *testing.T, config *viper.Viper) {
assert.Equal(t, map[string]interface{}{"field": "value"}, config.Get("object"))
assert.Equal(t, map[string]any{"field": "value"}, config.Get("object"))
assert.Equal(t, "value", config.Get("object.field"))
assert.Equal(t, []interface{}{"item-1", "item-2"}, config.Get("array"))
assert.Equal(t, []any{"item-1", "item-2"}, config.Get("array"))
assert.Equal(t, "string-value", config.Get("string-key"))
assert.Equal(t, 42, config.GetInt("int-key"))
}
Expand Down
2 changes: 1 addition & 1 deletion config/configuration_schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func GetConfigurationSchema() ([]ConfigurationDetails, error) {
}

// ConvertStructToJSON converts the passed datastructure to a JSON
func ConvertStructToJSON(payLoad interface{}) ([]byte, error) {
func ConvertStructToJSON(payLoad any) ([]byte, error) {
b, err := json.Marshal(&payLoad)
if err != nil {
return nil, err
Expand Down
14 changes: 9 additions & 5 deletions config/version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,13 @@ func Test_getBuildTime(t *testing.T) {
}

func TestCheckVersionOfDaemon(t *testing.T) {
versionTag = "v0.1.9"
message ,err := CheckVersionOfDaemon()
assert.Nil(t, err)
assert.Contains(t,message,"There is a newer version of the Daemon")
versionTag = "v5.1.2"
message, err := CheckVersionOfDaemon()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "There is a newer version of the Daemon")

}
versionTag, _ = GetLatestDaemonVersion()
message, err = CheckVersionOfDaemon()
assert.Nil(t, err)
assert.Contains(t, message, "Daemon version is "+versionTag)
}
2 changes: 1 addition & 1 deletion escrow/free_call_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func NewFreeCallUserStorage(atomicStorage storage.AtomicStorage) *FreeCallUserSt
}*/
}

func serializeFreeCallKey(key interface{}) (serialized string, err error) {
func serializeFreeCallKey(key any) (serialized string, err error) {
myKey := key.(*FreeCallUserKey)
return myKey.String(), nil
}
Expand Down
6 changes: 3 additions & 3 deletions escrow/payment_channel_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ func NewPaymentChannelStorage(atomicStorage storage.AtomicStorage) *PaymentChann

}

func serializeKey(key interface{}) (slice string, err error) {
func serializeKey(key any) (slice string, err error) {
return fmt.Sprintf("%v", key), nil
}
func serialize(value interface{}) (slice string, err error) {
func serialize(value any) (slice string, err error) {
var b bytes.Buffer
e := gob.NewEncoder(&b)
err = e.Encode(value)
Expand All @@ -48,7 +48,7 @@ func serialize(value interface{}) (slice string, err error) {
return
}

func deserialize(slice string, value interface{}) (err error) {
func deserialize(slice string, value any) (err error) {
b := bytes.NewBuffer([]byte(slice))
d := gob.NewDecoder(b)
err = d.Decode(value)
Expand Down
14 changes: 7 additions & 7 deletions escrow/prepaid_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ func (h *lockingPrepaidService) GetUsage(key PrePaidDataKey) (data *PrePaidData,

}

//Defines the condition that needs to be met, it generates the respective typed Data when
//conditions are satisfied, you define your own validations in here
//It takes in the latest typed values read.
// Defines the condition that needs to be met, it generates the respective typed Data when
// conditions are satisfied, you define your own validations in here
// It takes in the latest typed values read.
type ConditionFunc func(conditionValues []storage.TypedKeyValueData, revisedAmount *big.Int, channelId *big.Int) ([]storage.TypedKeyValueData, error)

func (h *lockingPrepaidService) UpdateUsage(channelId *big.Int, revisedAmount *big.Int, updateUsageType string) (err error) {
Expand Down Expand Up @@ -78,16 +78,16 @@ func (h *lockingPrepaidService) UpdateUsage(channelId *big.Int, revisedAmount *b
}
return nil
}
func getAllKeys(channelId *big.Int) []interface{} {
keys := make([]interface{}, 3)
func getAllKeys(channelId *big.Int) []any {
keys := make([]any, 3)
for i, usageType := range []string{REFUND_AMOUNT, PLANNED_AMOUNT, USED_AMOUNT} {
keys[i] = PrePaidDataKey{ChannelID: channelId, UsageType: usageType}
}
return keys
}

//this function will be used to read typed data ,convert it in to a business structure
//on which validations can be easily performed and return back the business structure.
// this function will be used to read typed data ,convert it in to a business structure
// on which validations can be easily performed and return back the business structure.
func convertTypedDataToPrePaidUsage(data []storage.TypedKeyValueData) (new *PrePaidUsageData, err error) {
usageData := &PrePaidUsageData{PlannedAmount: big.NewInt(0),
UsedAmount: big.NewInt(0), RefundAmount: big.NewInt(0)}
Expand Down
10 changes: 5 additions & 5 deletions escrow/prepaid_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ type PrePaidPayment struct {
AuthToken string
}

//Used when the Request comes in
// Used when the Request comes in
func (payment *PrePaidPayment) String() string {
return fmt.Sprintf("{ID:%v/%v/%v}", payment.ChannelID, payment.OrganizationId, payment.GroupId)
}

//Kept the bare minimum here , other details like group and sender address of this channel can
//always be retrieved from BlockChain
// Kept the bare minimum here , other details like group and sender address of this channel can
// always be retrieved from BlockChain
type PrePaidData struct {
Amount *big.Int
}
Expand All @@ -44,7 +44,7 @@ const (
REFUND_AMOUNT string = "R"
)

//This will ony be used for doing any business checks
// This will ony be used for doing any business checks
type PrePaidUsageData struct {
ChannelID *big.Int
PlannedAmount *big.Int
Expand Down Expand Up @@ -80,7 +80,7 @@ func (data PrePaidUsageData) Clone() *PrePaidUsageData {
}
}

func serializePrePaidKey(key interface{}) (serialized string, err error) {
func serializePrePaidKey(key any) (serialized string, err error) {
myKey := key.(PrePaidDataKey)
return myKey.String(), nil
}
Expand Down
2 changes: 1 addition & 1 deletion etcddb/etcddb_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ func (client *EtcdClient) checkTxnResponse(keys []string, txnResp *clientv3.TxnR
}
latestStateArray = append(latestStateArray, latestValues...)
}
keySet.Do(func(elem interface{}) {
keySet.Do(func(elem any) {
latestStateArray = append(latestStateArray, keyValueVersion{
Key: elem.(string),
Present: false,
Expand Down
4 changes: 4 additions & 0 deletions etcddb/etcddb_conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ func GetEtcdClientConf(vip *viper.Viper, metaData *blockchain.OrganizationMetaDa
Endpoints: metaData.GetPaymentStorageEndPoints(),
}

if vip == nil {
return
}

confFromVip := &EtcdClientConf{}
subVip := config.SubWithDefault(vip, config.PaymentChannelStorageClientKey)
err = subVip.Unmarshal(confFromVip)
Expand Down
36 changes: 18 additions & 18 deletions handler/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ Modified from https://github.com/mwitkow/grpc-proxy/blob/67591eb23c48346a480470e
Original Copyright 2017 Michal Witkowski. All Rights Reserved. See LICENSE-GRPC-PROXY for licensing terms.
Modifications Copyright 2018 SingularityNET Foundation. All Rights Reserved. See LICENSE for licensing terms.
*/
func (g grpcHandler) grpcToGRPC(srv interface{}, inStream grpc.ServerStream) error {
func (g grpcHandler) grpcToGRPC(srv any, inStream grpc.ServerStream) error {
method, ok := grpc.MethodFromServerStream(inStream)

if !ok {
Expand Down Expand Up @@ -266,7 +266,7 @@ func (g grpcHandler) grpcToHTTP(srv any, inStream grpc.ServerStream) error {
methodSegs := strings.Split(method, "/")
method = methodSegs[len(methodSegs)-1]

zap.L().Debug("Calling method", zap.String("method", method))
zap.L().Info("Calling method", zap.String("method", method))

f := &codec.GrpcFrame{}
if err := inStream.RecvMsg(f); err != nil {
Expand Down Expand Up @@ -340,7 +340,7 @@ func (g grpcHandler) grpcToHTTP(srv any, inStream grpc.ServerStream) error {
if err != nil {
return status.Errorf(codes.Internal, "error reading response; error: %+cred", err)
}
zap.L().Info("Getting response", zap.String("response", string(resp)))
zap.L().Debug("Getting response", zap.String("response", string(resp)))

protoMessage := jsonToProto(g.serviceMetaData.ProtoFile, resp, method)
if err = inStream.SendMsg(protoMessage); err != nil {
Expand All @@ -356,19 +356,19 @@ func jsonToProto(protoFile protoreflect.FileDescriptor, json []byte, methodName
zap.L().Debug("Count services: ", zap.Int("value", protoFile.Services().Len()))

if protoFile.Services().Len() == 0 {
zap.L().Info("service in proto not found")
zap.L().Warn("service in proto not found")
return proto
}

service := protoFile.Services().Get(0)
if service == nil {
zap.L().Info("service in proto not found")
zap.L().Warn("service in proto not found")
return proto
}

method := service.Methods().ByName(protoreflect.Name(methodName))
if method == nil {
zap.L().Info("method not found")
zap.L().Warn("method not found in proto")
return proto
}
output := method.Output()
Expand All @@ -385,19 +385,19 @@ func jsonToProto(protoFile protoreflect.FileDescriptor, json []byte, methodName
func protoToJson(protoFile protoreflect.FileDescriptor, in []byte, methodName string) (json []byte) {

if protoFile.Services().Len() == 0 {
zap.L().Info("service in proto not found")
zap.L().Warn("service in proto not found")
return []byte("error, invalid proto file")
}

service := protoFile.Services().Get(0)
if service == nil {
zap.L().Info("service in proto not found")
zap.L().Warn("service in proto not found")
return []byte("error, invalid proto file")
}

method := service.Methods().ByName(protoreflect.Name(methodName))
if method == nil {
zap.L().Info("method not found")
zap.L().Warn("method not found in proto")
return []byte("error, invalid proto file or input request")
}

Expand All @@ -406,20 +406,20 @@ func protoToJson(protoFile protoreflect.FileDescriptor, in []byte, methodName st
msg := dynamicpb.NewMessage(input)
err := proto.Unmarshal(in, msg)
if err != nil {
zap.L().Error("Errog in unmarshaling", zap.Error(err))
zap.L().Error("Error in unmarshalling", zap.Error(err))
return []byte("error, invalid proto file or input request")
}
json, err = protojson.MarshalOptions{UseProtoNames: true}.Marshal(msg)
if err != nil {
zap.L().Error("Errog in marshaling", zap.Error(err))
zap.L().Error("Error in marshaling", zap.Error(err))
return []byte("error, invalid proto file or input request")
}
zap.L().Debug("Getting json", zap.String("json", string(json)))

return json
}

func (g grpcHandler) grpcToJSONRPC(srv interface{}, inStream grpc.ServerStream) error {
func (g grpcHandler) grpcToJSONRPC(srv any, inStream grpc.ServerStream) error {
method, ok := grpc.MethodFromServerStream(inStream)

if !ok {
Expand All @@ -438,7 +438,7 @@ func (g grpcHandler) grpcToJSONRPC(srv interface{}, inStream grpc.ServerStream)
return status.Errorf(codes.Internal, "error receiving request; error: %+v", err)
}

params := new(interface{})
params := new(any)

if err := json.Unmarshal(f.Data, params); err != nil {
return status.Errorf(codes.Internal, "error unmarshaling request; error: %+v", err)
Expand Down Expand Up @@ -525,19 +525,19 @@ func (f *WrapperServerStream) Context() context.Context {
return f.stream.Context()
}

func (f *WrapperServerStream) SendMsg(m interface{}) error {
func (f *WrapperServerStream) SendMsg(m any) error {
return f.stream.SendMsg(m)
}

func (f *WrapperServerStream) RecvMsg(m interface{}) error {
func (f *WrapperServerStream) RecvMsg(m any) error {
return f.stream.RecvMsg(m)
}

func (f *WrapperServerStream) OriginalRecvMsg() interface{} {
func (f *WrapperServerStream) OriginalRecvMsg() any {
return f.recvMessage
}

func (g grpcHandler) grpcToProcess(srv interface{}, inStream grpc.ServerStream) error {
func (g grpcHandler) grpcToProcess(srv any, inStream grpc.ServerStream) error {
method, ok := grpc.MethodFromServerStream(inStream)

if !ok {
Expand Down Expand Up @@ -579,7 +579,7 @@ func (g grpcHandler) grpcToProcess(srv interface{}, inStream grpc.ServerStream)
return nil
}

func grpcLoopback(srv interface{}, inStream grpc.ServerStream) error {
func grpcLoopback(srv any, inStream grpc.ServerStream) error {
f := &codec.GrpcFrame{}
if err := inStream.RecvMsg(f); err != nil {
return status.Errorf(codes.Internal, "error receiving request; error: %+v", err)
Expand Down
Loading

0 comments on commit b72fa0f

Please sign in to comment.