From 43a59adbd0fd0dbc806f964d76e011cfd8f6ad84 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Thu, 21 Jul 2022 16:21:44 +0300 Subject: [PATCH 01/14] rpc/server: move to services/rpcsrv `server` is not a good package name and it's an internal service, so it can be just about anywhere. --- .gitignore | 2 +- cli/executor_test.go | 8 ++++---- cli/server/server.go | 6 +++--- pkg/core/basic_chain_test.go | 2 +- pkg/rpc/client/rpc_test.go | 2 +- pkg/rpc/client/wsclient_test.go | 2 +- pkg/{rpc/server => services/rpcsrv}/client_test.go | 2 +- pkg/{rpc/server => services/rpcsrv}/error.go | 2 +- pkg/{rpc/server => services/rpcsrv}/params/param.go | 0 .../server => services/rpcsrv}/params/param_test.go | 0 .../server => services/rpcsrv}/params/params.go | 0 .../server => services/rpcsrv}/params/txBuilder.go | 0 .../rpcsrv}/params/tx_builder_test.go | 0 pkg/{rpc/server => services/rpcsrv}/params/types.go | 0 .../server => services/rpcsrv}/params/types_test.go | 0 pkg/{rpc/server => services/rpcsrv}/prometheus.go | 2 +- pkg/{rpc/server => services/rpcsrv}/server.go | 4 ++-- .../rpcsrv}/server_helper_test.go | 6 +++--- pkg/{rpc/server => services/rpcsrv}/server_test.go | 4 ++-- pkg/{rpc/server => services/rpcsrv}/subscription.go | 2 +- .../server => services/rpcsrv}/subscription_test.go | 2 +- .../rpcsrv}/testdata/testblocks.acc | Bin pkg/{rpc/server => services/rpcsrv}/tokens.go | 2 +- pkg/{rpc/server => services/rpcsrv}/util.go | 2 +- 24 files changed, 25 insertions(+), 25 deletions(-) rename pkg/{rpc/server => services/rpcsrv}/client_test.go (99%) rename pkg/{rpc/server => services/rpcsrv}/error.go (99%) rename pkg/{rpc/server => services/rpcsrv}/params/param.go (100%) rename pkg/{rpc/server => services/rpcsrv}/params/param_test.go (100%) rename pkg/{rpc/server => services/rpcsrv}/params/params.go (100%) rename pkg/{rpc/server => services/rpcsrv}/params/txBuilder.go (100%) rename pkg/{rpc/server => services/rpcsrv}/params/tx_builder_test.go (100%) rename pkg/{rpc/server => services/rpcsrv}/params/types.go (100%) rename pkg/{rpc/server => services/rpcsrv}/params/types_test.go (100%) rename pkg/{rpc/server => services/rpcsrv}/prometheus.go (97%) rename pkg/{rpc/server => services/rpcsrv}/server.go (99%) rename pkg/{rpc/server => services/rpcsrv}/server_helper_test.go (97%) rename pkg/{rpc/server => services/rpcsrv}/server_test.go (99%) rename pkg/{rpc/server => services/rpcsrv}/subscription.go (99%) rename pkg/{rpc/server => services/rpcsrv}/subscription_test.go (99%) rename pkg/{rpc/server => services/rpcsrv}/testdata/testblocks.acc (100%) rename pkg/{rpc/server => services/rpcsrv}/tokens.go (98%) rename pkg/{rpc/server => services/rpcsrv}/util.go (95%) diff --git a/.gitignore b/.gitignore index 88843343e..fbc04a091 100644 --- a/.gitignore +++ b/.gitignore @@ -50,7 +50,7 @@ testdata/ !pkg/compiler/testdata !pkg/config/testdata !pkg/consensus/testdata -!pkg/rpc/server/testdata +!pkg/services/rpcsrv/testdata !pkg/services/notary/testdata !pkg/services/oracle/testdata !pkg/smartcontract/testdata diff --git a/cli/executor_test.go b/cli/executor_test.go index 6f69a6881..93d2f9843 100644 --- a/cli/executor_test.go +++ b/cli/executor_test.go @@ -20,7 +20,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/network" - "github.com/nspcc-dev/neo-go/pkg/rpc/server" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm/vmstate" @@ -56,7 +56,7 @@ type executor struct { // Chain is a blockchain instance (can be empty). Chain *core.Blockchain // RPC is an RPC server to query (can be empty). - RPC *server.Server + RPC *rpcsrv.Server // NetSrv is a network server (can be empty). NetSrv *network.Server // Out contains command output. @@ -120,7 +120,7 @@ func (w *ConcurrentBuffer) Reset() { w.buf.Reset() } -func newTestChain(t *testing.T, f func(*config.Config), run bool) (*core.Blockchain, *server.Server, *network.Server) { +func newTestChain(t *testing.T, f func(*config.Config), run bool) (*core.Blockchain, *rpcsrv.Server, *network.Server) { configPath := "../config/protocol.unit_testnet.single.yml" cfg, err := config.LoadFile(configPath) require.NoError(t, err, "could not load config") @@ -154,7 +154,7 @@ func newTestChain(t *testing.T, f func(*config.Config), run bool) (*core.Blockch netSrv.AddExtensibleHPService(cons, consensus.Category, cons.OnPayload, cons.OnTransaction) go netSrv.Start(make(chan error, 1)) errCh := make(chan error, 2) - rpcServer := server.New(chain, cfg.ApplicationConfiguration.RPC, netSrv, nil, logger, errCh) + rpcServer := rpcsrv.New(chain, cfg.ApplicationConfiguration.RPC, netSrv, nil, logger, errCh) rpcServer.Start() return chain, &rpcServer, netSrv diff --git a/cli/server/server.go b/cli/server/server.go index 93cde7568..64246094d 100644 --- a/cli/server/server.go +++ b/cli/server/server.go @@ -22,7 +22,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/network" "github.com/nspcc-dev/neo-go/pkg/network/metrics" - "github.com/nspcc-dev/neo-go/pkg/rpc/server" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv" "github.com/nspcc-dev/neo-go/pkg/services/notary" "github.com/nspcc-dev/neo-go/pkg/services/oracle" "github.com/nspcc-dev/neo-go/pkg/services/stateroot" @@ -505,7 +505,7 @@ func startServer(ctx *cli.Context) error { return cli.NewExitError(err, 1) } errChan := make(chan error) - rpcServer := server.New(chain, cfg.ApplicationConfiguration.RPC, serv, oracleSrv, log, errChan) + rpcServer := rpcsrv.New(chain, cfg.ApplicationConfiguration.RPC, serv, oracleSrv, log, errChan) serv.AddService(&rpcServer) go serv.Start(errChan) @@ -532,7 +532,7 @@ Main: case syscall.SIGHUP: log.Info("SIGHUP received, restarting rpc-server") rpcServer.Shutdown() - rpcServer = server.New(chain, cfg.ApplicationConfiguration.RPC, serv, oracleSrv, log, errChan) + rpcServer = rpcsrv.New(chain, cfg.ApplicationConfiguration.RPC, serv, oracleSrv, log, errChan) serv.AddService(&rpcServer) // Replaces old one by service name. if !cfg.ApplicationConfiguration.RPC.StartWhenSynchronized || serv.IsInSync() { rpcServer.Start() diff --git a/pkg/core/basic_chain_test.go b/pkg/core/basic_chain_test.go index aac129172..0bbac46dc 100644 --- a/pkg/core/basic_chain_test.go +++ b/pkg/core/basic_chain_test.go @@ -19,7 +19,7 @@ const ( // basicChainPrefix is a prefix used to store Basic chain .acc file for tests. // It is also used to retrieve smart contracts that should be deployed to // Basic chain. - basicChainPrefix = "../rpc/server/testdata/" + basicChainPrefix = "../services/rpcsrv/testdata/" // bcPersistInterval is the time period Blockchain persists changes to the // underlying storage. bcPersistInterval = time.Second diff --git a/pkg/rpc/client/rpc_test.go b/pkg/rpc/client/rpc_test.go index c50c2b271..ae1f89863 100644 --- a/pkg/rpc/client/rpc_test.go +++ b/pkg/rpc/client/rpc_test.go @@ -28,7 +28,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" - "github.com/nspcc-dev/neo-go/pkg/rpc/server/params" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/smartcontract/nef" diff --git a/pkg/rpc/client/wsclient_test.go b/pkg/rpc/client/wsclient_test.go index b4d93fec7..2b6bde70f 100644 --- a/pkg/rpc/client/wsclient_test.go +++ b/pkg/rpc/client/wsclient_test.go @@ -18,7 +18,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/network/payload" "github.com/nspcc-dev/neo-go/pkg/rpc/request" - "github.com/nspcc-dev/neo-go/pkg/rpc/server/params" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/stretchr/testify/require" "go.uber.org/atomic" diff --git a/pkg/rpc/server/client_test.go b/pkg/services/rpcsrv/client_test.go similarity index 99% rename from pkg/rpc/server/client_test.go rename to pkg/services/rpcsrv/client_test.go index 40df78ee8..33f672cff 100644 --- a/pkg/rpc/server/client_test.go +++ b/pkg/services/rpcsrv/client_test.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "bytes" diff --git a/pkg/rpc/server/error.go b/pkg/services/rpcsrv/error.go similarity index 99% rename from pkg/rpc/server/error.go rename to pkg/services/rpcsrv/error.go index 8c5223224..102a4f07f 100644 --- a/pkg/rpc/server/error.go +++ b/pkg/services/rpcsrv/error.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "net/http" diff --git a/pkg/rpc/server/params/param.go b/pkg/services/rpcsrv/params/param.go similarity index 100% rename from pkg/rpc/server/params/param.go rename to pkg/services/rpcsrv/params/param.go diff --git a/pkg/rpc/server/params/param_test.go b/pkg/services/rpcsrv/params/param_test.go similarity index 100% rename from pkg/rpc/server/params/param_test.go rename to pkg/services/rpcsrv/params/param_test.go diff --git a/pkg/rpc/server/params/params.go b/pkg/services/rpcsrv/params/params.go similarity index 100% rename from pkg/rpc/server/params/params.go rename to pkg/services/rpcsrv/params/params.go diff --git a/pkg/rpc/server/params/txBuilder.go b/pkg/services/rpcsrv/params/txBuilder.go similarity index 100% rename from pkg/rpc/server/params/txBuilder.go rename to pkg/services/rpcsrv/params/txBuilder.go diff --git a/pkg/rpc/server/params/tx_builder_test.go b/pkg/services/rpcsrv/params/tx_builder_test.go similarity index 100% rename from pkg/rpc/server/params/tx_builder_test.go rename to pkg/services/rpcsrv/params/tx_builder_test.go diff --git a/pkg/rpc/server/params/types.go b/pkg/services/rpcsrv/params/types.go similarity index 100% rename from pkg/rpc/server/params/types.go rename to pkg/services/rpcsrv/params/types.go diff --git a/pkg/rpc/server/params/types_test.go b/pkg/services/rpcsrv/params/types_test.go similarity index 100% rename from pkg/rpc/server/params/types_test.go rename to pkg/services/rpcsrv/params/types_test.go diff --git a/pkg/rpc/server/prometheus.go b/pkg/services/rpcsrv/prometheus.go similarity index 97% rename from pkg/rpc/server/prometheus.go rename to pkg/services/rpcsrv/prometheus.go index 60b1351bf..8de59c1e7 100644 --- a/pkg/rpc/server/prometheus.go +++ b/pkg/services/rpcsrv/prometheus.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "fmt" diff --git a/pkg/rpc/server/server.go b/pkg/services/rpcsrv/server.go similarity index 99% rename from pkg/rpc/server/server.go rename to pkg/services/rpcsrv/server.go index 28ccfa246..73244a556 100644 --- a/pkg/rpc/server/server.go +++ b/pkg/services/rpcsrv/server.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "bytes" @@ -45,7 +45,7 @@ import ( "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/rpc/response/result/subscriptions" - "github.com/nspcc-dev/neo-go/pkg/rpc/server/params" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" "github.com/nspcc-dev/neo-go/pkg/services/oracle" "github.com/nspcc-dev/neo-go/pkg/services/oracle/broadcaster" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" diff --git a/pkg/rpc/server/server_helper_test.go b/pkg/services/rpcsrv/server_helper_test.go similarity index 97% rename from pkg/rpc/server/server_helper_test.go rename to pkg/services/rpcsrv/server_helper_test.go index 64e08c7ad..7dbad237e 100644 --- a/pkg/rpc/server/server_helper_test.go +++ b/pkg/services/rpcsrv/server_helper_test.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "fmt" @@ -25,7 +25,7 @@ import ( ) const ( - notaryPath = "../../services/notary/testdata/notary1.json" + notaryPath = "../notary/testdata/notary1.json" notaryPass = "one" ) @@ -50,7 +50,7 @@ func getUnitTestChain(t testing.TB, enableOracle bool, enableNotary bool, disabl if enableOracle { cfg.ApplicationConfiguration.Oracle.Enabled = true cfg.ApplicationConfiguration.Oracle.UnlockWallet = config.Wallet{ - Path: "../../services/oracle/testdata/oracle1.json", + Path: "../oracle/testdata/oracle1.json", Password: "one", } } diff --git a/pkg/rpc/server/server_test.go b/pkg/services/rpcsrv/server_test.go similarity index 99% rename from pkg/rpc/server/server_test.go rename to pkg/services/rpcsrv/server_test.go index 4190a1b18..dedce792b 100644 --- a/pkg/rpc/server/server_test.go +++ b/pkg/services/rpcsrv/server_test.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "bytes" @@ -37,7 +37,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/network/payload" "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/rpc/server/params" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" rpc2 "github.com/nspcc-dev/neo-go/pkg/services/oracle/broadcaster" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" diff --git a/pkg/rpc/server/subscription.go b/pkg/services/rpcsrv/subscription.go similarity index 99% rename from pkg/rpc/server/subscription.go rename to pkg/services/rpcsrv/subscription.go index ef9d6ea66..3c4964913 100644 --- a/pkg/rpc/server/subscription.go +++ b/pkg/services/rpcsrv/subscription.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "github.com/gorilla/websocket" diff --git a/pkg/rpc/server/subscription_test.go b/pkg/services/rpcsrv/subscription_test.go similarity index 99% rename from pkg/rpc/server/subscription_test.go rename to pkg/services/rpcsrv/subscription_test.go index bd90cc10c..0a2d2e82e 100644 --- a/pkg/rpc/server/subscription_test.go +++ b/pkg/services/rpcsrv/subscription_test.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "encoding/json" diff --git a/pkg/rpc/server/testdata/testblocks.acc b/pkg/services/rpcsrv/testdata/testblocks.acc similarity index 100% rename from pkg/rpc/server/testdata/testblocks.acc rename to pkg/services/rpcsrv/testdata/testblocks.acc diff --git a/pkg/rpc/server/tokens.go b/pkg/services/rpcsrv/tokens.go similarity index 98% rename from pkg/rpc/server/tokens.go rename to pkg/services/rpcsrv/tokens.go index 9cfd5cd7a..fab1f905d 100644 --- a/pkg/rpc/server/tokens.go +++ b/pkg/services/rpcsrv/tokens.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" diff --git a/pkg/rpc/server/util.go b/pkg/services/rpcsrv/util.go similarity index 95% rename from pkg/rpc/server/util.go rename to pkg/services/rpcsrv/util.go index bbacc9b2d..9607eef18 100644 --- a/pkg/rpc/server/util.go +++ b/pkg/services/rpcsrv/util.go @@ -1,4 +1,4 @@ -package server +package rpcsrv import ( "errors" From 8c668765d208df45d86429785f0143f5e5845fb7 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Thu, 21 Jul 2022 22:39:53 +0300 Subject: [PATCH 02/14] rpc/client: move to pkg/rpcclient Better package name, closer to user. --- cli/cmdargs/parser.go | 8 +-- cli/options/options.go | 6 +- cli/smartcontract/smart_contract.go | 4 +- cli/wallet/nep11.go | 4 +- cli/wallet/nep17.go | 14 ++--- cli/wallet/validator.go | 6 +- docs/notary.md | 16 ++--- internal/basicchain/basic.go | 2 +- pkg/{rpc/client => rpcclient}/client.go | 2 +- pkg/{rpc/client => rpcclient}/doc.go | 6 +- pkg/{rpc/client => rpcclient}/doc_test.go | 8 +-- pkg/{rpc/client => rpcclient}/helper.go | 4 +- pkg/{rpc/client => rpcclient}/native.go | 4 +- pkg/{rpc/client => rpcclient}/nep.go | 2 +- pkg/{rpc/client => rpcclient}/nep11.go | 2 +- pkg/{rpc/client => rpcclient}/nep17.go | 2 +- pkg/{rpc/client => rpcclient}/nns/record.go | 0 pkg/{rpc/client => rpcclient}/policy.go | 2 +- pkg/{rpc/client => rpcclient}/rpc.go | 2 +- pkg/{rpc/client => rpcclient}/rpc_test.go | 2 +- pkg/{rpc/client => rpcclient}/wsclient.go | 2 +- .../client => rpcclient}/wsclient_test.go | 2 +- pkg/services/helpers/rpcbroadcaster/client.go | 10 +-- pkg/services/oracle/broadcaster/oracle.go | 4 +- pkg/services/rpcsrv/client_test.go | 62 +++++++++---------- scripts/compare-states/compare-states.go | 10 +-- 26 files changed, 93 insertions(+), 93 deletions(-) rename pkg/{rpc/client => rpcclient}/client.go (99%) rename pkg/{rpc/client => rpcclient}/doc.go (90%) rename pkg/{rpc/client => rpcclient}/doc_test.go (80%) rename pkg/{rpc/client => rpcclient}/helper.go (99%) rename pkg/{rpc/client => rpcclient}/native.go (98%) rename pkg/{rpc/client => rpcclient}/nep.go (99%) rename pkg/{rpc/client => rpcclient}/nep11.go (99%) rename pkg/{rpc/client => rpcclient}/nep17.go (99%) rename pkg/{rpc/client => rpcclient}/nns/record.go (100%) rename pkg/{rpc/client => rpcclient}/policy.go (99%) rename pkg/{rpc/client => rpcclient}/rpc.go (99%) rename pkg/{rpc/client => rpcclient}/rpc_test.go (99%) rename pkg/{rpc/client => rpcclient}/wsclient.go (99%) rename pkg/{rpc/client => rpcclient}/wsclient_test.go (99%) diff --git a/cli/cmdargs/parser.go b/cli/cmdargs/parser.go index cddb51cb7..0379cf7f5 100644 --- a/cli/cmdargs/parser.go +++ b/cli/cmdargs/parser.go @@ -9,7 +9,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/address" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/wallet" "github.com/urfave/cli" @@ -188,14 +188,14 @@ func ParseParams(args []string, calledFromMain bool) (int, []smartcontract.Param // GetSignersAccounts returns the list of signers combined with the corresponding // accounts from the provided wallet. -func GetSignersAccounts(wall *wallet.Wallet, signers []transaction.Signer) ([]client.SignerAccount, error) { - signersAccounts := make([]client.SignerAccount, len(signers)) +func GetSignersAccounts(wall *wallet.Wallet, signers []transaction.Signer) ([]rpcclient.SignerAccount, error) { + signersAccounts := make([]rpcclient.SignerAccount, len(signers)) for i := range signers { signerAcc := wall.GetAccount(signers[i].Account) if signerAcc == nil { return nil, fmt.Errorf("no account was found in the wallet for signer #%d (%s)", i, address.Uint160ToString(signers[i].Account)) } - signersAccounts[i] = client.SignerAccount{ + signersAccounts[i] = rpcclient.SignerAccount{ Signer: signers[i], Account: signerAcc, } diff --git a/cli/options/options.go b/cli/options/options.go index ae536dd2f..0f4b72562 100644 --- a/cli/options/options.go +++ b/cli/options/options.go @@ -9,7 +9,7 @@ import ( "time" "github.com/nspcc-dev/neo-go/pkg/config/netmode" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/urfave/cli" ) @@ -70,12 +70,12 @@ func GetTimeoutContext(ctx *cli.Context) (context.Context, func()) { } // GetRPCClient returns an RPC client instance for the given Context. -func GetRPCClient(gctx context.Context, ctx *cli.Context) (*client.Client, cli.ExitCoder) { +func GetRPCClient(gctx context.Context, ctx *cli.Context) (*rpcclient.Client, cli.ExitCoder) { endpoint := ctx.String(RPCEndpointFlag) if len(endpoint) == 0 { return nil, cli.NewExitError(errNoEndpoint, 1) } - c, err := client.New(gctx, endpoint, client.Options{}) + c, err := rpcclient.New(gctx, endpoint, rpcclient.Options{}) if err != nil { return nil, cli.NewExitError(err, 1) } diff --git a/cli/smartcontract/smart_contract.go b/cli/smartcontract/smart_contract.go index 148c8218f..2e28a586c 100644 --- a/cli/smartcontract/smart_contract.go +++ b/cli/smartcontract/smart_contract.go @@ -21,7 +21,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" @@ -645,7 +645,7 @@ func invokeWithArgs(ctx *cli.Context, acc *wallet.Account, wall *wallet.Wallet, var ( err error gas, sysgas fixedn.Fixed8 - cosignersAccounts []client.SignerAccount + cosignersAccounts []rpcclient.SignerAccount resp *result.Invoke sender util.Uint160 signAndPush = acc != nil diff --git a/cli/wallet/nep11.go b/cli/wallet/nep11.go index ab1cb4d5b..0631e8bc8 100644 --- a/cli/wallet/nep11.go +++ b/cli/wallet/nep11.go @@ -13,7 +13,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" @@ -250,7 +250,7 @@ func transferNEP11(ctx *cli.Context) error { return transferNEP(ctx, manifest.NEP11StandardName) } -func signAndSendNEP11Transfer(ctx *cli.Context, c *client.Client, acc *wallet.Account, token, to util.Uint160, tokenID []byte, amount *big.Int, data interface{}, cosigners []client.SignerAccount) error { +func signAndSendNEP11Transfer(ctx *cli.Context, c *rpcclient.Client, acc *wallet.Account, token, to util.Uint160, tokenID []byte, amount *big.Int, data interface{}, cosigners []rpcclient.SignerAccount) error { gas := flags.Fixed8FromContext(ctx, "gas") sysgas := flags.Fixed8FromContext(ctx, "sysgas") diff --git a/cli/wallet/nep17.go b/cli/wallet/nep17.go index 7b045b3c0..6bda7a68d 100644 --- a/cli/wallet/nep17.go +++ b/cli/wallet/nep17.go @@ -15,8 +15,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/native/nativenames" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/wallet" @@ -278,7 +278,7 @@ func printAssetBalance(ctx *cli.Context, asset util.Uint160, tokenName, tokenSym fmt.Fprintf(ctx.App.Writer, "\tUpdated: %d\n", balance.LastUpdated) } -func getNativeNEP17Symbol(c *client.Client, name string) (string, util.Uint160, error) { +func getNativeNEP17Symbol(c *rpcclient.Client, name string) (string, util.Uint160, error) { h, err := c.GetNativeContractHash(name) if err != nil { return "", util.Uint160{}, fmt.Errorf("failed to get native %s hash: %w", name, err) @@ -296,7 +296,7 @@ func getMatchingToken(ctx *cli.Context, w *wallet.Wallet, name string, standard }, len(w.Extra.Tokens), name, standard) } -func getMatchingTokenRPC(ctx *cli.Context, c *client.Client, addr util.Uint160, name string, standard string) (*wallet.Token, error) { +func getMatchingTokenRPC(ctx *cli.Context, c *rpcclient.Client, addr util.Uint160, name string, standard string) (*wallet.Token, error) { switch standard { case manifest.NEP17StandardName: bs, err := c.GetNEP17Balances(addr) @@ -493,7 +493,7 @@ func multiTransferNEP17(ctx *cli.Context) error { return cli.NewExitError("empty recipients list", 1) } var ( - recipients []client.TransferTarget + recipients []rpcclient.TransferTarget cosignersOffset = ctx.NArg() ) cache := make(map[string]*wallet.Token) @@ -526,7 +526,7 @@ func multiTransferNEP17(ctx *cli.Context) error { if err != nil { return cli.NewExitError(fmt.Errorf("invalid amount: %w", err), 1) } - recipients = append(recipients, client.TransferTarget{ + recipients = append(recipients, rpcclient.TransferTarget{ Token: token.Hash, Address: addr, Amount: amount.Int64(), @@ -608,7 +608,7 @@ func transferNEP(ctx *cli.Context, standard string) error { if err != nil { return cli.NewExitError(fmt.Errorf("invalid amount: %w", err), 1) } - return signAndSendNEP17Transfer(ctx, c, acc, []client.TransferTarget{{ + return signAndSendNEP17Transfer(ctx, c, acc, []rpcclient.TransferTarget{{ Token: token.Hash, Address: to, Amount: amount.Int64(), @@ -636,7 +636,7 @@ func transferNEP(ctx *cli.Context, standard string) error { } } -func signAndSendNEP17Transfer(ctx *cli.Context, c *client.Client, acc *wallet.Account, recipients []client.TransferTarget, cosigners []client.SignerAccount) error { +func signAndSendNEP17Transfer(ctx *cli.Context, c *rpcclient.Client, acc *wallet.Account, recipients []rpcclient.TransferTarget, cosigners []rpcclient.SignerAccount) error { gas := flags.Fixed8FromContext(ctx, "gas") sysgas := flags.Fixed8FromContext(ctx, "sysgas") diff --git a/cli/wallet/validator.go b/cli/wallet/validator.go index dc0511ff4..dd95c57b9 100644 --- a/cli/wallet/validator.go +++ b/cli/wallet/validator.go @@ -11,7 +11,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm/emit" @@ -125,7 +125,7 @@ func handleCandidate(ctx *cli.Context, method string, sysGas int64) error { w := io.NewBufBinWriter() emit.AppCall(w.BinWriter, neoContractHash, method, callflag.States, acc.PrivateKey().PublicKey().Bytes()) emit.Opcodes(w.BinWriter, opcode.ASSERT) - res, err := c.SignAndPushInvocationTx(w.Bytes(), acc, sysGas, gas, []client.SignerAccount{{ + res, err := c.SignAndPushInvocationTx(w.Bytes(), acc, sysGas, gas, []rpcclient.SignerAccount{{ Signer: transaction.Signer{ Account: acc.Contract.ScriptHash(), Scopes: transaction.CalledByEntry, @@ -186,7 +186,7 @@ func handleVote(ctx *cli.Context) error { emit.AppCall(w.BinWriter, neoContractHash, "vote", callflag.States, addr.BytesBE(), pubArg) emit.Opcodes(w.BinWriter, opcode.ASSERT) - res, err := c.SignAndPushInvocationTx(w.Bytes(), acc, -1, gas, []client.SignerAccount{{ + res, err := c.SignAndPushInvocationTx(w.Bytes(), acc, -1, gas, []rpcclient.SignerAccount{{ Signer: transaction.Signer{ Account: acc.Contract.ScriptHash(), Scopes: transaction.CalledByEntry, diff --git a/docs/notary.md b/docs/notary.md index 49ffbb991..c70515650 100644 --- a/docs/notary.md +++ b/docs/notary.md @@ -255,7 +255,7 @@ won't pass verification. Notary native contract supports `onNEP17Payment` method. Thus, to deposit funds to the Notary native contract, transfer the desired amount of GAS to the contract address. Use -[func (*Client) TransferNEP17](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.TransferNEP17) +[func (*Client) TransferNEP17](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpcclient#Client.TransferNEP17) with the `data` parameter matching the following requirements: - `data` should be an array of two elements: `to` and `till`. - `to` denotes the receiver of the deposit. It can be nil in case `to` equals @@ -308,7 +308,7 @@ the steps to create a signature request: constraints: * Notary signer hash is the hash of a native Notary contract that can be fetched from - [func (*Client) GetNativeContractHash](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.GetNativeContractHash). + [func (*Client) GetNativeContractHash](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpcclient#Client.GetNativeContractHash). * A notary signer must have `None` scope. * A notary signer shouldn't be placed at the beginning of the signer list because Notary contract does not pay main transaction fees. Other positions @@ -317,11 +317,11 @@ the steps to create a signature request: field) and calculate system fee using regular rules (that will be `SystemFee` transaction field). Probably, you'll perform one of these actions: 1. If the script is a contract method call, use `invokefunction` RPC API - [func (*Client) InvokeFunction](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.InvokeFunction) + [func (*Client) InvokeFunction](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpcclient#Client.InvokeFunction) and fetch the script and the gas consumed from the result. 2. If the script is more complicated than just a contract method call, construct the script manually and use `invokescript` RPC API - [func (*Client) InvokeScript](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.InvokeScript) + [func (*Client) InvokeScript](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpcclient#Client.InvokeScript) to fetch the gas consumed from the result. 3. Or just construct the script and set system fee manually. 3. Calculate the height main transaction is valid until (that will be @@ -361,12 +361,12 @@ the steps to create a signature request: `NotaryAssisted` attribute usage and for notary contract witness verification (that is to be added by the notary node in the end of signature collection process). Use - [func (*Client) CalculateNotaryFee](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.CalculateNotaryFee) + [func (*Client) CalculateNotaryFee](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpcclient#Client.CalculateNotaryFee) to calculate notary network fee. Use `NKeys` estimated at step 4 as an argument. - *Regular network fee.* That's the amount of GAS to be paid for other witnesses verification. Use - [func (*Client) AddNetworkFee](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.AddNetworkFee) + [func (*Client) AddNetworkFee](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpcclient#Client.AddNetworkFee) to calculate regular network fee and add it to the transaction. Use partially-filled main transaction from the previous steps as `tx` argument. Use notary network fee calculated at the previous substep as `extraFee` @@ -402,13 +402,13 @@ the steps to create a signature request: tries to push all associated fallbacks. Use the following rules to define `fallbackValidFor`: - `fallbackValidFor` shouldn't be more than `MaxNotValidBeforeDelta` value. - - Use [func (*Client) GetMaxNotValidBeforeDelta](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.GetMaxNotValidBeforeDelta) + - Use [func (*Client) GetMaxNotValidBeforeDelta](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpcclient#Client.GetMaxNotValidBeforeDelta) to check `MaxNotValidBefore` value. 11. Construct a script for the fallback transaction. The script may do something useful, i.g. invoke method of a contract. However, if you don't need to perform anything special on fallback invocation, you can use simple `opcode.RET` script. 12. Sign and submit P2P notary request. Use - [func (*Client) SignAndPushP2PNotaryRequest](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.SignAndPushP2PNotaryRequest) for it. + [func (*Client) SignAndPushP2PNotaryRequest](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpcclient#Client.SignAndPushP2PNotaryRequest) for it. - Use the signed main transaction from step 8 as `mainTx` argument. - Use the fallback script from step 10 as `fallbackScript` argument. - Use `-1` as `fallbackSysFee` argument to define system fee by test diff --git a/internal/basicchain/basic.go b/internal/basicchain/basic.go index b617827d3..f0071cfd3 100644 --- a/internal/basicchain/basic.go +++ b/internal/basicchain/basic.go @@ -14,7 +14,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/neotest" - "github.com/nspcc-dev/neo-go/pkg/rpc/client/nns" + "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" "github.com/nspcc-dev/neo-go/pkg/wallet" diff --git a/pkg/rpc/client/client.go b/pkg/rpcclient/client.go similarity index 99% rename from pkg/rpc/client/client.go rename to pkg/rpcclient/client.go index b511871b7..2f45522d0 100644 --- a/pkg/rpc/client/client.go +++ b/pkg/rpcclient/client.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "bytes" diff --git a/pkg/rpc/client/doc.go b/pkg/rpcclient/doc.go similarity index 90% rename from pkg/rpc/client/doc.go rename to pkg/rpcclient/doc.go index e08927fdf..b93f525fc 100644 --- a/pkg/rpc/client/doc.go +++ b/pkg/rpcclient/doc.go @@ -1,6 +1,6 @@ /* -Package client implements NEO-specific JSON-RPC 2.0 client. -This package is currently in alpha and is subject to change. +Package rpcclient implements NEO-specific JSON-RPC 2.0 client. +This package is currently in beta and is subject to change. Client @@ -77,4 +77,4 @@ Unsupported methods sendtoaddress */ -package client +package rpcclient diff --git a/pkg/rpc/client/doc_test.go b/pkg/rpcclient/doc_test.go similarity index 80% rename from pkg/rpc/client/doc_test.go rename to pkg/rpcclient/doc_test.go index cbaa96fc7..d0fbe3e63 100644 --- a/pkg/rpc/client/doc_test.go +++ b/pkg/rpcclient/doc_test.go @@ -1,4 +1,4 @@ -package client_test +package rpcclient_test import ( "context" @@ -6,14 +6,14 @@ import ( "os" "github.com/nspcc-dev/neo-go/pkg/encoding/address" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" ) func Example() { endpoint := "http://seed5.bridgeprotocol.io:10332" - opts := client.Options{} + opts := rpcclient.Options{} - c, err := client.New(context.TODO(), endpoint, opts) + c, err := rpcclient.New(context.TODO(), endpoint, opts) if err != nil { fmt.Println(err) os.Exit(1) diff --git a/pkg/rpc/client/helper.go b/pkg/rpcclient/helper.go similarity index 99% rename from pkg/rpc/client/helper.go rename to pkg/rpcclient/helper.go index 73695ee24..a46f99d98 100644 --- a/pkg/rpc/client/helper.go +++ b/pkg/rpcclient/helper.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "crypto/elliptic" @@ -10,7 +10,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/io" - "github.com/nspcc-dev/neo-go/pkg/rpc/client/nns" + "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns" "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" diff --git a/pkg/rpc/client/native.go b/pkg/rpcclient/native.go similarity index 98% rename from pkg/rpc/client/native.go rename to pkg/rpcclient/native.go index d8471a6ce..f5cc6bd16 100644 --- a/pkg/rpc/client/native.go +++ b/pkg/rpcclient/native.go @@ -1,4 +1,4 @@ -package client +package rpcclient // Various non-policy things from native contracts. @@ -11,7 +11,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/native/nativenames" "github.com/nspcc-dev/neo-go/pkg/core/native/noderoles" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" - "github.com/nspcc-dev/neo-go/pkg/rpc/client/nns" + "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns" "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/util" diff --git a/pkg/rpc/client/nep.go b/pkg/rpcclient/nep.go similarity index 99% rename from pkg/rpc/client/nep.go rename to pkg/rpcclient/nep.go index 3afc79bd2..e761e0352 100644 --- a/pkg/rpc/client/nep.go +++ b/pkg/rpcclient/nep.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "fmt" diff --git a/pkg/rpc/client/nep11.go b/pkg/rpcclient/nep11.go similarity index 99% rename from pkg/rpc/client/nep11.go rename to pkg/rpcclient/nep11.go index 6522d3b02..124a49546 100644 --- a/pkg/rpc/client/nep11.go +++ b/pkg/rpcclient/nep11.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "fmt" diff --git a/pkg/rpc/client/nep17.go b/pkg/rpcclient/nep17.go similarity index 99% rename from pkg/rpc/client/nep17.go rename to pkg/rpcclient/nep17.go index 3f23a1378..acdff51eb 100644 --- a/pkg/rpc/client/nep17.go +++ b/pkg/rpcclient/nep17.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "fmt" diff --git a/pkg/rpc/client/nns/record.go b/pkg/rpcclient/nns/record.go similarity index 100% rename from pkg/rpc/client/nns/record.go rename to pkg/rpcclient/nns/record.go diff --git a/pkg/rpc/client/policy.go b/pkg/rpcclient/policy.go similarity index 99% rename from pkg/rpc/client/policy.go rename to pkg/rpcclient/policy.go index 8fe8f0a2b..481848526 100644 --- a/pkg/rpc/client/policy.go +++ b/pkg/rpcclient/policy.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "fmt" diff --git a/pkg/rpc/client/rpc.go b/pkg/rpcclient/rpc.go similarity index 99% rename from pkg/rpc/client/rpc.go rename to pkg/rpcclient/rpc.go index 9cdd148b7..a165d40a7 100644 --- a/pkg/rpc/client/rpc.go +++ b/pkg/rpcclient/rpc.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "encoding/base64" diff --git a/pkg/rpc/client/rpc_test.go b/pkg/rpcclient/rpc_test.go similarity index 99% rename from pkg/rpc/client/rpc_test.go rename to pkg/rpcclient/rpc_test.go index ae1f89863..183fcbf9e 100644 --- a/pkg/rpc/client/rpc_test.go +++ b/pkg/rpcclient/rpc_test.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "context" diff --git a/pkg/rpc/client/wsclient.go b/pkg/rpcclient/wsclient.go similarity index 99% rename from pkg/rpc/client/wsclient.go rename to pkg/rpcclient/wsclient.go index d98c5093b..758816946 100644 --- a/pkg/rpc/client/wsclient.go +++ b/pkg/rpcclient/wsclient.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "context" diff --git a/pkg/rpc/client/wsclient_test.go b/pkg/rpcclient/wsclient_test.go similarity index 99% rename from pkg/rpc/client/wsclient_test.go rename to pkg/rpcclient/wsclient_test.go index 2b6bde70f..7dcd1ee5a 100644 --- a/pkg/rpc/client/wsclient_test.go +++ b/pkg/rpcclient/wsclient_test.go @@ -1,4 +1,4 @@ -package client +package rpcclient import ( "context" diff --git a/pkg/services/helpers/rpcbroadcaster/client.go b/pkg/services/helpers/rpcbroadcaster/client.go index ca45d7135..43c4e97c2 100644 --- a/pkg/services/helpers/rpcbroadcaster/client.go +++ b/pkg/services/helpers/rpcbroadcaster/client.go @@ -4,13 +4,13 @@ import ( "context" "time" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" "go.uber.org/zap" ) // RPCClient represent an rpc client for a single node. type RPCClient struct { - client *client.Client + client *rpcclient.Client addr string close chan struct{} finished chan struct{} @@ -21,7 +21,7 @@ type RPCClient struct { } // SendMethod represents an rpc method for sending data to other nodes. -type SendMethod func(*client.Client, []interface{}) error +type SendMethod func(*rpcclient.Client, []interface{}) error // NewRPCClient returns a new rpc client for the provided address and method. func (r *RPCBroadcaster) NewRPCClient(addr string, method SendMethod, timeout time.Duration, ch chan []interface{}) *RPCClient { @@ -38,7 +38,7 @@ func (r *RPCBroadcaster) NewRPCClient(addr string, method SendMethod, timeout ti func (c *RPCClient) run() { // We ignore error as not every node can be available on startup. - c.client, _ = client.New(context.Background(), c.addr, client.Options{ + c.client, _ = rpcclient.New(context.Background(), c.addr, rpcclient.Options{ DialTimeout: c.sendTimeout, RequestTimeout: c.sendTimeout, }) @@ -50,7 +50,7 @@ run: case ps := <-c.responses: if c.client == nil { var err error - c.client, err = client.New(context.Background(), c.addr, client.Options{ + c.client, err = rpcclient.New(context.Background(), c.addr, rpcclient.Options{ DialTimeout: c.sendTimeout, RequestTimeout: c.sendTimeout, }) diff --git a/pkg/services/oracle/broadcaster/oracle.go b/pkg/services/oracle/broadcaster/oracle.go index 9fc2627e2..b14b09e5c 100644 --- a/pkg/services/oracle/broadcaster/oracle.go +++ b/pkg/services/oracle/broadcaster/oracle.go @@ -8,7 +8,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "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/rpcclient" "github.com/nspcc-dev/neo-go/pkg/services/helpers/rpcbroadcaster" "github.com/nspcc-dev/neo-go/pkg/services/oracle" "go.uber.org/zap" @@ -33,7 +33,7 @@ func New(cfg config.OracleConfiguration, log *zap.Logger) oracle.Broadcaster { RPCBroadcaster: *rpcbroadcaster.NewRPCBroadcaster(log, cfg.ResponseTimeout), } for i := range cfg.Nodes { - r.Clients[cfg.Nodes[i]] = r.NewRPCClient(cfg.Nodes[i], (*client.Client).SubmitRawOracleResponse, + r.Clients[cfg.Nodes[i]] = r.NewRPCClient(cfg.Nodes[i], (*rpcclient.Client).SubmitRawOracleResponse, cfg.ResponseTimeout, make(chan []interface{}, defaultChanCapacity)) } return r diff --git a/pkg/services/rpcsrv/client_test.go b/pkg/services/rpcsrv/client_test.go index 33f672cff..1e79df772 100644 --- a/pkg/services/rpcsrv/client_test.go +++ b/pkg/services/rpcsrv/client_test.go @@ -27,9 +27,9 @@ import ( "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/network" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" - "github.com/nspcc-dev/neo-go/pkg/rpc/client/nns" "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" + "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" @@ -48,7 +48,7 @@ func TestClient_NEP17(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -93,7 +93,7 @@ func TestAddNetworkFeeCalculateNetworkFee(t *testing.T) { const extraFee = 10 var nonce uint32 - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -341,7 +341,7 @@ func TestCalculateNetworkFee(t *testing.T) { defer rpcSrv.Shutdown() const extraFee = 10 - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -410,7 +410,7 @@ func TestSignAndPushInvocationTx(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -458,7 +458,7 @@ func TestSignAndPushInvocationTx(t *testing.T) { t.Run("good", func(t *testing.T) { t.Run("signer0: sig", func(t *testing.T) { - h, err := c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []client.SignerAccount{ + h, err := c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []rpcclient.SignerAccount{ { Signer: transaction.Signer{ Account: priv0.GetScriptHash(), @@ -471,7 +471,7 @@ func TestSignAndPushInvocationTx(t *testing.T) { check(t, h) }) t.Run("signer0: sig; signer1: sig", func(t *testing.T) { - h, err := c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []client.SignerAccount{ + h, err := c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []rpcclient.SignerAccount{ { Signer: transaction.Signer{ Account: priv0.GetScriptHash(), @@ -491,7 +491,7 @@ func TestSignAndPushInvocationTx(t *testing.T) { check(t, h) }) t.Run("signer0: sig; signer1: contract-based paramless", func(t *testing.T) { - h, err := c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []client.SignerAccount{ + h, err := c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []rpcclient.SignerAccount{ { Signer: transaction.Signer{ Account: priv0.GetScriptHash(), @@ -513,7 +513,7 @@ func TestSignAndPushInvocationTx(t *testing.T) { }) t.Run("error", func(t *testing.T) { t.Run("signer0: sig; signer1: contract-based with params", func(t *testing.T) { - _, err := c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []client.SignerAccount{ + _, err := c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []rpcclient.SignerAccount{ { Signer: transaction.Signer{ Account: priv0.GetScriptHash(), @@ -541,7 +541,7 @@ func TestSignAndPushInvocationTx(t *testing.T) { Parameters: []wallet.ContractParam{{Name: "parameter0", Type: smartcontract.SignatureType}}, }, } - _, err = c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []client.SignerAccount{ + _, err = c.SignAndPushInvocationTx([]byte{byte(opcode.PUSH1)}, acc0, 30, 0, []rpcclient.SignerAccount{ { Signer: transaction.Signer{ Account: priv0.GetScriptHash(), @@ -567,7 +567,7 @@ func TestSignAndPushP2PNotaryRequest(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) acc, err := wallet.NewAccount() require.NoError(t, err) @@ -658,7 +658,7 @@ func TestCalculateNotaryFee(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) t.Run("client not initialized", func(t *testing.T) { @@ -671,7 +671,7 @@ func TestPing(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -686,7 +686,7 @@ func TestCreateTxFromScript(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -715,7 +715,7 @@ func TestCreateNEP17TransferTx(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -735,7 +735,7 @@ func TestCreateNEP17TransferTx(t *testing.T) { require.NoError(t, ic.VM.Run()) }) t.Run("none scope", func(t *testing.T) { - _, err := c.CreateNEP17TransferTx(acc, util.Uint160{}, gasContractHash, 1000, 0, nil, []client.SignerAccount{{ + _, err := c.CreateNEP17TransferTx(acc, util.Uint160{}, gasContractHash, 1000, 0, nil, []rpcclient.SignerAccount{{ Signer: transaction.Signer{ Account: priv.PublicKey().GetScriptHash(), Scopes: transaction.None, @@ -744,7 +744,7 @@ func TestCreateNEP17TransferTx(t *testing.T) { require.Error(t, err) }) t.Run("customcontracts scope", func(t *testing.T) { - tx, err := c.CreateNEP17TransferTx(acc, util.Uint160{}, gasContractHash, 1000, 0, nil, []client.SignerAccount{{ + tx, err := c.CreateNEP17TransferTx(acc, util.Uint160{}, gasContractHash, 1000, 0, nil, []rpcclient.SignerAccount{{ Signer: transaction.Signer{ Account: priv.PublicKey().GetScriptHash(), Scopes: transaction.CustomContracts, @@ -765,7 +765,7 @@ func TestInvokeVerify(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -857,7 +857,7 @@ func TestClient_GetNativeContracts(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -871,7 +871,7 @@ func TestClient_NEP11_ND(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -937,7 +937,7 @@ func TestClient_NEP11_D(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -1016,7 +1016,7 @@ func TestClient_NNS(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -1088,7 +1088,7 @@ func TestClient_IteratorSessions(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -1230,7 +1230,7 @@ func TestClient_GetNotaryServiceFeePerKey(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -1245,7 +1245,7 @@ func TestClient_GetOraclePrice(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -1260,7 +1260,7 @@ func TestClient_InvokeAndPackIteratorResults(t *testing.T) { defer chain.Close() defer rpcSrv.Shutdown() - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -1319,7 +1319,7 @@ func TestClient_Iterator_SessionConfigVariations(t *testing.T) { // storageItemsCount is the amount of storage items stored in Storage contract, it's hard-coded in the contract code. const storageItemsCount = 255 - checkSessionEnabled := func(t *testing.T, c *client.Client) { + checkSessionEnabled := func(t *testing.T, c *rpcclient.Client) { // We expect Iterator with designated ID to be presented on stack. It should be possible to retrieve its values via `traverseiterator` call. res, err := c.InvokeFunction(storageHash, "iterateOverValues", []smartcontract.Parameter{}, nil) require.NoError(t, err) @@ -1347,7 +1347,7 @@ func TestClient_Iterator_SessionConfigVariations(t *testing.T) { require.NoError(t, chain.AddBlock(b)) } - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -1386,7 +1386,7 @@ func TestClient_Iterator_SessionConfigVariations(t *testing.T) { require.NoError(t, chain.AddBlock(b)) } - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) @@ -1400,7 +1400,7 @@ func TestClient_Iterator_SessionConfigVariations(t *testing.T) { require.NoError(t, chain.AddBlock(b)) } - c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) + c, err := rpcclient.New(context.Background(), httpSrv.URL, rpcclient.Options{}) require.NoError(t, err) require.NoError(t, c.Init()) diff --git a/scripts/compare-states/compare-states.go b/scripts/compare-states/compare-states.go index 5a5497f51..7e0e6ad7a 100644 --- a/scripts/compare-states/compare-states.go +++ b/scripts/compare-states/compare-states.go @@ -7,7 +7,7 @@ import ( "os" "github.com/davecgh/go-spew/spew" - "github.com/nspcc-dev/neo-go/pkg/rpc/client" + "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/pmezard/go-difflib/difflib" "github.com/urfave/cli" @@ -15,8 +15,8 @@ import ( var errStateMatches = errors.New("state matches") -func initClient(addr string, name string) (*client.Client, uint32, error) { - c, err := client.New(context.Background(), addr, client.Options{}) +func initClient(addr string, name string) (*rpcclient.Client, uint32, error) { + c, err := rpcclient.New(context.Background(), addr, rpcclient.Options{}) if err != nil { return nil, 0, fmt.Errorf("RPC %s: %w", name, err) } @@ -31,7 +31,7 @@ func initClient(addr string, name string) (*client.Client, uint32, error) { return c, h, nil } -func getRoots(ca *client.Client, cb *client.Client, h uint32) (util.Uint256, util.Uint256, error) { +func getRoots(ca *rpcclient.Client, cb *rpcclient.Client, h uint32) (util.Uint256, util.Uint256, error) { ra, err := ca.GetStateRootByHeight(h) if err != nil { return util.Uint256{}, util.Uint256{}, fmt.Errorf("getstateroot from A for %d: %w", h, err) @@ -43,7 +43,7 @@ func getRoots(ca *client.Client, cb *client.Client, h uint32) (util.Uint256, uti return ra.Root, rb.Root, nil } -func bisectState(ca *client.Client, cb *client.Client, h uint32) (uint32, error) { +func bisectState(ca *rpcclient.Client, cb *rpcclient.Client, h uint32) (uint32, error) { ra, rb, err := getRoots(ca, cb, 0) if err != nil { return 0, err From 2e27c3d82972c4c5e3b5555a07643ae28f63f767 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Thu, 21 Jul 2022 23:38:23 +0300 Subject: [PATCH 03/14] metrics: move package to services Where it belongs. --- cli/server/server.go | 4 ++-- pkg/{network => services}/metrics/metrics.go | 0 pkg/{network => services}/metrics/pprof.go | 0 pkg/{network => services}/metrics/prometheus.go | 0 4 files changed, 2 insertions(+), 2 deletions(-) rename pkg/{network => services}/metrics/metrics.go (100%) rename pkg/{network => services}/metrics/pprof.go (100%) rename pkg/{network => services}/metrics/prometheus.go (100%) diff --git a/cli/server/server.go b/cli/server/server.go index 64246094d..c772e1927 100644 --- a/cli/server/server.go +++ b/cli/server/server.go @@ -21,10 +21,10 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/network" - "github.com/nspcc-dev/neo-go/pkg/network/metrics" - "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv" + "github.com/nspcc-dev/neo-go/pkg/services/metrics" "github.com/nspcc-dev/neo-go/pkg/services/notary" "github.com/nspcc-dev/neo-go/pkg/services/oracle" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv" "github.com/nspcc-dev/neo-go/pkg/services/stateroot" "github.com/urfave/cli" "go.uber.org/zap" diff --git a/pkg/network/metrics/metrics.go b/pkg/services/metrics/metrics.go similarity index 100% rename from pkg/network/metrics/metrics.go rename to pkg/services/metrics/metrics.go diff --git a/pkg/network/metrics/pprof.go b/pkg/services/metrics/pprof.go similarity index 100% rename from pkg/network/metrics/pprof.go rename to pkg/services/metrics/pprof.go diff --git a/pkg/network/metrics/prometheus.go b/pkg/services/metrics/prometheus.go similarity index 100% rename from pkg/network/metrics/prometheus.go rename to pkg/services/metrics/prometheus.go From 1e0750e3cdf88706dfb126adf747fa2ce06b0de9 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 19:09:29 +0300 Subject: [PATCH 04/14] rpc: merge response and request under pkg/neorpc Move result there also. --- cli/contract_test.go | 2 +- cli/multisig_test.go | 2 +- cli/query/query.go | 2 +- cli/smartcontract/smart_contract.go | 2 +- cli/wallet/nep17.go | 2 +- internal/fakechain/fakechain.go | 2 +- pkg/core/blockchain.go | 2 +- pkg/core/blockchain_neotest_test.go | 2 +- pkg/core/blockchainer/blockchainer.go | 2 +- pkg/{rpc/response => neorpc}/errors.go | 2 +- pkg/{rpc/response => neorpc}/events.go | 2 +- .../result/application_log.go | 0 pkg/{rpc/response => neorpc}/result/block.go | 0 .../result/block_header.go | 0 .../response => neorpc}/result/findstates.go | 0 pkg/{rpc/response => neorpc}/result/invoke.go | 0 .../response => neorpc}/result/invoke_test.go | 0 pkg/{rpc/response => neorpc}/result/mpt.go | 0 .../response => neorpc}/result/mpt_test.go | 0 pkg/{rpc/response => neorpc}/result/netfee.go | 0 pkg/{rpc/response => neorpc}/result/peers.go | 0 .../response => neorpc}/result/peers_test.go | 0 .../response => neorpc}/result/raw_mempool.go | 0 .../result/relay_result.go | 0 .../subscriptions/notary_request_event.go | 0 .../subscriptions/notification_event.go | 0 .../subscriptions/notification_event_test.go | 0 pkg/{rpc/response => neorpc}/result/tokens.go | 0 .../result/tx_raw_output.go | 0 .../result/unclaimed_gas.go | 0 .../result/validate_address.go | 0 .../response => neorpc}/result/validator.go | 0 .../result/validator_test.go | 0 .../response => neorpc}/result/version.go | 0 .../result/version_test.go | 0 pkg/{rpc/request => neorpc}/types.go | 40 +- pkg/rpc/response/types.go | 34 -- pkg/rpcclient/client.go | 13 +- pkg/rpcclient/helper.go | 2 +- pkg/rpcclient/native.go | 2 +- pkg/rpcclient/nep11.go | 2 +- pkg/rpcclient/rpc.go | 8 +- pkg/rpcclient/rpc_test.go | 2 +- pkg/rpcclient/wsclient.go | 53 +- pkg/rpcclient/wsclient_test.go | 18 +- pkg/services/rpcsrv/client_test.go | 2 +- pkg/services/rpcsrv/error.go | 24 +- pkg/services/rpcsrv/params/param.go | 10 +- pkg/services/rpcsrv/params/param_test.go | 16 +- pkg/services/rpcsrv/params/types.go | 4 +- pkg/services/rpcsrv/server.go | 539 +++++++++--------- pkg/services/rpcsrv/server_test.go | 14 +- pkg/services/rpcsrv/subscription.go | 29 +- pkg/services/rpcsrv/subscription_test.go | 92 +-- pkg/services/rpcsrv/tokens.go | 2 +- 55 files changed, 462 insertions(+), 466 deletions(-) rename pkg/{rpc/response => neorpc}/errors.go (99%) rename pkg/{rpc/response => neorpc}/events.go (99%) rename pkg/{rpc/response => neorpc}/result/application_log.go (100%) rename pkg/{rpc/response => neorpc}/result/block.go (100%) rename pkg/{rpc/response => neorpc}/result/block_header.go (100%) rename pkg/{rpc/response => neorpc}/result/findstates.go (100%) rename pkg/{rpc/response => neorpc}/result/invoke.go (100%) rename pkg/{rpc/response => neorpc}/result/invoke_test.go (100%) rename pkg/{rpc/response => neorpc}/result/mpt.go (100%) rename pkg/{rpc/response => neorpc}/result/mpt_test.go (100%) rename pkg/{rpc/response => neorpc}/result/netfee.go (100%) rename pkg/{rpc/response => neorpc}/result/peers.go (100%) rename pkg/{rpc/response => neorpc}/result/peers_test.go (100%) rename pkg/{rpc/response => neorpc}/result/raw_mempool.go (100%) rename pkg/{rpc/response => neorpc}/result/relay_result.go (100%) rename pkg/{rpc/response => neorpc}/result/subscriptions/notary_request_event.go (100%) rename pkg/{rpc/response => neorpc}/result/subscriptions/notification_event.go (100%) rename pkg/{rpc/response => neorpc}/result/subscriptions/notification_event_test.go (100%) rename pkg/{rpc/response => neorpc}/result/tokens.go (100%) rename pkg/{rpc/response => neorpc}/result/tx_raw_output.go (100%) rename pkg/{rpc/response => neorpc}/result/unclaimed_gas.go (100%) rename pkg/{rpc/response => neorpc}/result/validate_address.go (100%) rename pkg/{rpc/response => neorpc}/result/validator.go (100%) rename pkg/{rpc/response => neorpc}/result/validator_test.go (100%) rename pkg/{rpc/response => neorpc}/result/version.go (100%) rename pkg/{rpc/response => neorpc}/result/version_test.go (100%) rename pkg/{rpc/request => neorpc}/types.go (77%) delete mode 100644 pkg/rpc/response/types.go diff --git a/cli/contract_test.go b/cli/contract_test.go index 1db9e312d..6b2733bb1 100644 --- a/cli/contract_test.go +++ b/cli/contract_test.go @@ -19,7 +19,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/smartcontract/nef" "github.com/nspcc-dev/neo-go/pkg/util" diff --git a/cli/multisig_test.go b/cli/multisig_test.go index c203a5d4c..2e69f2499 100644 --- a/cli/multisig_test.go +++ b/cli/multisig_test.go @@ -12,7 +12,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/address" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm/vmstate" diff --git a/cli/query/query.go b/cli/query/query.go index 6dd387ac6..492be40e6 100644 --- a/cli/query/query.go +++ b/cli/query/query.go @@ -17,7 +17,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm" diff --git a/cli/smartcontract/smart_contract.go b/cli/smartcontract/smart_contract.go index 2e28a586c..e14e31b7b 100644 --- a/cli/smartcontract/smart_contract.go +++ b/cli/smartcontract/smart_contract.go @@ -21,8 +21,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/rpcclient" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/smartcontract/nef" diff --git a/cli/wallet/nep17.go b/cli/wallet/nep17.go index 6bda7a68d..0999df7e5 100644 --- a/cli/wallet/nep17.go +++ b/cli/wallet/nep17.go @@ -15,7 +15,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/native/nativenames" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/util" diff --git a/internal/fakechain/fakechain.go b/internal/fakechain/fakechain.go index 9674034c9..0490d0ba2 100644 --- a/internal/fakechain/fakechain.go +++ b/internal/fakechain/fakechain.go @@ -19,7 +19,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result/subscriptions" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" uatomic "go.uber.org/atomic" diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 366ea38b4..09ad86e26 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -33,7 +33,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" "github.com/nspcc-dev/neo-go/pkg/io" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result/subscriptions" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" diff --git a/pkg/core/blockchain_neotest_test.go b/pkg/core/blockchain_neotest_test.go index 15e8a56d3..5849baa2e 100644 --- a/pkg/core/blockchain_neotest_test.go +++ b/pkg/core/blockchain_neotest_test.go @@ -36,7 +36,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/neotest" "github.com/nspcc-dev/neo-go/pkg/neotest/chain" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result/subscriptions" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" diff --git a/pkg/core/blockchainer/blockchainer.go b/pkg/core/blockchainer/blockchainer.go index f8503d31f..ba47bdd00 100644 --- a/pkg/core/blockchainer/blockchainer.go +++ b/pkg/core/blockchainer/blockchainer.go @@ -12,7 +12,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result/subscriptions" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" ) diff --git a/pkg/rpc/response/errors.go b/pkg/neorpc/errors.go similarity index 99% rename from pkg/rpc/response/errors.go rename to pkg/neorpc/errors.go index 21a50de0b..cc42af56e 100644 --- a/pkg/rpc/response/errors.go +++ b/pkg/neorpc/errors.go @@ -1,4 +1,4 @@ -package response +package neorpc import ( "fmt" diff --git a/pkg/rpc/response/events.go b/pkg/neorpc/events.go similarity index 99% rename from pkg/rpc/response/events.go rename to pkg/neorpc/events.go index 15264e041..ab01628e5 100644 --- a/pkg/rpc/response/events.go +++ b/pkg/neorpc/events.go @@ -1,4 +1,4 @@ -package response +package neorpc import ( "encoding/json" diff --git a/pkg/rpc/response/result/application_log.go b/pkg/neorpc/result/application_log.go similarity index 100% rename from pkg/rpc/response/result/application_log.go rename to pkg/neorpc/result/application_log.go diff --git a/pkg/rpc/response/result/block.go b/pkg/neorpc/result/block.go similarity index 100% rename from pkg/rpc/response/result/block.go rename to pkg/neorpc/result/block.go diff --git a/pkg/rpc/response/result/block_header.go b/pkg/neorpc/result/block_header.go similarity index 100% rename from pkg/rpc/response/result/block_header.go rename to pkg/neorpc/result/block_header.go diff --git a/pkg/rpc/response/result/findstates.go b/pkg/neorpc/result/findstates.go similarity index 100% rename from pkg/rpc/response/result/findstates.go rename to pkg/neorpc/result/findstates.go diff --git a/pkg/rpc/response/result/invoke.go b/pkg/neorpc/result/invoke.go similarity index 100% rename from pkg/rpc/response/result/invoke.go rename to pkg/neorpc/result/invoke.go diff --git a/pkg/rpc/response/result/invoke_test.go b/pkg/neorpc/result/invoke_test.go similarity index 100% rename from pkg/rpc/response/result/invoke_test.go rename to pkg/neorpc/result/invoke_test.go diff --git a/pkg/rpc/response/result/mpt.go b/pkg/neorpc/result/mpt.go similarity index 100% rename from pkg/rpc/response/result/mpt.go rename to pkg/neorpc/result/mpt.go diff --git a/pkg/rpc/response/result/mpt_test.go b/pkg/neorpc/result/mpt_test.go similarity index 100% rename from pkg/rpc/response/result/mpt_test.go rename to pkg/neorpc/result/mpt_test.go diff --git a/pkg/rpc/response/result/netfee.go b/pkg/neorpc/result/netfee.go similarity index 100% rename from pkg/rpc/response/result/netfee.go rename to pkg/neorpc/result/netfee.go diff --git a/pkg/rpc/response/result/peers.go b/pkg/neorpc/result/peers.go similarity index 100% rename from pkg/rpc/response/result/peers.go rename to pkg/neorpc/result/peers.go diff --git a/pkg/rpc/response/result/peers_test.go b/pkg/neorpc/result/peers_test.go similarity index 100% rename from pkg/rpc/response/result/peers_test.go rename to pkg/neorpc/result/peers_test.go diff --git a/pkg/rpc/response/result/raw_mempool.go b/pkg/neorpc/result/raw_mempool.go similarity index 100% rename from pkg/rpc/response/result/raw_mempool.go rename to pkg/neorpc/result/raw_mempool.go diff --git a/pkg/rpc/response/result/relay_result.go b/pkg/neorpc/result/relay_result.go similarity index 100% rename from pkg/rpc/response/result/relay_result.go rename to pkg/neorpc/result/relay_result.go diff --git a/pkg/rpc/response/result/subscriptions/notary_request_event.go b/pkg/neorpc/result/subscriptions/notary_request_event.go similarity index 100% rename from pkg/rpc/response/result/subscriptions/notary_request_event.go rename to pkg/neorpc/result/subscriptions/notary_request_event.go diff --git a/pkg/rpc/response/result/subscriptions/notification_event.go b/pkg/neorpc/result/subscriptions/notification_event.go similarity index 100% rename from pkg/rpc/response/result/subscriptions/notification_event.go rename to pkg/neorpc/result/subscriptions/notification_event.go diff --git a/pkg/rpc/response/result/subscriptions/notification_event_test.go b/pkg/neorpc/result/subscriptions/notification_event_test.go similarity index 100% rename from pkg/rpc/response/result/subscriptions/notification_event_test.go rename to pkg/neorpc/result/subscriptions/notification_event_test.go diff --git a/pkg/rpc/response/result/tokens.go b/pkg/neorpc/result/tokens.go similarity index 100% rename from pkg/rpc/response/result/tokens.go rename to pkg/neorpc/result/tokens.go diff --git a/pkg/rpc/response/result/tx_raw_output.go b/pkg/neorpc/result/tx_raw_output.go similarity index 100% rename from pkg/rpc/response/result/tx_raw_output.go rename to pkg/neorpc/result/tx_raw_output.go diff --git a/pkg/rpc/response/result/unclaimed_gas.go b/pkg/neorpc/result/unclaimed_gas.go similarity index 100% rename from pkg/rpc/response/result/unclaimed_gas.go rename to pkg/neorpc/result/unclaimed_gas.go diff --git a/pkg/rpc/response/result/validate_address.go b/pkg/neorpc/result/validate_address.go similarity index 100% rename from pkg/rpc/response/result/validate_address.go rename to pkg/neorpc/result/validate_address.go diff --git a/pkg/rpc/response/result/validator.go b/pkg/neorpc/result/validator.go similarity index 100% rename from pkg/rpc/response/result/validator.go rename to pkg/neorpc/result/validator.go diff --git a/pkg/rpc/response/result/validator_test.go b/pkg/neorpc/result/validator_test.go similarity index 100% rename from pkg/rpc/response/result/validator_test.go rename to pkg/neorpc/result/validator_test.go diff --git a/pkg/rpc/response/result/version.go b/pkg/neorpc/result/version.go similarity index 100% rename from pkg/rpc/response/result/version.go rename to pkg/neorpc/result/version.go diff --git a/pkg/rpc/response/result/version_test.go b/pkg/neorpc/result/version_test.go similarity index 100% rename from pkg/rpc/response/result/version_test.go rename to pkg/neorpc/result/version_test.go diff --git a/pkg/rpc/request/types.go b/pkg/neorpc/types.go similarity index 77% rename from pkg/rpc/request/types.go rename to pkg/neorpc/types.go index 1da9a5f70..d78991380 100644 --- a/pkg/rpc/request/types.go +++ b/pkg/neorpc/types.go @@ -1,4 +1,9 @@ -package request +/* +Package neorpc contains a set of types used for JSON-RPC communication with Neo servers. +It defines basic request/response types as well as a set of errors and additional +parameters used for specific requests/responses. +*/ +package neorpc import ( "encoding/json" @@ -17,10 +22,10 @@ const ( ) type ( - // Raw represents JSON-RPC request. It's generic enough to be used in many + // Request represents JSON-RPC request. It's generic enough to be used in many // generic JSON-RPC communication scenarios, yet at the same time it's // tailored for NeoGo RPC Client needs. - Raw struct { + Request struct { // JSONRPC is the protocol version, only valid when it contains JSONRPCVersion. JSONRPC string `json:"jsonrpc"` // Method is the method being called. @@ -37,6 +42,35 @@ type ( ID uint64 `json:"id"` } + // Header is a generic JSON-RPC 2.0 response header (ID and JSON-RPC version). + Header struct { + ID json.RawMessage `json:"id"` + JSONRPC string `json:"jsonrpc"` + } + + // HeaderAndError adds an Error (that can be empty) to the Header, it's used + // to construct type-specific responses. + HeaderAndError struct { + Header + Error *Error `json:"error,omitempty"` + } + + // Raw represents a standard raw JSON-RPC 2.0 + // response: http://www.jsonrpc.org/specification#response_object. + Response struct { + HeaderAndError + Result json.RawMessage `json:"result,omitempty"` + } + + // Notification is a type used to represent wire format of events, they're + // special in that they look like requests but they don't have IDs and their + // "method" is actually an event name. + Notification struct { + JSONRPC string `json:"jsonrpc"` + Event EventID `json:"method"` + Payload []interface{} `json:"params"` + } + // BlockFilter is a wrapper structure for the block event filter. The only // allowed filter is primary index. BlockFilter struct { diff --git a/pkg/rpc/response/types.go b/pkg/rpc/response/types.go deleted file mode 100644 index 136082768..000000000 --- a/pkg/rpc/response/types.go +++ /dev/null @@ -1,34 +0,0 @@ -package response - -import ( - "encoding/json" -) - -// Header is a generic JSON-RPC 2.0 response header (ID and JSON-RPC version). -type Header struct { - ID json.RawMessage `json:"id"` - JSONRPC string `json:"jsonrpc"` -} - -// HeaderAndError adds an Error (that can be empty) to the Header, it's used -// to construct type-specific responses. -type HeaderAndError struct { - Header - Error *Error `json:"error,omitempty"` -} - -// Raw represents a standard raw JSON-RPC 2.0 -// response: http://www.jsonrpc.org/specification#response_object. -type Raw struct { - HeaderAndError - Result json.RawMessage `json:"result,omitempty"` -} - -// Notification is a type used to represent wire format of events, they're -// special in that they look like requests but they don't have IDs and their -// "method" is actually an event name. -type Notification struct { - JSONRPC string `json:"jsonrpc"` - Event EventID `json:"method"` - Payload []interface{} `json:"params"` -} diff --git a/pkg/rpcclient/client.go b/pkg/rpcclient/client.go index 2f45522d0..1b70593fd 100644 --- a/pkg/rpcclient/client.go +++ b/pkg/rpcclient/client.go @@ -13,8 +13,7 @@ import ( "time" "github.com/nspcc-dev/neo-go/pkg/config/netmode" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" - "github.com/nspcc-dev/neo-go/pkg/rpc/response" + "github.com/nspcc-dev/neo-go/pkg/neorpc" "github.com/nspcc-dev/neo-go/pkg/util" "go.uber.org/atomic" ) @@ -34,7 +33,7 @@ type Client struct { endpoint *url.URL ctx context.Context opts Options - requestF func(*request.Raw) (*response.Raw, error) + requestF func(*neorpc.Request) (*neorpc.Response, error) cacheLock sync.RWMutex // cache stores RPC node related information the client is bound to. @@ -176,8 +175,8 @@ func (c *Client) performRequest(method string, p []interface{}, v interface{}) e if p == nil { p = []interface{}{} // neo-project/neo-modules#742 } - var r = request.Raw{ - JSONRPC: request.JSONRPCVersion, + var r = neorpc.Request{ + JSONRPC: neorpc.JSONRPCVersion, Method: method, Params: p, ID: c.getNextRequestID(), @@ -195,10 +194,10 @@ func (c *Client) performRequest(method string, p []interface{}, v interface{}) e return json.Unmarshal(raw.Result, v) } -func (c *Client) makeHTTPRequest(r *request.Raw) (*response.Raw, error) { +func (c *Client) makeHTTPRequest(r *neorpc.Request) (*neorpc.Response, error) { var ( buf = new(bytes.Buffer) - raw = new(response.Raw) + raw = new(neorpc.Response) ) if err := json.NewEncoder(buf).Encode(r); err != nil { diff --git a/pkg/rpcclient/helper.go b/pkg/rpcclient/helper.go index a46f99d98..5f1614585 100644 --- a/pkg/rpcclient/helper.go +++ b/pkg/rpcclient/helper.go @@ -10,8 +10,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/io" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" "github.com/nspcc-dev/neo-go/pkg/util" diff --git a/pkg/rpcclient/native.go b/pkg/rpcclient/native.go index f5cc6bd16..4b7d49ccb 100644 --- a/pkg/rpcclient/native.go +++ b/pkg/rpcclient/native.go @@ -11,8 +11,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/native/nativenames" "github.com/nspcc-dev/neo-go/pkg/core/native/noderoles" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/util" ) diff --git a/pkg/rpcclient/nep11.go b/pkg/rpcclient/nep11.go index 124a49546..4ddc66855 100644 --- a/pkg/rpcclient/nep11.go +++ b/pkg/rpcclient/nep11.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" diff --git a/pkg/rpcclient/rpc.go b/pkg/rpcclient/rpc.go index a165d40a7..abfed089f 100644 --- a/pkg/rpcclient/rpc.go +++ b/pkg/rpcclient/rpc.go @@ -20,9 +20,9 @@ import ( "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" "github.com/nspcc-dev/neo-go/pkg/io" + "github.com/nspcc-dev/neo-go/pkg/neorpc" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/network/payload" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" @@ -694,9 +694,9 @@ func (c *Client) invokeSomething(method string, p []interface{}, signers []trans if len(witnesses) != len(signers) { return nil, fmt.Errorf("number of witnesses should match number of signers, got %d vs %d", len(witnesses), len(signers)) } - signersWithWitnesses := make([]request.SignerWithWitness, len(signers)) + signersWithWitnesses := make([]neorpc.SignerWithWitness, len(signers)) for i := range signersWithWitnesses { - signersWithWitnesses[i] = request.SignerWithWitness{ + signersWithWitnesses[i] = neorpc.SignerWithWitness{ Signer: signers[i], Witness: witnesses[i], } diff --git a/pkg/rpcclient/rpc_test.go b/pkg/rpcclient/rpc_test.go index 183fcbf9e..a7c6dc80a 100644 --- a/pkg/rpcclient/rpc_test.go +++ b/pkg/rpcclient/rpc_test.go @@ -27,7 +27,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" "github.com/nspcc-dev/neo-go/pkg/io" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" diff --git a/pkg/rpcclient/wsclient.go b/pkg/rpcclient/wsclient.go index 758816946..2e0c75677 100644 --- a/pkg/rpcclient/wsclient.go +++ b/pkg/rpcclient/wsclient.go @@ -13,9 +13,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/block" "github.com/nspcc-dev/neo-go/pkg/core/state" "github.com/nspcc-dev/neo-go/pkg/core/transaction" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" - "github.com/nspcc-dev/neo-go/pkg/rpc/response" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result/subscriptions" + "github.com/nspcc-dev/neo-go/pkg/neorpc" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/util" "go.uber.org/atomic" ) @@ -38,7 +37,7 @@ type WSClient struct { ws *websocket.Conn done chan struct{} - requests chan *request.Raw + requests chan *neorpc.Request shutdown chan struct{} closeCalled atomic.Bool @@ -49,21 +48,21 @@ type WSClient struct { subscriptions map[string]bool respLock sync.RWMutex - respChannels map[uint64]chan *response.Raw + respChannels map[uint64]chan *neorpc.Response } // Notification represents a server-generated notification for client subscriptions. // Value can be one of block.Block, state.AppExecResult, subscriptions.NotificationEvent // transaction.Transaction or subscriptions.NotaryRequestEvent based on Type. type Notification struct { - Type response.EventID + Type neorpc.EventID Value interface{} } // requestResponse is a combined type for request and response since we can get // any of them here. type requestResponse struct { - response.Raw + neorpc.Response Method string `json:"method"` RawParams []json.RawMessage `json:"params,omitempty"` } @@ -103,8 +102,8 @@ func NewWS(ctx context.Context, endpoint string, opts Options) (*WSClient, error shutdown: make(chan struct{}), done: make(chan struct{}), closeCalled: *atomic.NewBool(false), - respChannels: make(map[uint64]chan *response.Raw), - requests: make(chan *request.Raw), + respChannels: make(map[uint64]chan *neorpc.Response), + requests: make(chan *neorpc.Request), subscriptions: make(map[string]bool), } @@ -159,20 +158,20 @@ readloop: break readloop } if rr.ID == nil && rr.Method != "" { - event, err := response.GetEventIDFromString(rr.Method) + event, err := neorpc.GetEventIDFromString(rr.Method) if err != nil { // Bad event received. connCloseErr = fmt.Errorf("failed to perse event ID from string %s: %w", rr.Method, err) break readloop } - if event != response.MissedEventID && len(rr.RawParams) != 1 { + if event != neorpc.MissedEventID && len(rr.RawParams) != 1 { // Bad event received. connCloseErr = fmt.Errorf("bad event received: %s / %d", event, len(rr.RawParams)) break readloop } var val interface{} switch event { - case response.BlockEventID: + case neorpc.BlockEventID: sr, err := c.StateRootInHeader() if err != nil { // Client is not initialized. @@ -180,22 +179,22 @@ readloop: break readloop } val = block.New(sr) - case response.TransactionEventID: + case neorpc.TransactionEventID: val = &transaction.Transaction{} - case response.NotificationEventID: + case neorpc.NotificationEventID: val = new(subscriptions.NotificationEvent) - case response.ExecutionEventID: + case neorpc.ExecutionEventID: val = new(state.AppExecResult) - case response.NotaryRequestEventID: + case neorpc.NotaryRequestEventID: val = new(subscriptions.NotaryRequestEvent) - case response.MissedEventID: + case neorpc.MissedEventID: // No value. default: // Bad event received. connCloseErr = fmt.Errorf("unknown event received: %d", event) break readloop } - if event != response.MissedEventID { + if event != neorpc.MissedEventID { err = json.Unmarshal(rr.RawParams[0], val) if err != nil { // Bad event received. @@ -215,7 +214,7 @@ readloop: connCloseErr = fmt.Errorf("unknown response channel for response %d", id) break readloop // Unknown response (unexpected response ID). } - ch <- &rr.Raw + ch <- &rr.Response } else { // Malformed response, neither valid request, nor valid response. connCloseErr = fmt.Errorf("malformed response") @@ -284,14 +283,14 @@ func (c *WSClient) unregisterRespChannel(id uint64) { } } -func (c *WSClient) getResponseChannel(id uint64) chan *response.Raw { +func (c *WSClient) getResponseChannel(id uint64) chan *neorpc.Response { c.respLock.RLock() defer c.respLock.RUnlock() return c.respChannels[id] } -func (c *WSClient) makeWsRequest(r *request.Raw) (*response.Raw, error) { - ch := make(chan *response.Raw) +func (c *WSClient) makeWsRequest(r *neorpc.Request) (*neorpc.Response, error) { + ch := make(chan *neorpc.Response) c.respLock.Lock() select { case <-c.done: @@ -354,7 +353,7 @@ func (c *WSClient) performUnsubscription(id string) error { func (c *WSClient) SubscribeForNewBlocks(primary *int) (string, error) { params := []interface{}{"block_added"} if primary != nil { - params = append(params, request.BlockFilter{Primary: *primary}) + params = append(params, neorpc.BlockFilter{Primary: *primary}) } return c.performSubscription(params) } @@ -365,7 +364,7 @@ func (c *WSClient) SubscribeForNewBlocks(primary *int) (string, error) { func (c *WSClient) SubscribeForNewTransactions(sender *util.Uint160, signer *util.Uint160) (string, error) { params := []interface{}{"transaction_added"} if sender != nil || signer != nil { - params = append(params, request.TxFilter{Sender: sender, Signer: signer}) + params = append(params, neorpc.TxFilter{Sender: sender, Signer: signer}) } return c.performSubscription(params) } @@ -377,7 +376,7 @@ func (c *WSClient) SubscribeForNewTransactions(sender *util.Uint160, signer *uti func (c *WSClient) SubscribeForExecutionNotifications(contract *util.Uint160, name *string) (string, error) { params := []interface{}{"notification_from_execution"} if contract != nil || name != nil { - params = append(params, request.NotificationFilter{Contract: contract, Name: name}) + params = append(params, neorpc.NotificationFilter{Contract: contract, Name: name}) } return c.performSubscription(params) } @@ -392,7 +391,7 @@ func (c *WSClient) SubscribeForTransactionExecutions(state *string) (string, err if *state != "HALT" && *state != "FAULT" { return "", errors.New("bad state parameter") } - params = append(params, request.ExecutionFilter{State: *state}) + params = append(params, neorpc.ExecutionFilter{State: *state}) } return c.performSubscription(params) } @@ -404,7 +403,7 @@ func (c *WSClient) SubscribeForTransactionExecutions(state *string) (string, err func (c *WSClient) SubscribeForNotaryRequests(sender *util.Uint160, mainSigner *util.Uint160) (string, error) { params := []interface{}{"notary_request_event"} if sender != nil { - params = append(params, request.TxFilter{Sender: sender, Signer: mainSigner}) + params = append(params, neorpc.TxFilter{Sender: sender, Signer: mainSigner}) } return c.performSubscription(params) } diff --git a/pkg/rpcclient/wsclient_test.go b/pkg/rpcclient/wsclient_test.go index 7dcd1ee5a..eb730d2c0 100644 --- a/pkg/rpcclient/wsclient_test.go +++ b/pkg/rpcclient/wsclient_test.go @@ -16,8 +16,8 @@ import ( "github.com/gorilla/websocket" "github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/core/transaction" + "github.com/nspcc-dev/neo-go/pkg/neorpc" "github.com/nspcc-dev/neo-go/pkg/network/payload" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/stretchr/testify/require" @@ -200,7 +200,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(request.BlockFilter) + filt := new(neorpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, 3, filt.Primary) }, @@ -213,7 +213,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(request.TxFilter) + filt := new(neorpc.TxFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Sender) require.Nil(t, filt.Signer) @@ -227,7 +227,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(request.TxFilter) + filt := new(neorpc.TxFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Nil(t, filt.Sender) require.Equal(t, util.Uint160{0, 42}, *filt.Signer) @@ -242,7 +242,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(request.TxFilter) + filt := new(neorpc.TxFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Sender) require.Equal(t, util.Uint160{0, 42}, *filt.Signer) @@ -256,7 +256,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(request.NotificationFilter) + filt := new(neorpc.NotificationFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Contract) require.Nil(t, filt.Name) @@ -270,7 +270,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(request.NotificationFilter) + filt := new(neorpc.NotificationFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, "my_pretty_notification", *filt.Name) require.Nil(t, filt.Contract) @@ -285,7 +285,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(request.NotificationFilter) + filt := new(neorpc.NotificationFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Contract) require.Equal(t, "my_pretty_notification", *filt.Name) @@ -299,7 +299,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(request.ExecutionFilter) + filt := new(neorpc.ExecutionFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, "FAULT", filt.State) }, diff --git a/pkg/services/rpcsrv/client_test.go b/pkg/services/rpcsrv/client_test.go index 1e79df772..219963faf 100644 --- a/pkg/services/rpcsrv/client_test.go +++ b/pkg/services/rpcsrv/client_test.go @@ -26,8 +26,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/network" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" "github.com/nspcc-dev/neo-go/pkg/rpcclient" "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns" "github.com/nspcc-dev/neo-go/pkg/smartcontract" diff --git a/pkg/services/rpcsrv/error.go b/pkg/services/rpcsrv/error.go index 102a4f07f..819b40b8a 100644 --- a/pkg/services/rpcsrv/error.go +++ b/pkg/services/rpcsrv/error.go @@ -3,25 +3,25 @@ package rpcsrv import ( "net/http" - "github.com/nspcc-dev/neo-go/pkg/rpc/response" + "github.com/nspcc-dev/neo-go/pkg/neorpc" ) // abstractResult is an interface which represents either single JSON-RPC 2.0 response // or batch JSON-RPC 2.0 response. type abstractResult interface { - RunForErrors(f func(jsonErr *response.Error)) + RunForErrors(f func(jsonErr *neorpc.Error)) } // abstract represents abstract JSON-RPC 2.0 response. It is used as a server-side response // representation. type abstract struct { - response.Header - Error *response.Error `json:"error,omitempty"` - Result interface{} `json:"result,omitempty"` + neorpc.Header + Error *neorpc.Error `json:"error,omitempty"` + Result interface{} `json:"result,omitempty"` } // RunForErrors implements abstractResult interface. -func (a abstract) RunForErrors(f func(jsonErr *response.Error)) { +func (a abstract) RunForErrors(f func(jsonErr *neorpc.Error)) { if a.Error != nil { f(a.Error) } @@ -31,7 +31,7 @@ func (a abstract) RunForErrors(f func(jsonErr *response.Error)) { type abstractBatch []abstract // RunForErrors implements abstractResult interface. -func (ab abstractBatch) RunForErrors(f func(jsonErr *response.Error)) { +func (ab abstractBatch) RunForErrors(f func(jsonErr *neorpc.Error)) { for _, a := range ab { if a.Error != nil { f(a.Error) @@ -39,16 +39,16 @@ func (ab abstractBatch) RunForErrors(f func(jsonErr *response.Error)) { } } -func getHTTPCodeForError(respErr *response.Error) int { +func getHTTPCodeForError(respErr *neorpc.Error) int { var httpCode int switch respErr.Code { - case response.BadRequestCode: + case neorpc.BadRequestCode: httpCode = http.StatusBadRequest - case response.InvalidRequestCode, response.RPCErrorCode, response.InvalidParamsCode: + case neorpc.InvalidRequestCode, neorpc.RPCErrorCode, neorpc.InvalidParamsCode: httpCode = http.StatusUnprocessableEntity - case response.MethodNotFoundCode: + case neorpc.MethodNotFoundCode: httpCode = http.StatusMethodNotAllowed - case response.InternalServerErrorCode: + case neorpc.InternalServerErrorCode: httpCode = http.StatusInternalServerError default: httpCode = http.StatusUnprocessableEntity diff --git a/pkg/services/rpcsrv/params/param.go b/pkg/services/rpcsrv/params/param.go index b4dfcd4da..db392d58d 100644 --- a/pkg/services/rpcsrv/params/param.go +++ b/pkg/services/rpcsrv/params/param.go @@ -14,7 +14,7 @@ import ( "github.com/google/uuid" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/encoding/address" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" + "github.com/nspcc-dev/neo-go/pkg/neorpc" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/util" ) @@ -380,13 +380,13 @@ func (p *Param) GetBytesBase64() ([]byte, error) { return base64.StdEncoding.DecodeString(s) } -// GetSignerWithWitness returns a request.SignerWithWitness value of the parameter. -func (p *Param) GetSignerWithWitness() (request.SignerWithWitness, error) { +// GetSignerWithWitness returns a neorpc.SignerWithWitness value of the parameter. +func (p *Param) GetSignerWithWitness() (neorpc.SignerWithWitness, error) { // This one doesn't need to be cached, it's used only once. - c := request.SignerWithWitness{} + c := neorpc.SignerWithWitness{} err := json.Unmarshal(p.RawMessage, &c) if err != nil { - return request.SignerWithWitness{}, fmt.Errorf("not a signer: %w", err) + return neorpc.SignerWithWitness{}, fmt.Errorf("not a signer: %w", err) } return c, nil } diff --git a/pkg/services/rpcsrv/params/param_test.go b/pkg/services/rpcsrv/params/param_test.go index 44227ab59..af7c0bbc1 100644 --- a/pkg/services/rpcsrv/params/param_test.go +++ b/pkg/services/rpcsrv/params/param_test.go @@ -12,7 +12,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/encoding/address" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" + "github.com/nspcc-dev/neo-go/pkg/neorpc" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/stretchr/testify/assert" @@ -155,7 +155,7 @@ func TestParam_UnmarshalJSON(t *testing.T) { require.NoError(t, err) expectedAcc, err := util.Uint160DecodeStringLE("cadb3dc2faa3ef14a13b619c9a43124755aa2569") require.NoError(t, err) - require.Equal(t, request.SignerWithWitness{Signer: transaction.Signer{Account: expectedAcc}}, actual) + require.Equal(t, neorpc.SignerWithWitness{Signer: transaction.Signer{Account: expectedAcc}}, actual) }, expectedRawMessage: []byte(`{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569"}`), }, @@ -165,7 +165,7 @@ func TestParam_UnmarshalJSON(t *testing.T) { require.NoError(t, err) expectedAcc, err := address.StringToUint160("NYxb4fSZVKAz8YsgaPK2WkT3KcAE9b3Vag") require.NoError(t, err) - require.Equal(t, request.SignerWithWitness{Signer: transaction.Signer{Account: expectedAcc, Scopes: transaction.Global}}, actual) + require.Equal(t, neorpc.SignerWithWitness{Signer: transaction.Signer{Account: expectedAcc, Scopes: transaction.Global}}, actual) }, expectedRawMessage: []byte(`{"account": "NYxb4fSZVKAz8YsgaPK2WkT3KcAE9b3Vag", "scopes": "Global"}`), }, @@ -244,21 +244,21 @@ func TestGetWitness(t *testing.T) { testCases := []struct { raw string - expected request.SignerWithWitness + expected neorpc.SignerWithWitness }{ - {`{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569"}`, request.SignerWithWitness{ + {`{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569"}`, neorpc.SignerWithWitness{ Signer: transaction.Signer{ Account: accountHash, Scopes: transaction.None, }}, }, - {`{"account": "NYxb4fSZVKAz8YsgaPK2WkT3KcAE9b3Vag", "scopes": "Global"}`, request.SignerWithWitness{ + {`{"account": "NYxb4fSZVKAz8YsgaPK2WkT3KcAE9b3Vag", "scopes": "Global"}`, neorpc.SignerWithWitness{ Signer: transaction.Signer{ Account: addrHash, Scopes: transaction.Global, }}, }, - {`{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569", "scopes": "Global"}`, request.SignerWithWitness{ + {`{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569", "scopes": "Global"}`, neorpc.SignerWithWitness{ Signer: transaction.Signer{ Account: accountHash, Scopes: transaction.Global, @@ -405,7 +405,7 @@ func TestParamGetBytesBase64(t *testing.T) { } func TestParamGetSigner(t *testing.T) { - c := request.SignerWithWitness{ + c := neorpc.SignerWithWitness{ Signer: transaction.Signer{ Account: util.Uint160{1, 2, 3, 4}, Scopes: transaction.Global, diff --git a/pkg/services/rpcsrv/params/types.go b/pkg/services/rpcsrv/params/types.go index 48e3403eb..2ce86d876 100644 --- a/pkg/services/rpcsrv/params/types.go +++ b/pkg/services/rpcsrv/params/types.go @@ -7,7 +7,7 @@ import ( "fmt" "io" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" + "github.com/nspcc-dev/neo-go/pkg/neorpc" ) const ( @@ -106,6 +106,6 @@ func NewRequest() *Request { // NewIn creates a new In struct. func NewIn() *In { return &In{ - JSONRPC: request.JSONRPCVersion, + JSONRPC: neorpc.JSONRPCVersion, } } diff --git a/pkg/services/rpcsrv/server.go b/pkg/services/rpcsrv/server.go index 73244a556..c500ff7ec 100644 --- a/pkg/services/rpcsrv/server.go +++ b/pkg/services/rpcsrv/server.go @@ -38,16 +38,15 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" + "github.com/nspcc-dev/neo-go/pkg/neorpc" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/network" "github.com/nspcc-dev/neo-go/pkg/network/payload" "github.com/nspcc-dev/neo-go/pkg/rpc" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" - "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/rpc/response/result/subscriptions" - "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" "github.com/nspcc-dev/neo-go/pkg/services/oracle" "github.com/nspcc-dev/neo-go/pkg/services/oracle/broadcaster" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" @@ -135,7 +134,7 @@ const ( defaultSessionPoolSize = 20 ) -var rpcHandlers = map[string]func(*Server, params.Params) (interface{}, *response.Error){ +var rpcHandlers = map[string]func(*Server, params.Params) (interface{}, *neorpc.Error){ "calculatenetworkfee": (*Server).calculateNetworkFee, "findstates": (*Server).findStates, "getapplicationlog": (*Server).getApplicationLog, @@ -184,13 +183,13 @@ var rpcHandlers = map[string]func(*Server, params.Params) (interface{}, *respons "verifyproof": (*Server).verifyProof, } -var rpcWsHandlers = map[string]func(*Server, params.Params, *subscriber) (interface{}, *response.Error){ +var rpcWsHandlers = map[string]func(*Server, params.Params, *subscriber) (interface{}, *neorpc.Error){ "subscribe": (*Server).subscribe, "unsubscribe": (*Server).unsubscribe, } -var invalidBlockHeightError = func(index int, height int) *response.Error { - return response.NewRPCError("Invalid block height", fmt.Sprintf("param at index %d should be greater than or equal to 0 and less then or equal to current block height, got: %d", index, height)) +var invalidBlockHeightError = func(index int, height int) *neorpc.Error { + return neorpc.NewRPCError("Invalid block height", fmt.Sprintf("param at index %d should be greater than or equal to 0 and less then or equal to current block height, got: %d", index, height)) } // upgrader is a no-op websocket.Upgrader that reuses HTTP server buffers and @@ -365,7 +364,7 @@ func (s *Server) handleHTTPRequest(w http.ResponseWriter, httpRequest *http.Requ s.writeHTTPErrorResponse( params.NewIn(), w, - response.NewInternalServerError("websocket users limit reached"), + neorpc.NewInternalServerError("websocket users limit reached"), ) return } @@ -389,14 +388,14 @@ func (s *Server) handleHTTPRequest(w http.ResponseWriter, httpRequest *http.Requ s.writeHTTPErrorResponse( params.NewIn(), w, - response.NewInvalidParamsError(fmt.Sprintf("invalid method '%s', please retry with 'POST'", httpRequest.Method)), + neorpc.NewInvalidParamsError(fmt.Sprintf("invalid method '%s', please retry with 'POST'", httpRequest.Method)), ) return } err := req.DecodeData(httpRequest.Body) if err != nil { - s.writeHTTPErrorResponse(params.NewIn(), w, response.NewParseError(err.Error())) + s.writeHTTPErrorResponse(params.NewIn(), w, neorpc.NewParseError(err.Error())) return } @@ -419,9 +418,9 @@ func (s *Server) handleRequest(req *params.Request, sub *subscriber) abstractRes func (s *Server) handleIn(req *params.In, sub *subscriber) abstract { var res interface{} - var resErr *response.Error - if req.JSONRPC != request.JSONRPCVersion { - return s.packResponse(req, nil, response.NewInvalidParamsError(fmt.Sprintf("problem parsing JSON: invalid version, expected 2.0 got '%s'", req.JSONRPC))) + var resErr *neorpc.Error + if req.JSONRPC != neorpc.JSONRPCVersion { + return s.packResponse(req, nil, neorpc.NewInvalidParamsError(fmt.Sprintf("problem parsing JSON: invalid version, expected 2.0 got '%s'", req.JSONRPC))) } reqParams := params.Params(req.RawParams) @@ -432,7 +431,7 @@ func (s *Server) handleIn(req *params.In, sub *subscriber) abstract { incCounter(req.Method) - resErr = response.NewMethodNotFoundError(fmt.Sprintf("method %q not supported", req.Method)) + resErr = neorpc.NewMethodNotFoundError(fmt.Sprintf("method %q not supported", req.Method)) handler, ok := rpcHandlers[req.Method] if ok { res, resErr = handler(s, reqParams) @@ -510,7 +509,7 @@ requestloop: break } res := s.handleRequest(req, subscr) - res.RunForErrors(func(jsonErr *response.Error) { + res.RunForErrors(func(jsonErr *neorpc.Error) { s.logRequestError(req, jsonErr) }) select { @@ -522,7 +521,7 @@ requestloop: s.subsLock.Lock() delete(s.subscribers, subscr) for _, e := range subscr.feeds { - if e.event != response.InvalidEventID { + if e.event != neorpc.InvalidEventID { s.unsubscribeFromChannel(e.event) } } @@ -531,29 +530,29 @@ requestloop: ws.Close() } -func (s *Server) getBestBlockHash(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getBestBlockHash(_ params.Params) (interface{}, *neorpc.Error) { return "0x" + s.chain.CurrentBlockHash().StringLE(), nil } -func (s *Server) getBlockCount(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getBlockCount(_ params.Params) (interface{}, *neorpc.Error) { return s.chain.BlockHeight() + 1, nil } -func (s *Server) getBlockHeaderCount(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getBlockHeaderCount(_ params.Params) (interface{}, *neorpc.Error) { return s.chain.HeaderHeight() + 1, nil } -func (s *Server) getConnectionCount(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getConnectionCount(_ params.Params) (interface{}, *neorpc.Error) { return s.coreServer.PeerCount(), nil } -func (s *Server) blockHashFromParam(param *params.Param) (util.Uint256, *response.Error) { +func (s *Server) blockHashFromParam(param *params.Param) (util.Uint256, *neorpc.Error) { var ( hash util.Uint256 err error ) if param == nil { - return hash, response.ErrInvalidParams + return hash, neorpc.ErrInvalidParams } if hash, err = param.GetUint256(); err != nil { @@ -579,7 +578,7 @@ func (s *Server) fillBlockMetadata(obj io.Serializable, h *block.Header) result. return res } -func (s *Server) getBlock(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) getBlock(reqParams params.Params) (interface{}, *neorpc.Error) { param := reqParams.Value(0) hash, respErr := s.blockHashFromParam(param) if respErr != nil { @@ -588,7 +587,7 @@ func (s *Server) getBlock(reqParams params.Params) (interface{}, *response.Error block, err := s.chain.GetBlock(hash) if err != nil { - return nil, response.NewRPCError("Failed to get block", err.Error()) + return nil, neorpc.NewRPCError("Failed to get block", err.Error()) } if v, _ := reqParams.Value(1).GetBoolean(); v { @@ -603,19 +602,19 @@ func (s *Server) getBlock(reqParams params.Params) (interface{}, *response.Error return writer.Bytes(), nil } -func (s *Server) getBlockHash(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) getBlockHash(reqParams params.Params) (interface{}, *neorpc.Error) { num, err := s.blockHeightFromParam(reqParams.Value(0)) if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } return s.chain.GetHeaderHash(num), nil } -func (s *Server) getVersion(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getVersion(_ params.Params) (interface{}, *neorpc.Error) { port, err := s.coreServer.Port() if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("cannot fetch tcp port: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("cannot fetch tcp port: %s", err)) } cfg := s.chain.GetConfig() @@ -640,7 +639,7 @@ func (s *Server) getVersion(_ params.Params) (interface{}, *response.Error) { }, nil } -func (s *Server) getPeers(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getPeers(_ params.Params) (interface{}, *neorpc.Error) { peers := result.NewGetPeers() peers.AddUnconnected(s.coreServer.UnconnectedPeers()) peers.AddConnected(s.coreServer.ConnectedPeers()) @@ -648,7 +647,7 @@ func (s *Server) getPeers(_ params.Params) (interface{}, *response.Error) { return peers, nil } -func (s *Server) getRawMempool(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) getRawMempool(reqParams params.Params) (interface{}, *neorpc.Error) { verbose, _ := reqParams.Value(0).GetBoolean() mp := s.chain.GetMemPool() hashList := make([]util.Uint256, 0) @@ -665,10 +664,10 @@ func (s *Server) getRawMempool(reqParams params.Params) (interface{}, *response. }, nil } -func (s *Server) validateAddress(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) validateAddress(reqParams params.Params) (interface{}, *neorpc.Error) { param, err := reqParams.Value(0).GetString() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } return result.ValidateAddress{ @@ -678,21 +677,21 @@ func (s *Server) validateAddress(reqParams params.Params) (interface{}, *respons } // calculateNetworkFee calculates network fee for the transaction. -func (s *Server) calculateNetworkFee(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) calculateNetworkFee(reqParams params.Params) (interface{}, *neorpc.Error) { if len(reqParams) < 1 { - return 0, response.ErrInvalidParams + return 0, neorpc.ErrInvalidParams } byteTx, err := reqParams[0].GetBytesBase64() if err != nil { - return 0, response.WrapErrorWithData(response.ErrInvalidParams, err.Error()) + return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) } tx, err := transaction.NewTransactionFromBytes(byteTx) if err != nil { - return 0, response.WrapErrorWithData(response.ErrInvalidParams, err.Error()) + return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) } hashablePart, err := tx.EncodeHashableFields() if err != nil { - return 0, response.WrapErrorWithData(response.ErrInvalidParams, fmt.Sprintf("failed to compute tx size: %s", err)) + return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("failed to compute tx size: %s", err)) } size := len(hashablePart) + io.GetVarSize(len(tx.Signers)) var ( @@ -711,7 +710,7 @@ func (s *Server) calculateNetworkFee(reqParams params.Params) (interface{}, *res if verificationScript == nil { // then it still might be a contract-based verification gasConsumed, err := s.chain.VerifyWitness(signer.Account, tx, &tx.Scripts[i], int64(s.config.MaxGasInvoke)) if err != nil { - return 0, response.NewRPCError("Invalid signature", fmt.Sprintf("contract verification for signer #%d failed: %s", i, err)) + return 0, neorpc.NewRPCError("Invalid signature", fmt.Sprintf("contract verification for signer #%d failed: %s", i, err)) } netFee += gasConsumed size += io.GetVarSize([]byte{}) + // verification script is empty (contract-based witness) @@ -732,27 +731,27 @@ func (s *Server) calculateNetworkFee(reqParams params.Params) (interface{}, *res } // getApplicationLog returns the contract log based on the specified txid or blockid. -func (s *Server) getApplicationLog(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) getApplicationLog(reqParams params.Params) (interface{}, *neorpc.Error) { hash, err := reqParams.Value(0).GetUint256() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } trig := trigger.All if len(reqParams) > 1 { trigString, err := reqParams.Value(1).GetString() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } trig, err = trigger.FromString(trigString) if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } } appExecResults, err := s.chain.GetAppExecResults(hash, trigger.All) if err != nil { - return nil, response.WrapErrorWithData(response.ErrUnknownScriptContainer, fmt.Sprintf("failed to locate application log: %s", err)) + return nil, neorpc.WrapErrorWithData(neorpc.ErrUnknownScriptContainer, fmt.Sprintf("failed to locate application log: %s", err)) } return result.NewApplicationLog(hash, appExecResults, trig), nil } @@ -781,10 +780,10 @@ func (s *Server) getNEP11Tokens(h util.Uint160, acc util.Uint160, bw *io.BufBinW return vals, sym, int(dec.Int64()), nil } -func (s *Server) getNEP11Balances(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getNEP11Balances(ps params.Params) (interface{}, *neorpc.Error) { u, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } bs := &result.NEP11Balances{ @@ -793,7 +792,7 @@ func (s *Server) getNEP11Balances(ps params.Params) (interface{}, *response.Erro } lastUpdated, err := s.chain.GetTokenLastUpdated(u) if err != nil { - return nil, response.NewRPCError("Failed to get NEP-11 last updated block", err.Error()) + return nil, neorpc.NewRPCError("Failed to get NEP-11 last updated block", err.Error()) } var count int stateSyncPoint := lastUpdated[math.MinInt32] @@ -816,7 +815,7 @@ contract_loop: if !ok { cfg := s.chain.GetConfig() if !cfg.P2PStateExchangeExtensions && cfg.RemoveUntraceableBlocks { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to get LastUpdatedBlock for balance of %s token: internal database inconsistency", cs.Hash.StringLE())) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get LastUpdatedBlock for balance of %s token: internal database inconsistency", cs.Hash.StringLE())) } lub = stateSyncPoint } @@ -870,18 +869,18 @@ func (s *Server) invokeNEP11Properties(h util.Uint160, id []byte, bw *io.BufBinW return item.Value().([]stackitem.MapElement), nil } -func (s *Server) getNEP11Properties(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getNEP11Properties(ps params.Params) (interface{}, *neorpc.Error) { asset, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } token, err := ps.Value(1).GetBytesHex() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } props, err := s.invokeNEP11Properties(asset, token, nil) if err != nil { - return nil, response.NewRPCError("Failed to get NEP-11 properties", err.Error()) + return nil, neorpc.NewRPCError("Failed to get NEP-11 properties", err.Error()) } res := make(map[string]interface{}) for _, kv := range props { @@ -906,10 +905,10 @@ func (s *Server) getNEP11Properties(ps params.Params) (interface{}, *response.Er return res, nil } -func (s *Server) getNEP17Balances(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getNEP17Balances(ps params.Params) (interface{}, *neorpc.Error) { u, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } bs := &result.NEP17Balances{ @@ -918,7 +917,7 @@ func (s *Server) getNEP17Balances(ps params.Params) (interface{}, *response.Erro } lastUpdated, err := s.chain.GetTokenLastUpdated(u) if err != nil { - return nil, response.NewRPCError("Failed to get NEP-17 last updated block", err.Error()) + return nil, neorpc.NewRPCError("Failed to get NEP-17 last updated block", err.Error()) } stateSyncPoint := lastUpdated[math.MinInt32] bw := io.NewBufBinWriter() @@ -938,7 +937,7 @@ func (s *Server) getNEP17Balances(ps params.Params) (interface{}, *response.Erro if !ok { cfg := s.chain.GetConfig() if !cfg.P2PStateExchangeExtensions && cfg.RemoveUntraceableBlocks { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to get LastUpdatedBlock for balance of %s token: internal database inconsistency", cs.Hash.StringLE())) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get LastUpdatedBlock for balance of %s token: internal database inconsistency", cs.Hash.StringLE())) } lub = stateSyncPoint } @@ -1086,23 +1085,23 @@ func getTimestampsAndLimit(ps params.Params, index int) (uint64, uint64, int, in return start, end, limit, page, nil } -func (s *Server) getNEP11Transfers(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getNEP11Transfers(ps params.Params) (interface{}, *neorpc.Error) { return s.getTokenTransfers(ps, true) } -func (s *Server) getNEP17Transfers(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getNEP17Transfers(ps params.Params) (interface{}, *neorpc.Error) { return s.getTokenTransfers(ps, false) } -func (s *Server) getTokenTransfers(ps params.Params, isNEP11 bool) (interface{}, *response.Error) { +func (s *Server) getTokenTransfers(ps params.Params, isNEP11 bool) (interface{}, *neorpc.Error) { u, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } start, end, limit, page, err := getTimestampsAndLimit(ps, 1) if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("malformed timestamps/limit: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("malformed timestamps/limit: %s", err)) } bs := &tokenTransfers{ @@ -1193,7 +1192,7 @@ func (s *Server) getTokenTransfers(ps params.Params, isNEP11 bool) (interface{}, }) } if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("invalid transfer log: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("invalid transfer log: %s", err)) } return bs, nil } @@ -1211,24 +1210,24 @@ func (s *Server) getHash(contractID int32, cache map[int32]util.Uint160) (util.U return h, nil } -func (s *Server) contractIDFromParam(param *params.Param) (int32, *response.Error) { +func (s *Server) contractIDFromParam(param *params.Param) (int32, *neorpc.Error) { var result int32 if param == nil { - return 0, response.ErrInvalidParams + return 0, neorpc.ErrInvalidParams } if scriptHash, err := param.GetUint160FromHex(); err == nil { cs := s.chain.GetContractState(scriptHash) if cs == nil { - return 0, response.ErrUnknown + return 0, neorpc.ErrUnknown } result = cs.ID } else { id, err := param.GetInt() if err != nil { - return 0, response.ErrInvalidParams + return 0, neorpc.ErrInvalidParams } if err := checkInt32(id); err != nil { - return 0, response.WrapErrorWithData(response.ErrInvalidParams, err.Error()) + return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) } result = int32(id) } @@ -1236,14 +1235,14 @@ func (s *Server) contractIDFromParam(param *params.Param) (int32, *response.Erro } // getContractScriptHashFromParam returns the contract script hash by hex contract hash, address, id or native contract name. -func (s *Server) contractScriptHashFromParam(param *params.Param) (util.Uint160, *response.Error) { +func (s *Server) contractScriptHashFromParam(param *params.Param) (util.Uint160, *neorpc.Error) { var result util.Uint160 if param == nil { - return result, response.ErrInvalidParams + return result, neorpc.ErrInvalidParams } nameOrHashOrIndex, err := param.GetString() if err != nil { - return result, response.ErrInvalidParams + return result, neorpc.ErrInvalidParams } result, err = param.GetUint160FromAddressOrHex() if err == nil { @@ -1255,14 +1254,14 @@ func (s *Server) contractScriptHashFromParam(param *params.Param) (util.Uint160, } id, err := strconv.Atoi(nameOrHashOrIndex) if err != nil { - return result, response.NewRPCError("Invalid contract identifier (name/hash/index is expected)", err.Error()) + return result, neorpc.NewRPCError("Invalid contract identifier (name/hash/index is expected)", err.Error()) } if err := checkInt32(id); err != nil { - return result, response.WrapErrorWithData(response.ErrInvalidParams, err.Error()) + return result, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) } result, err = s.chain.GetContractScriptHash(int32(id)) if err != nil { - return result, response.NewRPCError("Unknown contract", "") + return result, neorpc.NewRPCError("Unknown contract", "") } return result, nil } @@ -1276,21 +1275,21 @@ func makeStorageKey(id int32, key []byte) []byte { var errKeepOnlyLatestState = errors.New("'KeepOnlyLatestState' setting is enabled") -func (s *Server) getProof(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getProof(ps params.Params) (interface{}, *neorpc.Error) { if s.chain.GetConfig().KeepOnlyLatestState { - return nil, response.NewInvalidRequestError(fmt.Sprintf("'getproof' is not supported: %s", errKeepOnlyLatestState)) + return nil, neorpc.NewInvalidRequestError(fmt.Sprintf("'getproof' is not supported: %s", errKeepOnlyLatestState)) } root, err := ps.Value(0).GetUint256() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } sc, err := ps.Value(1).GetUint160FromHex() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } key, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } cs, respErr := s.getHistoricalContractState(root, sc) if respErr != nil { @@ -1299,7 +1298,7 @@ func (s *Server) getProof(ps params.Params) (interface{}, *response.Error) { skey := makeStorageKey(cs.ID, key) proof, err := s.chain.GetStateModule().GetStateProof(root, skey) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to get proof: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get proof: %s", err)) } return &result.ProofWithKey{ Key: skey, @@ -1307,21 +1306,21 @@ func (s *Server) getProof(ps params.Params) (interface{}, *response.Error) { }, nil } -func (s *Server) verifyProof(ps params.Params) (interface{}, *response.Error) { +func (s *Server) verifyProof(ps params.Params) (interface{}, *neorpc.Error) { if s.chain.GetConfig().KeepOnlyLatestState { - return nil, response.NewInvalidRequestError(fmt.Sprintf("'verifyproof' is not supported: %s", errKeepOnlyLatestState)) + return nil, neorpc.NewInvalidRequestError(fmt.Sprintf("'verifyproof' is not supported: %s", errKeepOnlyLatestState)) } root, err := ps.Value(0).GetUint256() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } proofStr, err := ps.Value(1).GetString() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } var p result.ProofWithKey if err := p.FromString(proofStr); err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } vp := new(result.VerifyProof) val, ok := mpt.VerifyProof(root, p.Key, p.Proof) @@ -1331,27 +1330,27 @@ func (s *Server) verifyProof(ps params.Params) (interface{}, *response.Error) { return vp, nil } -func (s *Server) getState(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getState(ps params.Params) (interface{}, *neorpc.Error) { root, err := ps.Value(0).GetUint256() if err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, "invalid stateroot") + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "invalid stateroot") } if s.chain.GetConfig().KeepOnlyLatestState { curr, err := s.chain.GetStateModule().GetStateRoot(s.chain.BlockHeight()) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to get current stateroot: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get current stateroot: %s", err)) } if !curr.Root.Equals(root) { - return nil, response.NewInvalidRequestError(fmt.Sprintf("'getstate' is not supported for old states: %s", errKeepOnlyLatestState)) + return nil, neorpc.NewInvalidRequestError(fmt.Sprintf("'getstate' is not supported for old states: %s", errKeepOnlyLatestState)) } } csHash, err := ps.Value(1).GetUint160FromHex() if err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, "invalid contract hash") + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "invalid contract hash") } key, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, "invalid key") + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "invalid key") } cs, respErr := s.getHistoricalContractState(root, csHash) if respErr != nil { @@ -1360,32 +1359,32 @@ func (s *Server) getState(ps params.Params) (interface{}, *response.Error) { sKey := makeStorageKey(cs.ID, key) res, err := s.chain.GetStateModule().GetState(root, sKey) if err != nil { - return nil, response.NewRPCError("Failed to get historical item state", err.Error()) + return nil, neorpc.NewRPCError("Failed to get historical item state", err.Error()) } return res, nil } -func (s *Server) findStates(ps params.Params) (interface{}, *response.Error) { +func (s *Server) findStates(ps params.Params) (interface{}, *neorpc.Error) { root, err := ps.Value(0).GetUint256() if err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, "invalid stateroot") + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "invalid stateroot") } if s.chain.GetConfig().KeepOnlyLatestState { curr, err := s.chain.GetStateModule().GetStateRoot(s.chain.BlockHeight()) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to get current stateroot: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get current stateroot: %s", err)) } if !curr.Root.Equals(root) { - return nil, response.NewInvalidRequestError(fmt.Sprintf("'findstates' is not supported for old states: %s", errKeepOnlyLatestState)) + return nil, neorpc.NewInvalidRequestError(fmt.Sprintf("'findstates' is not supported for old states: %s", errKeepOnlyLatestState)) } } csHash, err := ps.Value(1).GetUint160FromHex() if err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, fmt.Sprintf("invalid contract hash: %s", err)) + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid contract hash: %s", err)) } prefix, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, fmt.Sprintf("invalid prefix: %s", err)) + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid prefix: %s", err)) } var ( key []byte @@ -1394,11 +1393,11 @@ func (s *Server) findStates(ps params.Params) (interface{}, *response.Error) { if len(ps) > 3 { key, err = ps.Value(3).GetBytesBase64() if err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, fmt.Sprintf("invalid key: %s", err)) + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid key: %s", err)) } if len(key) > 0 { if !bytes.HasPrefix(key, prefix) { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, "key doesn't match prefix") + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "key doesn't match prefix") } key = key[len(prefix):] } else { @@ -1409,7 +1408,7 @@ func (s *Server) findStates(ps params.Params) (interface{}, *response.Error) { if len(ps) > 4 { count, err = ps.Value(4).GetInt() if err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, fmt.Sprintf("invalid count: %s", err)) + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid count: %s", err)) } if count > s.config.MaxFindResultItems { count = s.config.MaxFindResultItems @@ -1422,7 +1421,7 @@ func (s *Server) findStates(ps params.Params) (interface{}, *response.Error) { pKey := makeStorageKey(cs.ID, prefix) kvs, err := s.chain.GetStateModule().FindStates(root, pKey, key, count+1) // +1 to define result truncation if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to find historical items: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to find historical items: %s", err)) } res := result.FindStates{} if len(kvs) == count+1 { @@ -1432,7 +1431,7 @@ func (s *Server) findStates(ps params.Params) (interface{}, *response.Error) { if len(kvs) > 0 { proof, err := s.chain.GetStateModule().GetStateProof(root, kvs[0].Key) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to get first proof: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get first proof: %s", err)) } res.FirstProof = &result.ProofWithKey{ Key: kvs[0].Key, @@ -1442,7 +1441,7 @@ func (s *Server) findStates(ps params.Params) (interface{}, *response.Error) { if len(kvs) > 1 { proof, err := s.chain.GetStateModule().GetStateProof(root, kvs[len(kvs)-1].Key) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to get last proof: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get last proof: %s", err)) } res.LastProof = &result.ProofWithKey{ Key: kvs[len(kvs)-1].Key, @@ -1459,21 +1458,21 @@ func (s *Server) findStates(ps params.Params) (interface{}, *response.Error) { return res, nil } -func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint160) (*state.Contract, *response.Error) { +func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint160) (*state.Contract, *neorpc.Error) { csKey := makeStorageKey(native.ManagementContractID, native.MakeContractKey(csHash)) csBytes, err := s.chain.GetStateModule().GetState(root, csKey) if err != nil { - return nil, response.NewRPCError("Failed to get historical contract state", err.Error()) + return nil, neorpc.NewRPCError("Failed to get historical contract state", err.Error()) } contract := new(state.Contract) err = stackitem.DeserializeConvertible(csBytes, contract) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to deserialize historical contract state: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to deserialize historical contract state: %s", err)) } return contract, nil } -func (s *Server) getStateHeight(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getStateHeight(_ params.Params) (interface{}, *neorpc.Error) { var height = s.chain.BlockHeight() var stateHeight = s.chain.GetStateModule().CurrentValidatedHeight() if s.chain.GetConfig().StateRootInHeader { @@ -1485,17 +1484,17 @@ func (s *Server) getStateHeight(_ params.Params) (interface{}, *response.Error) }, nil } -func (s *Server) getStateRoot(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getStateRoot(ps params.Params) (interface{}, *neorpc.Error) { p := ps.Value(0) if p == nil { - return nil, response.NewInvalidParamsError("missing stateroot identifier") + return nil, neorpc.NewInvalidParamsError("missing stateroot identifier") } var rt *state.MPTRoot var h util.Uint256 height, err := p.GetIntStrict() if err == nil { if err := checkUint32(height); err != nil { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, err.Error()) + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) } rt, err = s.chain.GetStateModule().GetStateRoot(uint32(height)) } else if h, err = p.GetUint256(); err == nil { @@ -1506,14 +1505,14 @@ func (s *Server) getStateRoot(ps params.Params) (interface{}, *response.Error) { } } if err != nil { - return nil, response.ErrUnknownStateRoot + return nil, neorpc.ErrUnknownStateRoot } return rt, nil } -func (s *Server) getStorage(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getStorage(ps params.Params) (interface{}, *neorpc.Error) { id, rErr := s.contractIDFromParam(ps.Value(0)) - if rErr == response.ErrUnknown { + if rErr == neorpc.ErrUnknown { return nil, nil } if rErr != nil { @@ -1522,7 +1521,7 @@ func (s *Server) getStorage(ps params.Params) (interface{}, *response.Error) { key, err := ps.Value(1).GetBytesBase64() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } item := s.chain.GetStorageItem(id, key) @@ -1533,14 +1532,14 @@ func (s *Server) getStorage(ps params.Params) (interface{}, *response.Error) { return []byte(item), nil } -func (s *Server) getrawtransaction(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) getrawtransaction(reqParams params.Params) (interface{}, *neorpc.Error) { txHash, err := reqParams.Value(0).GetUint256() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } tx, height, err := s.chain.GetTransaction(txHash) if err != nil { - return nil, response.ErrUnknownTransaction + return nil, neorpc.ErrUnknownTransaction } if v, _ := reqParams.Value(1).GetBoolean(); v { res := result.TransactionOutputRaw{ @@ -1552,14 +1551,14 @@ func (s *Server) getrawtransaction(reqParams params.Params) (interface{}, *respo _header := s.chain.GetHeaderHash(int(height)) header, err := s.chain.GetHeader(_header) if err != nil { - return nil, response.NewRPCError("Failed to get header for the transaction", err.Error()) + return nil, neorpc.NewRPCError("Failed to get header for the transaction", err.Error()) } aers, err := s.chain.GetAppExecResults(txHash, trigger.Application) if err != nil { - return nil, response.NewRPCError("Failed to get application log for the transaction", err.Error()) + return nil, neorpc.NewRPCError("Failed to get application log for the transaction", err.Error()) } if len(aers) == 0 { - return nil, response.NewRPCError("Inconsistent application log", "application log for the transaction is empty") + return nil, neorpc.NewRPCError("Inconsistent application log", "application log for the transaction is empty") } res.TransactionMetadata = result.TransactionMetadata{ Blockhash: header.Hash(), @@ -1572,15 +1571,15 @@ func (s *Server) getrawtransaction(reqParams params.Params) (interface{}, *respo return tx.Bytes(), nil } -func (s *Server) getTransactionHeight(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getTransactionHeight(ps params.Params) (interface{}, *neorpc.Error) { h, err := ps.Value(0).GetUint256() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } _, height, err := s.chain.GetTransaction(h) if err != nil || height == math.MaxUint32 { - return nil, response.ErrUnknownTransaction + return nil, neorpc.ErrUnknownTransaction } return height, nil @@ -1588,33 +1587,33 @@ func (s *Server) getTransactionHeight(ps params.Params) (interface{}, *response. // getContractState returns contract state (contract information, according to the contract script hash, // contract id or native contract name). -func (s *Server) getContractState(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) getContractState(reqParams params.Params) (interface{}, *neorpc.Error) { scriptHash, err := s.contractScriptHashFromParam(reqParams.Value(0)) if err != nil { return nil, err } cs := s.chain.GetContractState(scriptHash) if cs == nil { - return nil, response.NewRPCError("Unknown contract", "") + return nil, neorpc.NewRPCError("Unknown contract", "") } return cs, nil } -func (s *Server) getNativeContracts(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getNativeContracts(_ params.Params) (interface{}, *neorpc.Error) { return s.chain.GetNatives(), nil } // getBlockSysFee returns the system fees of the block, based on the specified index. -func (s *Server) getBlockSysFee(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) getBlockSysFee(reqParams params.Params) (interface{}, *neorpc.Error) { num, err := s.blockHeightFromParam(reqParams.Value(0)) if err != nil { - return 0, response.NewRPCError("Invalid height", "invalid block identifier") + return 0, neorpc.NewRPCError("Invalid height", "invalid block identifier") } headerHash := s.chain.GetHeaderHash(num) block, errBlock := s.chain.GetBlock(headerHash) if errBlock != nil { - return 0, response.ErrUnknownBlock + return 0, neorpc.ErrUnknownBlock } var blockSysFee int64 @@ -1626,7 +1625,7 @@ func (s *Server) getBlockSysFee(reqParams params.Params) (interface{}, *response } // getBlockHeader returns the corresponding block header information according to the specified script hash. -func (s *Server) getBlockHeader(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) getBlockHeader(reqParams params.Params) (interface{}, *neorpc.Error) { param := reqParams.Value(0) hash, respErr := s.blockHashFromParam(param) if respErr != nil { @@ -1636,7 +1635,7 @@ func (s *Server) getBlockHeader(reqParams params.Params) (interface{}, *response verbose, _ := reqParams.Value(1).GetBoolean() h, err := s.chain.GetHeader(hash) if err != nil { - return nil, response.ErrUnknownHeader + return nil, neorpc.ErrUnknownHeader } if verbose { @@ -1650,16 +1649,16 @@ func (s *Server) getBlockHeader(reqParams params.Params) (interface{}, *response buf := io.NewBufBinWriter() h.EncodeBinary(buf.BinWriter) if buf.Err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("encoding error: %s", buf.Err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("encoding error: %s", buf.Err)) } return buf.Bytes(), nil } // getUnclaimedGas returns unclaimed GAS amount of the specified address. -func (s *Server) getUnclaimedGas(ps params.Params) (interface{}, *response.Error) { +func (s *Server) getUnclaimedGas(ps params.Params) (interface{}, *neorpc.Error) { u, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } neo, _ := s.chain.GetGoverningTokenBalance(u) @@ -1670,7 +1669,7 @@ func (s *Server) getUnclaimedGas(ps params.Params) (interface{}, *response.Error } gas, err := s.chain.CalculateClaimable(u, s.chain.BlockHeight()+1) // +1 as in C#, for the next block. if err != nil { - return nil, response.NewRPCError("Can't calculate claimable", err.Error()) + return nil, neorpc.NewRPCError("Can't calculate claimable", err.Error()) } return result.UnclaimedGas{ Address: u, @@ -1679,16 +1678,16 @@ func (s *Server) getUnclaimedGas(ps params.Params) (interface{}, *response.Error } // getCandidates returns the current list of candidates with their active/inactive voting status. -func (s *Server) getCandidates(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getCandidates(_ params.Params) (interface{}, *neorpc.Error) { var validators keys.PublicKeys validators, err := s.chain.GetNextBlockValidators() if err != nil { - return nil, response.NewRPCError("Can't get next block validators", err.Error()) + return nil, neorpc.NewRPCError("Can't get next block validators", err.Error()) } enrollments, err := s.chain.GetEnrollments() if err != nil { - return nil, response.NewRPCError("Can't get enrollments", err.Error()) + return nil, neorpc.NewRPCError("Can't get enrollments", err.Error()) } var res = make([]result.Candidate, 0) for _, v := range enrollments { @@ -1702,16 +1701,16 @@ func (s *Server) getCandidates(_ params.Params) (interface{}, *response.Error) { } // getNextBlockValidators returns validators for the next block with voting status. -func (s *Server) getNextBlockValidators(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getNextBlockValidators(_ params.Params) (interface{}, *neorpc.Error) { var validators keys.PublicKeys validators, err := s.chain.GetNextBlockValidators() if err != nil { - return nil, response.NewRPCError("Can't get next block validators", err.Error()) + return nil, neorpc.NewRPCError("Can't get next block validators", err.Error()) } enrollments, err := s.chain.GetEnrollments() if err != nil { - return nil, response.NewRPCError("Can't get enrollments", err.Error()) + return nil, neorpc.NewRPCError("Can't get enrollments", err.Error()) } var res = make([]result.Validator, 0) for _, v := range enrollments { @@ -1727,16 +1726,16 @@ func (s *Server) getNextBlockValidators(_ params.Params) (interface{}, *response } // getCommittee returns the current list of NEO committee members. -func (s *Server) getCommittee(_ params.Params) (interface{}, *response.Error) { +func (s *Server) getCommittee(_ params.Params) (interface{}, *neorpc.Error) { keys, err := s.chain.GetCommittee() if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("can't get committee members: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("can't get committee members: %s", err)) } return keys, nil } // invokeFunction implements the `invokeFunction` RPC call. -func (s *Server) invokeFunction(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) invokeFunction(reqParams params.Params) (interface{}, *neorpc.Error) { tx, verbose, respErr := s.getInvokeFunctionParams(reqParams) if respErr != nil { return nil, respErr @@ -1745,13 +1744,13 @@ func (s *Server) invokeFunction(reqParams params.Params) (interface{}, *response } // invokeFunctionHistoric implements the `invokeFunctionHistoric` RPC call. -func (s *Server) invokeFunctionHistoric(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) invokeFunctionHistoric(reqParams params.Params) (interface{}, *neorpc.Error) { b, respErr := s.getHistoricParams(reqParams) if respErr != nil { return nil, respErr } if len(reqParams) < 2 { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } tx, verbose, respErr := s.getInvokeFunctionParams(reqParams[1:]) if respErr != nil { @@ -1760,9 +1759,9 @@ func (s *Server) invokeFunctionHistoric(reqParams params.Params) (interface{}, * return s.runScriptInVM(trigger.Application, tx.Script, util.Uint160{}, tx, b, verbose) } -func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction.Transaction, bool, *response.Error) { +func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction.Transaction, bool, *neorpc.Error) { if len(reqParams) < 2 { - return nil, false, response.ErrInvalidParams + return nil, false, neorpc.ErrInvalidParams } scriptHash, responseErr := s.contractScriptHashFromParam(reqParams.Value(0)) if responseErr != nil { @@ -1770,7 +1769,7 @@ func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction. } method, err := reqParams[1].GetString() if err != nil { - return nil, false, response.ErrInvalidParams + return nil, false, neorpc.ErrInvalidParams } var invparams *params.Param if len(reqParams) > 2 { @@ -1780,7 +1779,7 @@ func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction. if len(reqParams) > 3 { signers, _, err := reqParams[3].GetSignersWithWitnesses() if err != nil { - return nil, false, response.ErrInvalidParams + return nil, false, neorpc.ErrInvalidParams } tx.Signers = signers } @@ -1788,7 +1787,7 @@ func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction. if len(reqParams) > 4 { verbose, err = reqParams[4].GetBoolean() if err != nil { - return nil, false, response.ErrInvalidParams + return nil, false, neorpc.ErrInvalidParams } } if len(tx.Signers) == 0 { @@ -1796,14 +1795,14 @@ func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction. } script, err := params.CreateFunctionInvocationScript(scriptHash, method, invparams) if err != nil { - return nil, false, response.NewInternalServerError(fmt.Sprintf("can't create invocation script: %s", err)) + return nil, false, neorpc.NewInternalServerError(fmt.Sprintf("can't create invocation script: %s", err)) } tx.Script = script return tx, verbose, nil } // invokescript implements the `invokescript` RPC call. -func (s *Server) invokescript(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) invokescript(reqParams params.Params) (interface{}, *neorpc.Error) { tx, verbose, respErr := s.getInvokeScriptParams(reqParams) if respErr != nil { return nil, respErr @@ -1812,13 +1811,13 @@ func (s *Server) invokescript(reqParams params.Params) (interface{}, *response.E } // invokescripthistoric implements the `invokescripthistoric` RPC call. -func (s *Server) invokescripthistoric(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) invokescripthistoric(reqParams params.Params) (interface{}, *neorpc.Error) { b, respErr := s.getHistoricParams(reqParams) if respErr != nil { return nil, respErr } if len(reqParams) < 2 { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } tx, verbose, respErr := s.getInvokeScriptParams(reqParams[1:]) if respErr != nil { @@ -1827,17 +1826,17 @@ func (s *Server) invokescripthistoric(reqParams params.Params) (interface{}, *re return s.runScriptInVM(trigger.Application, tx.Script, util.Uint160{}, tx, b, verbose) } -func (s *Server) getInvokeScriptParams(reqParams params.Params) (*transaction.Transaction, bool, *response.Error) { +func (s *Server) getInvokeScriptParams(reqParams params.Params) (*transaction.Transaction, bool, *neorpc.Error) { script, err := reqParams.Value(0).GetBytesBase64() if err != nil { - return nil, false, response.ErrInvalidParams + return nil, false, neorpc.ErrInvalidParams } tx := &transaction.Transaction{} if len(reqParams) > 1 { signers, witnesses, err := reqParams[1].GetSignersWithWitnesses() if err != nil { - return nil, false, response.WrapErrorWithData(response.ErrInvalidParams, err.Error()) + return nil, false, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) } tx.Signers = signers tx.Scripts = witnesses @@ -1846,7 +1845,7 @@ func (s *Server) getInvokeScriptParams(reqParams params.Params) (*transaction.Tr if len(reqParams) > 2 { verbose, err = reqParams[2].GetBoolean() if err != nil { - return nil, false, response.WrapErrorWithData(response.ErrInvalidParams, err.Error()) + return nil, false, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) } } if len(tx.Signers) == 0 { @@ -1857,7 +1856,7 @@ func (s *Server) getInvokeScriptParams(reqParams params.Params) (*transaction.Tr } // invokeContractVerify implements the `invokecontractverify` RPC call. -func (s *Server) invokeContractVerify(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) invokeContractVerify(reqParams params.Params) (interface{}, *neorpc.Error) { scriptHash, tx, invocationScript, respErr := s.getInvokeContractVerifyParams(reqParams) if respErr != nil { return nil, respErr @@ -1866,13 +1865,13 @@ func (s *Server) invokeContractVerify(reqParams params.Params) (interface{}, *re } // invokeContractVerifyHistoric implements the `invokecontractverifyhistoric` RPC call. -func (s *Server) invokeContractVerifyHistoric(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) invokeContractVerifyHistoric(reqParams params.Params) (interface{}, *neorpc.Error) { b, respErr := s.getHistoricParams(reqParams) if respErr != nil { return nil, respErr } if len(reqParams) < 2 { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } scriptHash, tx, invocationScript, respErr := s.getInvokeContractVerifyParams(reqParams[1:]) if respErr != nil { @@ -1881,7 +1880,7 @@ func (s *Server) invokeContractVerifyHistoric(reqParams params.Params) (interfac return s.runScriptInVM(trigger.Verification, invocationScript, scriptHash, tx, b, false) } -func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Uint160, *transaction.Transaction, []byte, *response.Error) { +func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Uint160, *transaction.Transaction, []byte, *neorpc.Error) { scriptHash, responseErr := s.contractScriptHashFromParam(reqParams.Value(0)) if responseErr != nil { return util.Uint160{}, nil, nil, responseErr @@ -1891,12 +1890,12 @@ func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Ui if len(reqParams) > 1 { args, err := reqParams[1].GetArray() // second `invokecontractverify` parameter is an array of arguments for `verify` method if err != nil { - return util.Uint160{}, nil, nil, response.WrapErrorWithData(response.ErrInvalidParams, err.Error()) + return util.Uint160{}, nil, nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) } if len(args) > 0 { err := params.ExpandArrayIntoScript(bw.BinWriter, args) if err != nil { - return util.Uint160{}, nil, nil, response.NewInternalServerError(fmt.Sprintf("can't create witness invocation script: %s", err)) + return util.Uint160{}, nil, nil, neorpc.NewInternalServerError(fmt.Sprintf("can't create witness invocation script: %s", err)) } } } @@ -1906,7 +1905,7 @@ func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Ui if len(reqParams) > 2 { signers, witnesses, err := reqParams[2].GetSignersWithWitnesses() if err != nil { - return util.Uint160{}, nil, nil, response.ErrInvalidParams + return util.Uint160{}, nil, nil, neorpc.ErrInvalidParams } tx.Signers = signers tx.Scripts = witnesses @@ -1921,24 +1920,24 @@ func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Ui // with the specified index to perform the historic call. It also checks that // specified stateroot is stored at the specified height for further request // handling consistency. -func (s *Server) getHistoricParams(reqParams params.Params) (*block.Block, *response.Error) { +func (s *Server) getHistoricParams(reqParams params.Params) (*block.Block, *neorpc.Error) { if s.chain.GetConfig().KeepOnlyLatestState { - return nil, response.NewInvalidRequestError(fmt.Sprintf("only latest state is supported: %s", errKeepOnlyLatestState)) + return nil, neorpc.NewInvalidRequestError(fmt.Sprintf("only latest state is supported: %s", errKeepOnlyLatestState)) } if len(reqParams) < 1 { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } height, respErr := s.blockHeightFromParam(reqParams.Value(0)) if respErr != nil { hash, err := reqParams.Value(0).GetUint256() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("invalid block hash or index or stateroot hash: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid block hash or index or stateroot hash: %s", err)) } b, err := s.chain.GetBlock(hash) if err != nil { stateH, err := s.chain.GetStateModule().GetLatestStateHeight(hash) if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("unknown block or stateroot: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("unknown block or stateroot: %s", err)) } height = int(stateH) } else { @@ -1947,7 +1946,7 @@ func (s *Server) getHistoricParams(reqParams params.Params) (*block.Block, *resp } b, err := s.getFakeNextBlock(uint32(height + 1)) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("can't create fake block for height %d: %s", height+1, err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("can't create fake block for height %d: %s", height+1, err)) } return b, nil } @@ -1966,7 +1965,7 @@ func (s *Server) getFakeNextBlock(nextBlockHeight uint32) (*block.Block, error) return b, nil } -func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, verbose bool) (*interop.Context, *response.Error) { +func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, verbose bool) (*interop.Context, *neorpc.Error) { var ( err error ic *interop.Context @@ -1974,13 +1973,13 @@ func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contrac if b == nil { b, err = s.getFakeNextBlock(s.chain.BlockHeight() + 1) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("can't create fake block: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("can't create fake block: %s", err)) } ic = s.chain.GetTestVM(t, tx, b) } else { ic, err = s.chain.GetTestHistoricVM(t, tx, b) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to create historic VM: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to create historic VM: %s", err)) } } if verbose { @@ -1997,7 +1996,7 @@ func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contrac err = s.chain.InitVerificationContext(ic, contractScriptHash, &transaction.Witness{InvocationScript: script, VerificationScript: []byte{}}) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("can't prepare verification VM: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("can't prepare verification VM: %s", err)) } } else { ic.VM.LoadScriptWithFlags(script, callflag.All) @@ -2010,7 +2009,7 @@ func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contrac // witness invocation script in case of `verification` trigger (it pushes `verify` // arguments on stack before verification). In case of contract verification // contractScriptHash should be specified. -func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, verbose bool) (*result.Invoke, *response.Error) { +func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, verbose bool) (*result.Invoke, *neorpc.Error) { ic, respErr := s.prepareInvocationContext(t, script, contractScriptHash, tx, b, verbose) if respErr != nil { return nil, respErr @@ -2031,7 +2030,7 @@ func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash ic.Finalize() b, err = s.getFakeNextBlock(ic.Block.Index) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("unable to prepare block for historic call: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("unable to prepare block for historic call: %s", err)) } // Rerun with MPT-backed storage. return s.runScriptInVM(t, script, contractScriptHash, tx, b, verbose) @@ -2058,7 +2057,7 @@ func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash if len(s.sessions) >= s.config.SessionPoolSize { ic.Finalize() s.sessionsLock.Unlock() - return nil, response.NewInternalServerError("max session capacity reached") + return nil, neorpc.NewInternalServerError("max session capacity reached") } s.sessions[sessionID] = sess s.sessionsLock.Unlock() @@ -2133,27 +2132,27 @@ func (s *Server) registerOrDumpIterator(item stackitem.Item) (stackitem.Item, uu return stackitem.NewInterop(resIterator), iterID } -func (s *Server) traverseIterator(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) traverseIterator(reqParams params.Params) (interface{}, *neorpc.Error) { if !s.config.SessionEnabled { - return nil, response.NewInvalidRequestError("sessions are disabled") + return nil, neorpc.NewInvalidRequestError("sessions are disabled") } sID, err := reqParams.Value(0).GetUUID() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("invalid session ID: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid session ID: %s", err)) } iID, err := reqParams.Value(1).GetUUID() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("invalid iterator ID: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid iterator ID: %s", err)) } count, err := reqParams.Value(2).GetInt() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("invalid iterator items count: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid iterator items count: %s", err)) } if err := checkInt32(count); err != nil { - return nil, response.NewInvalidParamsError("invalid iterator items count: not an int32") + return nil, neorpc.NewInvalidParamsError("invalid iterator items count: not an int32") } if count > s.config.MaxIteratorResultItems { - return nil, response.NewInvalidParamsError(fmt.Sprintf("iterator items count is out of range (%d at max)", s.config.MaxIteratorResultItems)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("iterator items count is out of range (%d at max)", s.config.MaxIteratorResultItems)) } s.sessionsLock.Lock() @@ -2184,19 +2183,19 @@ func (s *Server) traverseIterator(reqParams params.Params) (interface{}, *respon for j := range iVals { result[j], err = stackitem.ToJSONWithTypes(iVals[j]) if err != nil { - return nil, response.NewInternalServerError(fmt.Sprintf("failed to marshal iterator value: %s", err)) + return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to marshal iterator value: %s", err)) } } return result, nil } -func (s *Server) terminateSession(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) terminateSession(reqParams params.Params) (interface{}, *neorpc.Error) { if !s.config.SessionEnabled { - return nil, response.NewInvalidRequestError("sessions are disabled") + return nil, neorpc.NewInvalidRequestError("sessions are disabled") } sID, err := reqParams.Value(0).GetUUID() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("invalid session ID: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid session ID: %s", err)) } strSID := sID.String() s.sessionsLock.Lock() @@ -2217,24 +2216,24 @@ func (s *Server) terminateSession(reqParams params.Params) (interface{}, *respon } // submitBlock broadcasts a raw block over the NEO network. -func (s *Server) submitBlock(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) submitBlock(reqParams params.Params) (interface{}, *neorpc.Error) { blockBytes, err := reqParams.Value(0).GetBytesBase64() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("missing parameter or not a base64: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("missing parameter or not a base64: %s", err)) } b := block.New(s.stateRootEnabled) r := io.NewBinReaderFromBuf(blockBytes) b.DecodeBinary(r) if r.Err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("can't decode block: %s", r.Err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("can't decode block: %s", r.Err)) } err = s.chain.AddBlock(b) if err != nil { switch { case errors.Is(err, core.ErrInvalidBlockIndex) || errors.Is(err, core.ErrAlreadyExists): - return nil, response.WrapErrorWithData(response.ErrAlreadyExists, err.Error()) + return nil, neorpc.WrapErrorWithData(neorpc.ErrAlreadyExists, err.Error()) default: - return nil, response.WrapErrorWithData(response.ErrValidationFailed, err.Error()) + return nil, neorpc.WrapErrorWithData(neorpc.ErrValidationFailed, err.Error()) } } return &result.RelayResult{ @@ -2243,43 +2242,43 @@ func (s *Server) submitBlock(reqParams params.Params) (interface{}, *response.Er } // submitNotaryRequest broadcasts P2PNotaryRequest over the NEO network. -func (s *Server) submitNotaryRequest(ps params.Params) (interface{}, *response.Error) { +func (s *Server) submitNotaryRequest(ps params.Params) (interface{}, *neorpc.Error) { if !s.chain.P2PSigExtensionsEnabled() { - return nil, response.NewRPCError("P2PSignatureExtensions are disabled", "") + return nil, neorpc.NewRPCError("P2PSignatureExtensions are disabled", "") } bytePayload, err := ps.Value(0).GetBytesBase64() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("not a base64: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("not a base64: %s", err)) } r, err := payload.NewP2PNotaryRequestFromBytes(bytePayload) if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("can't decode notary payload: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("can't decode notary payload: %s", err)) } return getRelayResult(s.coreServer.RelayP2PNotaryRequest(r), r.FallbackTransaction.Hash()) } // getRelayResult returns successful relay result or an error. -func getRelayResult(err error, hash util.Uint256) (interface{}, *response.Error) { +func getRelayResult(err error, hash util.Uint256) (interface{}, *neorpc.Error) { switch { case err == nil: return result.RelayResult{ Hash: hash, }, nil case errors.Is(err, core.ErrAlreadyExists): - return nil, response.WrapErrorWithData(response.ErrAlreadyExists, err.Error()) + return nil, neorpc.WrapErrorWithData(neorpc.ErrAlreadyExists, err.Error()) case errors.Is(err, core.ErrOOM): - return nil, response.WrapErrorWithData(response.ErrOutOfMemory, err.Error()) + return nil, neorpc.WrapErrorWithData(neorpc.ErrOutOfMemory, err.Error()) case errors.Is(err, core.ErrPolicy): - return nil, response.WrapErrorWithData(response.ErrPolicyFail, err.Error()) + return nil, neorpc.WrapErrorWithData(neorpc.ErrPolicyFail, err.Error()) default: - return nil, response.WrapErrorWithData(response.ErrValidationFailed, err.Error()) + return nil, neorpc.WrapErrorWithData(neorpc.ErrValidationFailed, err.Error()) } } -func (s *Server) submitOracleResponse(ps params.Params) (interface{}, *response.Error) { +func (s *Server) submitOracleResponse(ps params.Params) (interface{}, *neorpc.Error) { if s.oracle == nil { - return nil, response.NewRPCError("Oracle is not enabled", "") + return nil, neorpc.NewRPCError("Oracle is not enabled", "") } var pub *keys.PublicKey pubBytes, err := ps.Value(0).GetBytesBase64() @@ -2287,55 +2286,55 @@ func (s *Server) submitOracleResponse(ps params.Params) (interface{}, *response. pub, err = keys.NewPublicKeyFromBytes(pubBytes, elliptic.P256()) } if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("public key is missing: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("public key is missing: %s", err)) } reqID, err := ps.Value(1).GetInt() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("request ID is missing: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("request ID is missing: %s", err)) } txSig, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("tx signature is missing: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("tx signature is missing: %s", err)) } msgSig, err := ps.Value(3).GetBytesBase64() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("msg signature is missing: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("msg signature is missing: %s", err)) } data := broadcaster.GetMessage(pubBytes, uint64(reqID), txSig) if !pub.Verify(msgSig, hash.Sha256(data).BytesBE()) { - return nil, response.NewRPCError("Invalid request signature", "") + return nil, neorpc.NewRPCError("Invalid request signature", "") } s.oracle.AddResponse(pub, uint64(reqID), txSig) return json.RawMessage([]byte("{}")), nil } -func (s *Server) sendrawtransaction(reqParams params.Params) (interface{}, *response.Error) { +func (s *Server) sendrawtransaction(reqParams params.Params) (interface{}, *neorpc.Error) { if len(reqParams) < 1 { - return nil, response.NewInvalidParamsError("not enough parameters") + return nil, neorpc.NewInvalidParamsError("not enough parameters") } byteTx, err := reqParams[0].GetBytesBase64() if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("not a base64: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("not a base64: %s", err)) } tx, err := transaction.NewTransactionFromBytes(byteTx) if err != nil { - return nil, response.NewInvalidParamsError(fmt.Sprintf("can't decode transaction: %s", err)) + return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("can't decode transaction: %s", err)) } return getRelayResult(s.coreServer.RelayTxn(tx), tx.Hash()) } // subscribe handles subscription requests from websocket clients. -func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (interface{}, *response.Error) { +func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (interface{}, *neorpc.Error) { streamName, err := reqParams.Value(0).GetString() if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } - event, err := response.GetEventIDFromString(streamName) - if err != nil || event == response.MissedEventID { - return nil, response.ErrInvalidParams + event, err := neorpc.GetEventIDFromString(streamName) + if err != nil || event == neorpc.MissedEventID { + return nil, neorpc.ErrInvalidParams } - if event == response.NotaryRequestEventID && !s.chain.P2PSigExtensionsEnabled() { - return nil, response.WrapErrorWithData(response.ErrInvalidParams, "P2PSigExtensions are disabled") + if event == neorpc.NotaryRequestEventID && !s.chain.P2PSigExtensionsEnabled() { + return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "P2PSigExtensions are disabled") } // Optional filter. var filter interface{} @@ -2344,20 +2343,20 @@ func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (interface{ jd := json.NewDecoder(bytes.NewReader(param.RawMessage)) jd.DisallowUnknownFields() switch event { - case response.BlockEventID: - flt := new(request.BlockFilter) + case neorpc.BlockEventID: + flt := new(neorpc.BlockFilter) err = jd.Decode(flt) filter = *flt - case response.TransactionEventID, response.NotaryRequestEventID: - flt := new(request.TxFilter) + case neorpc.TransactionEventID, neorpc.NotaryRequestEventID: + flt := new(neorpc.TxFilter) err = jd.Decode(flt) filter = *flt - case response.NotificationEventID: - flt := new(request.NotificationFilter) + case neorpc.NotificationEventID: + flt := new(neorpc.NotificationFilter) err = jd.Decode(flt) filter = *flt - case response.ExecutionEventID: - flt := new(request.ExecutionFilter) + case neorpc.ExecutionEventID: + flt := new(neorpc.ExecutionFilter) err = jd.Decode(flt) if err == nil && (flt.State == "HALT" || flt.State == "FAULT") { filter = *flt @@ -2366,7 +2365,7 @@ func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (interface{ } } if err != nil { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } } @@ -2374,17 +2373,17 @@ func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (interface{ defer s.subsLock.Unlock() select { case <-s.shutdown: - return nil, response.NewInternalServerError("server is shutting down") + return nil, neorpc.NewInternalServerError("server is shutting down") default: } var id int for ; id < len(sub.feeds); id++ { - if sub.feeds[id].event == response.InvalidEventID { + if sub.feeds[id].event == neorpc.InvalidEventID { break } } if id == len(sub.feeds) { - return nil, response.NewInternalServerError("maximum number of subscriptions is reached") + return nil, neorpc.NewInternalServerError("maximum number of subscriptions is reached") } sub.feeds[id].event = event sub.feeds[id].filter = filter @@ -2395,29 +2394,29 @@ func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (interface{ // subscribeToChannel subscribes RPC server to appropriate chain events if // it's not yet subscribed for them. It's supposed to be called with s.subsLock // taken by the caller. -func (s *Server) subscribeToChannel(event response.EventID) { +func (s *Server) subscribeToChannel(event neorpc.EventID) { switch event { - case response.BlockEventID: + case neorpc.BlockEventID: if s.blockSubs == 0 { s.chain.SubscribeForBlocks(s.blockCh) } s.blockSubs++ - case response.TransactionEventID: + case neorpc.TransactionEventID: if s.transactionSubs == 0 { s.chain.SubscribeForTransactions(s.transactionCh) } s.transactionSubs++ - case response.NotificationEventID: + case neorpc.NotificationEventID: if s.notificationSubs == 0 { s.chain.SubscribeForNotifications(s.notificationCh) } s.notificationSubs++ - case response.ExecutionEventID: + case neorpc.ExecutionEventID: if s.executionSubs == 0 { s.chain.SubscribeForExecutions(s.executionCh) } s.executionSubs++ - case response.NotaryRequestEventID: + case neorpc.NotaryRequestEventID: if s.notaryRequestSubs == 0 { s.coreServer.SubscribeForNotaryRequests(s.notaryRequestCh) } @@ -2426,18 +2425,18 @@ func (s *Server) subscribeToChannel(event response.EventID) { } // unsubscribe handles unsubscription requests from websocket clients. -func (s *Server) unsubscribe(reqParams params.Params, sub *subscriber) (interface{}, *response.Error) { +func (s *Server) unsubscribe(reqParams params.Params, sub *subscriber) (interface{}, *neorpc.Error) { id, err := reqParams.Value(0).GetInt() if err != nil || id < 0 { - return nil, response.ErrInvalidParams + return nil, neorpc.ErrInvalidParams } s.subsLock.Lock() defer s.subsLock.Unlock() - if len(sub.feeds) <= id || sub.feeds[id].event == response.InvalidEventID { - return nil, response.ErrInvalidParams + if len(sub.feeds) <= id || sub.feeds[id].event == neorpc.InvalidEventID { + return nil, neorpc.ErrInvalidParams } event := sub.feeds[id].event - sub.feeds[id].event = response.InvalidEventID + sub.feeds[id].event = neorpc.InvalidEventID sub.feeds[id].filter = nil s.unsubscribeFromChannel(event) return true, nil @@ -2446,29 +2445,29 @@ func (s *Server) unsubscribe(reqParams params.Params, sub *subscriber) (interfac // unsubscribeFromChannel unsubscribes RPC server from appropriate chain events // if there are no other subscribers for it. It's supposed to be called with // s.subsLock taken by the caller. -func (s *Server) unsubscribeFromChannel(event response.EventID) { +func (s *Server) unsubscribeFromChannel(event neorpc.EventID) { switch event { - case response.BlockEventID: + case neorpc.BlockEventID: s.blockSubs-- if s.blockSubs == 0 { s.chain.UnsubscribeFromBlocks(s.blockCh) } - case response.TransactionEventID: + case neorpc.TransactionEventID: s.transactionSubs-- if s.transactionSubs == 0 { s.chain.UnsubscribeFromTransactions(s.transactionCh) } - case response.NotificationEventID: + case neorpc.NotificationEventID: s.notificationSubs-- if s.notificationSubs == 0 { s.chain.UnsubscribeFromNotifications(s.notificationCh) } - case response.ExecutionEventID: + case neorpc.ExecutionEventID: s.executionSubs-- if s.executionSubs == 0 { s.chain.UnsubscribeFromExecutions(s.executionCh) } - case response.NotaryRequestEventID: + case neorpc.NotaryRequestEventID: s.notaryRequestSubs-- if s.notaryRequestSubs == 0 { s.coreServer.UnsubscribeFromNotaryRequests(s.notaryRequestCh) @@ -2477,9 +2476,9 @@ func (s *Server) unsubscribeFromChannel(event response.EventID) { } func (s *Server) handleSubEvents() { - b, err := json.Marshal(response.Notification{ - JSONRPC: request.JSONRPCVersion, - Event: response.MissedEventID, + b, err := json.Marshal(neorpc.Notification{ + JSONRPC: neorpc.JSONRPCVersion, + Event: neorpc.MissedEventID, Payload: make([]interface{}, 0), }) if err != nil { @@ -2493,8 +2492,8 @@ func (s *Server) handleSubEvents() { } chloop: for { - var resp = response.Notification{ - JSONRPC: request.JSONRPCVersion, + var resp = neorpc.Notification{ + JSONRPC: neorpc.JSONRPCVersion, Payload: make([]interface{}, 1), } var msg *websocket.PreparedMessage @@ -2502,19 +2501,19 @@ chloop: case <-s.shutdown: break chloop case b := <-s.blockCh: - resp.Event = response.BlockEventID + resp.Event = neorpc.BlockEventID resp.Payload[0] = b case execution := <-s.executionCh: - resp.Event = response.ExecutionEventID + resp.Event = neorpc.ExecutionEventID resp.Payload[0] = execution case notification := <-s.notificationCh: - resp.Event = response.NotificationEventID + resp.Event = neorpc.NotificationEventID resp.Payload[0] = notification case tx := <-s.transactionCh: - resp.Event = response.TransactionEventID + resp.Event = neorpc.TransactionEventID resp.Payload[0] = tx case e := <-s.notaryRequestCh: - resp.Event = response.NotaryRequestEventID + resp.Event = neorpc.NotaryRequestEventID resp.Payload[0] = &subscriptions.NotaryRequestEvent{ Type: e.Type, NotaryRequest: e.Data.(*payload.P2PNotaryRequest), @@ -2596,10 +2595,10 @@ drainloop: close(s.notaryRequestCh) } -func (s *Server) blockHeightFromParam(param *params.Param) (int, *response.Error) { +func (s *Server) blockHeightFromParam(param *params.Param) (int, *neorpc.Error) { num, err := param.GetInt() if err != nil { - return 0, response.ErrInvalidParams + return 0, neorpc.ErrInvalidParams } if num < 0 || num > int(s.chain.BlockHeight()) { @@ -2608,9 +2607,9 @@ func (s *Server) blockHeightFromParam(param *params.Param) (int, *response.Error return num, nil } -func (s *Server) packResponse(r *params.In, result interface{}, respErr *response.Error) abstract { +func (s *Server) packResponse(r *params.In, result interface{}, respErr *neorpc.Error) abstract { resp := abstract{ - Header: response.Header{ + Header: neorpc.Header{ JSONRPC: r.JSONRPC, ID: r.RawID, }, @@ -2624,7 +2623,7 @@ func (s *Server) packResponse(r *params.In, result interface{}, respErr *respons } // logRequestError is a request error logger. -func (s *Server) logRequestError(r *params.Request, jsonErr *response.Error) { +func (s *Server) logRequestError(r *params.Request, jsonErr *neorpc.Error) { logFields := []zap.Field{ zap.Int64("code", jsonErr.Code), } @@ -2640,7 +2639,7 @@ func (s *Server) logRequestError(r *params.Request, jsonErr *response.Error) { logText := "Error encountered with rpc request" switch jsonErr.Code { - case response.InternalServerErrorCode: + case neorpc.InternalServerErrorCode: s.log.Error(logText, logFields...) default: s.log.Info(logText, logFields...) @@ -2648,14 +2647,14 @@ func (s *Server) logRequestError(r *params.Request, jsonErr *response.Error) { } // writeHTTPErrorResponse writes an error response to the ResponseWriter. -func (s *Server) writeHTTPErrorResponse(r *params.In, w http.ResponseWriter, jsonErr *response.Error) { +func (s *Server) writeHTTPErrorResponse(r *params.In, w http.ResponseWriter, jsonErr *neorpc.Error) { resp := s.packResponse(r, nil, jsonErr) s.writeHTTPServerResponse(¶ms.Request{In: r}, w, resp) } func (s *Server) writeHTTPServerResponse(r *params.Request, w http.ResponseWriter, resp abstractResult) { // Errors can happen in many places and we can only catch ALL of them here. - resp.RunForErrors(func(jsonErr *response.Error) { + resp.RunForErrors(func(jsonErr *neorpc.Error) { s.logRequestError(r, jsonErr) }) if r.In != nil { diff --git a/pkg/services/rpcsrv/server_test.go b/pkg/services/rpcsrv/server_test.go index dedce792b..77b73fd46 100644 --- a/pkg/services/rpcsrv/server_test.go +++ b/pkg/services/rpcsrv/server_test.go @@ -33,12 +33,12 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" + "github.com/nspcc-dev/neo-go/pkg/neorpc" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/network" "github.com/nspcc-dev/neo-go/pkg/network/payload" - "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/services/rpcsrv/params" rpc2 "github.com/nspcc-dev/neo-go/pkg/services/oracle/broadcaster" + "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm/emit" @@ -1928,11 +1928,11 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] } resultRPC = `[` + resultRPC[:len(resultRPC)-1] + `]` body := doRPCCall(resultRPC, httpSrv.URL, t) - var responses []response.Raw + var responses []neorpc.Response err := json.Unmarshal(body, &responses) require.Nil(t, err) for i, tc := range cases { - var resp response.Raw + var resp neorpc.Response for _, r := range responses { if bytes.Equal(r.ID, []byte(strconv.Itoa(i))) { resp = r @@ -2478,7 +2478,7 @@ func (tc rpcTestCase) getResultPair(e *executor) (expected interface{}, res inte } func checkErrGetResult(t *testing.T, body []byte, expectingFail bool, expectedErr ...string) json.RawMessage { - var resp response.Raw + var resp neorpc.Response err := json.Unmarshal(body, &resp) require.Nil(t, err) if expectingFail { @@ -2495,7 +2495,7 @@ func checkErrGetResult(t *testing.T, body []byte, expectingFail bool, expectedEr } func checkErrGetBatchResult(t *testing.T, body []byte, expectingFail bool) json.RawMessage { - var resp []response.Raw + var resp []neorpc.Response err := json.Unmarshal(body, &resp) require.Nil(t, err) require.Equal(t, 1, len(resp)) diff --git a/pkg/services/rpcsrv/subscription.go b/pkg/services/rpcsrv/subscription.go index 3c4964913..7ec7ab72b 100644 --- a/pkg/services/rpcsrv/subscription.go +++ b/pkg/services/rpcsrv/subscription.go @@ -5,9 +5,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/block" "github.com/nspcc-dev/neo-go/pkg/core/state" "github.com/nspcc-dev/neo-go/pkg/core/transaction" - "github.com/nspcc-dev/neo-go/pkg/rpc/request" - "github.com/nspcc-dev/neo-go/pkg/rpc/response" - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result/subscriptions" + "github.com/nspcc-dev/neo-go/pkg/neorpc" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "go.uber.org/atomic" ) @@ -24,7 +23,7 @@ type ( feeds [maxFeeds]feed } feed struct { - event response.EventID + event neorpc.EventID filter interface{} } ) @@ -44,7 +43,7 @@ const ( notificationBufSize = 1024 ) -func (f *feed) Matches(r *response.Notification) bool { +func (f *feed) Matches(r *neorpc.Notification) bool { if r.Event != f.event { return false } @@ -52,12 +51,12 @@ func (f *feed) Matches(r *response.Notification) bool { return true } switch f.event { - case response.BlockEventID: - filt := f.filter.(request.BlockFilter) + case neorpc.BlockEventID: + filt := f.filter.(neorpc.BlockFilter) b := r.Payload[0].(*block.Block) return int(b.PrimaryIndex) == filt.Primary - case response.TransactionEventID: - filt := f.filter.(request.TxFilter) + case neorpc.TransactionEventID: + filt := f.filter.(neorpc.TxFilter) tx := r.Payload[0].(*transaction.Transaction) senderOK := filt.Sender == nil || tx.Sender().Equals(*filt.Sender) signerOK := true @@ -71,18 +70,18 @@ func (f *feed) Matches(r *response.Notification) bool { } } return senderOK && signerOK - case response.NotificationEventID: - filt := f.filter.(request.NotificationFilter) + case neorpc.NotificationEventID: + filt := f.filter.(neorpc.NotificationFilter) notification := r.Payload[0].(*subscriptions.NotificationEvent) hashOk := filt.Contract == nil || notification.ScriptHash.Equals(*filt.Contract) nameOk := filt.Name == nil || notification.Name == *filt.Name return hashOk && nameOk - case response.ExecutionEventID: - filt := f.filter.(request.ExecutionFilter) + case neorpc.ExecutionEventID: + filt := f.filter.(neorpc.ExecutionFilter) applog := r.Payload[0].(*state.AppExecResult) return applog.VMState.String() == filt.State - case response.NotaryRequestEventID: - filt := f.filter.(request.TxFilter) + case neorpc.NotaryRequestEventID: + filt := f.filter.(neorpc.TxFilter) req := r.Payload[0].(*subscriptions.NotaryRequestEvent) senderOk := filt.Sender == nil || req.NotaryRequest.FallbackTransaction.Signers[1].Account == *filt.Sender signerOK := true diff --git a/pkg/services/rpcsrv/subscription_test.go b/pkg/services/rpcsrv/subscription_test.go index 0a2d2e82e..1a5e5a957 100644 --- a/pkg/services/rpcsrv/subscription_test.go +++ b/pkg/services/rpcsrv/subscription_test.go @@ -11,7 +11,7 @@ import ( "github.com/nspcc-dev/neo-go/internal/testchain" "github.com/nspcc-dev/neo-go/pkg/core" "github.com/nspcc-dev/neo-go/pkg/encoding/address" - "github.com/nspcc-dev/neo-go/pkg/rpc/response" + "github.com/nspcc-dev/neo-go/pkg/neorpc" "github.com/stretchr/testify/require" "go.uber.org/atomic" ) @@ -36,8 +36,8 @@ func wsReader(t *testing.T, ws *websocket.Conn, msgCh chan<- []byte, isFinished } } -func callWSGetRaw(t *testing.T, ws *websocket.Conn, msg string, respCh <-chan []byte) *response.Raw { - var resp = new(response.Raw) +func callWSGetRaw(t *testing.T, ws *websocket.Conn, msg string, respCh <-chan []byte) *neorpc.Response { + var resp = new(neorpc.Response) require.NoError(t, ws.SetWriteDeadline(time.Now().Add(time.Second))) require.NoError(t, ws.WriteMessage(websocket.TextMessage, []byte(msg))) @@ -47,8 +47,8 @@ func callWSGetRaw(t *testing.T, ws *websocket.Conn, msg string, respCh <-chan [] return resp } -func getNotification(t *testing.T, respCh <-chan []byte) *response.Notification { - var resp = new(response.Notification) +func getNotification(t *testing.T, respCh <-chan []byte) *neorpc.Notification { + var resp = new(neorpc.Notification) body := <-respCh require.NoError(t, json.Unmarshal(body, resp)) return resp @@ -107,10 +107,10 @@ func TestSubscriptions(t *testing.T) { for _, b := range getTestBlocks(t) { require.NoError(t, chain.AddBlock(b)) resp := getNotification(t, respMsgs) - require.Equal(t, response.ExecutionEventID, resp.Event) + require.Equal(t, neorpc.ExecutionEventID, resp.Event) for { resp = getNotification(t, respMsgs) - if resp.Event != response.NotificationEventID { + if resp.Event != neorpc.NotificationEventID { break } } @@ -118,25 +118,25 @@ func TestSubscriptions(t *testing.T) { if i > 0 { resp = getNotification(t, respMsgs) } - require.Equal(t, response.ExecutionEventID, resp.Event) + require.Equal(t, neorpc.ExecutionEventID, resp.Event) for { resp := getNotification(t, respMsgs) - if resp.Event == response.NotificationEventID { + if resp.Event == neorpc.NotificationEventID { continue } - require.Equal(t, response.TransactionEventID, resp.Event) + require.Equal(t, neorpc.TransactionEventID, resp.Event) break } } resp = getNotification(t, respMsgs) - require.Equal(t, response.ExecutionEventID, resp.Event) + require.Equal(t, neorpc.ExecutionEventID, resp.Event) for { resp = getNotification(t, respMsgs) - if resp.Event != response.NotificationEventID { + if resp.Event != neorpc.NotificationEventID { break } } - require.Equal(t, response.BlockEventID, resp.Event) + require.Equal(t, neorpc.BlockEventID, resp.Event) } // We should manually add NotaryRequest to test notification. @@ -145,7 +145,7 @@ func TestSubscriptions(t *testing.T) { require.NoError(t, err) for { resp := getNotification(t, respMsgs) - if resp.Event == response.NotaryRequestEventID { + if resp.Event == neorpc.NotaryRequestEventID { break } } @@ -163,22 +163,22 @@ func TestFilteredSubscriptions(t *testing.T) { var cases = map[string]struct { params string - check func(*testing.T, *response.Notification) + check func(*testing.T, *neorpc.Notification) }{ "tx matching sender": { params: `["transaction_added", {"sender":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.TransactionEventID, resp.Event) + require.Equal(t, neorpc.TransactionEventID, resp.Event) sender := rmap["sender"].(string) require.Equal(t, address.Uint160ToString(goodSender), sender) }, }, "tx matching signer": { params: `["transaction_added", {"signer":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.TransactionEventID, resp.Event) + require.Equal(t, neorpc.TransactionEventID, resp.Event) signers := rmap["signers"].([]interface{}) signer0 := signers[0].(map[string]interface{}) signer0acc := signer0["account"].(string) @@ -187,9 +187,9 @@ func TestFilteredSubscriptions(t *testing.T) { }, "tx matching sender and signer": { params: `["transaction_added", {"sender":"` + goodSender.StringLE() + `", "signer":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.TransactionEventID, resp.Event) + require.Equal(t, neorpc.TransactionEventID, resp.Event) sender := rmap["sender"].(string) require.Equal(t, address.Uint160ToString(goodSender), sender) signers := rmap["signers"].([]interface{}) @@ -200,27 +200,27 @@ func TestFilteredSubscriptions(t *testing.T) { }, "notification matching contract hash": { params: `["notification_from_execution", {"contract":"` + testContractHash + `"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.NotificationEventID, resp.Event) + require.Equal(t, neorpc.NotificationEventID, resp.Event) c := rmap["contract"].(string) require.Equal(t, "0x"+testContractHash, c) }, }, "notification matching name": { params: `["notification_from_execution", {"name":"my_pretty_notification"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.NotificationEventID, resp.Event) + require.Equal(t, neorpc.NotificationEventID, resp.Event) n := rmap["name"].(string) require.Equal(t, "my_pretty_notification", n) }, }, "notification matching contract hash and name": { params: `["notification_from_execution", {"contract":"` + testContractHash + `", "name":"my_pretty_notification"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.NotificationEventID, resp.Event) + require.Equal(t, neorpc.NotificationEventID, resp.Event) c := rmap["contract"].(string) require.Equal(t, "0x"+testContractHash, c) n := rmap["name"].(string) @@ -229,28 +229,28 @@ func TestFilteredSubscriptions(t *testing.T) { }, "execution matching": { params: `["transaction_executed", {"state":"HALT"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.ExecutionEventID, resp.Event) + require.Equal(t, neorpc.ExecutionEventID, resp.Event) st := rmap["vmstate"].(string) require.Equal(t, "HALT", st) }, }, "tx non-matching": { params: `["transaction_added", {"sender":"00112233445566778899aabbccddeeff00112233"}]`, - check: func(t *testing.T, _ *response.Notification) { + check: func(t *testing.T, _ *neorpc.Notification) { t.Fatal("unexpected match for EnrollmentTransaction") }, }, "notification non-matching": { params: `["notification_from_execution", {"contract":"00112233445566778899aabbccddeeff00112233"}]`, - check: func(t *testing.T, _ *response.Notification) { + check: func(t *testing.T, _ *neorpc.Notification) { t.Fatal("unexpected match for contract 00112233445566778899aabbccddeeff00112233") }, }, "execution non-matching": { params: `["transaction_executed", {"state":"FAULT"}]`, - check: func(t *testing.T, _ *response.Notification) { + check: func(t *testing.T, _ *neorpc.Notification) { t.Fatal("unexpected match for faulted execution") }, }, @@ -276,7 +276,7 @@ func TestFilteredSubscriptions(t *testing.T) { for { resp := getNotification(t, respMsgs) rmap := resp.Payload[0].(map[string]interface{}) - if resp.Event == response.BlockEventID { + if resp.Event == neorpc.BlockEventID { index := rmap["index"].(float64) if uint32(index) == lastBlock { break @@ -302,13 +302,13 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { var cases = map[string]struct { params string - check func(*testing.T, *response.Notification) + check func(*testing.T, *neorpc.Notification) }{ "matching sender": { params: `["notary_request_event", {"sender":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.NotaryRequestEventID, resp.Event) + require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) require.Equal(t, "added", rmap["type"].(string)) req := rmap["notaryrequest"].(map[string]interface{}) fbTx := req["fallbacktx"].(map[string]interface{}) @@ -318,9 +318,9 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { }, "matching signer": { params: `["notary_request_event", {"signer":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.NotaryRequestEventID, resp.Event) + require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) require.Equal(t, "added", rmap["type"].(string)) req := rmap["notaryrequest"].(map[string]interface{}) mainTx := req["maintx"].(map[string]interface{}) @@ -332,9 +332,9 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { }, "matching sender and signer": { params: `["notary_request_event", {"sender":"` + goodSender.StringLE() + `", "signer":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *response.Notification) { + check: func(t *testing.T, resp *neorpc.Notification) { rmap := resp.Payload[0].(map[string]interface{}) - require.Equal(t, response.NotaryRequestEventID, resp.Event) + require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) require.Equal(t, "added", rmap["type"].(string)) req := rmap["notaryrequest"].(map[string]interface{}) mainTx := req["maintx"].(map[string]interface{}) @@ -370,7 +370,7 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { require.NoError(t, err) nonce++ - var resp = new(response.Notification) + var resp = new(neorpc.Notification) select { case body := <-respMsgs: require.NoError(t, json.Unmarshal(body, resp)) @@ -378,7 +378,7 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { t.Fatal("timeout waiting for event") } - require.Equal(t, response.NotaryRequestEventID, resp.Event) + require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) this.check(t, resp) callUnsubscribe(t, c, respMsgs, subID) @@ -410,7 +410,7 @@ func TestFilteredBlockSubscriptions(t *testing.T) { } for i := 0; i < expectedCnt; i++ { - var resp = new(response.Notification) + var resp = new(neorpc.Notification) select { case body := <-respMsgs: require.NoError(t, json.Unmarshal(body, resp)) @@ -418,7 +418,7 @@ func TestFilteredBlockSubscriptions(t *testing.T) { t.Fatal("timeout waiting for event") } - require.Equal(t, response.BlockEventID, resp.Event) + require.Equal(t, neorpc.BlockEventID, resp.Event) rmap := resp.Payload[0].(map[string]interface{}) primary := rmap["primary"].(float64) require.Equal(t, 3, int(primary)) @@ -565,8 +565,8 @@ func TestSubscriptionOverflow(t *testing.T) { } for i := 0; i < blockCnt; i++ { resp := getNotification(t, respMsgs) - if resp.Event != response.BlockEventID { - require.Equal(t, response.MissedEventID, resp.Event) + if resp.Event != neorpc.BlockEventID { + require.Equal(t, neorpc.MissedEventID, resp.Event) receivedMiss = true break } diff --git a/pkg/services/rpcsrv/tokens.go b/pkg/services/rpcsrv/tokens.go index fab1f905d..4844a85d4 100644 --- a/pkg/services/rpcsrv/tokens.go +++ b/pkg/services/rpcsrv/tokens.go @@ -1,7 +1,7 @@ package rpcsrv import ( - "github.com/nspcc-dev/neo-go/pkg/rpc/response/result" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" ) // tokenTransfers is a generic type used to represent NEP-11 and NEP-17 transfers. From 8e70cd3596c6fbf26ed3d5516dfc422f5f41cd69 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 19:17:48 +0300 Subject: [PATCH 05/14] rpc: move rpc.Config to pkg/config, remove pkg/rpc Makes no sense keeping it as is and TLS can be reused in the future. --- cli/server/server_test.go | 3 +-- pkg/config/application_config.go | 3 +-- pkg/config/config.go | 3 +-- pkg/{rpc => config}/rpc_config.go | 12 ++++++------ pkg/services/rpcsrv/server.go | 6 +++--- 5 files changed, 12 insertions(+), 15 deletions(-) rename pkg/{rpc => config}/rpc_config.go (84%) diff --git a/cli/server/server_test.go b/cli/server/server_test.go index b55d5b600..f3f8c107c 100644 --- a/cli/server/server_test.go +++ b/cli/server/server_test.go @@ -10,7 +10,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/core/storage/dbconfig" - "github.com/nspcc-dev/neo-go/pkg/rpc" "github.com/stretchr/testify/require" "github.com/urfave/cli" "go.uber.org/zap" @@ -303,7 +302,7 @@ func TestConfigureAddresses(t *testing.T) { t.Run("custom RPC address", func(t *testing.T) { cfg := &config.ApplicationConfiguration{ Address: defaultAddress, - RPC: rpc.Config{ + RPC: config.RPC{ Address: customAddress, }, } diff --git a/pkg/config/application_config.go b/pkg/config/application_config.go index 0a8cb6435..cbf7be3d1 100644 --- a/pkg/config/application_config.go +++ b/pkg/config/application_config.go @@ -2,7 +2,6 @@ package config import ( "github.com/nspcc-dev/neo-go/pkg/core/storage/dbconfig" - "github.com/nspcc-dev/neo-go/pkg/rpc" ) // ApplicationConfiguration config specific to the node. @@ -22,7 +21,7 @@ type ApplicationConfiguration struct { Prometheus BasicService `yaml:"Prometheus"` ProtoTickInterval int64 `yaml:"ProtoTickInterval"` Relay bool `yaml:"Relay"` - RPC rpc.Config `yaml:"RPC"` + RPC RPC `yaml:"RPC"` UnlockWallet Wallet `yaml:"UnlockWallet"` Oracle OracleConfiguration `yaml:"Oracle"` P2PNotary P2PNotary `yaml:"P2PNotary"` diff --git a/pkg/config/config.go b/pkg/config/config.go index be64e5a5f..b2dc05e27 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -5,7 +5,6 @@ import ( "os" "github.com/nspcc-dev/neo-go/pkg/config/netmode" - "github.com/nspcc-dev/neo-go/pkg/rpc" "gopkg.in/yaml.v3" ) @@ -58,7 +57,7 @@ func LoadFile(configPath string) (Config, error) { ApplicationConfiguration: ApplicationConfiguration{ PingInterval: 30, PingTimeout: 90, - RPC: rpc.Config{ + RPC: RPC{ MaxIteratorResultItems: DefaultMaxIteratorResultItems, MaxFindResultItems: 100, MaxNEP11Tokens: 100, diff --git a/pkg/rpc/rpc_config.go b/pkg/config/rpc_config.go similarity index 84% rename from pkg/rpc/rpc_config.go rename to pkg/config/rpc_config.go index 1e3a3f1d0..09cb3bc25 100644 --- a/pkg/rpc/rpc_config.go +++ b/pkg/config/rpc_config.go @@ -1,12 +1,12 @@ -package rpc +package config import ( "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" ) type ( - // Config is an RPC service configuration information. - Config struct { + // RPC is an RPC service configuration information. + RPC struct { Address string `yaml:"Address"` Enabled bool `yaml:"Enabled"` EnableCORSWorkaround bool `yaml:"EnableCORSWorkaround"` @@ -22,11 +22,11 @@ type ( SessionBackedByMPT bool `yaml:"SessionBackedByMPT"` SessionPoolSize int `yaml:"SessionPoolSize"` StartWhenSynchronized bool `yaml:"StartWhenSynchronized"` - TLSConfig TLSConfig `yaml:"TLSConfig"` + TLSConfig TLS `yaml:"TLSConfig"` } - // TLSConfig describes SSL/TLS configuration. - TLSConfig struct { + // TLS describes SSL/TLS configuration. + TLS struct { Address string `yaml:"Address"` CertFile string `yaml:"CertFile"` Enabled bool `yaml:"Enabled"` diff --git a/pkg/services/rpcsrv/server.go b/pkg/services/rpcsrv/server.go index c500ff7ec..a2504e4cb 100644 --- a/pkg/services/rpcsrv/server.go +++ b/pkg/services/rpcsrv/server.go @@ -20,6 +20,7 @@ import ( "github.com/google/uuid" "github.com/gorilla/websocket" + "github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/config/limits" "github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/core" @@ -43,7 +44,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/network" "github.com/nspcc-dev/neo-go/pkg/network/payload" - "github.com/nspcc-dev/neo-go/pkg/rpc" "github.com/nspcc-dev/neo-go/pkg/services/oracle" "github.com/nspcc-dev/neo-go/pkg/services/oracle/broadcaster" "github.com/nspcc-dev/neo-go/pkg/services/rpcsrv/params" @@ -62,7 +62,7 @@ type ( Server struct { *http.Server chain blockchainer.Blockchainer - config rpc.Config + config config.RPC // wsReadLimit represents web-socket message limit for a receiving side. wsReadLimit int64 network netmode.Magic @@ -197,7 +197,7 @@ var invalidBlockHeightError = func(index int, height int) *neorpc.Error { var upgrader = websocket.Upgrader{} // New creates a new Server struct. -func New(chain blockchainer.Blockchainer, conf rpc.Config, coreServer *network.Server, +func New(chain blockchainer.Blockchainer, conf config.RPC, coreServer *network.Server, orc *oracle.Oracle, log *zap.Logger, errChan chan error) Server { httpServer := &http.Server{ Addr: conf.Address + ":" + strconv.FormatUint(uint64(conf.Port), 10), From 4acd1688a1cc72f73f670657365909f679e01c26 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 21:17:23 +0300 Subject: [PATCH 06/14] subscriptions: move NotificationEvent to state 1. It's not good for pkg/core to import anything from pkg/neorpc. 2. The type is closely tied to the state package, even though it's not stored in the DB --- internal/fakechain/fakechain.go | 5 +- pkg/core/blockchain.go | 17 +++--- pkg/core/blockchain_neotest_test.go | 3 +- pkg/core/blockchainer/blockchainer.go | 5 +- pkg/core/state/notification_event.go | 46 +++++++++++++++ pkg/core/state/notification_event_test.go | 12 ++++ .../subscriptions/notification_event.go | 56 ------------------- .../subscriptions/notification_event_test.go | 21 ------- pkg/rpcclient/wsclient.go | 4 +- pkg/services/rpcsrv/server.go | 4 +- pkg/services/rpcsrv/subscription.go | 2 +- 11 files changed, 76 insertions(+), 99 deletions(-) delete mode 100644 pkg/neorpc/result/subscriptions/notification_event.go delete mode 100644 pkg/neorpc/result/subscriptions/notification_event_test.go diff --git a/internal/fakechain/fakechain.go b/internal/fakechain/fakechain.go index 0490d0ba2..61568ee05 100644 --- a/internal/fakechain/fakechain.go +++ b/internal/fakechain/fakechain.go @@ -19,7 +19,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" - "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" uatomic "go.uber.org/atomic" @@ -404,7 +403,7 @@ func (chain *FakeChain) SubscribeForExecutions(ch chan<- *state.AppExecResult) { } // SubscribeForNotifications implements the Blockchainer interface. -func (chain *FakeChain) SubscribeForNotifications(ch chan<- *subscriptions.NotificationEvent) { +func (chain *FakeChain) SubscribeForNotifications(ch chan<- *state.ContainedNotificationEvent) { panic("TODO") } @@ -444,7 +443,7 @@ func (chain *FakeChain) UnsubscribeFromExecutions(ch chan<- *state.AppExecResult } // UnsubscribeFromNotifications implements the Blockchainer interface. -func (chain *FakeChain) UnsubscribeFromNotifications(ch chan<- *subscriptions.NotificationEvent) { +func (chain *FakeChain) UnsubscribeFromNotifications(ch chan<- *state.ContainedNotificationEvent) { panic("TODO") } diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 09ad86e26..0ad95d083 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -33,7 +33,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" "github.com/nspcc-dev/neo-go/pkg/io" - "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" @@ -755,7 +754,7 @@ func (bc *Blockchain) notificationDispatcher() { // expected, but maps are convenient for adding/deleting elements). blockFeed = make(map[chan<- *block.Block]bool) txFeed = make(map[chan<- *transaction.Transaction]bool) - notificationFeed = make(map[chan<- *subscriptions.NotificationEvent]bool) + notificationFeed = make(map[chan<- *state.ContainedNotificationEvent]bool) executionFeed = make(map[chan<- *state.AppExecResult]bool) ) for { @@ -768,7 +767,7 @@ func (bc *Blockchain) notificationDispatcher() { blockFeed[ch] = true case chan<- *transaction.Transaction: txFeed[ch] = true - case chan<- *subscriptions.NotificationEvent: + case chan<- *state.ContainedNotificationEvent: notificationFeed[ch] = true case chan<- *state.AppExecResult: executionFeed[ch] = true @@ -781,7 +780,7 @@ func (bc *Blockchain) notificationDispatcher() { delete(blockFeed, ch) case chan<- *transaction.Transaction: delete(txFeed, ch) - case chan<- *subscriptions.NotificationEvent: + case chan<- *state.ContainedNotificationEvent: delete(notificationFeed, ch) case chan<- *state.AppExecResult: delete(executionFeed, ch) @@ -801,7 +800,7 @@ func (bc *Blockchain) notificationDispatcher() { } for i := range aer.Events { for ch := range notificationFeed { - ch <- &subscriptions.NotificationEvent{ + ch <- &state.ContainedNotificationEvent{ Container: aer.Container, NotificationEvent: aer.Events[i], } @@ -821,7 +820,7 @@ func (bc *Blockchain) notificationDispatcher() { if aer.VMState == vmstate.Halt { for i := range aer.Events { for ch := range notificationFeed { - ch <- &subscriptions.NotificationEvent{ + ch <- &state.ContainedNotificationEvent{ Container: aer.Container, NotificationEvent: aer.Events[i], } @@ -842,7 +841,7 @@ func (bc *Blockchain) notificationDispatcher() { } for i := range aer.Events { for ch := range notificationFeed { - ch <- &subscriptions.NotificationEvent{ + ch <- &state.ContainedNotificationEvent{ Container: aer.Container, NotificationEvent: aer.Events[i], } @@ -1782,7 +1781,7 @@ func (bc *Blockchain) SubscribeForTransactions(ch chan<- *transaction.Transactio // transactions use SubscribeForExecutions instead. Make sure this channel is // read from regularly as not reading these events might affect other Blockchain // functions. -func (bc *Blockchain) SubscribeForNotifications(ch chan<- *subscriptions.NotificationEvent) { +func (bc *Blockchain) SubscribeForNotifications(ch chan<- *state.ContainedNotificationEvent) { bc.subCh <- ch } @@ -1810,7 +1809,7 @@ func (bc *Blockchain) UnsubscribeFromTransactions(ch chan<- *transaction.Transac // UnsubscribeFromNotifications unsubscribes given channel from new // execution-generated notifications, you can close it afterwards. Passing // non-subscribed channel is a no-op. -func (bc *Blockchain) UnsubscribeFromNotifications(ch chan<- *subscriptions.NotificationEvent) { +func (bc *Blockchain) UnsubscribeFromNotifications(ch chan<- *state.ContainedNotificationEvent) { bc.unsubCh <- ch } diff --git a/pkg/core/blockchain_neotest_test.go b/pkg/core/blockchain_neotest_test.go index 5849baa2e..35d5bc3a1 100644 --- a/pkg/core/blockchain_neotest_test.go +++ b/pkg/core/blockchain_neotest_test.go @@ -36,7 +36,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/neotest" "github.com/nspcc-dev/neo-go/pkg/neotest/chain" - "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" @@ -760,7 +759,7 @@ func TestBlockchain_Subscriptions(t *testing.T) { const chBufSize = 16 blockCh := make(chan *block.Block, chBufSize) txCh := make(chan *transaction.Transaction, chBufSize) - notificationCh := make(chan *subscriptions.NotificationEvent, chBufSize) + notificationCh := make(chan *state.ContainedNotificationEvent, chBufSize) executionCh := make(chan *state.AppExecResult, chBufSize) bc, acc := chain.NewSingle(t) diff --git a/pkg/core/blockchainer/blockchainer.go b/pkg/core/blockchainer/blockchainer.go index ba47bdd00..6032841f2 100644 --- a/pkg/core/blockchainer/blockchainer.go +++ b/pkg/core/blockchainer/blockchainer.go @@ -12,7 +12,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" - "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/util" ) @@ -70,14 +69,14 @@ type Blockchainer interface { SetNotary(mod services.Notary) SubscribeForBlocks(ch chan<- *block.Block) SubscribeForExecutions(ch chan<- *state.AppExecResult) - SubscribeForNotifications(ch chan<- *subscriptions.NotificationEvent) + SubscribeForNotifications(ch chan<- *state.ContainedNotificationEvent) SubscribeForTransactions(ch chan<- *transaction.Transaction) VerifyTx(*transaction.Transaction) error VerifyWitness(util.Uint160, hash.Hashable, *transaction.Witness, int64) (int64, error) GetMemPool() *mempool.Pool UnsubscribeFromBlocks(ch chan<- *block.Block) UnsubscribeFromExecutions(ch chan<- *state.AppExecResult) - UnsubscribeFromNotifications(ch chan<- *subscriptions.NotificationEvent) + UnsubscribeFromNotifications(ch chan<- *state.ContainedNotificationEvent) UnsubscribeFromTransactions(ch chan<- *transaction.Transaction) // Policer. GetBaseExecFee() int64 diff --git a/pkg/core/state/notification_event.go b/pkg/core/state/notification_event.go index 317df0808..70d1683ed 100644 --- a/pkg/core/state/notification_event.go +++ b/pkg/core/state/notification_event.go @@ -27,6 +27,13 @@ type AppExecResult struct { Execution } +// ContainedNotificationEvent represents a wrapper for a notification from script execution. +type ContainedNotificationEvent struct { + // Container hash is the hash of script container which is either a block or a transaction. + Container util.Uint256 + NotificationEvent +} + // EncodeBinary implements the Serializable interface. func (ne *NotificationEvent) EncodeBinary(w *io.BinWriter) { ne.EncodeBinaryWithContext(w, stackitem.NewSerializationContext()) @@ -276,3 +283,42 @@ func (e *Execution) UnmarshalJSON(data []byte) error { e.FaultException = aux.FaultException return nil } + +// containedNotificationEventAux is an auxiliary struct for JSON marshalling. +type containedNotificationEventAux struct { + Container util.Uint256 `json:"container"` +} + +// MarshalJSON implements the json.Marshaler interface. +func (ne *ContainedNotificationEvent) MarshalJSON() ([]byte, error) { + h, err := json.Marshal(&containedNotificationEventAux{ + Container: ne.Container, + }) + if err != nil { + return nil, fmt.Errorf("failed to marshal hash: %w", err) + } + exec, err := json.Marshal(ne.NotificationEvent) + if err != nil { + return nil, fmt.Errorf("failed to marshal execution: %w", err) + } + + if h[len(h)-1] != '}' || exec[0] != '{' { + return nil, errors.New("can't merge internal jsons") + } + h[len(h)-1] = ',' + h = append(h, exec[1:]...) + return h, nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface. +func (ne *ContainedNotificationEvent) UnmarshalJSON(data []byte) error { + aux := new(containedNotificationEventAux) + if err := json.Unmarshal(data, aux); err != nil { + return err + } + if err := json.Unmarshal(data, &ne.NotificationEvent); err != nil { + return err + } + ne.Container = aux.Container + return nil +} diff --git a/pkg/core/state/notification_event_test.go b/pkg/core/state/notification_event_test.go index 0a4a11082..d61e96287 100644 --- a/pkg/core/state/notification_event_test.go +++ b/pkg/core/state/notification_event_test.go @@ -8,6 +8,7 @@ import ( "github.com/nspcc-dev/neo-go/internal/testserdes" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" + "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" "github.com/nspcc-dev/neo-go/pkg/vm/vmstate" "github.com/stretchr/testify/require" @@ -241,3 +242,14 @@ func TestMarshalUnmarshalJSONAppExecResult(t *testing.T) { } }) } + +func TestContainedNotificationEvent_MarshalUnmarshalJSON(t *testing.T) { + testserdes.MarshalUnmarshalJSON(t, &ContainedNotificationEvent{ + Container: util.Uint256{1, 2, 3}, + NotificationEvent: NotificationEvent{ + ScriptHash: util.Uint160{4, 5, 6}, + Name: "alarm", + Item: stackitem.NewArray([]stackitem.Item{stackitem.NewByteArray([]byte("qwerty"))}), + }, + }, new(ContainedNotificationEvent)) +} diff --git a/pkg/neorpc/result/subscriptions/notification_event.go b/pkg/neorpc/result/subscriptions/notification_event.go deleted file mode 100644 index 305375071..000000000 --- a/pkg/neorpc/result/subscriptions/notification_event.go +++ /dev/null @@ -1,56 +0,0 @@ -package subscriptions - -import ( - "encoding/json" - "errors" - "fmt" - - "github.com/nspcc-dev/neo-go/pkg/core/state" - "github.com/nspcc-dev/neo-go/pkg/util" -) - -// NotificationEvent represents a wrapper for a notification from script execution. -type NotificationEvent struct { - // Container hash is the hash of script container which is either a block or a transaction. - Container util.Uint256 - state.NotificationEvent -} - -// notificationEventAux is an auxiliary struct for JSON marshalling. -type notificationEventAux struct { - Container util.Uint256 `json:"container"` -} - -// MarshalJSON implements the json.Marshaler interface. -func (ne *NotificationEvent) MarshalJSON() ([]byte, error) { - h, err := json.Marshal(¬ificationEventAux{ - Container: ne.Container, - }) - if err != nil { - return nil, fmt.Errorf("failed to marshal hash: %w", err) - } - exec, err := json.Marshal(ne.NotificationEvent) - if err != nil { - return nil, fmt.Errorf("failed to marshal execution: %w", err) - } - - if h[len(h)-1] != '}' || exec[0] != '{' { - return nil, errors.New("can't merge internal jsons") - } - h[len(h)-1] = ',' - h = append(h, exec[1:]...) - return h, nil -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -func (ne *NotificationEvent) UnmarshalJSON(data []byte) error { - aux := new(notificationEventAux) - if err := json.Unmarshal(data, aux); err != nil { - return err - } - if err := json.Unmarshal(data, &ne.NotificationEvent); err != nil { - return err - } - ne.Container = aux.Container - return nil -} diff --git a/pkg/neorpc/result/subscriptions/notification_event_test.go b/pkg/neorpc/result/subscriptions/notification_event_test.go deleted file mode 100644 index e22df6447..000000000 --- a/pkg/neorpc/result/subscriptions/notification_event_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package subscriptions - -import ( - "testing" - - "github.com/nspcc-dev/neo-go/internal/testserdes" - "github.com/nspcc-dev/neo-go/pkg/core/state" - "github.com/nspcc-dev/neo-go/pkg/util" - "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" -) - -func TestNotificationEvent_MarshalUnmarshalJSON(t *testing.T) { - testserdes.MarshalUnmarshalJSON(t, &NotificationEvent{ - Container: util.Uint256{1, 2, 3}, - NotificationEvent: state.NotificationEvent{ - ScriptHash: util.Uint160{4, 5, 6}, - Name: "alarm", - Item: stackitem.NewArray([]stackitem.Item{stackitem.NewByteArray([]byte("qwerty"))}), - }, - }, new(NotificationEvent)) -} diff --git a/pkg/rpcclient/wsclient.go b/pkg/rpcclient/wsclient.go index 2e0c75677..ad8915580 100644 --- a/pkg/rpcclient/wsclient.go +++ b/pkg/rpcclient/wsclient.go @@ -52,7 +52,7 @@ type WSClient struct { } // Notification represents a server-generated notification for client subscriptions. -// Value can be one of block.Block, state.AppExecResult, subscriptions.NotificationEvent +// Value can be one of block.Block, state.AppExecResult, state.ContainedNotificationEvent // transaction.Transaction or subscriptions.NotaryRequestEvent based on Type. type Notification struct { Type neorpc.EventID @@ -182,7 +182,7 @@ readloop: case neorpc.TransactionEventID: val = &transaction.Transaction{} case neorpc.NotificationEventID: - val = new(subscriptions.NotificationEvent) + val = new(state.ContainedNotificationEvent) case neorpc.ExecutionEventID: val = new(state.AppExecResult) case neorpc.NotaryRequestEventID: diff --git a/pkg/services/rpcsrv/server.go b/pkg/services/rpcsrv/server.go index a2504e4cb..bc9b36951 100644 --- a/pkg/services/rpcsrv/server.go +++ b/pkg/services/rpcsrv/server.go @@ -87,7 +87,7 @@ type ( notaryRequestSubs int blockCh chan *block.Block executionCh chan *state.AppExecResult - notificationCh chan *subscriptions.NotificationEvent + notificationCh chan *state.ContainedNotificationEvent transactionCh chan *transaction.Transaction notaryRequestCh chan mempoolevent.Event } @@ -245,7 +245,7 @@ func New(chain blockchainer.Blockchainer, conf config.RPC, coreServer *network.S // These are NOT buffered to preserve original order of events. blockCh: make(chan *block.Block), executionCh: make(chan *state.AppExecResult), - notificationCh: make(chan *subscriptions.NotificationEvent), + notificationCh: make(chan *state.ContainedNotificationEvent), transactionCh: make(chan *transaction.Transaction), notaryRequestCh: make(chan mempoolevent.Event), } diff --git a/pkg/services/rpcsrv/subscription.go b/pkg/services/rpcsrv/subscription.go index 7ec7ab72b..dec18b223 100644 --- a/pkg/services/rpcsrv/subscription.go +++ b/pkg/services/rpcsrv/subscription.go @@ -72,7 +72,7 @@ func (f *feed) Matches(r *neorpc.Notification) bool { return senderOK && signerOK case neorpc.NotificationEventID: filt := f.filter.(neorpc.NotificationFilter) - notification := r.Payload[0].(*subscriptions.NotificationEvent) + notification := r.Payload[0].(*state.ContainedNotificationEvent) hashOk := filt.Contract == nil || notification.ScriptHash.Equals(*filt.Contract) nameOk := filt.Name == nil || notification.Name == *filt.Name return hashOk && nameOk From b3c25b5a1f01e774cddc468c56929a6e606cfa6b Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 21:26:29 +0300 Subject: [PATCH 07/14] neorpc/result: move NotaryRequestEvent to this package Not worth a package of its own. --- pkg/neorpc/result/{subscriptions => }/notary_request_event.go | 2 +- pkg/rpcclient/wsclient.go | 4 ++-- pkg/services/rpcsrv/server.go | 3 +-- pkg/services/rpcsrv/subscription.go | 4 ++-- 4 files changed, 6 insertions(+), 7 deletions(-) rename pkg/neorpc/result/{subscriptions => }/notary_request_event.go (94%) diff --git a/pkg/neorpc/result/subscriptions/notary_request_event.go b/pkg/neorpc/result/notary_request_event.go similarity index 94% rename from pkg/neorpc/result/subscriptions/notary_request_event.go rename to pkg/neorpc/result/notary_request_event.go index f1cd35daa..030968a12 100644 --- a/pkg/neorpc/result/subscriptions/notary_request_event.go +++ b/pkg/neorpc/result/notary_request_event.go @@ -1,4 +1,4 @@ -package subscriptions +package result import ( "github.com/nspcc-dev/neo-go/pkg/core/mempoolevent" diff --git a/pkg/rpcclient/wsclient.go b/pkg/rpcclient/wsclient.go index ad8915580..ab77f141d 100644 --- a/pkg/rpcclient/wsclient.go +++ b/pkg/rpcclient/wsclient.go @@ -14,7 +14,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/state" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/neorpc" - "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "github.com/nspcc-dev/neo-go/pkg/util" "go.uber.org/atomic" ) @@ -186,7 +186,7 @@ readloop: case neorpc.ExecutionEventID: val = new(state.AppExecResult) case neorpc.NotaryRequestEventID: - val = new(subscriptions.NotaryRequestEvent) + val = new(result.NotaryRequestEvent) case neorpc.MissedEventID: // No value. default: diff --git a/pkg/services/rpcsrv/server.go b/pkg/services/rpcsrv/server.go index bc9b36951..c0ae35b69 100644 --- a/pkg/services/rpcsrv/server.go +++ b/pkg/services/rpcsrv/server.go @@ -41,7 +41,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/neorpc" "github.com/nspcc-dev/neo-go/pkg/neorpc/result" - "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" "github.com/nspcc-dev/neo-go/pkg/network" "github.com/nspcc-dev/neo-go/pkg/network/payload" "github.com/nspcc-dev/neo-go/pkg/services/oracle" @@ -2514,7 +2513,7 @@ chloop: resp.Payload[0] = tx case e := <-s.notaryRequestCh: resp.Event = neorpc.NotaryRequestEventID - resp.Payload[0] = &subscriptions.NotaryRequestEvent{ + resp.Payload[0] = &result.NotaryRequestEvent{ Type: e.Type, NotaryRequest: e.Data.(*payload.P2PNotaryRequest), } diff --git a/pkg/services/rpcsrv/subscription.go b/pkg/services/rpcsrv/subscription.go index dec18b223..6ec1be3fb 100644 --- a/pkg/services/rpcsrv/subscription.go +++ b/pkg/services/rpcsrv/subscription.go @@ -6,7 +6,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/state" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/neorpc" - "github.com/nspcc-dev/neo-go/pkg/neorpc/result/subscriptions" + "github.com/nspcc-dev/neo-go/pkg/neorpc/result" "go.uber.org/atomic" ) @@ -82,7 +82,7 @@ func (f *feed) Matches(r *neorpc.Notification) bool { return applog.VMState.String() == filt.State case neorpc.NotaryRequestEventID: filt := f.filter.(neorpc.TxFilter) - req := r.Payload[0].(*subscriptions.NotaryRequestEvent) + req := r.Payload[0].(*result.NotaryRequestEvent) senderOk := filt.Sender == nil || req.NotaryRequest.FallbackTransaction.Signers[1].Account == *filt.Sender signerOK := true if filt.Signer != nil { From 5b49636ebeedf40e8b3d4043f79d04082137a66b Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 21:58:05 +0300 Subject: [PATCH 08/14] neotest: use real *core.Blockchain Hiding it behind blockchainer.Blockchain doesn't improve the testing system, there is no other implementation of it that can fulfil all the needs of the neotest and at the same time this limits the functions available to tests. --- pkg/neotest/basic.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pkg/neotest/basic.go b/pkg/neotest/basic.go index 1a5879ceb..7d85882f4 100644 --- a/pkg/neotest/basic.go +++ b/pkg/neotest/basic.go @@ -8,8 +8,8 @@ import ( "testing" "github.com/nspcc-dev/neo-go/pkg/config/netmode" + "github.com/nspcc-dev/neo-go/pkg/core" "github.com/nspcc-dev/neo-go/pkg/core/block" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" "github.com/nspcc-dev/neo-go/pkg/core/fee" "github.com/nspcc-dev/neo-go/pkg/core/native" "github.com/nspcc-dev/neo-go/pkg/core/native/nativenames" @@ -29,7 +29,7 @@ import ( // Executor is a wrapper over chain state. type Executor struct { - Chain blockchainer.Blockchainer + Chain *core.Blockchain Validator Signer Committee Signer CommitteeHash util.Uint160 @@ -37,7 +37,7 @@ type Executor struct { } // NewExecutor creates a new executor instance from the provided blockchain and committee. -func NewExecutor(t testing.TB, bc blockchainer.Blockchainer, validator, committee Signer) *Executor { +func NewExecutor(t testing.TB, bc *core.Blockchain, validator, committee Signer) *Executor { checkMultiSigner(t, validator) checkMultiSigner(t, committee) @@ -254,12 +254,12 @@ func (e *Executor) EnsureGASBalance(t testing.TB, acc util.Uint160, isOk func(ba } // NewDeployTx returns a new deployment tx for the contract signed by the committee. -func (e *Executor) NewDeployTx(t testing.TB, bc blockchainer.Blockchainer, c *Contract, data interface{}) *transaction.Transaction { +func (e *Executor) NewDeployTx(t testing.TB, bc *core.Blockchain, c *Contract, data interface{}) *transaction.Transaction { return NewDeployTxBy(t, bc, e.Validator, c, data) } // NewDeployTxBy returns a new deployment tx for the contract signed by the specified signer. -func NewDeployTxBy(t testing.TB, bc blockchainer.Blockchainer, signer Signer, c *Contract, data interface{}) *transaction.Transaction { +func NewDeployTxBy(t testing.TB, bc *core.Blockchain, signer Signer, c *Contract, data interface{}) *transaction.Transaction { rawManifest, err := json.Marshal(c.Manifest) require.NoError(t, err) @@ -284,7 +284,7 @@ func NewDeployTxBy(t testing.TB, bc blockchainer.Blockchainer, signer Signer, c // AddSystemFee adds system fee to the transaction. If negative value specified, // then system fee is defined by test invocation. -func AddSystemFee(bc blockchainer.Blockchainer, tx *transaction.Transaction, sysFee int64) { +func AddSystemFee(bc *core.Blockchain, tx *transaction.Transaction, sysFee int64) { if sysFee >= 0 { tx.SystemFee = sysFee return @@ -294,7 +294,7 @@ func AddSystemFee(bc blockchainer.Blockchainer, tx *transaction.Transaction, sys } // AddNetworkFee adds network fee to the transaction. -func AddNetworkFee(bc blockchainer.Blockchainer, tx *transaction.Transaction, signers ...Signer) { +func AddNetworkFee(bc *core.Blockchain, tx *transaction.Transaction, signers ...Signer) { baseFee := bc.GetBaseExecFee() size := io.GetVarSize(tx) for _, sgr := range signers { @@ -362,7 +362,7 @@ func (e *Executor) AddBlockCheckHalt(t testing.TB, txs ...*transaction.Transacti } // TestInvoke creates a test VM with a dummy block and executes a transaction in it. -func TestInvoke(bc blockchainer.Blockchainer, tx *transaction.Transaction) (*vm.VM, error) { +func TestInvoke(bc *core.Blockchain, tx *transaction.Transaction) (*vm.VM, error) { lastBlock, err := bc.GetBlock(bc.GetHeaderHash(int(bc.BlockHeight()))) if err != nil { return nil, err From 3a6626f21fbe05c6a194f5ee38069327d5e45730 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 21:59:42 +0300 Subject: [PATCH 09/14] blockchainer: drop unused `services` dependency --- internal/fakechain/fakechain.go | 11 ----------- pkg/core/blockchainer/blockchainer.go | 3 --- 2 files changed, 14 deletions(-) diff --git a/internal/fakechain/fakechain.go b/internal/fakechain/fakechain.go index 61568ee05..e2cc7827f 100644 --- a/internal/fakechain/fakechain.go +++ b/internal/fakechain/fakechain.go @@ -10,7 +10,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/core/block" "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer/services" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/mempool" "github.com/nspcc-dev/neo-go/pkg/core/mpt" @@ -382,16 +381,6 @@ func (chain *FakeChain) PoolTx(tx *transaction.Transaction, _ ...*mempool.Pool) return chain.PoolTxF(tx) } -// SetOracle implements the Blockchainer interface. -func (chain FakeChain) SetOracle(services.Oracle) { - panic("TODO") -} - -// SetNotary implements the Blockchainer interface. -func (chain *FakeChain) SetNotary(notary services.Notary) { - panic("TODO") -} - // SubscribeForBlocks implements the Blockchainer interface. func (chain *FakeChain) SubscribeForBlocks(ch chan<- *block.Block) { chain.blocksCh = append(chain.blocksCh, ch) diff --git a/pkg/core/blockchainer/blockchainer.go b/pkg/core/blockchainer/blockchainer.go index 6032841f2..f73348b3a 100644 --- a/pkg/core/blockchainer/blockchainer.go +++ b/pkg/core/blockchainer/blockchainer.go @@ -5,7 +5,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/core/block" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer/services" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/mempool" "github.com/nspcc-dev/neo-go/pkg/core/state" @@ -61,12 +60,10 @@ type Blockchainer interface { GetTestVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) *interop.Context GetTestHistoricVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) (*interop.Context, error) GetTransaction(util.Uint256) (*transaction.Transaction, uint32, error) - SetOracle(service services.Oracle) mempool.Feer // fee interface ManagementContractHash() util.Uint160 PoolTx(t *transaction.Transaction, pools ...*mempool.Pool) error PoolTxWithData(t *transaction.Transaction, data interface{}, mp *mempool.Pool, feer mempool.Feer, verificationFunction func(t *transaction.Transaction, data interface{}) error) error - SetNotary(mod services.Notary) SubscribeForBlocks(ch chan<- *block.Block) SubscribeForExecutions(ch chan<- *state.AppExecResult) SubscribeForNotifications(ch chan<- *state.ContainedNotificationEvent) From dc7950d0503e07ab6a90c82671e2400aafb58a8e Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 22:10:33 +0300 Subject: [PATCH 10/14] testchain: don't use blockchainer.Blockchain It's not needed. --- internal/testchain/address.go | 3 +-- internal/testchain/transaction.go | 23 +++++++++++++++++------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/internal/testchain/address.go b/internal/testchain/address.go index 92aebb107..d116214fc 100644 --- a/internal/testchain/address.go +++ b/internal/testchain/address.go @@ -5,7 +5,6 @@ import ( "time" "github.com/nspcc-dev/neo-go/pkg/core/block" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" @@ -156,7 +155,7 @@ func SignCommittee(h hash.Hashable) []byte { // NewBlock creates a new block for the given blockchain with the given offset // (usually, 1), primary node index and transactions. -func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block { +func NewBlock(t *testing.T, bc Ledger, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block { witness := transaction.Witness{VerificationScript: MultisigVerificationScript()} height := bc.BlockHeight() h := bc.GetHeaderHash(int(height)) diff --git a/internal/testchain/transaction.go b/internal/testchain/transaction.go index 387b7e6a9..3c5aac449 100644 --- a/internal/testchain/transaction.go +++ b/internal/testchain/transaction.go @@ -9,7 +9,7 @@ import ( "github.com/nspcc-dev/neo-go/cli/smartcontract" "github.com/nspcc-dev/neo-go/pkg/compiler" "github.com/nspcc-dev/neo-go/pkg/config" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" + "github.com/nspcc-dev/neo-go/pkg/core/block" "github.com/nspcc-dev/neo-go/pkg/core/fee" "github.com/nspcc-dev/neo-go/pkg/core/native" "github.com/nspcc-dev/neo-go/pkg/core/state" @@ -23,13 +23,24 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/opcode" ) +// Ledger is an interface that abstracts the implementation of the blockchain. +type Ledger interface { + BlockHeight() uint32 + FeePerByte() int64 + GetBaseExecFee() int64 + GetHeader(hash util.Uint256) (*block.Header, error) + GetHeaderHash(int) util.Uint256 + HeaderHeight() uint32 + ManagementContractHash() util.Uint160 +} + var ( ownerHash = MultisigScriptHash() ownerScript = MultisigVerificationScript() ) // NewTransferFromOwner returns a transaction transferring funds from NEO and GAS owner. -func NewTransferFromOwner(bc blockchainer.Blockchainer, contractHash, to util.Uint160, amount int64, +func NewTransferFromOwner(bc Ledger, contractHash, to util.Uint160, amount int64, nonce, validUntil uint32) (*transaction.Transaction, error) { w := io.NewBufBinWriter() emit.AppCall(w.BinWriter, contractHash, "transfer", callflag.All, ownerHash, to, amount, nil) @@ -53,7 +64,7 @@ func NewTransferFromOwner(bc blockchainer.Blockchainer, contractHash, to util.Ui // NewDeployTx returns a new deployment transaction for a contract with the source from r and a name equal to // the filename without '.go' suffix. -func NewDeployTx(bc blockchainer.Blockchainer, name string, sender util.Uint160, r gio.Reader, confFile *string) (*transaction.Transaction, util.Uint160, []byte, error) { +func NewDeployTx(bc Ledger, name string, sender util.Uint160, r gio.Reader, confFile *string) (*transaction.Transaction, util.Uint160, []byte, error) { // nef.NewFile() cares about version a lot. config.Version = "0.90.0-test" @@ -111,18 +122,18 @@ func NewDeployTx(bc blockchainer.Blockchainer, name string, sender util.Uint160, } // SignTx signs the provided transactions with validator keys. -func SignTx(bc blockchainer.Blockchainer, txs ...*transaction.Transaction) error { +func SignTx(bc Ledger, txs ...*transaction.Transaction) error { signTxGeneric(bc, Sign, ownerScript, txs...) return nil } // SignTxCommittee signs transactions by committee. -func SignTxCommittee(bc blockchainer.Blockchainer, txs ...*transaction.Transaction) error { +func SignTxCommittee(bc Ledger, txs ...*transaction.Transaction) error { signTxGeneric(bc, SignCommittee, CommitteeVerificationScript(), txs...) return nil } -func signTxGeneric(bc blockchainer.Blockchainer, sign func(hash.Hashable) []byte, verif []byte, txs ...*transaction.Transaction) { +func signTxGeneric(bc Ledger, sign func(hash.Hashable) []byte, verif []byte, txs ...*transaction.Transaction) { for _, tx := range txs { size := io.GetVarSize(tx) netFee, sizeDelta := fee.Calculate(bc.GetBaseExecFee(), verif) From fcbda00f8a3847b93c129bda929778ee2b315a99 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 22:18:55 +0300 Subject: [PATCH 11/14] blockchainer/services: drop this package It doesn't add any value. --- pkg/core/blockchain.go | 5 ++--- pkg/core/blockchainer/services/notary.go | 8 -------- pkg/core/blockchainer/services/oracle.go | 23 ----------------------- pkg/core/native/designate.go | 5 ++--- pkg/core/native/notary.go | 5 +++++ pkg/core/native/oracle.go | 21 ++++++++++++++++++--- 6 files changed, 27 insertions(+), 40 deletions(-) delete mode 100644 pkg/core/blockchainer/services/notary.go delete mode 100644 pkg/core/blockchainer/services/oracle.go diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 0ad95d083..4d3ec192a 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -16,7 +16,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config/limits" "github.com/nspcc-dev/neo-go/pkg/core/block" "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer/services" "github.com/nspcc-dev/neo-go/pkg/core/dao" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/interop/contract" @@ -291,7 +290,7 @@ func NewBlockchain(s storage.Store, cfg config.ProtocolConfiguration, log *zap.L // SetOracle sets oracle module. It doesn't protected by mutex and // must be called before `bc.Run()` to avoid data race. -func (bc *Blockchain) SetOracle(mod services.Oracle) { +func (bc *Blockchain) SetOracle(mod native.OracleService) { orc := bc.contracts.Oracle md, ok := orc.GetMethod(manifest.MethodVerify, -1) if !ok { @@ -305,7 +304,7 @@ func (bc *Blockchain) SetOracle(mod services.Oracle) { // SetNotary sets notary module. It doesn't protected by mutex and // must be called before `bc.Run()` to avoid data race. -func (bc *Blockchain) SetNotary(mod services.Notary) { +func (bc *Blockchain) SetNotary(mod native.NotaryService) { bc.contracts.Designate.NotaryService.Store(mod) } diff --git a/pkg/core/blockchainer/services/notary.go b/pkg/core/blockchainer/services/notary.go deleted file mode 100644 index 76ccd8a7d..000000000 --- a/pkg/core/blockchainer/services/notary.go +++ /dev/null @@ -1,8 +0,0 @@ -package services - -import "github.com/nspcc-dev/neo-go/pkg/crypto/keys" - -// Notary is a Notary module interface. -type Notary interface { - UpdateNotaryNodes(pubs keys.PublicKeys) -} diff --git a/pkg/core/blockchainer/services/oracle.go b/pkg/core/blockchainer/services/oracle.go deleted file mode 100644 index 426e03967..000000000 --- a/pkg/core/blockchainer/services/oracle.go +++ /dev/null @@ -1,23 +0,0 @@ -package services - -import ( - "github.com/nspcc-dev/neo-go/pkg/core/state" - "github.com/nspcc-dev/neo-go/pkg/crypto/keys" - "github.com/nspcc-dev/neo-go/pkg/util" -) - -// Oracle specifies oracle service interface. -type Oracle interface { - // AddRequests processes new requests. - AddRequests(map[uint64]*state.OracleRequest) - // RemoveRequests removes already processed requests. - RemoveRequests([]uint64) - // UpdateOracleNodes updates oracle nodes. - UpdateOracleNodes(keys.PublicKeys) - // UpdateNativeContract updates oracle contract native script and hash. - UpdateNativeContract([]byte, []byte, util.Uint160, int) - // Start runs oracle module. - Start() - // Shutdown shutdowns oracle module. - Shutdown() -} diff --git a/pkg/core/native/designate.go b/pkg/core/native/designate.go index e843031ef..492e8849f 100644 --- a/pkg/core/native/designate.go +++ b/pkg/core/native/designate.go @@ -9,7 +9,6 @@ import ( "sort" "sync/atomic" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer/services" "github.com/nspcc-dev/neo-go/pkg/core/dao" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/interop/runtime" @@ -239,11 +238,11 @@ func (s *Designate) updateCachedRoleData(cache *DesignationCache, d *dao.Simple, func (s *Designate) notifyRoleChanged(v *roleData, r noderoles.Role) { switch r { case noderoles.Oracle: - if orc, _ := s.OracleService.Load().(services.Oracle); orc != nil { + if orc, _ := s.OracleService.Load().(OracleService); orc != nil { orc.UpdateOracleNodes(v.nodes.Copy()) } case noderoles.P2PNotary: - if ntr, _ := s.NotaryService.Load().(services.Notary); ntr != nil { + if ntr, _ := s.NotaryService.Load().(NotaryService); ntr != nil { ntr.UpdateNotaryNodes(v.nodes.Copy()) } case noderoles.StateValidator: diff --git a/pkg/core/native/notary.go b/pkg/core/native/notary.go index d965f6310..6943fbf4c 100644 --- a/pkg/core/native/notary.go +++ b/pkg/core/native/notary.go @@ -38,6 +38,11 @@ type NotaryCache struct { notaryServiceFeePerKey int64 } +// NotaryService is a Notary module interface. +type NotaryService interface { + UpdateNotaryNodes(pubs keys.PublicKeys) +} + const ( notaryContractID = -10 // prefixDeposit is a prefix for storing Notary deposits. diff --git a/pkg/core/native/oracle.go b/pkg/core/native/oracle.go index 505a2680c..8f99fd936 100644 --- a/pkg/core/native/oracle.go +++ b/pkg/core/native/oracle.go @@ -9,7 +9,6 @@ import ( "strings" "sync/atomic" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer/services" "github.com/nspcc-dev/neo-go/pkg/core/dao" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/interop/contract" @@ -50,6 +49,22 @@ type OracleCache struct { requestPrice int64 } +// OracleService specifies oracle module interface. +type OracleService interface { + // AddRequests processes new requests. + AddRequests(map[uint64]*state.OracleRequest) + // RemoveRequests removes already processed requests. + RemoveRequests([]uint64) + // UpdateOracleNodes updates oracle nodes. + UpdateOracleNodes(keys.PublicKeys) + // UpdateNativeContract updates oracle contract native script and hash. + UpdateNativeContract([]byte, []byte, util.Uint160, int) + // Start runs oracle module. + Start() + // Shutdown shutdowns oracle module. + Shutdown() +} + const ( oracleContractID = -9 maxURLLength = 256 @@ -164,7 +179,7 @@ func (o *Oracle) PostPersist(ic *interop.Context) error { single := big.NewInt(p) var removedIDs []uint64 - orc, _ := o.Module.Load().(services.Oracle) + orc, _ := o.Module.Load().(OracleService) for _, tx := range ic.Block.Transactions { resp := getResponse(tx) if resp == nil { @@ -521,7 +536,7 @@ func (o *Oracle) getConvertibleFromDAO(d *dao.Simple, key []byte, item stackitem // updateCache updates cached Oracle values if they've been changed. func (o *Oracle) updateCache(d *dao.Simple) error { - orc, _ := o.Module.Load().(services.Oracle) + orc, _ := o.Module.Load().(OracleService) if orc == nil { return nil } From 284335a4d2a3903d51bca7b7718d5a9e883074ce Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 22:43:12 +0300 Subject: [PATCH 12/14] blockchainer: strip unused methods --- internal/fakechain/fakechain.go | 25 ------------------------- pkg/core/blockchainer/blockchainer.go | 14 -------------- 2 files changed, 39 deletions(-) diff --git a/internal/fakechain/fakechain.go b/internal/fakechain/fakechain.go index e2cc7827f..6bb90590f 100644 --- a/internal/fakechain/fakechain.go +++ b/internal/fakechain/fakechain.go @@ -91,16 +91,6 @@ func (chain *FakeChain) PutTx(tx *transaction.Transaction) { chain.txs[tx.Hash()] = tx } -// ApplyPolicyToTxSet implements the Blockchainer interface. -func (chain *FakeChain) ApplyPolicyToTxSet([]*transaction.Transaction) []*transaction.Transaction { - panic("TODO") -} - -// IsTxStillRelevant implements the Blockchainer interface. -func (chain *FakeChain) IsTxStillRelevant(t *transaction.Transaction, txpool *mempool.Pool, isPartialTx bool) bool { - panic("TODO") -} - // InitVerificationContext initializes context for witness check. func (chain *FakeChain) InitVerificationContext(ic *interop.Context, hash util.Uint160, witness *transaction.Witness) error { panic("TODO") @@ -208,11 +198,6 @@ func (chain *FakeChain) BlockHeight() uint32 { return atomic.LoadUint32(&chain.Blockheight) } -// Close implements the Blockchainer interface. -func (chain *FakeChain) Close() { - panic("TODO") -} - // HeaderHeight implements the Blockchainer interface. func (chain *FakeChain) HeaderHeight() uint32 { return atomic.LoadUint32(&chain.Blockheight) @@ -323,11 +308,6 @@ func (chain *FakeChain) GetTestVM(t trigger.Type, tx *transaction.Transaction, b panic("TODO") } -// CurrentHeaderHash implements the Blockchainer interface. -func (chain *FakeChain) CurrentHeaderHash() util.Uint256 { - return util.Uint256{} -} - // CurrentBlockHash implements the Blockchainer interface. func (chain *FakeChain) CurrentBlockHash() util.Uint256 { return util.Uint256{} @@ -371,11 +351,6 @@ func (chain *FakeChain) GetUtilityTokenBalance(uint160 util.Uint160) *big.Int { panic("TODO") } -// ManagementContractHash implements the Blockchainer interface. -func (chain FakeChain) ManagementContractHash() util.Uint160 { - panic("TODO") -} - // PoolTx implements the Blockchainer interface. func (chain *FakeChain) PoolTx(tx *transaction.Transaction, _ ...*mempool.Pool) error { return chain.PoolTxF(tx) diff --git a/pkg/core/blockchainer/blockchainer.go b/pkg/core/blockchainer/blockchainer.go index f73348b3a..ab1fec6d5 100644 --- a/pkg/core/blockchainer/blockchainer.go +++ b/pkg/core/blockchainer/blockchainer.go @@ -18,15 +18,11 @@ import ( // Blockchainer is an interface that abstracts the implementation // of the blockchain. type Blockchainer interface { - ApplyPolicyToTxSet([]*transaction.Transaction) []*transaction.Transaction AddBlock(block *block.Block) error - AddHeaders(...*block.Header) error BlockHeight() uint32 GetConfig() config.ProtocolConfiguration CalculateClaimable(h util.Uint160, endHeight uint32) (*big.Int, error) - Close() InitVerificationContext(ic *interop.Context, hash util.Uint160, witness *transaction.Witness) error - IsTxStillRelevant(t *transaction.Transaction, txpool *mempool.Pool, isPartialTx bool) bool HeaderHeight() uint32 GetBlock(hash util.Uint256) (*block.Block, error) GetCommittee() (keys.PublicKeys, error) @@ -38,13 +34,8 @@ type Blockchainer interface { ForEachNEP17Transfer(acc util.Uint160, newestTimestamp uint64, f func(*state.NEP17Transfer) (bool, error)) error GetHeaderHash(int) util.Uint256 GetHeader(hash util.Uint256) (*block.Header, error) - CurrentHeaderHash() util.Uint256 CurrentBlockHash() util.Uint256 - HasBlock(util.Uint256) bool - HasTransaction(util.Uint256) bool - IsExtensibleAllowed(util.Uint160) bool GetAppExecResults(util.Uint256, trigger.Type) ([]state.AppExecResult, error) - GetNotaryDepositExpiration(acc util.Uint160) uint32 GetNativeContractScriptHash(string) (util.Uint160, error) GetNatives() []state.NativeContract GetNextBlockValidators() ([]*keys.PublicKey, error) @@ -52,7 +43,6 @@ type Blockchainer interface { GetNEP17Contracts() []util.Uint160 GetTokenLastUpdated(acc util.Uint160) (map[int32]uint32, error) GetNotaryContractScriptHash() util.Uint160 - GetNotaryBalance(acc util.Uint160) *big.Int GetNotaryServiceFeePerKey() int64 GetValidators() ([]*keys.PublicKey, error) GetStateModule() StateRoot @@ -61,9 +51,6 @@ type Blockchainer interface { GetTestHistoricVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) (*interop.Context, error) GetTransaction(util.Uint256) (*transaction.Transaction, uint32, error) mempool.Feer // fee interface - ManagementContractHash() util.Uint160 - PoolTx(t *transaction.Transaction, pools ...*mempool.Pool) error - PoolTxWithData(t *transaction.Transaction, data interface{}, mp *mempool.Pool, feer mempool.Feer, verificationFunction func(t *transaction.Transaction, data interface{}) error) error SubscribeForBlocks(ch chan<- *block.Block) SubscribeForExecutions(ch chan<- *state.AppExecResult) SubscribeForNotifications(ch chan<- *state.ContainedNotificationEvent) @@ -78,6 +65,5 @@ type Blockchainer interface { // Policer. GetBaseExecFee() int64 GetMaxVerificationGAS() int64 - GetStoragePrice() int64 FeePerByte() int64 } From 5ee7ea34b1f2813fef90ad2e64ef6a3dc69e5232 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 22:52:58 +0300 Subject: [PATCH 13/14] blockchainer: drop Blockchainer completely It's only used by the RPC server now, so it can be internalized. --- pkg/core/blockchainer/blockchainer.go | 69 --------------------------- pkg/services/rpcsrv/server.go | 56 +++++++++++++++++++++- 2 files changed, 54 insertions(+), 71 deletions(-) delete mode 100644 pkg/core/blockchainer/blockchainer.go diff --git a/pkg/core/blockchainer/blockchainer.go b/pkg/core/blockchainer/blockchainer.go deleted file mode 100644 index ab1fec6d5..000000000 --- a/pkg/core/blockchainer/blockchainer.go +++ /dev/null @@ -1,69 +0,0 @@ -package blockchainer - -import ( - "math/big" - - "github.com/nspcc-dev/neo-go/pkg/config" - "github.com/nspcc-dev/neo-go/pkg/core/block" - "github.com/nspcc-dev/neo-go/pkg/core/interop" - "github.com/nspcc-dev/neo-go/pkg/core/mempool" - "github.com/nspcc-dev/neo-go/pkg/core/state" - "github.com/nspcc-dev/neo-go/pkg/core/transaction" - "github.com/nspcc-dev/neo-go/pkg/crypto/hash" - "github.com/nspcc-dev/neo-go/pkg/crypto/keys" - "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" - "github.com/nspcc-dev/neo-go/pkg/util" -) - -// Blockchainer is an interface that abstracts the implementation -// of the blockchain. -type Blockchainer interface { - AddBlock(block *block.Block) error - BlockHeight() uint32 - GetConfig() config.ProtocolConfiguration - CalculateClaimable(h util.Uint160, endHeight uint32) (*big.Int, error) - InitVerificationContext(ic *interop.Context, hash util.Uint160, witness *transaction.Witness) error - HeaderHeight() uint32 - GetBlock(hash util.Uint256) (*block.Block, error) - GetCommittee() (keys.PublicKeys, error) - GetContractState(hash util.Uint160) *state.Contract - GetContractScriptHash(id int32) (util.Uint160, error) - GetEnrollments() ([]state.Validator, error) - GetGoverningTokenBalance(acc util.Uint160) (*big.Int, uint32) - ForEachNEP11Transfer(acc util.Uint160, newestTimestamp uint64, f func(*state.NEP11Transfer) (bool, error)) error - ForEachNEP17Transfer(acc util.Uint160, newestTimestamp uint64, f func(*state.NEP17Transfer) (bool, error)) error - GetHeaderHash(int) util.Uint256 - GetHeader(hash util.Uint256) (*block.Header, error) - CurrentBlockHash() util.Uint256 - GetAppExecResults(util.Uint256, trigger.Type) ([]state.AppExecResult, error) - GetNativeContractScriptHash(string) (util.Uint160, error) - GetNatives() []state.NativeContract - GetNextBlockValidators() ([]*keys.PublicKey, error) - GetNEP11Contracts() []util.Uint160 - GetNEP17Contracts() []util.Uint160 - GetTokenLastUpdated(acc util.Uint160) (map[int32]uint32, error) - GetNotaryContractScriptHash() util.Uint160 - GetNotaryServiceFeePerKey() int64 - GetValidators() ([]*keys.PublicKey, error) - GetStateModule() StateRoot - GetStorageItem(id int32, key []byte) state.StorageItem - GetTestVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) *interop.Context - GetTestHistoricVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) (*interop.Context, error) - GetTransaction(util.Uint256) (*transaction.Transaction, uint32, error) - mempool.Feer // fee interface - SubscribeForBlocks(ch chan<- *block.Block) - SubscribeForExecutions(ch chan<- *state.AppExecResult) - SubscribeForNotifications(ch chan<- *state.ContainedNotificationEvent) - SubscribeForTransactions(ch chan<- *transaction.Transaction) - VerifyTx(*transaction.Transaction) error - VerifyWitness(util.Uint160, hash.Hashable, *transaction.Witness, int64) (int64, error) - GetMemPool() *mempool.Pool - UnsubscribeFromBlocks(ch chan<- *block.Block) - UnsubscribeFromExecutions(ch chan<- *state.AppExecResult) - UnsubscribeFromNotifications(ch chan<- *state.ContainedNotificationEvent) - UnsubscribeFromTransactions(ch chan<- *transaction.Transaction) - // Policer. - GetBaseExecFee() int64 - GetMaxVerificationGAS() int64 - FeePerByte() int64 -} diff --git a/pkg/services/rpcsrv/server.go b/pkg/services/rpcsrv/server.go index c0ae35b69..3d09fbc73 100644 --- a/pkg/services/rpcsrv/server.go +++ b/pkg/services/rpcsrv/server.go @@ -29,6 +29,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/fee" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/interop/iterator" + "github.com/nspcc-dev/neo-go/pkg/core/mempool" "github.com/nspcc-dev/neo-go/pkg/core/mempoolevent" "github.com/nspcc-dev/neo-go/pkg/core/mpt" "github.com/nspcc-dev/neo-go/pkg/core/native" @@ -57,10 +58,61 @@ import ( ) type ( + // Ledger abstracts away the Blockchain as used by the RPC server. + Ledger interface { + AddBlock(block *block.Block) error + BlockHeight() uint32 + CalculateClaimable(h util.Uint160, endHeight uint32) (*big.Int, error) + CurrentBlockHash() util.Uint256 + FeePerByte() int64 + ForEachNEP11Transfer(acc util.Uint160, newestTimestamp uint64, f func(*state.NEP11Transfer) (bool, error)) error + ForEachNEP17Transfer(acc util.Uint160, newestTimestamp uint64, f func(*state.NEP17Transfer) (bool, error)) error + GetAppExecResults(util.Uint256, trigger.Type) ([]state.AppExecResult, error) + GetBaseExecFee() int64 + GetBlock(hash util.Uint256) (*block.Block, error) + GetCommittee() (keys.PublicKeys, error) + GetConfig() config.ProtocolConfiguration + GetContractScriptHash(id int32) (util.Uint160, error) + GetContractState(hash util.Uint160) *state.Contract + GetEnrollments() ([]state.Validator, error) + GetGoverningTokenBalance(acc util.Uint160) (*big.Int, uint32) + GetHeader(hash util.Uint256) (*block.Header, error) + GetHeaderHash(int) util.Uint256 + GetMaxVerificationGAS() int64 + GetMemPool() *mempool.Pool + GetNEP11Contracts() []util.Uint160 + GetNEP17Contracts() []util.Uint160 + GetNativeContractScriptHash(string) (util.Uint160, error) + GetNatives() []state.NativeContract + GetNextBlockValidators() ([]*keys.PublicKey, error) + GetNotaryContractScriptHash() util.Uint160 + GetNotaryServiceFeePerKey() int64 + GetStateModule() blockchainer.StateRoot + GetStorageItem(id int32, key []byte) state.StorageItem + GetTestHistoricVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) (*interop.Context, error) + GetTestVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) *interop.Context + GetTokenLastUpdated(acc util.Uint160) (map[int32]uint32, error) + GetTransaction(util.Uint256) (*transaction.Transaction, uint32, error) + GetValidators() ([]*keys.PublicKey, error) + HeaderHeight() uint32 + InitVerificationContext(ic *interop.Context, hash util.Uint160, witness *transaction.Witness) error + SubscribeForBlocks(ch chan<- *block.Block) + SubscribeForExecutions(ch chan<- *state.AppExecResult) + SubscribeForNotifications(ch chan<- *state.ContainedNotificationEvent) + SubscribeForTransactions(ch chan<- *transaction.Transaction) + UnsubscribeFromBlocks(ch chan<- *block.Block) + UnsubscribeFromExecutions(ch chan<- *state.AppExecResult) + UnsubscribeFromNotifications(ch chan<- *state.ContainedNotificationEvent) + UnsubscribeFromTransactions(ch chan<- *transaction.Transaction) + VerifyTx(*transaction.Transaction) error + VerifyWitness(util.Uint160, hash.Hashable, *transaction.Witness, int64) (int64, error) + mempool.Feer // fee interface + } + // Server represents the JSON-RPC 2.0 server. Server struct { *http.Server - chain blockchainer.Blockchainer + chain Ledger config config.RPC // wsReadLimit represents web-socket message limit for a receiving side. wsReadLimit int64 @@ -196,7 +248,7 @@ var invalidBlockHeightError = func(index int, height int) *neorpc.Error { var upgrader = websocket.Upgrader{} // New creates a new Server struct. -func New(chain blockchainer.Blockchainer, conf config.RPC, coreServer *network.Server, +func New(chain Ledger, conf config.RPC, coreServer *network.Server, orc *oracle.Oracle, log *zap.Logger, errChan chan error) Server { httpServer := &http.Server{ Addr: conf.Address + ":" + strconv.FormatUint(uint64(conf.Port), 10), From 88542630ac582e4fb32b57946d5d4369e06ac72a Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 22 Jul 2022 23:14:02 +0300 Subject: [PATCH 14/14] blockchainer: drop the package completely It's not an ideal solution, but at least it solves the problem for now. Caveats: * consensus only needs one method, so it's mirrored to Blockchain * rpcsrv uses core.* definition of the StateRoot (so technically it might as well not have an internal Ledger), but it uses core already unfortunately --- internal/fakechain/fakechain.go | 6 ------ pkg/consensus/consensus.go | 10 +++++----- pkg/consensus/consensus_test.go | 2 +- pkg/core/blockchain.go | 20 ++++++++++++++++++-- pkg/core/blockchainer/state_root.go | 19 ------------------- pkg/services/rpcsrv/server.go | 3 +-- 6 files changed, 25 insertions(+), 35 deletions(-) delete mode 100644 pkg/core/blockchainer/state_root.go diff --git a/internal/fakechain/fakechain.go b/internal/fakechain/fakechain.go index 6bb90590f..0ac04a4c5 100644 --- a/internal/fakechain/fakechain.go +++ b/internal/fakechain/fakechain.go @@ -9,7 +9,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/core/block" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/mempool" "github.com/nspcc-dev/neo-go/pkg/core/mpt" @@ -293,11 +292,6 @@ func (chain *FakeChain) GetEnrollments() ([]state.Validator, error) { panic("TODO") } -// GetStateModule implements the Blockchainer interface. -func (chain *FakeChain) GetStateModule() blockchainer.StateRoot { - return nil -} - // GetStorageItem implements the Blockchainer interface. func (chain *FakeChain) GetStorageItem(id int32, key []byte) state.StorageItem { panic("TODO") diff --git a/pkg/consensus/consensus.go b/pkg/consensus/consensus.go index ec1273ef8..c9bce1663 100644 --- a/pkg/consensus/consensus.go +++ b/pkg/consensus/consensus.go @@ -13,9 +13,9 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/config/netmode" coreb "github.com/nspcc-dev/neo-go/pkg/core/block" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/mempool" + "github.com/nspcc-dev/neo-go/pkg/core/state" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" @@ -50,7 +50,7 @@ type Ledger interface { GetConfig() config.ProtocolConfiguration GetMemPool() *mempool.Pool GetNextBlockValidators() ([]*keys.PublicKey, error) - GetStateModule() blockchainer.StateRoot + GetStateRoot(height uint32) (*state.MPTRoot, error) GetTransaction(util.Uint256) (*transaction.Transaction, uint32, error) GetValidators() ([]*keys.PublicKey, error) PoolTx(t *transaction.Transaction, pools ...*mempool.Pool) error @@ -250,7 +250,7 @@ func (s *service) newPrepareRequest() payload.PrepareRequest { r := new(prepareRequest) if s.ProtocolConfiguration.StateRootInHeader { r.stateRootEnabled = true - if sr, err := s.Chain.GetStateModule().GetStateRoot(s.dbft.BlockIndex - 1); err == nil { + if sr, err := s.Chain.GetStateRoot(s.dbft.BlockIndex - 1); err == nil { r.stateRoot = sr.Root } else { panic(err) @@ -535,7 +535,7 @@ func (s *service) verifyRequest(p payload.ConsensusPayload) error { return errInvalidVersion } if s.ProtocolConfiguration.StateRootInHeader { - sr, err := s.Chain.GetStateModule().GetStateRoot(s.dbft.BlockIndex - 1) + sr, err := s.Chain.GetStateRoot(s.dbft.BlockIndex - 1) if err != nil { return err } else if sr.Root != req.stateRoot { @@ -689,7 +689,7 @@ func (s *service) newBlockFromContext(ctx *dbft.Context) block.Block { block.Block.Nonce = ctx.Nonce block.Block.Index = ctx.BlockIndex if s.ProtocolConfiguration.StateRootInHeader { - sr, err := s.Chain.GetStateModule().GetStateRoot(ctx.BlockIndex - 1) + sr, err := s.Chain.GetStateRoot(ctx.BlockIndex - 1) if err != nil { s.log.Fatal(fmt.Sprintf("failed to get state root: %s", err.Error())) } diff --git a/pkg/consensus/consensus_test.go b/pkg/consensus/consensus_test.go index 058875afb..a49af9759 100644 --- a/pkg/consensus/consensus_test.go +++ b/pkg/consensus/consensus_test.go @@ -321,7 +321,7 @@ func TestService_PrepareRequest(t *testing.T) { prevHash: prevHash, }) - sr, err := srv.Chain.GetStateModule().GetStateRoot(srv.dbft.BlockIndex - 1) + sr, err := srv.Chain.GetStateRoot(srv.dbft.BlockIndex - 1) require.NoError(t, err) checkRequest(t, errInvalidTransactionsCount, &prepareRequest{stateRootEnabled: true, diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 4d3ec192a..ca47cb7f2 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -15,7 +15,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/config/limits" "github.com/nspcc-dev/neo-go/pkg/core/block" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" "github.com/nspcc-dev/neo-go/pkg/core/dao" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/interop/contract" @@ -181,6 +180,18 @@ type Blockchain struct { unsubCh chan interface{} } +// StateRoot represents local state root module. +type StateRoot interface { + CurrentLocalHeight() uint32 + CurrentLocalStateRoot() util.Uint256 + CurrentValidatedHeight() uint32 + FindStates(root util.Uint256, prefix, start []byte, max int) ([]storage.KeyValue, error) + GetState(root util.Uint256, key []byte) ([]byte, error) + GetStateProof(root util.Uint256, key []byte) ([][]byte, error) + GetStateRoot(height uint32) (*state.MPTRoot, error) + GetLatestStateHeight(root util.Uint256) (uint32, error) +} + // bcEvent is an internal event generated by the Blockchain and then // broadcasted to other parties. It joins the new block and associated // invocation logs, all the other events visible from outside can be produced @@ -995,8 +1006,13 @@ func (bc *Blockchain) addHeaders(verify bool, headers ...*block.Header) error { return nil } +// GetStateRoot returns state root for the given height. +func (bc *Blockchain) GetStateRoot(height uint32) (*state.MPTRoot, error) { + return bc.stateRoot.GetStateRoot(height) +} + // GetStateModule returns state root service instance. -func (bc *Blockchain) GetStateModule() blockchainer.StateRoot { +func (bc *Blockchain) GetStateModule() StateRoot { return bc.stateRoot } diff --git a/pkg/core/blockchainer/state_root.go b/pkg/core/blockchainer/state_root.go deleted file mode 100644 index 3b11f6c63..000000000 --- a/pkg/core/blockchainer/state_root.go +++ /dev/null @@ -1,19 +0,0 @@ -package blockchainer - -import ( - "github.com/nspcc-dev/neo-go/pkg/core/state" - "github.com/nspcc-dev/neo-go/pkg/core/storage" - "github.com/nspcc-dev/neo-go/pkg/util" -) - -// StateRoot represents local state root module. -type StateRoot interface { - CurrentLocalHeight() uint32 - CurrentLocalStateRoot() util.Uint256 - CurrentValidatedHeight() uint32 - FindStates(root util.Uint256, prefix, start []byte, max int) ([]storage.KeyValue, error) - GetState(root util.Uint256, key []byte) ([]byte, error) - GetStateProof(root util.Uint256, key []byte) ([][]byte, error) - GetStateRoot(height uint32) (*state.MPTRoot, error) - GetLatestStateHeight(root util.Uint256) (uint32, error) -} diff --git a/pkg/services/rpcsrv/server.go b/pkg/services/rpcsrv/server.go index 3d09fbc73..b08968046 100644 --- a/pkg/services/rpcsrv/server.go +++ b/pkg/services/rpcsrv/server.go @@ -25,7 +25,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/core" "github.com/nspcc-dev/neo-go/pkg/core/block" - "github.com/nspcc-dev/neo-go/pkg/core/blockchainer" "github.com/nspcc-dev/neo-go/pkg/core/fee" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/interop/iterator" @@ -87,7 +86,7 @@ type ( GetNextBlockValidators() ([]*keys.PublicKey, error) GetNotaryContractScriptHash() util.Uint160 GetNotaryServiceFeePerKey() int64 - GetStateModule() blockchainer.StateRoot + GetStateModule() core.StateRoot GetStorageItem(id int32, key []byte) state.StorageItem GetTestHistoricVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) (*interop.Context, error) GetTestVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) *interop.Context