Skip to content

Commit

Permalink
rpc/nns: add InferHash convenience function
Browse files Browse the repository at this point in the history
Refs. #348

Signed-off-by: Roman Khimov <roman@nspcc.ru>
  • Loading branch information
roman-khimov committed Sep 22, 2023
1 parent d2f3761 commit eb5f2ee
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
29 changes: 29 additions & 0 deletions rpc/nns/hashes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package nns

import (
"github.com/nspcc-dev/neo-go/pkg/core/state"
"github.com/nspcc-dev/neo-go/pkg/util"
)

// ID is the default NNS contract ID in all NeoFS networks. NeoFS networks
// always deploy NNS first and can't work without it, therefore it always gets
// and ID of 1.
const ID = 1

// ContractStateGetter is the interface required for contract state resolution
// using a known contract ID.
type ContractStateGetter interface {
GetContractStateByID(int32) (*state.Contract, error)
}

// InferHash simplifies resolving NNS contract hash in existing NeoFS networks.
// It assumes that NNS follows [ID] assignment assumptions which likely won't
// be the case for any non-NeoFS network.
func InferHash(sg ContractStateGetter) (util.Uint160, error) {
c, err := sg.GetContractStateByID(ID)
if err != nil {
return util.Uint160{}, err
}

return c.Hash, nil
}
37 changes: 37 additions & 0 deletions rpc/nns/hashes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package nns

import (
"errors"
"testing"

"github.com/nspcc-dev/neo-go/pkg/core/state"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/stretchr/testify/require"
)

type stateGetter struct {
f func(int32) (*state.Contract, error)
}

func (s stateGetter) GetContractStateByID(id int32) (*state.Contract, error) {
return s.f(id)
}

func TestInferHash(t *testing.T) {
var sg stateGetter
sg.f = func(int32) (*state.Contract, error) {
return nil, errors.New("bad")
}
_, err := InferHash(sg)
require.Error(t, err)
sg.f = func(int32) (*state.Contract, error) {
return &state.Contract{
ContractBase: state.ContractBase{
Hash: util.Uint160{0x01, 0x02, 0x03},
},
}, nil
}
h, err := InferHash(sg)
require.NoError(t, err)
require.Equal(t, util.Uint160{0x01, 0x02, 0x03}, h)
}

0 comments on commit eb5f2ee

Please sign in to comment.