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)
})
}