Skip to content

Commit

Permalink
fix some test error
Browse files Browse the repository at this point in the history
  • Loading branch information
trestinlsd committed Sep 3, 2024
1 parent 2a1db4c commit bf369ac
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 50 deletions.
20 changes: 10 additions & 10 deletions x/avs/keeper/bls_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,27 @@ func (suite *AVSTestSuite) TestOperator_pubkey() {
suite.NoError(err)
suite.Equal(publicKey.Marshal(), pub.PubKey)

taskRes := types.TaskResponse{TaskID: 1, NumberSum: big.NewInt(100)}
taskRes := types.TaskResponse{TaskID: 17, NumberSum: big.NewInt(1000)}

hashAbi, _ := types.GetTaskResponseDigestEncodeByAbi(taskRes)

msgBytes := hashAbi[:]
fmt.Println("ResHash:", hex.EncodeToString(msgBytes))

msg, _ := types.GetTaskResponseDigest(taskRes)
msgBytes := msg[:]
sig := privateKey.Sign(msgBytes)
fmt.Println("sig:", hex.EncodeToString(sig.Marshal()))
jsonData, err := types.MarshalTaskResponse(taskRes)
hash := crypto.Keccak256Hash(jsonData)
fmt.Println("res:", hex.EncodeToString(jsonData))
fmt.Println("hash:", hash.String())
sig1, _ := hex.DecodeString("af22f968871395eca62fdb91bc39c2d93569b50678ed73f00c3a6e054512bdc6cb73da7972c9553931aec25bce4973cf15227d2d596492642baaaf2ac1a1a9605b5cf1312fc1e3532aa43a22460e5ce7c081d643dce806f95f26a2df84bdfc66")
fmt.Println(sig1)

valid := sig.Verify(publicKey, msgBytes)
suite.True(valid)

valid1, _ := blst.VerifySignature(sig.Marshal(), msg, publicKey)
valid1, _ := blst.VerifySignature(sig.Marshal(), hashAbi, publicKey)
suite.NoError(err)

suite.True(valid1)

jsonData, err := types.MarshalTaskResponse(taskRes)
fmt.Println("jsondata:", hex.EncodeToString(jsonData))

}

func (suite *AVSTestSuite) Test_hash() {
Expand Down
6 changes: 6 additions & 0 deletions x/avs/keeper/impl_epoch_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ func (wrapper EpochsHooksWrapper) AfterEpochEnd(
// Calculate actual threshold
taskPowerTotal, err := wrapper.keeper.operatorKeeper.GetAVSUSDValue(ctx, avsAddr)

if err != nil || taskPowerTotal.IsZero() || operatorPowerTotal.IsZero() {
ctx.Logger().Error("Failed to update task result statistics", "task result", taskAddr, "error", err)
// Handle the error gracefully, continue to the next
continue
}

actualThreshold := taskPowerTotal.Quo(operatorPowerTotal).Mul(sdk.NewDec(100))
if err != nil {
ctx.Logger().Error("Failed to update task result statistics", "task result", taskAddr, "error", err)
Expand Down
60 changes: 38 additions & 22 deletions x/avs/keeper/miscellaneous_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,59 @@ import (
utiltx "github.com/ExocoreNetwork/exocore/testutil/tx"
"github.com/ExocoreNetwork/exocore/x/avs/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"math/big"
"testing"
)

var (
structThing, _ = abi.NewType("tuple", "struct", []abi.ArgumentMarshaling{
{Name: "field_one", Type: "uint256"},
{Name: "field_two", Type: "address"},
})

args = abi.Arguments{
{Type: structThing, Name: "param_one"},
}
)

func TestReceiptMarshalBinary(t *testing.T) {

record := struct {
FieldOne *big.Int
FieldTwo common.Address
}{
big.NewInt(2e18),
common.HexToAddress("0x0002"),
task := types.TaskResponse{
TaskID: 10,
NumberSum: big.NewInt(1000),
}

packed, err := args.Pack(&record)
packed, err := types.Args.Pack(&task)
if err != nil {
fmt.Println("bad bad ", err)
return
} else {
fmt.Println("abi encoded", hexutil.Encode(packed))
}
b, _ := args.Unpack(packed)
fmt.Println("unpacked", b)

var args = make(map[string]interface{})

err = types.Args.UnpackIntoMap(args, packed)
result, _ := types.Args.Unpack(packed)
fmt.Println("unpacked", result[0])
hash := crypto.Keccak256Hash(packed)
fmt.Println("hash:", hash.String())

key := args["TaskResponse"]
fmt.Println("key", key)
for _, elem := range result {
switch v := elem.(type) {
case uint64:
fmt.Println("Found uint64:", v)
case *big.Int:
fmt.Println("Found *big.Int:", v)
case *types.TaskResponse:
fmt.Println("types.TaskResponse type found")
default:
fmt.Println("Unknown type found")
}
}
taskNew, _ := result[0].(*types.TaskResponse)
fmt.Println("hash:", taskNew)

var taskResponse types.TaskResponse

if err := types.Args.Copy(&taskResponse, result); err != nil {
fmt.Println("unpacked", result)
}
fmt.Println("taskResponse", taskResponse)

}

func Test_difference(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions x/avs/keeper/multi_operator_submit_task_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func (suite *AVSTestSuite) TestSubmitTask_OnlyPhaseOne_Mul() {
suite.prepareMul()
for index, operatorAddress := range suite.operatorAddresses {
taskRes := avstypes.TaskResponse{TaskID: 1, NumberSum: big.NewInt(100)}
msg, _ := avstypes.GetTaskResponseDigest(taskRes)
msg, _ := avstypes.GetTaskResponseDigestEncodeByAbi(taskRes)
msgBytes := msg[:]
sig := suite.blsKeys[index].Sign(msgBytes)

Expand Down Expand Up @@ -205,7 +205,7 @@ func (suite *AVSTestSuite) TestSubmitTask_OnlyPhaseTwo_Mul() {
hash := crypto.Keccak256Hash(jsonData)
// pub, err := suite.App.AVSManagerKeeper.GetOperatorPubKey(suite.Ctx, suite.operatorAddr.String())
suite.NoError(err)
msg, _ := avstypes.GetTaskResponseDigest(taskRes)
msg, _ := avstypes.GetTaskResponseDigestEncodeByAbi(taskRes)
msgBytes := msg[:]
sig := suite.blsKeys[index].Sign(msgBytes)

Expand Down
4 changes: 2 additions & 2 deletions x/avs/keeper/submit_task_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func (suite *AVSTestSuite) TestSubmitTask_OnlyPhaseOne() {
// pub, err := suite.App.AVSManagerKeeper.GetOperatorPubKey(suite.Ctx, suite.operatorAddr.String())
suite.NoError(err)

msg, _ := avstypes.GetTaskResponseDigest(taskRes)
msg, _ := avstypes.GetTaskResponseDigestEncodeByAbi(taskRes)
msgBytes := msg[:]
sig := suite.blsKey.Sign(msgBytes)

Expand Down Expand Up @@ -197,7 +197,7 @@ func (suite *AVSTestSuite) TestSubmitTask_OnlyPhaseTwo() {
// pub, err := suite.App.AVSManagerKeeper.GetOperatorPubKey(suite.Ctx, suite.operatorAddr.String())
suite.NoError(err)

msg, _ := avstypes.GetTaskResponseDigest(taskRes)
msg, _ := avstypes.GetTaskResponseDigestEncodeByAbi(taskRes)
msgBytes := msg[:]
sig := suite.blsKey.Sign(msgBytes)

Expand Down
23 changes: 12 additions & 11 deletions x/avs/keeper/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package keeper
import (
"bytes"
"fmt"
"strconv"

"github.com/ethereum/go-ethereum/crypto"

Check failure on line 6 in x/avs/keeper/task.go

View workflow job for this annotation

GitHub Actions / Run golangci-lint

File is not `gofumpt`-ed (gofumpt)
"strconv"
"strings"

errorsmod "cosmossdk.io/errors"

Expand Down Expand Up @@ -240,20 +240,21 @@ func (k *Keeper) SetTaskResultInfo(

// check hash
taskResponseDigest := crypto.Keccak256Hash(info.TaskResponse)
if taskResponseDigest.String() != info.TaskResponseHash {
hashWithoutPrefix := strings.TrimPrefix(taskResponseDigest.String(), "0x")
if hashWithoutPrefix != info.TaskResponseHash {
return errorsmod.Wrap(
types.ErrHashValue,
"SetTaskResultInfo: task response is nil",
)
}
// check taskID
resp, err := types.UnmarshalTaskResponse(info.TaskResponse)
if err != nil || info.TaskId != resp.TaskID {
return errorsmod.Wrap(
types.ErrParamError,
fmt.Sprintf("SetTaskResultInfo: invalid param value:%s", info.Stage),
)
}
// TODO :check taskID
//resp, err := types.UnmarshalTaskResponse(info.TaskResponse)

Check failure on line 251 in x/avs/keeper/task.go

View workflow job for this annotation

GitHub Actions / Run golangci-lint

commentFormatting: put a space between `//` and comment text (gocritic)
//if err != nil || info.TaskId != resp.TaskID {
// return errorsmod.Wrap(
// types.ErrParamError,
// fmt.Sprintf("SetTaskResultInfo: invalid param value:%s", info.Stage),
// )
//}
// check bls sig
flag, err := blst.VerifySignature(info.BlsSignature, taskResponseDigest, pubKey)
if !flag || err != nil {
Expand Down
31 changes: 28 additions & 3 deletions x/avs/types/types.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package types

import (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/ethereum/go-ethereum/accounts/abi"

Check failure on line 7 in x/avs/types/types.go

View workflow job for this annotation

GitHub Actions / Run golangci-lint

File is not `gofumpt`-ed (gofumpt)
"math/big"
"strings"

Check failure on line 9 in x/avs/types/types.go

View workflow job for this annotation

GitHub Actions / Run golangci-lint

File is not `gofumpt`-ed (gofumpt)

Expand Down Expand Up @@ -72,6 +75,17 @@ type AVSRegisterOrDeregisterParams struct {
Action uint64
}

var (
taskResponseType, _ = abi.NewType("tuple", "struct", []abi.ArgumentMarshaling{
{Name: "TaskID", Type: "uint64"},
{Name: "NumberSum", Type: "uint256"},
})

Args = abi.Arguments{
{Type: taskResponseType, Name: "TaskResponse"},
}
)

// ChainIDWithoutRevision returns the chainID without the revision number.
// For example, "exocoretestnet_233-1" returns "exocoretestnet_233".
func ChainIDWithoutRevision(chainID string) string {
Expand Down Expand Up @@ -100,7 +114,7 @@ type TaskResponse struct {
NumberSum *big.Int
}

// GetTaskResponseDigest returns the hash of the TaskResponse, which is what operators sign over
// GetTaskResponseDigestEncodeByjson returns the hash of the TaskResponse, which is what operators sign over
// MarshalTaskResponse marshals the TaskResponse struct into JSON bytes.
func MarshalTaskResponse(h TaskResponse) ([]byte, error) {
return json.Marshal(h)
Expand All @@ -113,8 +127,8 @@ func UnmarshalTaskResponse(jsonData []byte) (TaskResponse, error) {
return taskResponse, err
}

// GetTaskResponseDigest returns the hash of the TaskResponse, which is what operators sign over.
func GetTaskResponseDigest(h TaskResponse) ([32]byte, error) {
// GetTaskResponseDigestEncodeByjson returns the hash of the TaskResponse, which is what operators sign over.
func GetTaskResponseDigestEncodeByjson(h TaskResponse) ([32]byte, error) {
jsonData, err := MarshalTaskResponse(h)
if err != nil {
return [32]byte{}, err
Expand All @@ -123,6 +137,17 @@ func GetTaskResponseDigest(h TaskResponse) ([32]byte, error) {
return taskResponseDigest, nil
}

// GetTaskResponseDigestEncodeByAbi returns the hash of the TaskResponse, which is what operators sign over.
func GetTaskResponseDigestEncodeByAbi(h TaskResponse) ([32]byte, error) {
packed, err := Args.Pack(&h)
if err != nil {
return [32]byte{}, err
}
fmt.Println("Res:", hex.EncodeToString(packed))
hashAbi := crypto.Keccak256Hash(packed)
return hashAbi, nil
}

func Difference(a, b []string) []string {
var different []string //nolint:prealloc

Expand Down

0 comments on commit bf369ac

Please sign in to comment.