Add Inner Ring code

This commit is contained in:
Stanislav Bogatyrev 2020-07-24 16:54:03 +03:00
parent dadfd90dcd
commit b7b5079934
400 changed files with 11420 additions and 8690 deletions

View file

@ -0,0 +1,52 @@
package balance
import (
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/pkg/errors"
)
// GetBalanceOfArgs groups the arguments
// of "balance of" test invoke call.
type GetBalanceOfArgs struct {
wallet []byte // wallet script hash
}
// GetBalanceOfValues groups the stack parameters
// returned by "balance of" test invoke.
type GetBalanceOfValues struct {
amount int64 // wallet funds amount
}
// SetWallet sets the wallet script hash
// in a binary format.
func (g *GetBalanceOfArgs) SetWallet(v []byte) {
g.wallet = v
}
// Amount returns the amount of funds.
func (g *GetBalanceOfValues) Amount() int64 {
return g.amount
}
// BalanceOf performs the test invoke of "balance of"
// method of NeoFS Balance contract.
func (c *Client) BalanceOf(args GetBalanceOfArgs) (*GetBalanceOfValues, error) {
prms, err := c.client.TestInvoke(
c.balanceOfMethod,
args.wallet,
)
if err != nil {
return nil, errors.Wrapf(err, "could not perform test invocation (%s)", c.balanceOfMethod)
} else if ln := len(prms); ln != 1 {
return nil, errors.Errorf("unexpected stack item count (%s): %d", c.balanceOfMethod, ln)
}
amount, err := client.IntFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrapf(err, "could not get integer stack item from stack item (%s)", c.balanceOfMethod)
}
return &GetBalanceOfValues{
amount: amount,
}, nil
}

View file

@ -0,0 +1,102 @@
package balance
import (
"errors"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
)
// Client is a wrapper over StaticClient
// which makes calls with the names and arguments
// of the NeoFS Balance contract.
//
// Working client must be created via constructor New.
// Using the Client that has been created with new(Client)
// expression (or just declaring a Client variable) is unsafe
// and can lead to panic.
type Client struct {
client *client.StaticClient // static Balance contract client
*cfg // contract method names
}
// ErrNilClient is returned by functions that expect
// a non-nil Client pointer, but received nil.
var ErrNilClient = errors.New("balance contract client is nil")
// Option is a client configuration change function.
type Option func(*cfg)
type cfg struct {
balanceOfMethod, // balanceOf method name for invocation
decimalsMethod string // decimals method name for invocation
}
const (
defaultBalanceOfMethod = "balanceOf" // default "balance of" method name
defaultDecimalsMethod = "decimals" // default decimals method name
)
func defaultConfig() *cfg {
return &cfg{
balanceOfMethod: defaultBalanceOfMethod,
decimalsMethod: defaultDecimalsMethod,
}
}
// New creates, initializes and returns the Client instance.
//
// If StaticClient is nil, client.ErrNilStaticClient is returned.
//
// Other values are set according to provided options, or by default:
// * "balance of" method name: balanceOf;
// * decimals method name: decimals.
//
// If desired option satisfies the default value, it can be omitted.
// If multiple options of the same config value are supplied,
// the option with the highest index in the arguments will be used.
func New(c *client.StaticClient, opts ...Option) (*Client, error) {
if c == nil {
return nil, client.ErrNilStaticClient
}
res := &Client{
client: c,
cfg: defaultConfig(), // build default configuration
}
// apply options
for _, opt := range opts {
opt(res.cfg)
}
return res, nil
}
// WithBalanceOfMethod returns a client constructor option that
// specifies the "balance of" method name.
//
// Ignores empty value.
//
// If option not provided, "balanceOf" is used.
func WithBalanceOfMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.balanceOfMethod = n
}
}
}
// WithDecimalsMethod returns a client constructor option that
// specifies the method name of decimals receiving operation.
//
// Ignores empty value.
//
// If option not provided, "decimals" is used.
func WithDecimalsMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.decimalsMethod = n
}
}
}

View file

@ -0,0 +1,44 @@
package balance
import (
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/pkg/errors"
)
// DecimalsArgs groups the arguments
// of decimals test invoke call.
type DecimalsArgs struct {
}
// DecimalsValues groups the stack parameters
// returned by decimals test invoke.
type DecimalsValues struct {
decimals int64 // decimals value
}
// Decimals returns the decimals value.
func (d *DecimalsValues) Decimals() int64 {
return d.decimals
}
// Decimals performs the test invoke of decimals
// method of NeoFS Balance contract.
func (c *Client) Decimals(args DecimalsArgs) (*DecimalsValues, error) {
prms, err := c.client.TestInvoke(
c.decimalsMethod,
)
if err != nil {
return nil, errors.Wrapf(err, "could not perform test invocation (%s)", c.decimalsMethod)
} else if ln := len(prms); ln != 1 {
return nil, errors.Errorf("unexpected stack item count (%s): %d", c.decimalsMethod, ln)
}
decimals, err := client.IntFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrapf(err, "could not get integer stack item from stack item (%s)", c.decimalsMethod)
}
return &DecimalsValues{
decimals: decimals,
}, nil
}

View file

@ -0,0 +1,35 @@
package wrapper
import (
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
"github.com/nspcc-dev/neofs-node/pkg/core/container"
"github.com/nspcc-dev/neofs-node/pkg/morph/client/balance"
"github.com/pkg/errors"
)
// OwnerID represents the container owner identifier.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/core/container.OwnerID.
type OwnerID = container.OwnerID
// BalanceOf receives the amount of funds in the client's account
// through the Balance contract call, and returns it.
func (w *Wrapper) BalanceOf(ownerID OwnerID) (int64, error) {
// convert Neo wallet address to Uint160
u160, err := address.StringToUint160(ownerID.String())
if err != nil {
return 0, errors.Wrap(err, "could not convert wallet address to Uint160")
}
// prepare invocation arguments
args := balance.GetBalanceOfArgs{}
args.SetWallet(u160.BytesBE())
values, err := w.client.BalanceOf(args)
if err != nil {
return 0, errors.Wrap(err, "could not invoke smart contract")
}
return values.Amount(), nil
}

View file

@ -0,0 +1,22 @@
package wrapper
import (
"github.com/nspcc-dev/neofs-node/pkg/morph/client/balance"
"github.com/pkg/errors"
)
// Decimals decimal precision of currency transactions
// through the Balance contract call, and returns it.
func (w *Wrapper) Decimals() (uint32, error) {
// prepare invocation arguments
args := balance.DecimalsArgs{}
// invoke smart contract call
values, err := w.client.Decimals(args)
if err != nil {
return 0, errors.Wrap(err, "could not invoke smart contract")
}
// FIXME: avoid narrowing cast
return uint32(values.Decimals()), nil
}

View file

@ -0,0 +1,43 @@
package wrapper
import (
"errors"
"github.com/nspcc-dev/neofs-node/pkg/morph/client/balance"
)
// Client represents the Balance contract client.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/morph/client/balance.Client.
type Client = balance.Client
// Wrapper is a wrapper over balance contract
// client which implements:
// * tool for obtaining the amount of funds in the client's account;
// * tool for obtaining decimal precision of currency transactions.
//
// Working wrapper must be created via constructor New.
// Using the Wrapper that has been created with new(Wrapper)
// expression (or just declaring a Wrapper variable) is unsafe
// and can lead to panic.
type Wrapper struct {
client *Client
}
// ErrNilWrapper is returned by functions that expect
// a non-nil Wrapper pointer, but received nil.
var ErrNilWrapper = errors.New("balance contract client wrapper is nil")
// New creates, initializes and returns the Wrapper instance.
//
// If Client is nil, balance.ErrNilClient is returned.
func New(c *Client) (*Wrapper, error) {
if c == nil {
return nil, balance.ErrNilClient
}
return &Wrapper{
client: c,
}, nil
}

156
pkg/morph/client/client.go Normal file
View file

@ -0,0 +1,156 @@
package client
import (
"encoding/hex"
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
"github.com/nspcc-dev/neo-go/pkg/rpc/client"
sc "github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/wallet"
"github.com/nspcc-dev/neofs-node/pkg/util/logger"
"github.com/pkg/errors"
"go.uber.org/zap"
)
// Client is a neo-go wrapper that provides
// smart-contract invocation interface.
//
// Working client must be created via constructor New.
// Using the Client that has been created with new(Client)
// expression (or just declaring a Client variable) is unsafe
// and can lead to panic.
type Client struct {
logger *logger.Logger // logging component
client *client.Client // neo-go client
acc *wallet.Account // neo account
gas util.Uint160 // native gas script-hash
}
// ErrNilClient is returned by functions that expect
// a non-nil Client pointer, but received nil.
var ErrNilClient = errors.New("client is nil")
// HaltState returned if TestInvoke function processed without panic.
const HaltState = "HALT"
var errEmptyInvocationScript = errors.New("got empty invocation script from neo node")
var errScriptDecode = errors.New("could not decode invocation script from neo node")
// Invoke invokes contract method by sending transaction into blockchain.
// Supported args types: int64, string, util.Uint160, []byte and bool.
func (c *Client) Invoke(contract util.Uint160, fee util.Fixed8, method string, args ...interface{}) error {
params := make([]sc.Parameter, 0, len(args))
for i := range args {
param, err := toStackParameter(args[i])
if err != nil {
return err
}
params = append(params, param)
}
cosigner := []transaction.Cosigner{
{
Account: c.acc.PrivateKey().PublicKey().GetScriptHash(),
Scopes: transaction.Global,
},
}
resp, err := c.client.InvokeFunction(contract, method, params, cosigner)
if err != nil {
return err
}
if len(resp.Script) == 0 {
return errEmptyInvocationScript
}
script, err := hex.DecodeString(resp.Script)
if err != nil {
return errScriptDecode
}
sysFee := resp.GasConsumed + int64(fee) // consumed gas + extra fee
txHash, err := c.client.SignAndPushInvocationTx(script, c.acc, sysFee, 0, cosigner)
if err != nil {
return err
}
c.logger.Debug("neo client invoke",
zap.String("method", method),
zap.Stringer("tx_hash", txHash))
return nil
}
// TestInvoke invokes contract method locally in neo-go node. This method should
// be used to read data from smart-contract.
func (c *Client) TestInvoke(contract util.Uint160, method string, args ...interface{}) ([]sc.Parameter, error) {
var params = make([]sc.Parameter, 0, len(args))
for i := range args {
p, err := toStackParameter(args[i])
if err != nil {
return nil, err
}
params = append(params, p)
}
cosigner := []transaction.Cosigner{
{
Account: c.acc.PrivateKey().PublicKey().GetScriptHash(),
Scopes: transaction.Global,
},
}
val, err := c.client.InvokeFunction(contract, method, params, cosigner)
if err != nil {
return nil, err
}
if val.State != HaltState {
return nil, errors.Errorf("chain/client: contract execution finished with state %s", val.State)
}
return val.Stack, nil
}
// TransferGas to the receiver from local wallet
func (c *Client) TransferGas(receiver util.Uint160, amount util.Fixed8) error {
txHash, err := c.client.TransferNEP5(c.acc, receiver, c.gas, int64(amount), 0)
if err != nil {
return err
}
c.logger.Debug("native gas transfer invoke",
zap.String("to", receiver.StringLE()),
zap.Stringer("tx_hash", txHash))
return nil
}
func toStackParameter(value interface{}) (sc.Parameter, error) {
var result = sc.Parameter{
Value: value,
}
// todo: add more types
switch value.(type) {
case []byte:
result.Type = sc.ByteArrayType
case int64: // TODO: add other numerical types
result.Type = sc.IntegerType
default:
return result, errors.Errorf("chain/client: unsupported parameter %v", value)
}
return result, nil
}

View file

@ -0,0 +1,33 @@
package client
import (
"testing"
sc "github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/stretchr/testify/require"
)
func TestToStackParameter(t *testing.T) {
items := []struct {
value interface{}
expType sc.ParamType
}{
{
value: []byte{1, 2, 3},
expType: sc.ByteArrayType,
},
{
value: int64(100),
expType: sc.IntegerType,
},
}
for _, item := range items {
t.Run(item.expType.String()+" to stack parameter", func(t *testing.T) {
res, err := toStackParameter(item.value)
require.NoError(t, err)
require.Equal(t, item.expType, res.Type)
require.Equal(t, item.value, res.Value)
})
}
}

View file

@ -0,0 +1,162 @@
package client
import (
"context"
"crypto/ecdsa"
"time"
"github.com/nspcc-dev/neo-go/pkg/config/netmode"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neo-go/pkg/rpc/client"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/wallet"
crypto "github.com/nspcc-dev/neofs-crypto"
"github.com/nspcc-dev/neofs-node/pkg/util/logger"
"go.uber.org/zap"
)
// Option is a client configuration change function.
type Option func(*cfg)
// groups the configurations with default values.
type cfg struct {
ctx context.Context // neo-go client context
dialTimeout time.Duration // client dial timeout
magic netmode.Magic // type of Neo blockchain network
logger *logger.Logger // logging component
gas util.Uint160 // native gas script-hash
}
const defaultDialTimeout = 5 * time.Second
const defaultMagic = netmode.PrivNet
func defaultConfig() *cfg {
return &cfg{
ctx: context.Background(),
dialTimeout: defaultDialTimeout,
magic: defaultMagic,
logger: zap.L(),
gas: util.Uint160{},
}
}
// New creates, initializes and returns the Client instance.
//
// If private key is nil, crypto.ErrEmptyPrivateKey is returned.
//
// Other values are set according to provided options, or by default:
// * client context: Background;
// * dial timeout: 5s;
// * blockchain network type: netmode.PrivNet;
// * logger: zap.L().
//
// If desired option satisfies the default value, it can be omitted.
// If multiple options of the same config value are supplied,
// the option with the highest index in the arguments will be used.
func New(key *ecdsa.PrivateKey, endpoint string, opts ...Option) (*Client, error) {
if key == nil {
return nil, crypto.ErrEmptyPrivateKey
}
privKeyBytes := crypto.MarshalPrivateKey(key)
wif, err := keys.WIFEncode(privKeyBytes, keys.WIFVersion, true)
if err != nil {
return nil, err
}
account, err := wallet.NewAccountFromWIF(wif)
if err != nil {
return nil, err
}
// build default configuration
cfg := defaultConfig()
// apply options
for _, opt := range opts {
opt(cfg)
}
cli, err := client.New(cfg.ctx, endpoint, client.Options{
DialTimeout: cfg.dialTimeout,
Network: cfg.magic,
})
if err != nil {
return nil, err
}
return &Client{
logger: cfg.logger,
client: cli,
acc: account,
gas: cfg.gas,
}, nil
}
// WithContext returns a client constructor option that
// specifies the neo-go client context.
//
// Ignores nil value.
//
// If option not provided, context.Background() is used.
func WithContext(ctx context.Context) Option {
return func(c *cfg) {
if ctx != nil {
c.ctx = ctx
}
}
}
// WithDialTimeout returns a client constructor option
// that specifies neo-go client dial timeout duration.
//
// Ignores non-positive value.
//
// If option not provided, 5s timeout is used.
func WithDialTimeout(dur time.Duration) Option {
return func(c *cfg) {
if dur > 0 {
c.dialTimeout = dur
}
}
}
// WithMagic returns a client constructor option
// that specifies neo blockchain network type.
//
// If option not provided, netmode.PrivNet is used.
func WithMagic(mag netmode.Magic) Option {
return func(c *cfg) {
c.magic = mag
}
}
// WithLogger returns a client constructor option
// that specifies the component for writing log messages.
//
// Ignores nil value.
//
// If option not provided, zap.L() is used.
func WithLogger(logger *logger.Logger) Option {
return func(c *cfg) {
if logger != nil {
c.logger = logger
}
}
}
// WithGasContract returns a client constructor option
// that specifies native gas contract script hash.
//
// If option not provided, empty script hash is used.
func WithGasContract(gas util.Uint160) Option {
return func(c *cfg) {
c.gas = gas
}
}

View file

@ -0,0 +1,174 @@
package container
import (
"errors"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
)
// Client is a wrapper over StaticClient
// which makes calls with the names and arguments
// of the NeoFS Container contract.
//
// Working client must be created via constructor New.
// Using the Client that has been created with new(Client)
// expression (or just declaring a Client variable) is unsafe
// and can lead to panic.
type Client struct {
client *client.StaticClient // static Container contract client
*cfg // contract method names
}
// ErrNilClient is returned by functions that expect
// a non-nil Client pointer, but received nil.
var ErrNilClient = errors.New("container contract client is nil")
// Option is a client configuration change function.
type Option func(*cfg)
type cfg struct {
putMethod, // put container method name for invocation
deleteMethod, // delete container method name for invocation
getMethod, // get container method name for invocation
listMethod, // list container method name for invocation
setEACLMethod, // set eACL method name for invocation
eaclMethod string // get eACL method name for invocation
}
const (
defaultPutMethod = "Put" // default put container method name
defaultDeleteMethod = "Delete" // default delete container method name
defaultGetMethod = "Get" // default get container method name
defaultListMethod = "List" // default list containers method name
defaultEACLMethod = "EACL" // default get eACL method name
defaultSetEACLMethod = "SetEACL" // default set eACL method name
)
func defaultConfig() *cfg {
return &cfg{
putMethod: defaultPutMethod,
deleteMethod: defaultDeleteMethod,
getMethod: defaultGetMethod,
listMethod: defaultListMethod,
setEACLMethod: defaultSetEACLMethod,
eaclMethod: defaultEACLMethod,
}
}
// New creates, initializes and returns the Client instance.
//
// If StaticClient is nil, client.ErrNilStaticClient is returned.
//
// Other values are set according to provided options, or by default:
// * put container method name: Put;
// * delete container method name: Delete;
// * get container method name: Get;
// * list containers method name: List;
// * set eACL method name: SetEACL;
// * get eACL method name: EACL.
//
// If desired option satisfies the default value, it can be omitted.
// If multiple options of the same config value are supplied,
// the option with the highest index in the arguments will be used.
func New(c *client.StaticClient, opts ...Option) (*Client, error) {
if c == nil {
return nil, client.ErrNilStaticClient
}
res := &Client{
client: c,
cfg: defaultConfig(), // build default configuration
}
// apply options
for _, opt := range opts {
opt(res.cfg)
}
return res, nil
}
// WithPutMethod returns a client constructor option that
// specifies the method name of container storing operation.
//
// Ignores empty value.
//
// If option not provided, "Put" is used.
func WithPutMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.putMethod = n
}
}
}
// WithDeleteMethod returns a client constructor option that
// specifies the method name of container removal operation.
//
// Ignores empty value.
//
// If option not provided, "Delete" is used.
func WithDeleteMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.deleteMethod = n
}
}
}
// WithGetMethod returns a client constructor option that
// specifies the method name of container receiving operation.
//
// Ignores empty value.
//
// If option not provided, "Get" is used.
func WithGetMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.getMethod = n
}
}
}
// WithListMethod returns a client constructor option that
// specifies the method name of container listing operation.
//
// Ignores empty value.
//
// If option not provided, "List" is used.
func WithListMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.listMethod = n
}
}
}
// WithSetEACLMethod returns a client constructor option that
// specifies the method name of eACL storing operation.
//
// Ignores empty value.
//
// If option not provided, "SetEACL" is used.
func WithSetEACLMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.setEACLMethod = n
}
}
}
// WithEACLMethod returns a client constructor option that
// specifies the method name of eACL receiving operation.
//
// Ignores empty value.
//
// If option not provided, "EACL" is used.
func WithEACLMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.eaclMethod = n
}
}
}

View file

@ -0,0 +1,42 @@
package container
import "github.com/pkg/errors"
// DeleteArgs groups the arguments
// of delete container invocation call.
type DeleteArgs struct {
cid []byte // container identifier
ownerID []byte // container owner identifier
sig []byte // container identifier signature
}
// SetOwnerID sets the container owner identifier
// in a binary format.
func (p *DeleteArgs) SetOwnerID(v []byte) {
p.ownerID = v
}
// SetCID sets the container identifier
// in a binary format.
func (p *DeleteArgs) SetCID(v []byte) {
p.cid = v
}
// SetSignature sets the container identifier
// owner's signature.
func (p *DeleteArgs) SetSignature(v []byte) {
p.sig = v
}
// Delete invokes the call of delete container
// method of NeoFS Container contract.
func (c *Client) Delete(args DeleteArgs) error {
return errors.Wrapf(c.client.Invoke(
c.deleteMethod,
args.cid,
args.ownerID,
args.sig,
), "could not invoke method (%s)", c.deleteMethod)
}

View file

@ -0,0 +1,53 @@
package container
import (
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/pkg/errors"
)
// EACLArgs groups the arguments
// of get eACL test invoke call.
type EACLArgs struct {
cid []byte // container identifier
}
// EACLValues groups the stack parameters
// returned by get eACL test invoke.
type EACLValues struct {
eacl []byte // extended ACL table
}
// SetCID sets the container identifier
// in a binary format.
func (g *EACLArgs) SetCID(v []byte) {
g.cid = v
}
// EACL returns the eACL table
// in a binary format.
func (g *EACLValues) EACL() []byte {
return g.eacl
}
// EACL performs the test invoke of get eACL
// method of NeoFS Container contract.
func (c *Client) EACL(args EACLArgs) (*EACLValues, error) {
prms, err := c.client.TestInvoke(
c.eaclMethod,
args.cid,
)
if err != nil {
return nil, errors.Wrapf(err, "could not perform test invocation (%s)", c.eaclMethod)
} else if ln := len(prms); ln != 1 {
return nil, errors.Errorf("unexpected stack item count (%s): %d", c.eaclMethod, ln)
}
eacl, err := client.BytesFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrapf(err, "could not get byte array from stack item (%s)", c.eaclMethod)
}
return &EACLValues{
eacl: eacl,
}, nil
}

View file

@ -0,0 +1,42 @@
package container
import "github.com/pkg/errors"
// SetEACLArgs groups the arguments
// of set eACL invocation call.
type SetEACLArgs struct {
cid []byte // container identifier in a binary format
eacl []byte // extended ACL table
sig []byte // eACL table signature
}
// SetCID sets the container identifier
// in a binary format.
func (p *SetEACLArgs) SetCID(v []byte) {
p.cid = v
}
// SetEACL sets the extended ACL table
// in a binary format.
func (p *SetEACLArgs) SetEACL(v []byte) {
p.eacl = v
}
// SetSignature sets the eACL table structure
// owner's signature.
func (p *SetEACLArgs) SetSignature(v []byte) {
p.sig = v
}
// SetEACL invokes the call of set eACL method
// of NeoFS Container contract.
func (c *Client) SetEACL(args SetEACLArgs) error {
return errors.Wrapf(c.client.Invoke(
c.setEACLMethod,
args.cid,
args.eacl,
args.sig,
), "could not invoke method (%s)", c.setEACLMethod)
}

View file

@ -0,0 +1,53 @@
package container
import (
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/pkg/errors"
)
// GetArgs groups the arguments
// of get container test invoke call.
type GetArgs struct {
cid []byte // container identifier
}
// GetValues groups the stack parameters
// returned by get container test invoke.
type GetValues struct {
cnr []byte // container in a binary form
}
// SetCID sets the container identifier
// in a binary format.
func (g *GetArgs) SetCID(v []byte) {
g.cid = v
}
// Container returns the container
// in a binary format.
func (g *GetValues) Container() []byte {
return g.cnr
}
// Get performs the test invoke of get container
// method of NeoFS Container contract.
func (c *Client) Get(args GetArgs) (*GetValues, error) {
prms, err := c.client.TestInvoke(
c.getMethod,
args.cid,
)
if err != nil {
return nil, errors.Wrapf(err, "could not perform test invocation (%s)", c.getMethod)
} else if ln := len(prms); ln != 1 {
return nil, errors.Errorf("unexpected stack item count (%s): %d", c.getMethod, ln)
}
cnrBytes, err := client.BytesFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrapf(err, "could not get byte array from stack item (%s)", c.getMethod)
}
return &GetValues{
cnr: cnrBytes,
}, nil
}

View file

@ -0,0 +1,70 @@
package container
import (
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/pkg/errors"
)
// ListArgs groups the arguments
// of list containers test invoke call.
type ListArgs struct {
ownerID []byte // container owner identifier
}
// ListValues groups the stack parameters
// returned by list containers test invoke.
type ListValues struct {
cidList [][]byte // list of container identifiers
}
// SetOwnerID sets the container owner identifier
// in a binary format.
func (l *ListArgs) SetOwnerID(v []byte) {
l.ownerID = v
}
// CIDList returns the list of container
// identifiers in a binary format.
func (l *ListValues) CIDList() [][]byte {
return l.cidList
}
// List performs the test invoke of list container
// method of NeoFS Container contract.
func (c *Client) List(args ListArgs) (*ListValues, error) {
invokeArgs := make([]interface{}, 0, 1)
if len(args.ownerID) > 0 {
invokeArgs = append(invokeArgs, args.ownerID)
}
prms, err := c.client.TestInvoke(
c.listMethod,
invokeArgs...,
)
if err != nil {
return nil, errors.Wrapf(err, "could not perform test invocation (%s)", c.listMethod)
} else if ln := len(prms); ln != 1 {
return nil, errors.Errorf("unexpected stack item count (%s): %d", c.listMethod, ln)
}
prms, err = client.ArrayFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrapf(err, "could not get stack item array from stack item (%s)", c.listMethod)
}
res := &ListValues{
cidList: make([][]byte, 0, len(prms)),
}
for i := range prms {
cid, err := client.BytesFromStackParameter(prms[i])
if err != nil {
return nil, errors.Wrapf(err, "could not get byte array from stack item (%s)", c.listMethod)
}
res.cidList = append(res.cidList, cid)
}
return res, nil
}

View file

@ -0,0 +1,44 @@
package container
import (
"github.com/pkg/errors"
)
// PutArgs groups the arguments
// of put container invocation call.
type PutArgs struct {
ownerID []byte // container owner identifier
cnr []byte // container in a binary format
sig []byte // binary container signature
}
// SetOwnerID sets the container owner identifier
// in a binary format.
func (p *PutArgs) SetOwnerID(v []byte) {
p.ownerID = v
}
// SetContainer sets the container structure
// in a binary format.
func (p *PutArgs) SetContainer(v []byte) {
p.cnr = v
}
// SetSignature sets the container structure
// owner's signature.
func (p *PutArgs) SetSignature(v []byte) {
p.sig = v
}
// Put invokes the call of put container method
// of NeoFS Container contract.
func (c *Client) Put(args PutArgs) error {
return errors.Wrapf(c.client.Invoke(
c.putMethod,
args.ownerID,
args.cnr,
args.sig,
), "could not invoke method (%s)", c.putMethod)
}

View file

@ -0,0 +1,148 @@
package wrapper
import (
"github.com/nspcc-dev/neofs-api-go/refs"
"github.com/nspcc-dev/neofs-node/pkg/core/container"
"github.com/nspcc-dev/neofs-node/pkg/core/container/storage"
contract "github.com/nspcc-dev/neofs-node/pkg/morph/client/container"
"github.com/pkg/errors"
)
// OwnerID represents the container owner identifier.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/core/container/storage.OwnerID.
type OwnerID = storage.OwnerID
// Container represents the NeoFS Container structure.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/core/container/storage.Container.
type Container = storage.Container
// Put saves passed container structure in NeoFS system
// through Container contract call.
//
// Returns calculated container identifier and any error
// encountered that caused the saving to interrupt.
func (w *Wrapper) Put(cnr *Container) (*CID, error) {
// calculate container identifier
//
// Note: cid is used as return value only, but the calculation is performed
// primarily in order to catch potential error before contract client call.
cid, err := container.CalculateID(cnr)
if err != nil {
return nil, errors.Wrap(err, "could not calculate container identifier")
}
// marshal the container
cnrBytes, err := cnr.MarshalBinary()
if err != nil {
return nil, errors.Wrap(err, "could not marshal the container")
}
// prepare invocation arguments
args := contract.PutArgs{}
args.SetOwnerID(cnr.OwnerID().Bytes())
args.SetContainer(cnrBytes)
args.SetSignature(nil) // TODO: set signature from request when will appear.
// invoke smart contract call
if err := w.client.Put(args); err != nil {
return nil, errors.Wrap(err, "could not invoke smart contract")
}
return cid, nil
}
// Get reads the container from NeoFS system by identifier
// through Container contract call.
//
// If an empty slice is returned for the requested identifier,
// storage.ErrNotFound error is returned.
func (w *Wrapper) Get(cid CID) (*Container, error) {
// prepare invocation arguments
args := contract.GetArgs{}
args.SetCID(cid.Bytes())
// invoke smart contract call
values, err := w.client.Get(args)
if err != nil {
return nil, errors.Wrap(err, "could not invoke smart contract")
}
cnrBytes := values.Container()
if len(cnrBytes) == 0 {
return nil, storage.ErrNotFound
}
cnr := new(Container)
// unmarshal the container
if err := cnr.UnmarshalBinary(cnrBytes); err != nil {
return nil, errors.Wrap(err, "could not unmarshal container")
}
return cnr, nil
}
// Delete removes the container from NeoFS system
// through Container contract call.
//
// Returns any error encountered that caused
// the removal to interrupt.
func (w *Wrapper) Delete(cid CID) error {
// prepare invocation arguments
args := contract.DeleteArgs{}
args.SetCID(cid.Bytes())
args.SetOwnerID(nil) // TODO: add owner ID when will appear.
args.SetSignature(nil) // TODO: add CID signature when will appear.
// invoke smart contract call
//
// Note: errors.Wrap return nil on nil error arg.
return errors.Wrap(
w.client.Delete(args),
"could not invoke smart contract",
)
}
// List returns a list of container identifiers belonging
// to the specified owner of NeoFS system. The list is composed
// through Container contract call.
//
// Returns the identifiers of all NeoFS containers if pointer
// to owner identifier is nil.
func (w *Wrapper) List(ownerID *OwnerID) ([]CID, error) {
// prepare invocation arguments
args := contract.ListArgs{}
// Note: by default owner identifier slice is nil,
// so client won't attach invocation arguments.
// This behavior matches the nil argument of current method.
// If argument is not nil, we must specify owner identifier.
if ownerID != nil {
args.SetOwnerID(ownerID.Bytes())
}
// invoke smart contract call
values, err := w.client.List(args)
if err != nil {
return nil, errors.Wrap(err, "could not invoke smart contract")
}
binCIDList := values.CIDList()
cidList := make([]CID, 0, len(binCIDList))
// unmarshal all container identifiers
for i := range binCIDList {
cid, err := refs.CIDFromBytes(binCIDList[i])
if err != nil {
return nil, errors.Wrapf(err, "could not decode container ID #%d", i)
}
cidList = append(cidList, cid)
}
return cidList, nil
}

View file

@ -0,0 +1,51 @@
package wrapper
import (
eacl "github.com/nspcc-dev/neofs-api-go/acl/extended"
"github.com/nspcc-dev/neofs-node/pkg/core/container/acl/extended/storage"
contract "github.com/nspcc-dev/neofs-node/pkg/morph/client/container"
"github.com/pkg/errors"
)
// Table represents extended ACL rule table.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/core/container/acl/extended/storage.Table.
type Table = storage.Table
// GetEACL reads the extended ACL table from NeoFS system
// through Container contract call.
func (w *Wrapper) GetEACL(cid CID) (Table, error) {
// prepare invocation arguments
args := contract.EACLArgs{}
args.SetCID(cid.Bytes())
// invoke smart contract call
values, err := w.client.EACL(args)
if err != nil {
return nil, errors.Wrap(err, "could not invoke smart contract")
}
// unmarshal and return eACL table
return eacl.UnmarshalTable(values.EACL())
}
// PutEACL saves the extended ACL table in NeoFS system
// through Container contract call.
//
// Returns any error encountered that caused the saving to interrupt.
func (w *Wrapper) PutEACL(cid CID, table Table, sig []byte) error {
// prepare invocation arguments
args := contract.SetEACLArgs{}
args.SetEACL(eacl.MarshalTable(table))
args.SetCID(cid.Bytes())
args.SetSignature(sig)
// invoke smart contract call
//
// Note: errors.Wrap return nil on nil error arg.
return errors.Wrap(
w.client.SetEACL(args),
"could not invoke smart contract",
)
}

View file

@ -0,0 +1,43 @@
package wrapper
import (
"github.com/nspcc-dev/neofs-node/pkg/core/container/storage"
"github.com/nspcc-dev/neofs-node/pkg/morph/client/container"
)
// Client represents the Container contract client.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/morph/client/container.Client.
type Client = container.Client
// CID represents the container identifier.
//
// CID is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/core/container/storage.CID.
type CID = storage.CID
// Wrapper is a wrapper over container contract
// client which implements container storage and
// eACL storage methods.
//
// Working wrapper must be created via constructor New.
// Using the Wrapper that has been created with new(Wrapper)
// expression (or just declaring a Wrapper variable) is unsafe
// and can lead to panic.
type Wrapper struct {
client *Client
}
// New creates, initializes and returns the Wrapper instance.
//
// If Client is nil, container.ErrNilClient is returned.
func New(c *Client) (*Wrapper, error) {
if c == nil {
return nil, container.ErrNilClient
}
return &Wrapper{
client: c,
}, nil
}

View file

@ -0,0 +1,104 @@
package netmap
import (
"github.com/pkg/errors"
)
// PeerInfo groups the parameters of
// new NeoFS peer.
type PeerInfo struct {
address []byte // peer network address in a binary format
key []byte // peer public key
opts [][]byte // binary peer options
}
// AddPeerArgs groups the arguments
// of add peer invocation call.
type AddPeerArgs struct {
info PeerInfo // peer information
}
const addPeerFixedArgNumber = 2
// Address returns the peer network address
// in a binary format.
//
// Address format is dictated by application
// architecture.
func (a PeerInfo) Address() []byte {
return a.address
}
// SetAddress sets the peer network address
// in a binary format.
//
// Address format is dictated by application
// architecture.
func (a *PeerInfo) SetAddress(v []byte) {
a.address = v
}
// PublicKey returns the peer public key
// in a binary format.
//
// Key format is dictated by application
// architecture.
func (a PeerInfo) PublicKey() []byte {
return a.key
}
// SetPublicKey sets the peer public key
// in a binary format.
//
// Key format is dictated by application
// architecture.
func (a *PeerInfo) SetPublicKey(v []byte) {
a.key = v
}
// Options returns the peer options
// in a binary format.
//
// Option format is dictated by application
// architecture.
func (a PeerInfo) Options() [][]byte {
return a.opts
}
// SetOptions sets the peer options
// in a binary format.
//
// Option format is dictated by application
// architecture.
func (a *PeerInfo) SetOptions(v [][]byte) {
a.opts = v
}
// SetInfo sets the peer information.
func (a *AddPeerArgs) SetInfo(v PeerInfo) {
a.info = v
}
// AddPeer invokes the call of add peer method
// of NeoFS Netmap contract.
func (c *Client) AddPeer(args AddPeerArgs) error {
info := args.info
invokeArgs := make([]interface{}, 0, addPeerFixedArgNumber+len(info.opts))
invokeArgs = append(invokeArgs,
info.address,
info.key,
)
for i := range info.opts {
invokeArgs = append(invokeArgs, info.opts[i])
}
return errors.Wrapf(c.client.Invoke(
c.addPeerMethod,
invokeArgs...,
), "could not invoke method (%s)", c.addPeerMethod)
}

View file

@ -0,0 +1,156 @@
package netmap
import (
"errors"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
)
// Client is a wrapper over StaticClient
// which makes calls with the names and arguments
// of the NeoFS Netmap contract.
//
// Working client must be created via constructor New.
// Using the Client that has been created with new(Client)
// expression (or just declaring a Client variable) is unsafe
// and can lead to panic.
type Client struct {
client *client.StaticClient // static Netmap contract client
*cfg // contract method names
}
// ErrNilClient is returned by functions that expect
// a non-nil Client pointer, but received nil.
var ErrNilClient = errors.New("netmap contract client is nil")
// Option is a client configuration change function.
type Option func(*cfg)
type cfg struct {
addPeerMethod, // add peer method name for invocation
newEpochMethod, // new epoch method name for invocation
netMapMethod, // get network map method name
updateStateMethod, // update state method name for invocation
innerRingListMethod string // IR list method name for invocation
}
const (
defaultAddPeerMethod = "AddPeer" // default add peer method name
defaultNewEpochMethod = "NewEpoch" // default new epoch method name
defaultNetMapMethod = "Netmap" // default get network map method name
defaultUpdateStateMethod = "UpdateState" // default update state method name
defaultInnerRIngListMethod = "InnerRingList" // default IR list method name
)
func defaultConfig() *cfg {
return &cfg{
addPeerMethod: defaultAddPeerMethod,
newEpochMethod: defaultNewEpochMethod,
netMapMethod: defaultNetMapMethod,
updateStateMethod: defaultUpdateStateMethod,
innerRingListMethod: defaultInnerRIngListMethod,
}
}
// New creates, initializes and returns the Client instance.
//
// If StaticClient is nil, client.ErrNilStaticClient is returned.
//
// Other values are set according to provided options, or by default:
// * add peer method name: AddPeer;
// * new epoch method name: NewEpoch;
// * get network map method name: Netmap;
// * update state method name: UpdateState;
// * inner ring list method name: InnerRingList.
//
// If desired option satisfies the default value, it can be omitted.
// If multiple options of the same config value are supplied,
// the option with the highest index in the arguments will be used.
func New(c *client.StaticClient, opts ...Option) (*Client, error) {
if c == nil {
return nil, client.ErrNilStaticClient
}
res := &Client{
client: c,
cfg: defaultConfig(), // build default configuration
}
// apply options
for _, opt := range opts {
opt(res.cfg)
}
return res, nil
}
// WithAddPeerMethod returns a client constructor option that
// specifies the method name of adding peer operation.
//
// Ignores empty value.
//
// If option not provided, "AddPeer" is used.
func WithAddPeerMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.addPeerMethod = n
}
}
}
// WithNewEpochMethod returns a client constructor option that
// specifies the method name of new epoch operation.
//
// Ignores empty value.
//
// If option not provided, "NewEpoch" is used.
func WithNewEpochMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.newEpochMethod = n
}
}
}
// WithNetMapMethod returns a client constructor option that
// specifies the method name of network map receiving operation.
//
// Ignores empty value.
//
// If option not provided, "Netmap" is used.
func WithNetMapMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.netMapMethod = n
}
}
}
// WithUpdateStateMethod returns a client constructor option that
// specifies the method name of peer state updating operation.
//
// Ignores empty value.
//
// If option not provided, "UpdateState" is used.
func WithUpdateStateMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.updateStateMethod = n
}
}
}
// WithInnerRingListMethod returns a client constructor option that
// specifies the method name of inner ring listing operation.
//
// Ignores empty value.
//
// If option not provided, "InnerRingList" is used.
func WithInnerRingListMethod(n string) Option {
return func(c *cfg) {
if n != "" {
c.innerRingListMethod = n
}
}
}

View file

@ -0,0 +1,61 @@
package netmap
import (
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/pkg/errors"
)
// InnerRingListArgs groups the arguments
// of inner ring list test invoke call.
type InnerRingListArgs struct {
}
// InnerRingListValues groups the stack parameters
// returned by inner ring list test invoke.
type InnerRingListValues struct {
keys [][]byte // list of keys of IR nodes in a binary format
}
// KeyList return the list of IR node keys
// in a binary format.
func (g InnerRingListValues) KeyList() [][]byte {
return g.keys
}
// InnerRingList performs the test invoke of inner ring list
// method of NeoFS Netmap contract.
func (c *Client) InnerRingList(args InnerRingListArgs) (*InnerRingListValues, error) {
prms, err := c.client.TestInvoke(
c.innerRingListMethod,
)
if err != nil {
return nil, errors.Wrapf(err, "could not perform test invocation (%s)", c.innerRingListMethod)
} else if ln := len(prms); ln != 1 {
return nil, errors.Errorf("unexpected stack item count (%s): %d", c.innerRingListMethod, ln)
}
prms, err = client.ArrayFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrapf(err, "could not get stack item array from stack item (%s)", c.innerRingListMethod)
}
res := &InnerRingListValues{
keys: make([][]byte, 0, len(prms)),
}
for i := range prms {
nodePrms, err := client.ArrayFromStackParameter(prms[i])
if err != nil {
return nil, errors.Wrap(err, "could not get stack item array (Node #%d)")
}
key, err := client.BytesFromStackParameter(nodePrms[0])
if err != nil {
return nil, errors.Wrapf(err, "could not parse stack item (Key #%d)", i)
}
res.keys = append(res.keys, key)
}
return res, nil
}

View file

@ -0,0 +1,99 @@
package netmap
import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/pkg/errors"
)
// GetNetMapArgs groups the arguments
// of get network map test invoke call.
type GetNetMapArgs struct {
}
// GetNetMapValues groups the stack parameters
// returned by get network map test invoke.
type GetNetMapValues struct {
peers []PeerInfo // peer list in a binary format
}
const nodeInfoFixedPrmNumber = 3
// Peers return the list of peers from
// network map in a binary format.
func (g GetNetMapValues) Peers() []PeerInfo {
return g.peers
}
// NetMap performs the test invoke of get network map
// method of NeoFS Netmap contract.
func (c *Client) NetMap(args GetNetMapArgs) (*GetNetMapValues, error) {
prms, err := c.client.TestInvoke(
c.netMapMethod,
)
if err != nil {
return nil, errors.Wrapf(err, "could not perform test invocation (%s)", c.netMapMethod)
} else if ln := len(prms); ln != 1 {
return nil, errors.Errorf("unexpected stack item count (%s): %d", c.netMapMethod, ln)
}
prms, err = client.ArrayFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrapf(err, "could not get stack item array from stack item (%s)", c.netMapMethod)
}
res := &GetNetMapValues{
peers: make([]PeerInfo, 0, len(prms)),
}
for i := range prms {
peer, err := peerInfoFromStackItem(prms[i])
if err != nil {
return nil, errors.Wrapf(err, "could not parse stack item (Peer #%d)", i)
}
res.peers = append(res.peers, *peer)
}
return res, nil
}
func peerInfoFromStackItem(prm smartcontract.Parameter) (*PeerInfo, error) {
prms, err := client.ArrayFromStackParameter(prm)
if err != nil {
return nil, errors.Wrapf(err, "could not get stack item array (PeerInfo)")
} else if ln := len(prms); ln != nodeInfoFixedPrmNumber {
return nil, errors.Errorf("unexpected stack item count (PeerInfo): expected %d, has %d", 3, ln)
}
res := new(PeerInfo)
// Address
res.address, err = client.BytesFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrap(err, "could not get byte array from stack item (Address)")
}
// Public key
if res.key, err = client.BytesFromStackParameter(prms[1]); err != nil {
return nil, errors.Wrap(err, "could not get byte array from stack item (Public key)")
}
// Options
if prms, err = client.ArrayFromStackParameter(prms[2]); err != nil {
return nil, errors.Wrapf(err, "could not get stack item array (Options)")
}
res.opts = make([][]byte, 0, len(prms))
for i := range prms {
opt, err := client.BytesFromStackParameter(prms[i])
if err != nil {
return nil, errors.Wrapf(err, "could not get byte array from stack item (Option #%d)", i)
}
res.opts = append(res.opts, opt)
}
return res, nil
}

View file

@ -0,0 +1,23 @@
package netmap
import "github.com/pkg/errors"
// NewEpochArgs groups the arguments
// of new epoch invocation call.
type NewEpochArgs struct {
number int64 // new epoch number
}
// SetEpochNumber sets the new epoch number.
func (a *NewEpochArgs) SetEpochNumber(v int64) {
a.number = v
}
// NewEpoch invokes the call of new epoch method
// of NeoFS Netmap contract.
func (c *Client) NewEpoch(args NewEpochArgs) error {
return errors.Wrapf(c.client.Invoke(
c.addPeerMethod,
args.number,
), "could not invoke method (%s)", c.newEpochMethod)
}

View file

@ -0,0 +1,34 @@
package netmap
import (
"github.com/pkg/errors"
)
// UpdateStateArgs groups the arguments
// of update state invocation call.
type UpdateStateArgs struct {
key []byte // peer public key
state int64 // new peer state
}
// SetPublicKey sets peer public key
// in a binary format.
func (u *UpdateStateArgs) SetPublicKey(v []byte) {
u.key = v
}
// SetState sets the new peer state.
func (u *UpdateStateArgs) SetState(v int64) {
u.state = v
}
// UpdateState invokes the call of update state method
// of NeoFS Netmap contract.
func (c *Client) UpdateState(args UpdateStateArgs) error {
return errors.Wrapf(c.client.Invoke(
c.addPeerMethod,
args.key,
args.state,
), "could not invoke method (%s)", c.updateStateMethod)
}

View file

@ -0,0 +1,37 @@
package wrapper
import (
"github.com/nspcc-dev/neofs-node/pkg/core/netmap"
contract "github.com/nspcc-dev/neofs-node/pkg/morph/client/netmap"
"github.com/pkg/errors"
)
// AddPeer registers peer in NeoFS network through
// Netmap contract call.
func (w *Wrapper) AddPeer(nodeInfo netmap.Info) error {
// prepare invocation arguments
args := contract.AddPeerArgs{}
info := contract.PeerInfo{}
info.SetPublicKey(nodeInfo.PublicKey())
info.SetAddress([]byte(nodeInfo.Address()))
opts := nodeInfo.Options()
binOpts := make([][]byte, 0, len(opts))
for i := range opts {
binOpts = append(binOpts, []byte(opts[i]))
}
info.SetOptions(binOpts)
args.SetInfo(info)
// invoke smart contract call
//
// Note: errors.Wrap returns nil on nil error arg.
return errors.Wrap(
w.client.AddPeer(args),
"could not invoke smart contract",
)
}

View file

@ -0,0 +1,21 @@
package wrapper
import (
contract "github.com/nspcc-dev/neofs-node/pkg/morph/client/netmap"
"github.com/pkg/errors"
)
// InnerRingKeys receives public key list of inner
// ring nodes through Netmap contract call and returns it.
func (w *Wrapper) InnerRingKeys() ([][]byte, error) {
// prepare invocation arguments
args := contract.InnerRingListArgs{}
// invoke smart contract call
values, err := w.client.InnerRingList(args)
if err != nil {
return nil, errors.Wrap(err, "could not invoke smart contract")
}
return values.KeyList(), nil
}

View file

@ -0,0 +1,60 @@
package wrapper
import (
"github.com/nspcc-dev/neofs-node/pkg/core/netmap"
contract "github.com/nspcc-dev/neofs-node/pkg/morph/client/netmap"
"github.com/pkg/errors"
)
// NetMap represents the NeoFS network map.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/core/NetMap.
type NetMap = netmap.NetMap
// Info represents node information.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/core/netmap.Info.
type Info = netmap.Info
// GetNetMap receives information list about storage nodes
// through the Netmap contract call, composes network map
// from them and returns it.
func (w *Wrapper) GetNetMap() (*NetMap, error) {
// prepare invocation arguments
args := contract.GetNetMapArgs{}
// invoke smart contract call
values, err := w.client.NetMap(args)
if err != nil {
return nil, errors.Wrap(err, "could not invoke smart contract")
}
// parse response and fill the network map
nm := netmap.New()
peerList := values.Peers()
for i := range peerList {
info := Info{}
info.SetPublicKey(peerList[i].PublicKey())
info.SetAddress(string(peerList[i].Address()))
binOpts := peerList[i].Options()
opts := make([]string, 0, len(binOpts))
for j := range binOpts {
opts = append(opts, string(binOpts[j]))
}
info.SetOptions(opts)
if err := nm.AddNode(info); err != nil {
return nil, errors.Wrapf(err, "could not add node #%d to network map", i)
}
}
return nm, nil
}

View file

@ -0,0 +1,23 @@
package wrapper
import (
"github.com/nspcc-dev/neofs-node/pkg/core/netmap/epoch"
contract "github.com/nspcc-dev/neofs-node/pkg/morph/client/netmap"
"github.com/pkg/errors"
)
// NewEpoch updates NeoFS epoch number through
// Netmap contract call.
func (w *Wrapper) NewEpoch(e epoch.Epoch) error {
// prepare invocation arguments
args := contract.NewEpochArgs{}
args.SetEpochNumber(int64(epoch.ToUint64(e)))
// invoke smart contract call
//
// Note: errors.Wrap returns nil on nil error arg.
return errors.Wrap(
w.client.NewEpoch(args),
"could not invoke smart contract",
)
}

View file

@ -0,0 +1,32 @@
package wrapper
import (
contract "github.com/nspcc-dev/neofs-node/pkg/morph/client/netmap"
"github.com/pkg/errors"
)
// NodeState is a type of node states enumeration.
type NodeState int64
const (
_ NodeState = iota
// StateOffline is an offline node state value.
StateOffline
)
// UpdatePeerState changes peer status through Netmap contract
// call.
func (w *Wrapper) UpdatePeerState(key []byte, state NodeState) error {
args := contract.UpdateStateArgs{}
args.SetPublicKey(key)
args.SetState(int64(state))
// invoke smart contract call
//
// Note: errors.Wrap returns nil on nil error arg.
return errors.Wrap(
w.client.UpdateState(args),
"could not invoke smart contract",
)
}

View file

@ -0,0 +1,43 @@
package wrapper
import (
"errors"
"github.com/nspcc-dev/neofs-node/pkg/morph/client/netmap"
)
// Client represents the Netmap contract client.
//
// It is a type alias of
// github.com/nspcc-dev/neofs-node/pkg/morph/client/netmap.Client.
type Client = netmap.Client
// Wrapper is a wrapper over netmap contract
// client which implements:
// * network map storage;
// * tool for peer state updating.
//
// Working wrapper must be created via constructor New.
// Using the Wrapper that has been created with new(Wrapper)
// expression (or just declaring a Wrapper variable) is unsafe
// and can lead to panic.
type Wrapper struct {
client *Client
}
// ErrNilWrapper is returned by functions that expect
// a non-nil Wrapper pointer, but received nil.
var ErrNilWrapper = errors.New("netmap contract client wrapper is nil")
// New creates, initializes and returns the Wrapper instance.
//
// If Client is nil, netmap.ErrNilClient is returned.
func New(c *Client) (*Wrapper, error) {
if c == nil {
return nil, netmap.ErrNilClient
}
return &Wrapper{
client: c,
}, nil
}

View file

@ -0,0 +1,62 @@
package client
import (
"errors"
sc "github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
)
// StaticClient is a wrapper over Neo:Morph client
// that invokes single smart contract methods with fixed fee.
//
// Working static client must be created via constructor NewStatic.
// Using the StaticClient that has been created with new(StaticClient)
// expression (or just declaring a StaticClient variable) is unsafe
// and can lead to panic.
type StaticClient struct {
client *Client // neo-go client instance
scScriptHash util.Uint160 // contract script-hash
fee util.Fixed8 // invocation fee
}
// ErrNilStaticClient is returned by functions that expect
// a non-nil StaticClient pointer, but received nil.
var ErrNilStaticClient = errors.New("static client is nil")
// NewStatic creates, initializes and returns the StaticClient instance.
//
// If provided Client instance is nil, ErrNilClient is returned.
func NewStatic(client *Client, scriptHash util.Uint160, fee util.Fixed8) (*StaticClient, error) {
if client == nil {
return nil, ErrNilClient
}
return &StaticClient{
client: client,
scScriptHash: scriptHash,
fee: fee,
}, nil
}
// Invoke calls Invoke method of Client with static internal script hash and fee.
// Supported args types are the same as in Client.
func (s StaticClient) Invoke(method string, args ...interface{}) error {
return s.client.Invoke(
s.scScriptHash,
s.fee,
method,
args...,
)
}
// TestInvoke calls TestInvoke method of Client with static internal script hash.
func (s StaticClient) TestInvoke(method string, args ...interface{}) ([]sc.Parameter, error) {
return s.client.TestInvoke(
s.scScriptHash,
method,
args...,
)
}

128
pkg/morph/client/util.go Normal file
View file

@ -0,0 +1,128 @@
package client
import (
"encoding/binary"
sc "github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/pkg/errors"
)
/*
Use these function to parse stack parameters obtained from `TestInvoke`
function to native go types. You should know upfront return types of invoked
method.
*/
// BoolFromStackParameter receives boolean value from the value of a smart contract parameter.
func BoolFromStackParameter(param sc.Parameter) (bool, error) {
switch param.Type {
case sc.BoolType:
val, ok := param.Value.(bool)
if !ok {
return false, errors.Errorf("chain/client: can't convert %T to boolean", param.Value)
}
return val, nil
case sc.IntegerType:
val, ok := param.Value.(int64)
if !ok {
return false, errors.Errorf("chain/client: can't convert %T to boolean", param.Value)
}
return val > 0, nil
case sc.ByteArrayType:
val, ok := param.Value.([]byte)
if !ok {
return false, errors.Errorf("chain/client: can't convert %T to boolean", param.Value)
}
return len(val) != 0, nil
default:
return false, errors.Errorf("chain/client: %s is not a bool type", param.Type)
}
}
// IntFromStackParameter receives numerical value from the value of a smart contract parameter.
func IntFromStackParameter(param sc.Parameter) (int64, error) {
switch param.Type {
case sc.IntegerType:
val, ok := param.Value.(int64)
if !ok {
return 0, errors.Errorf("chain/client: can't convert %T to integer", param.Value)
}
return val, nil
case sc.ByteArrayType:
val, ok := param.Value.([]byte)
if !ok || len(val) > 8 {
return 0, errors.Errorf("chain/client: can't convert %T to integer", param.Value)
}
res := make([]byte, 8)
copy(res[:len(val)], val)
return int64(binary.LittleEndian.Uint64(res)), nil
default:
return 0, errors.Errorf("chain/client: %s is not an integer type", param.Type)
}
}
// BytesFromStackParameter receives binary value from the value of a smart contract parameter.
func BytesFromStackParameter(param sc.Parameter) ([]byte, error) {
if param.Type != sc.ByteArrayType {
if param.Type == sc.AnyType && param.Value == nil {
return nil, nil
}
return nil, errors.Errorf("chain/client: %s is not a byte array type", param.Type)
}
val, ok := param.Value.([]byte)
if !ok {
return nil, errors.Errorf("chain/client: can't convert %T to byte slice", param.Value)
}
return val, nil
}
// ArrayFromStackParameter returns the slice contract parameters from passed parameter.
//
// If passed parameter carries boolean false value, (nil, nil) returns.
func ArrayFromStackParameter(param sc.Parameter) ([]sc.Parameter, error) {
if param.Type == sc.BoolType && !param.Value.(bool) {
return nil, nil
}
if param.Type != sc.ArrayType {
return nil, errors.Errorf("chain/client: %s is not an array type", param.Type)
}
val, ok := param.Value.([]sc.Parameter)
if !ok {
return nil, errors.Errorf("chain/client: can't convert %T to parameter slice", param.Value)
}
return val, nil
}
// StringFromStackParameter receives string value from the value of a smart contract parameter.
func StringFromStackParameter(param sc.Parameter) (string, error) {
switch param.Type {
case sc.StringType:
val, ok := param.Value.(string)
if !ok {
return "", errors.Errorf("chain/client: can't convert %T to string", param.Value)
}
return val, nil
case sc.ByteArrayType:
val, ok := param.Value.([]byte)
if !ok {
return "", errors.Errorf("chain/client: can't convert %T to string", param.Value)
}
return string(val), nil
default:
return "", errors.Errorf("chain/client: %s is not a string type", param.Type)
}
}

View file

@ -0,0 +1,145 @@
package client
import (
"testing"
sc "github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/stretchr/testify/require"
)
var (
stringParam = sc.Parameter{
Type: sc.StringType,
Value: "Hello World",
}
intParam = sc.Parameter{
Type: sc.IntegerType,
Value: int64(1),
}
byteWithIntParam = sc.Parameter{
Type: sc.ByteArrayType,
Value: []byte{0x0a},
}
byteArrayParam = sc.Parameter{
Type: sc.ByteArrayType,
Value: []byte("Hello World"),
}
emptyByteArrayParam = sc.Parameter{
Type: sc.ByteArrayType,
Value: []byte{},
}
trueBoolParam = sc.Parameter{
Type: sc.BoolType,
Value: true,
}
falseBoolParam = sc.Parameter{
Type: sc.BoolType,
Value: false,
}
arrayParam = sc.Parameter{
Type: sc.ArrayType,
Value: []sc.Parameter{intParam, byteArrayParam},
}
)
func TestBoolFromStackParameter(t *testing.T) {
t.Run("true assert", func(t *testing.T) {
val, err := BoolFromStackParameter(trueBoolParam)
require.NoError(t, err)
require.True(t, val)
val, err = BoolFromStackParameter(intParam)
require.NoError(t, err)
require.True(t, val)
})
t.Run("false assert", func(t *testing.T) {
val, err := BoolFromStackParameter(falseBoolParam)
require.NoError(t, err)
require.False(t, val)
val, err = BoolFromStackParameter(emptyByteArrayParam)
require.NoError(t, err)
require.False(t, val)
})
t.Run("incorrect assert", func(t *testing.T) {
_, err := BoolFromStackParameter(stringParam)
require.Error(t, err)
})
}
func TestArrayFromStackParameter(t *testing.T) {
t.Run("correct assert", func(t *testing.T) {
val, err := ArrayFromStackParameter(arrayParam)
require.NoError(t, err)
require.Len(t, val, len(arrayParam.Value.([]sc.Parameter)))
})
t.Run("incorrect assert", func(t *testing.T) {
_, err := ArrayFromStackParameter(byteArrayParam)
require.Error(t, err)
})
t.Run("boolean false case", func(t *testing.T) {
val, err := ArrayFromStackParameter(falseBoolParam)
require.NoError(t, err)
require.Nil(t, val)
})
}
func TestBytesFromStackParameter(t *testing.T) {
t.Run("correct assert", func(t *testing.T) {
val, err := BytesFromStackParameter(byteArrayParam)
require.NoError(t, err)
require.Equal(t, byteArrayParam.Value.([]byte), val)
})
t.Run("incorrect assert", func(t *testing.T) {
_, err := BytesFromStackParameter(stringParam)
require.Error(t, err)
})
}
func TestIntFromStackParameter(t *testing.T) {
t.Run("correct assert", func(t *testing.T) {
val, err := IntFromStackParameter(intParam)
require.NoError(t, err)
require.Equal(t, intParam.Value.(int64), val)
val, err = IntFromStackParameter(byteWithIntParam)
require.NoError(t, err)
require.Equal(t, int64(0x0a), val)
val, err = IntFromStackParameter(emptyByteArrayParam)
require.NoError(t, err)
require.Equal(t, int64(0), val)
})
t.Run("incorrect assert", func(t *testing.T) {
_, err := IntFromStackParameter(byteArrayParam)
require.Error(t, err)
})
}
func TestStringFromStackParameter(t *testing.T) {
t.Run("correct assert", func(t *testing.T) {
val, err := StringFromStackParameter(stringParam)
require.NoError(t, err)
require.Equal(t, stringParam.Value.(string), val)
val, err = StringFromStackParameter(byteArrayParam)
require.NoError(t, err)
require.Equal(t, string(byteArrayParam.Value.([]byte)), val)
})
t.Run("incorrect assert", func(t *testing.T) {
_, err := StringFromStackParameter(intParam)
require.Error(t, err)
})
}

View file

@ -0,0 +1,90 @@
package balance
import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/pkg/errors"
)
// Lock structure of balance.Lock notification from morph chain.
type Lock struct {
id []byte
user util.Uint160
lock util.Uint160
amount int64 // Fixed16
until int64
}
// MorphEvent implements Neo:Morph Event interface.
func (Lock) MorphEvent() {}
// ID is a withdraw transaction hash.
func (l Lock) ID() []byte { return l.id }
// User returns withdraw receiver script hash from main net.
func (l Lock) User() util.Uint160 { return l.user }
// LockAccount return script hash for balance contract wallet.
func (l Lock) LockAccount() util.Uint160 { return l.lock }
// Amount of the locked assets.
func (l Lock) Amount() int64 { return l.amount }
// Until is a epoch before locked account exists.
func (l Lock) Until() int64 { return l.until }
// ParseLock from notification into lock structure.
func ParseLock(params []smartcontract.Parameter) (event.Event, error) {
var (
ev Lock
err error
)
if ln := len(params); ln != 5 {
return nil, event.WrongNumberOfParameters(5, ln)
}
// parse id
ev.id, err = client.BytesFromStackParameter(params[0])
if err != nil {
return nil, errors.Wrap(err, "could not get lock id")
}
// parse user
user, err := client.BytesFromStackParameter(params[1])
if err != nil {
return nil, errors.Wrap(err, "could not get lock user value")
}
ev.user, err = util.Uint160DecodeBytesBE(user)
if err != nil {
return nil, errors.Wrap(err, "could not convert lock user value to uint160")
}
// parse lock account
lock, err := client.BytesFromStackParameter(params[2])
if err != nil {
return nil, errors.Wrap(err, "could not get lock account value")
}
ev.lock, err = util.Uint160DecodeBytesBE(lock)
if err != nil {
return nil, errors.Wrap(err, "could not convert lock account value to uint160")
}
// parse amount
ev.amount, err = client.IntFromStackParameter(params[3])
if err != nil {
return nil, errors.Wrap(err, "could not get lock amount")
}
// parse until deadline
ev.until, err = client.IntFromStackParameter(params[4])
if err != nil {
return nil, errors.Wrap(err, "could not get lock deadline")
}
return ev, nil
}

View file

@ -0,0 +1,155 @@
package balance
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/stretchr/testify/require"
)
func TestParseLock(t *testing.T) {
var (
id = []byte("Hello World")
user = util.Uint160{0x1, 0x2, 0x3}
lock = util.Uint160{0x3, 0x2, 0x1}
amount int64 = 10
until int64 = 20
)
t.Run("wrong number of parameters", func(t *testing.T) {
prms := []smartcontract.Parameter{
{},
{},
}
_, err := ParseLock(prms)
require.EqualError(t, err, event.WrongNumberOfParameters(5, len(prms)).Error())
})
t.Run("wrong id parameter", func(t *testing.T) {
_, err := ParseLock([]smartcontract.Parameter{
{
Type: smartcontract.IntegerType,
},
})
require.Error(t, err)
})
t.Run("wrong from parameter", func(t *testing.T) {
_, err := ParseLock([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.IntegerType,
},
})
require.Error(t, err)
})
t.Run("wrong lock parameter", func(t *testing.T) {
_, err := ParseLock([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong amount parameter", func(t *testing.T) {
_, err := ParseLock([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.ByteArrayType,
Value: lock.BytesBE(),
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong until parameter", func(t *testing.T) {
_, err := ParseLock([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.ByteArrayType,
Value: lock.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("correct behavior", func(t *testing.T) {
ev, err := ParseLock([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.ByteArrayType,
Value: lock.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.IntegerType,
Value: until,
},
})
require.NoError(t, err)
require.Equal(t, Lock{
id: id,
user: user,
lock: lock,
amount: amount,
until: until,
}, ev)
})
}

31
pkg/morph/event/event.go Normal file
View file

@ -0,0 +1,31 @@
package event
// Type is a notification event enumeration type.
type Type string
// Event is an interface that is
// provided by Neo:Morph event structures.
type Event interface {
MorphEvent()
}
// Equal compares two Type values and
// returns true if they are equal.
func (t Type) Equal(t2 Type) bool {
return string(t) == string(t2)
}
// String returns casted to string Type.
func (t Type) String() string {
return string(t)
}
// TypeFromBytes converts bytes slice to Type.
func TypeFromBytes(data []byte) Type {
return Type(data)
}
// TypeFromString converts string to Type.
func TypeFromString(str string) Type {
return Type(str)
}

View file

@ -0,0 +1,23 @@
package event
// Handler is an Event processing function.
type Handler func(Event)
// HandlerInfo is a structure that groups
// the parameters of the handler of particular
// contract event.
type HandlerInfo struct {
scriptHashWithType
h Handler
}
// SetHandler is an event handler setter.
func (s *HandlerInfo) SetHandler(v Handler) {
s.h = v
}
// Handler returns an event handler.
func (s HandlerInfo) Handler() Handler {
return s.h
}

316
pkg/morph/event/listener.go Normal file
View file

@ -0,0 +1,316 @@
package event
import (
"context"
"sync"
"github.com/nspcc-dev/neo-go/pkg/rpc/response/result"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/nspcc-dev/neofs-node/pkg/morph/subscriber"
"github.com/pkg/errors"
"go.uber.org/zap"
)
// Listener is an interface of smart contract notification event listener.
type Listener interface {
// Must start the event listener.
//
// Must listen to events with the parser installed.
//
// Must return an error if event listening could not be started.
Listen(context.Context)
// Must set the parser of particular contract event.
//
// Parser of each event must be set once. All parsers must be set before Listen call.
//
// Must ignore nil parsers and all calls after listener has been started.
SetParser(ParserInfo)
// Must register the event handler for particular notification event of contract.
//
// The specified handler must be called after each capture and parsing of the event
//
// Must ignore nil handlers.
RegisterHandler(HandlerInfo)
// Must stop the event listener.
Stop()
}
// ListenerParams is a group of parameters
// for Listener constructor.
type ListenerParams struct {
Logger *zap.Logger
Subscriber subscriber.Subscriber
}
type listener struct {
mtx *sync.RWMutex
once *sync.Once
started bool
parsers map[scriptHashWithType]Parser
handlers map[scriptHashWithType][]Handler
log *zap.Logger
subscriber subscriber.Subscriber
}
const newListenerFailMsg = "could not instantiate Listener"
var (
errNilLogger = errors.New("nil logger")
errNilSubscriber = errors.New("nil event subscriber")
)
// Listen starts the listening for events with registered handlers.
//
// Executes once, all subsequent calls do nothing.
//
// Returns an error if listener was already started.
func (s listener) Listen(ctx context.Context) {
s.once.Do(func() {
if err := s.listen(ctx); err != nil {
s.log.Error("could not start listen to events",
zap.String("error", err.Error()),
)
}
})
}
func (s listener) listen(ctx context.Context) error {
// create the list of listening contract hashes
hashes := make([]util.Uint160, 0)
// fill the list with the contracts with set event parsers.
s.mtx.RLock()
for hashType := range s.parsers {
scHash := hashType.ScriptHash()
// prevent repetitions
for _, hash := range hashes {
if hash.Equals(scHash) {
continue
}
}
hashes = append(hashes, hashType.ScriptHash())
}
// mark listener as started
s.started = true
s.mtx.RUnlock()
chEvent, err := s.subscriber.SubscribeForNotification(hashes...)
if err != nil {
return err
}
s.listenLoop(ctx, chEvent)
return nil
}
func (s listener) listenLoop(ctx context.Context, chEvent <-chan *result.NotificationEvent) {
loop:
for {
select {
case <-ctx.Done():
s.log.Info("stop event listener by context",
zap.String("reason", ctx.Err().Error()),
)
break loop
case notifyEvent, ok := <-chEvent:
if !ok {
s.log.Warn("stop event listener by channel")
break loop
} else if notifyEvent == nil {
s.log.Warn("nil notification event was caught")
continue loop
}
s.parseAndHandle(notifyEvent)
}
}
}
func (s listener) parseAndHandle(notifyEvent *result.NotificationEvent) {
log := s.log.With(
zap.String("script hash LE", notifyEvent.Contract.StringLE()),
)
// stack item must be an array of items
arr, err := client.ArrayFromStackParameter(notifyEvent.Item)
if err != nil {
log.Warn("stack item is not an array type",
zap.String("error", err.Error()),
)
return
} else if len(arr) == 0 {
log.Warn("stack item array is empty")
return
}
// first item must be a byte array
typBytes, err := client.BytesFromStackParameter(arr[0])
if err != nil {
log.Warn("first array item is not a byte array",
zap.String("error", err.Error()),
)
return
}
// calculate event type from bytes
typEvent := TypeFromBytes(typBytes)
log = log.With(
zap.Stringer("event type", typEvent),
)
// get the event parser
keyEvent := scriptHashWithType{}
keyEvent.SetScriptHash(notifyEvent.Contract)
keyEvent.SetType(typEvent)
s.mtx.RLock()
parser, ok := s.parsers[keyEvent]
s.mtx.RUnlock()
if !ok {
log.Warn("event parser not set")
return
}
// parse the notification event
event, err := parser(arr[1:])
if err != nil {
log.Warn("could not parse notification event",
zap.String("error", err.Error()),
)
return
}
// handler the event
s.mtx.RLock()
handlers := s.handlers[keyEvent]
s.mtx.RUnlock()
if len(handlers) == 0 {
log.Info("handlers for parsed notification event were not registered",
zap.Any("event", event),
)
return
}
for _, handler := range handlers {
handler(event)
}
}
// SetParser sets the parser of particular contract event.
//
// Ignores nil and already set parsers.
// Ignores the parser if listener is started.
func (s listener) SetParser(p ParserInfo) {
log := s.log.With(
zap.String("script hash LE", p.ScriptHash().StringLE()),
zap.Stringer("event type", p.getType()),
)
parser := p.parser()
if parser == nil {
log.Info("ignore nil event parser")
return
}
s.mtx.Lock()
defer s.mtx.Unlock()
// check if the listener was started
if s.started {
log.Warn("listener has been already started, ignore parser")
return
}
// add event parser
if _, ok := s.parsers[p.scriptHashWithType]; !ok {
s.parsers[p.scriptHashWithType] = p.parser()
}
log.Info("registered new event parser")
}
// RegisterHandler registers the handler for particular notification event of contract.
//
// Ignores nil handlers.
// Ignores handlers of event without parser.
func (s listener) RegisterHandler(p HandlerInfo) {
log := s.log.With(
zap.String("script hash LE", p.ScriptHash().StringLE()),
zap.Stringer("event type", p.GetType()),
)
handler := p.Handler()
if handler == nil {
log.Warn("ignore nil event handler")
return
}
// check if parser was set
s.mtx.RLock()
_, ok := s.parsers[p.scriptHashWithType]
s.mtx.RUnlock()
if !ok {
log.Warn("ignore handler of event w/o parser")
return
}
// add event handler
s.mtx.Lock()
s.handlers[p.scriptHashWithType] = append(
s.handlers[p.scriptHashWithType],
p.Handler(),
)
s.mtx.Unlock()
log.Info("registered new event handler")
}
// Stop closes subscription channel with remote neo node.
func (s listener) Stop() {
s.subscriber.Close()
}
// NewListener create the notification event listener instance and returns Listener interface.
func NewListener(p ListenerParams) (Listener, error) {
switch {
case p.Logger == nil:
return nil, errors.Wrap(errNilLogger, newListenerFailMsg)
case p.Subscriber == nil:
return nil, errors.Wrap(errNilSubscriber, newListenerFailMsg)
}
return &listener{
mtx: new(sync.RWMutex),
once: new(sync.Once),
parsers: make(map[scriptHashWithType]Parser),
handlers: make(map[scriptHashWithType][]Handler),
log: p.Logger,
subscriber: p.Subscriber,
}, nil
}

View file

@ -0,0 +1,80 @@
package neofs
import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/pkg/errors"
)
// Cheque structure of neofs.Cheque notification from mainnet chain.
type Cheque struct {
id []byte
amount int64 // Fixed8
user util.Uint160
lock util.Uint160
}
// MorphEvent implements Neo:Morph Event interface.
func (Cheque) MorphEvent() {}
// ID is a withdraw transaction hash.
func (c Cheque) ID() []byte { return c.id }
// User returns withdraw receiver script hash from main net.
func (c Cheque) User() util.Uint160 { return c.user }
// Amount of the sent assets.
func (c Cheque) Amount() int64 { return c.amount }
// LockAccount return script hash for balance contract wallet.
func (c Cheque) LockAccount() util.Uint160 { return c.lock }
// ParseCheque from notification into cheque structure.
func ParseCheque(params []smartcontract.Parameter) (event.Event, error) {
var (
ev Cheque
err error
)
if ln := len(params); ln != 4 {
return nil, event.WrongNumberOfParameters(4, ln)
}
// parse id
ev.id, err = client.BytesFromStackParameter(params[0])
if err != nil {
return nil, errors.Wrap(err, "could not get cheque id")
}
// parse user
user, err := client.BytesFromStackParameter(params[1])
if err != nil {
return nil, errors.Wrap(err, "could not get cheque user")
}
ev.user, err = util.Uint160DecodeBytesBE(user)
if err != nil {
return nil, errors.Wrap(err, "could not convert cheque user to uint160")
}
// parse amount
ev.amount, err = client.IntFromStackParameter(params[2])
if err != nil {
return nil, errors.Wrap(err, "could not get cheque amount")
}
// parse lock account
lock, err := client.BytesFromStackParameter(params[3])
if err != nil {
return nil, errors.Wrap(err, "could not get cheque lock account")
}
ev.lock, err = util.Uint160DecodeBytesBE(lock)
if err != nil {
return nil, errors.Wrap(err, "could not convert cheque lock account to uint160")
}
return ev, nil
}

View file

@ -0,0 +1,123 @@
package neofs
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/stretchr/testify/require"
)
func TestParseCheque(t *testing.T) {
var (
id = []byte("Hello World")
user = util.Uint160{0x1, 0x2, 0x3}
lock = util.Uint160{0x3, 0x2, 0x1}
amount int64 = 10
)
t.Run("wrong number of parameters", func(t *testing.T) {
prms := []smartcontract.Parameter{
{},
{},
}
_, err := ParseCheque(prms)
require.EqualError(t, err, event.WrongNumberOfParameters(4, len(prms)).Error())
})
t.Run("wrong id parameter", func(t *testing.T) {
_, err := ParseCheque([]smartcontract.Parameter{
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong user parameter", func(t *testing.T) {
_, err := ParseCheque([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong amount parameter", func(t *testing.T) {
_, err := ParseCheque([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong lock parameter", func(t *testing.T) {
_, err := ParseCheque([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("correct behavior", func(t *testing.T) {
ev, err := ParseCheque([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: id,
},
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.ByteArrayType,
Value: lock.BytesBE(),
},
})
require.NoError(t, err)
require.Equal(t, Cheque{
id: id,
amount: amount,
user: user,
lock: lock,
}, ev)
})
}

View file

@ -0,0 +1,77 @@
package neofs
import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/pkg/errors"
)
// Deposit structure of neofs.Deposit notification from mainnet chain.
type Deposit struct {
id []byte
amount int64 // Fixed8
from util.Uint160
to util.Uint160
}
// MorphEvent implements Neo:Morph Event interface.
func (Deposit) MorphEvent() {}
// ID is a deposit transaction hash.
func (d Deposit) ID() []byte { return d.id }
// From is a script hash of asset sender in main net.
func (d Deposit) From() util.Uint160 { return d.from }
// To is a script hash of asset receiver in balance contract.
func (d Deposit) To() util.Uint160 { return d.to }
// Amount of transferred assets.
func (d Deposit) Amount() int64 { return d.amount }
// ParseDeposit notification into deposit structure.
func ParseDeposit(params []smartcontract.Parameter) (event.Event, error) {
var ev Deposit
if ln := len(params); ln != 4 {
return nil, event.WrongNumberOfParameters(4, ln)
}
// parse from
from, err := client.BytesFromStackParameter(params[0])
if err != nil {
return nil, errors.Wrap(err, "could not get deposit sender")
}
ev.from, err = util.Uint160DecodeBytesBE(from)
if err != nil {
return nil, errors.Wrap(err, "could not convert deposit sender to uint160")
}
// parse amount
ev.amount, err = client.IntFromStackParameter(params[1])
if err != nil {
return nil, errors.Wrap(err, "could not get deposit amount")
}
// parse to
to, err := client.BytesFromStackParameter(params[2])
if err != nil {
return nil, errors.Wrap(err, "could not get deposit receiver")
}
ev.to, err = util.Uint160DecodeBytesBE(to)
if err != nil {
return nil, errors.Wrap(err, "could not convert deposit receiver to uint160")
}
// parse id
ev.id, err = client.BytesFromStackParameter(params[3])
if err != nil {
return nil, errors.Wrap(err, "could not get deposit id")
}
return ev, nil
}

View file

@ -0,0 +1,123 @@
package neofs
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/stretchr/testify/require"
)
func TestParseDeposit(t *testing.T) {
var (
id = []byte("Hello World")
from = util.Uint160{0x1, 0x2, 0x3}
to = util.Uint160{0x3, 0x2, 0x1}
amount int64 = 10
)
t.Run("wrong number of parameters", func(t *testing.T) {
prms := []smartcontract.Parameter{
{},
{},
}
_, err := ParseDeposit(prms)
require.EqualError(t, err, event.WrongNumberOfParameters(4, len(prms)).Error())
})
t.Run("wrong from parameter", func(t *testing.T) {
_, err := ParseDeposit([]smartcontract.Parameter{
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong amount parameter", func(t *testing.T) {
_, err := ParseDeposit([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: from.BytesBE(),
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong to parameter", func(t *testing.T) {
_, err := ParseDeposit([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: from.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong id parameter", func(t *testing.T) {
_, err := ParseDeposit([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: from.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.ByteArrayType,
Value: to.BytesBE(),
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("correct behavior", func(t *testing.T) {
ev, err := ParseDeposit([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: from.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.ByteArrayType,
Value: to.BytesBE(),
},
{
Type: smartcontract.ByteArrayType,
Value: id,
},
})
require.NoError(t, err)
require.Equal(t, Deposit{
id: id,
amount: amount,
from: from,
to: to,
}, ev)
})
}

View file

@ -0,0 +1,62 @@
package neofs
import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/pkg/errors"
)
// Withdraw structure of neofs.Withdraw notification from mainnet chain.
type Withdraw struct {
id []byte
amount int64 // Fixed8
user util.Uint160
}
// MorphEvent implements Neo:Morph Event interface.
func (Withdraw) MorphEvent() {}
// ID is a withdraw transaction hash.
func (w Withdraw) ID() []byte { return w.id }
// User returns withdraw receiver script hash from main net.
func (w Withdraw) User() util.Uint160 { return w.user }
// Amount of the withdraw assets.
func (w Withdraw) Amount() int64 { return w.amount }
// ParseWithdraw notification into withdraw structure.
func ParseWithdraw(params []smartcontract.Parameter) (event.Event, error) {
var ev Withdraw
if ln := len(params); ln != 3 {
return nil, event.WrongNumberOfParameters(3, ln)
}
// parse user
user, err := client.BytesFromStackParameter(params[0])
if err != nil {
return nil, errors.Wrap(err, "could not get withdraw user")
}
ev.user, err = util.Uint160DecodeBytesBE(user)
if err != nil {
return nil, errors.Wrap(err, "could not convert withdraw user to uint160")
}
// parse amount
ev.amount, err = client.IntFromStackParameter(params[1])
if err != nil {
return nil, errors.Wrap(err, "could not get withdraw amount")
}
// parse id
ev.id, err = client.BytesFromStackParameter(params[2])
if err != nil {
return nil, errors.Wrap(err, "could not get withdraw id")
}
return ev, nil
}

View file

@ -0,0 +1,95 @@
package neofs
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/stretchr/testify/require"
)
func TestParseWithdraw(t *testing.T) {
var (
id = []byte("Hello World")
user = util.Uint160{0x1, 0x2, 0x3}
amount int64 = 10
)
t.Run("wrong number of parameters", func(t *testing.T) {
prms := []smartcontract.Parameter{
{},
{},
}
_, err := ParseWithdraw(prms)
require.EqualError(t, err, event.WrongNumberOfParameters(3, len(prms)).Error())
})
t.Run("wrong user parameter", func(t *testing.T) {
_, err := ParseWithdraw([]smartcontract.Parameter{
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong amount parameter", func(t *testing.T) {
_, err := ParseWithdraw([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("wrong id parameter", func(t *testing.T) {
_, err := ParseWithdraw([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.ArrayType,
},
})
require.Error(t, err)
})
t.Run("correct behavior", func(t *testing.T) {
ev, err := ParseWithdraw([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
Value: user.BytesBE(),
},
{
Type: smartcontract.IntegerType,
Value: amount,
},
{
Type: smartcontract.ByteArrayType,
Value: id,
},
})
require.NoError(t, err)
require.Equal(t, Withdraw{
id: id,
amount: amount,
user: user,
}, ev)
})
}

View file

@ -0,0 +1,39 @@
package netmap
import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neofs-node/pkg/morph/client"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/pkg/errors"
)
// NewEpoch is a new epoch Neo:Morph event.
type NewEpoch struct {
num uint64
}
// MorphEvent implements Neo:Morph Event interface.
func (NewEpoch) MorphEvent() {}
// EpochNumber returns new epoch number.
func (s NewEpoch) EpochNumber() uint64 {
return s.num
}
// ParseNewEpoch is a parser of new epoch notification event.
//
// Result is type of NewEpoch.
func ParseNewEpoch(prms []smartcontract.Parameter) (event.Event, error) {
if ln := len(prms); ln != 1 {
return nil, event.WrongNumberOfParameters(1, ln)
}
prmEpochNum, err := client.IntFromStackParameter(prms[0])
if err != nil {
return nil, errors.Wrap(err, "could not get integer epoch number")
}
return NewEpoch{
num: uint64(prmEpochNum),
}, nil
}

View file

@ -0,0 +1,47 @@
package netmap
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
"github.com/stretchr/testify/require"
)
func TestParseNewEpoch(t *testing.T) {
t.Run("wrong number of parameters", func(t *testing.T) {
prms := []smartcontract.Parameter{
{},
{},
}
_, err := ParseNewEpoch(prms)
require.EqualError(t, err, event.WrongNumberOfParameters(1, len(prms)).Error())
})
t.Run("wrong first parameter type", func(t *testing.T) {
_, err := ParseNewEpoch([]smartcontract.Parameter{
{
Type: smartcontract.ByteArrayType,
},
})
require.Error(t, err)
})
t.Run("correct behavior", func(t *testing.T) {
epochNum := uint64(100)
ev, err := ParseNewEpoch([]smartcontract.Parameter{
{
Type: smartcontract.IntegerType,
Value: int64(epochNum),
},
})
require.NoError(t, err)
require.Equal(t, NewEpoch{
num: epochNum,
}, ev)
})
}

53
pkg/morph/event/parser.go Normal file
View file

@ -0,0 +1,53 @@
package event
import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/pkg/errors"
)
// Parser is a function that constructs Event
// from the StackItem list.
type Parser func([]smartcontract.Parameter) (Event, error)
// ParserInfo is a structure that groups
// the parameters of particular contract
// notification event parser.
type ParserInfo struct {
scriptHashWithType
p Parser
}
type wrongPrmNumber struct {
exp, act int
}
// WrongNumberOfParameters returns an error about wrong number of smart contract parameters.
func WrongNumberOfParameters(exp, act int) error {
return &wrongPrmNumber{
exp: exp,
act: act,
}
}
func (s wrongPrmNumber) Error() string {
return errors.Errorf("wrong parameter count: expected %d, has %d", s.exp, s.act).Error()
}
// SetParser is an event parser setter.
func (s *ParserInfo) SetParser(v Parser) {
s.p = v
}
func (s ParserInfo) parser() Parser {
return s.p
}
// SetType is an event type setter.
func (s *ParserInfo) SetType(v Type) {
s.typ = v
}
func (s ParserInfo) getType() Type {
return s.typ
}

36
pkg/morph/event/utils.go Normal file
View file

@ -0,0 +1,36 @@
package event
import "github.com/nspcc-dev/neo-go/pkg/util"
type scriptHashValue struct {
hash util.Uint160
}
type typeValue struct {
typ Type
}
type scriptHashWithType struct {
scriptHashValue
typeValue
}
// SetScriptHash is a script hash setter.
func (s *scriptHashValue) SetScriptHash(v util.Uint160) {
s.hash = v
}
// ScriptHash is script hash getter.
func (s scriptHashValue) ScriptHash() util.Uint160 {
return s.hash
}
// SetType is an event type setter.
func (s *typeValue) SetType(v Type) {
s.typ = v
}
// GetType is an event type getter.
func (s typeValue) GetType() Type {
return s.typ
}

View file

@ -0,0 +1,156 @@
package subscriber
import (
"context"
"errors"
"sync"
"time"
"github.com/nspcc-dev/neo-go/pkg/rpc/client"
"github.com/nspcc-dev/neo-go/pkg/rpc/response"
"github.com/nspcc-dev/neo-go/pkg/rpc/response/result"
"github.com/nspcc-dev/neo-go/pkg/util"
"go.uber.org/zap"
)
type (
// Subscriber is an interface of the NotificationEvent listener.
Subscriber interface {
SubscribeForNotification(...util.Uint160) (<-chan *result.NotificationEvent, error)
UnsubscribeForNotification()
Close()
}
subscriber struct {
*sync.RWMutex
log *zap.Logger
client *client.WSClient
notify chan *result.NotificationEvent
notifyIDs map[util.Uint160]string
}
// Params is a group of Subscriber constructor parameters.
Params struct {
Log *zap.Logger
Endpoint string
DialTimeout time.Duration
}
)
var (
errNilParams = errors.New("chain/subscriber: config was not provided to the constructor")
errNilLogger = errors.New("chain/subscriber: logger was not provided to the constructor")
)
func (s *subscriber) SubscribeForNotification(contracts ...util.Uint160) (<-chan *result.NotificationEvent, error) {
s.Lock()
defer s.Unlock()
notifyIDs := make(map[util.Uint160]string, len(contracts))
for i := range contracts {
// do not subscribe to already subscribed contracts
if _, ok := s.notifyIDs[contracts[i]]; ok {
continue
}
// subscribe to contract notifications
id, err := s.client.SubscribeForExecutionNotifications(&contracts[i])
if err != nil {
// if there is some error, undo all subscriptions and return error
for _, id := range notifyIDs {
_ = s.client.Unsubscribe(id)
}
return nil, err
}
// save notification id
notifyIDs[contracts[i]] = id
}
// update global map of subscribed contracts
for contract, id := range notifyIDs {
s.notifyIDs[contract] = id
}
return s.notify, nil
}
func (s *subscriber) UnsubscribeForNotification() {
s.Lock()
defer s.Unlock()
for i := range s.notifyIDs {
err := s.client.Unsubscribe(s.notifyIDs[i])
if err != nil {
s.log.Error("unsubscribe for notification",
zap.String("event", s.notifyIDs[i]),
zap.Error(err))
}
delete(s.notifyIDs, i)
}
}
func (s *subscriber) Close() {
s.client.Close()
}
func (s *subscriber) routeNotifications(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case notification := <-s.client.Notifications:
switch notification.Type {
case response.NotificationEventID:
notification, ok := notification.Value.(*result.NotificationEvent)
if !ok {
s.log.Error("can't cast notify event to the notify struct")
continue
}
s.notify <- notification
default:
s.log.Debug("unsupported notification from the chain",
zap.Uint8("type", uint8(notification.Type)),
)
}
}
}
}
// New is a constructs Neo:Morph event listener and returns Subscriber interface.
func New(ctx context.Context, p *Params) (Subscriber, error) {
switch {
case p == nil:
return nil, errNilParams
case p.Log == nil:
return nil, errNilLogger
}
wsClient, err := client.NewWS(ctx, p.Endpoint, client.Options{
DialTimeout: p.DialTimeout,
})
if err != nil {
return nil, err
}
sub := &subscriber{
RWMutex: new(sync.RWMutex),
log: p.Log,
client: wsClient,
notify: make(chan *result.NotificationEvent),
notifyIDs: make(map[util.Uint160]string),
}
// Worker listens all events from neo-go websocket and puts them
// into corresponding channel. It may be notifications, transactions,
// new blocks. For now only notifications.
go sub.routeNotifications(ctx)
return sub, nil
}