From 5d4ebf2ad3c654cd6ec863070766250901fb225e Mon Sep 17 00:00:00 2001 From: Danno Ferrin Date: Tue, 1 Jun 2021 08:03:09 -0600 Subject: [PATCH] Change Branding Brandning from Kaliedo -> Firefly * strip `kld` from go packages * change HTTP to 'fly' or 'firefly' depending on length * remove some documentation references to Kaliedo platform * Left some TODOs for when the new docs site goes up Signed-off-by: Danno Ferrin --- Makefile | 2 +- README.md | 19 +- cmd/ethconnect.go | 36 +- cmd/plugins.go | 12 +- codecov.yml | 4 +- internal/{kldauth => auth}/auth.go | 40 +-- internal/{kldauth => auth}/auth_test.go | 20 +- .../kldauthtest => auth/authtest}/testsm.go | 2 +- .../{kldcontracts => contracts}/kldparams.go | 18 +- .../remoteregistry.go | 46 +-- .../remoteregsitry_test.go | 14 +- .../{kldcontracts => contracts}/rest2eth.go | 142 ++++---- .../rest2eth_test.go | 298 ++++++++-------- .../smartcontractgw.go | 286 +++++++-------- .../smartcontractgw_test.go | 331 +++++++++--------- .../syncdispatcher.go | 32 +- .../syncdispatcher_test.go | 40 +-- internal/{klderrors => errors}/errors.go | 12 +- internal/{kldeth => eth}/compiler.go | 37 +- internal/{kldeth => eth}/compiler_test.go | 14 +- internal/{kldeth => eth}/getreceipt.go | 8 +- internal/{kldeth => eth}/getreceipt_test.go | 2 +- internal/{kldeth => eth}/privacygroup.go | 8 +- internal/{kldeth => eth}/privacygroup_test.go | 12 +- internal/{kldeth => eth}/rpc.go | 20 +- internal/{kldeth => eth}/rpc_test.go | 10 +- internal/{kldeth => eth}/rpcmock.go | 2 +- internal/{kldeth => eth}/send.go | 27 +- internal/{kldeth => eth}/signer.go | 2 +- internal/{kldeth => eth}/signer_test.go | 2 +- internal/{kldeth => eth}/txn.go | 130 +++---- internal/{kldeth => eth}/txn_test.go | 150 ++++---- internal/{kldeth => eth}/txncount.go | 8 +- internal/{kldeth => eth}/txncount_test.go | 12 +- internal/{eth => ethbind}/ethbinding.go | 2 +- internal/{kldevents => events}/eventstream.go | 34 +- .../{kldevents => events}/eventstream_test.go | 56 +-- .../{kldevents => events}/logprocessor.go | 22 +- .../logprocessor_test.go | 37 +- internal/{kldevents => events}/submanager.go | 44 +-- .../{kldevents => events}/submanager_test.go | 32 +- .../{kldevents => events}/subscription.go | 36 +- .../subscription_test.go | 28 +- internal/{kldevents => events}/webhooks.go | 12 +- internal/{kldevents => events}/websockets.go | 14 +- internal/{kldkafka => kafka}/client.go | 2 +- internal/{kldkafka => kafka}/client_test.go | 4 +- internal/{kldkafka => kafka}/clientmock.go | 2 +- internal/{kldkafka => kafka}/kafkabridge.go | 60 ++-- .../{kldkafka => kafka}/kafkabridge_test.go | 70 ++-- internal/{kldkafka => kafka}/kafkacommon.go | 24 +- .../{kldkafka => kafka}/kafkacommon_test.go | 2 +- .../mock_sarama/sarama_mocks.go | 0 internal/{kldkvstore => kvstore}/kvstore.go | 6 +- .../{kldkvstore => kvstore}/kvstore_test.go | 4 +- internal/{kldkvstore => kvstore}/memkv.go | 2 +- .../{kldkvstore => kvstore}/memkv_test.go | 2 +- .../{kldmessages => messages}/messages.go | 4 +- .../messages_test.go | 2 +- .../{kldmessages => messages}/timesorted.go | 2 +- .../timesorted_test.go | 2 +- .../{kldopenapi => openapi}/abi2swagger.go | 52 +-- .../abi2swagger_test.go | 14 +- internal/{kldrest => rest}/memreceipts.go | 6 +- .../{kldrest => rest}/memreceipts_test.go | 2 +- internal/{kldrest => rest}/mongoreceipts.go | 8 +- .../{kldrest => rest}/mongoreceipts_test.go | 2 +- internal/{kldrest => rest}/mongwrapper.go | 2 +- internal/{kldrest => rest}/receiptstore.go | 62 ++-- .../{kldrest => rest}/receiptstore_test.go | 100 +++--- internal/{kldrest => rest}/resterror.go | 2 +- internal/{kldrest => rest}/restgateway.go | 88 ++--- .../{kldrest => rest}/restgateway_test.go | 14 +- internal/{kldrest => rest}/webhooks.go | 38 +- internal/{kldrest => rest}/webhooks_test.go | 32 +- internal/{kldrest => rest}/webhooksdirect.go | 38 +- .../{kldrest => rest}/webhooksdirect_test.go | 32 +- internal/{kldrest => rest}/webhookskafka.go | 36 +- .../{kldrest => rest}/webhookskafka_test.go | 96 ++--- internal/{kldtx => tx}/addressbook.go | 38 +- internal/{kldtx => tx}/addressbook_test.go | 28 +- internal/{kldtx => tx}/hdwallet.go | 34 +- internal/{kldtx => tx}/hdwallet_test.go | 16 +- internal/{kldtx => tx}/txncontext.go | 8 +- internal/{kldtx => tx}/txndelaytracker.go | 2 +- .../{kldtx => tx}/txndelaytracker_test.go | 2 +- internal/{kldtx => tx}/txnprocessor.go | 82 ++--- internal/{kldtx => tx}/txnprocessor_test.go | 122 +++---- internal/{kldutils => utils}/cmdutils.go | 2 +- internal/{kldutils => utils}/cmdutils_test.go | 2 +- internal/{kldutils => utils}/ethutils.go | 14 +- internal/{kldutils => utils}/ethutils_test.go | 2 +- internal/{kldutils => utils}/hostsfile.go | 2 +- .../{kldutils => utils}/hostsfile_test.go | 2 +- internal/{kldutils => utils}/httprequester.go | 20 +- .../{kldutils => utils}/httprequester_test.go | 2 +- internal/{kldutils => utils}/maputils.go | 2 +- internal/{kldutils => utils}/maputils_test.go | 2 +- internal/{kldutils => utils}/payloadutils.go | 10 +- .../{kldutils => utils}/payloadutils_test.go | 2 +- internal/{kldutils => utils}/tlsutils.go | 6 +- internal/{kldutils => utils}/tlsutils_test.go | 2 +- internal/{kldutils => utils}/uuidutils.go | 2 +- .../{kldutils => utils}/uuidutils_test.go | 2 +- internal/{kldws => ws}/wsconn.go | 10 +- internal/{kldws => ws}/wsserver.go | 2 +- internal/{kldws => ws}/wsserver_test.go | 2 +- pkg/{kldplugins => plugins}/securitymodule.go | 2 +- test/abicoderv2_example.swagger.json | 44 +-- test/erc20.swagger.json | 80 ++--- test/lotsoftypes.swagger.json | 58 +-- test/unnamedinput.swagger.json | 56 +-- 112 files changed, 1792 insertions(+), 1795 deletions(-) rename internal/{kldauth => auth}/auth.go (75%) rename internal/{kldauth => auth}/auth_test.go (88%) rename internal/{kldauth/kldauthtest => auth/authtest}/testsm.go (99%) rename internal/{kldcontracts => contracts}/kldparams.go (75%) rename internal/{kldcontracts => contracts}/remoteregistry.go (84%) rename internal/{kldcontracts => contracts}/remoteregsitry_test.go (98%) rename internal/{kldcontracts => contracts}/rest2eth.go (79%) rename internal/{kldcontracts => contracts}/rest2eth_test.go (84%) rename internal/{kldcontracts => contracts}/smartcontractgw.go (79%) rename internal/{kldcontracts => contracts}/smartcontractgw_test.go (88%) rename internal/{kldcontracts => contracts}/syncdispatcher.go (75%) rename internal/{kldcontracts => contracts}/syncdispatcher_test.go (74%) rename internal/{klderrors => errors}/errors.go (99%) rename internal/{kldeth => eth}/compiler.go (78%) rename internal/{kldeth => eth}/compiler_test.go (94%) rename internal/{kldeth => eth}/getreceipt.go (84%) rename internal/{kldeth => eth}/getreceipt_test.go (99%) rename internal/{kldeth => eth}/privacygroup.go (86%) rename internal/{kldeth => eth}/privacygroup_test.go (87%) rename internal/{kldeth => eth}/rpc.go (88%) rename internal/{kldeth => eth}/rpc_test.go (94%) rename internal/{kldeth => eth}/rpcmock.go (99%) rename internal/{kldeth => eth}/send.go (87%) rename internal/{kldeth => eth}/signer.go (95%) rename internal/{kldeth => eth}/signer_test.go (96%) rename internal/{kldeth => eth}/txn.go (78%) rename internal/{kldeth => eth}/txn_test.go (94%) rename internal/{kldeth => eth}/txncount.go (88%) rename internal/{kldeth => eth}/txncount_test.go (84%) rename internal/{eth => ethbind}/ethbinding.go (99%) rename internal/{kldevents => events}/eventstream.go (95%) rename internal/{kldevents => events}/eventstream_test.go (94%) rename internal/{kldevents => events}/logprocessor.go (89%) rename internal/{kldevents => events}/logprocessor_test.go (73%) rename internal/{kldevents => events}/submanager.go (90%) rename internal/{kldevents => events}/submanager_test.go (91%) rename internal/{kldevents => events}/subscription.go (87%) rename internal/{kldevents => events}/subscription_test.go (89%) rename internal/{kldevents => events}/webhooks.go (88%) rename internal/{kldevents => events}/websockets.go (81%) rename internal/{kldkafka => kafka}/client.go (99%) rename internal/{kldkafka => kafka}/client_test.go (98%) rename internal/{kldkafka => kafka}/clientmock.go (99%) rename internal/{kldkafka => kafka}/kafkabridge.go (88%) rename internal/{kldkafka => kafka}/kafkabridge_test.go (90%) rename internal/{kldkafka => kafka}/kafkacommon.go (92%) rename internal/{kldkafka => kafka}/kafkacommon_test.go (99%) rename internal/{kldkafka => kafka}/mock_sarama/sarama_mocks.go (100%) rename internal/{kldkvstore => kvstore}/kvstore.go (94%) rename internal/{kldkvstore => kvstore}/kvstore_test.go (97%) rename internal/{kldkvstore => kvstore}/memkv.go (98%) rename internal/{kldkvstore => kvstore}/memkv_test.go (98%) rename internal/{kldmessages => messages}/messages.go (99%) rename internal/{kldmessages => messages}/messages_test.go (99%) rename internal/{kldmessages => messages}/timesorted.go (98%) rename internal/{kldmessages => messages}/timesorted_test.go (98%) rename internal/{kldopenapi => openapi}/abi2swagger.go (94%) rename internal/{kldopenapi => openapi}/abi2swagger_test.go (97%) rename internal/{kldrest => rest}/memreceipts.go (93%) rename internal/{kldrest => rest}/memreceipts_test.go (98%) rename internal/{kldrest => rest}/mongoreceipts.go (94%) rename internal/{kldrest => rest}/mongoreceipts_test.go (99%) rename internal/{kldrest => rest}/mongwrapper.go (99%) rename internal/{kldrest => rest}/receiptstore.go (79%) rename internal/{kldrest => rest}/receiptstore_test.go (84%) rename internal/{kldrest => rest}/resterror.go (98%) rename internal/{kldrest => rest}/restgateway.go (75%) rename internal/{kldrest => rest}/restgateway_test.go (96%) rename internal/{kldrest => rest}/webhooks.go (80%) rename internal/{kldrest => rest}/webhooks_test.go (78%) rename internal/{kldrest => rest}/webhooksdirect.go (81%) rename internal/{kldrest => rest}/webhooksdirect_test.go (86%) rename internal/{kldrest => rest}/webhookskafka.go (78%) rename internal/{kldrest => rest}/webhookskafka_test.go (82%) rename internal/{kldtx => tx}/addressbook.go (81%) rename internal/{kldtx => tx}/addressbook_test.go (95%) rename internal/{kldtx => tx}/hdwallet.go (80%) rename internal/{kldtx => tx}/hdwallet_test.go (91%) rename internal/{kldtx => tx}/txncontext.go (89%) rename internal/{kldtx => tx}/txndelaytracker.go (99%) rename internal/{kldtx => tx}/txndelaytracker_test.go (99%) rename internal/{kldtx => tx}/txnprocessor.go (87%) rename internal/{kldtx => tx}/txnprocessor_test.go (93%) rename internal/{kldutils => utils}/cmdutils.go (99%) rename internal/{kldutils => utils}/cmdutils_test.go (99%) rename internal/{kldutils => utils}/ethutils.go (73%) rename internal/{kldutils => utils}/ethutils_test.go (98%) rename internal/{kldutils => utils}/hostsfile.go (98%) rename internal/{kldutils => utils}/hostsfile_test.go (98%) rename internal/{kldutils => utils}/httprequester.go (79%) rename internal/{kldutils => utils}/httprequester_test.go (99%) rename internal/{kldutils => utils}/maputils.go (98%) rename internal/{kldutils => utils}/maputils_test.go (98%) rename internal/{kldutils => utils}/payloadutils.go (87%) rename internal/{kldutils => utils}/payloadutils_test.go (99%) rename internal/{kldutils => utils}/tlsutils.go (95%) rename internal/{kldutils => utils}/tlsutils_test.go (99%) rename internal/{kldutils => utils}/uuidutils.go (97%) rename internal/{kldutils => utils}/uuidutils_test.go (97%) rename internal/{kldws => ws}/wsconn.go (94%) rename internal/{kldws => ws}/wsserver.go (99%) rename internal/{kldws => ws}/wsserver_test.go (99%) rename pkg/{kldplugins => plugins}/securitymodule.go (99%) diff --git a/Makefile b/Makefile index e50c3378..49a621c3 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ coverage.txt: $(GOFILES) coverage.html: $(VGO) tool cover -html=coverage.txt mocks: - mockgen github.com/Shopify/sarama Client,ConsumerGroup,ConsumerGroupSession,ConsumerGroupClaim > internal/kldkafka/mock_sarama/sarama_mocks.go + mockgen github.com/Shopify/sarama Client,ConsumerGroup,ConsumerGroupSession,ConsumerGroupClaim > internal/kafka/mock_sarama/sarama_mocks.go test: coverage.txt coverage: coverage.txt coverage.html clean: force diff --git a/README.md b/README.md index d8618359..5b095f37 100644 --- a/README.md +++ b/README.md @@ -119,8 +119,7 @@ solidity: |- The JSON/RPC specification exposed natively by Go-ethereum and other Ethereum protocol implementations, provides a rich low-level API for interfacing with the node. It is usually exposed over HTTP (as well as IPC) so can be connected -over a network, and have security layered in front of it (as has been done within -the Kaleido platform). +over a network, and have security layered in front of it. However, applications seldom code directly to the JSON/RPC API when deploying contracts and sending transactions, because it is: @@ -145,7 +144,7 @@ So you ask, if the goal is simplicity, why not just put the HTTP API in front of There are some challenges in Enterprise grade Blockchain solutions (particularly in high throughput permissioned/private chains) that cannot be solved by a stateless HTTP bridging layer alone. -So for Kaleido, we started with a robust Messaging tier and layered the HTTP interface on top. +So for Firefly, we started with a robust Messaging tier and layered the HTTP interface on top. ## The asynchronous nature of Ethereum transactions @@ -224,9 +223,9 @@ trivially. Some examples as follows: ## Why Kafka? -We selected Kafka as the first Messaging platform (and built a multi-tenant secured Kafka transport into the Kaleido platform), because Kafka has message ordering and scale characteristics that are ideally suited to the Ethereum transaction model: +We selected Kafka as the first Messaging platform, because Kafka has message ordering and scale characteristics that are ideally suited to the Ethereum transaction model: - Transactions can be sprayed across partitions, while retaining order of the transactions for a particular sender. Allowing independent and dynamic scaling of the application, kaleido-io/ethconnect bridge and Go-ethereum node components. -- The modern replication based cloud-native and continuously available architecture is ideal for the Kaleido platform, and is likely to be a good fit for the modern Microservice architectures that are common in Blockchain projects. +- The modern replication based cloud-native and continuously available architecture is ideal for Hyperledger projects, and is likely to be a good fit for the modern Microservice architectures that are common in Blockchain projects. ## Topics @@ -316,8 +315,6 @@ blockchain. ## Running the Bridge -Whether you are running a Kaleido permissioned chain and want to use an instance of the kaleido-io/ethconnect bridge managed externally to the platform, or are using the OSS tool with another Ethereum network, here is how to use it. - ### Installation Requires [Go 1.11](https://golang.org/dl/) or later to install with `go get` @@ -347,8 +344,8 @@ You can run a single bridge using simple commandline options, which is ideal for ```sh $ ./ethconnect kafka --help -Copyright (C) 2018, 2019 Kaleido -For License details see https://kaleido.io/terms-of-service/ +Copyright (C) 2018,2021 Kaleido +Licensed under the Apache License, Version 2.0 Version: (Build Date: ) Kafka->Ethereum (JSON/RPC) Bridge @@ -384,8 +381,8 @@ Global Flags: ``` $ethconnect webhooks --help -Copyright (C) 2018, 2019 Kaleido -For License details see https://kaleido.io/terms-of-service/ +Copyright (C) 2018,2021 Kaleido +Licensed under the Apache License, Version 2.0 Version: (Build Date: ) diff --git a/cmd/ethconnect.go b/cmd/ethconnect.go index 746ca964..c047defd 100644 --- a/cmd/ethconnect.go +++ b/cmd/ethconnect.go @@ -25,10 +25,10 @@ import ( "gopkg.in/yaml.v2" "github.com/icza/dyno" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldkafka" - "github.com/kaleido-io/ethconnect/internal/kldrest" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/kafka" + "github.com/kaleido-io/ethconnect/internal/rest" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" prefixed "github.com/x-cray/logrus-prefixed-formatter" @@ -40,10 +40,10 @@ import ( // to run with a set of individual commands as goroutines // (rather than the simple commandline mode that runs a single command) type ServerConfig struct { - KafkaBridges map[string]*kldkafka.KafkaBridgeConf `json:"kafka"` - Webhooks map[string]*kldrest.RESTGatewayConf `json:"webhooks"` - RESTGateways map[string]*kldrest.RESTGatewayConf `json:"rest"` - Plugins PluginConfig `json:"plugins"` + KafkaBridges map[string]*kafka.KafkaBridgeConf `json:"kafka"` + Webhooks map[string]*rest.RESTGatewayConf `json:"webhooks"` + RESTGateways map[string]*rest.RESTGatewayConf `json:"rest"` + Plugins PluginConfig `json:"plugins"` } func initLogging(debugLevel int) { @@ -108,7 +108,7 @@ func initServer() (serverCmd *cobra.Command) { }, PreRunE: func(cmd *cobra.Command, args []string) (err error) { if serverCmdConfig.Filename == "" { - err = klderrors.Errorf(klderrors.ConfigNoYAML) + err = errors.Errorf(errors.ConfigNoYAML) return } return @@ -126,14 +126,14 @@ func initServer() (serverCmd *cobra.Command) { func readServerConfig() (serverConfig *ServerConfig, err error) { confBytes, err := ioutil.ReadFile(serverCmdConfig.Filename) if err != nil { - err = klderrors.Errorf(klderrors.ConfigFileReadFailed, serverCmdConfig.Filename, err) + err = errors.Errorf(errors.ConfigFileReadFailed, serverCmdConfig.Filename, err) return } if strings.ToLower(serverCmdConfig.Type) == "yaml" { // Convert to JSON first yamlGenericPayload := make(map[interface{}]interface{}) if err = yaml.Unmarshal(confBytes, &yamlGenericPayload); err != nil { - err = klderrors.Errorf(klderrors.ConfigYAMLParseFile, serverCmdConfig.Filename, err) + err = errors.Errorf(errors.ConfigYAMLParseFile, serverCmdConfig.Filename, err) return } genericPayload := dyno.ConvertMapI2MapS(yamlGenericPayload).(map[string]interface{}) @@ -143,7 +143,7 @@ func readServerConfig() (serverConfig *ServerConfig, err error) { serverConfig = &ServerConfig{} err = json.Unmarshal(confBytes, serverConfig) if err != nil { - err = klderrors.Errorf(klderrors.ConfigYAMLPostParseFile, serverCmdConfig.Filename, err) + err = errors.Errorf(errors.ConfigYAMLPostParseFile, serverCmdConfig.Filename, err) return } @@ -161,7 +161,7 @@ func startServer() (err error) { } if rootConfig.PrintYAML { - b, err := kldutils.MarshalToYAML(&serverConfig) + b, err := utils.MarshalToYAML(&serverConfig) print("# Full YAML configuration processed from supplied file\n" + string(b)) return err } @@ -169,7 +169,7 @@ func startServer() (err error) { anyRoutineFinished := make(chan bool) var dontPrintYaml = false for name, conf := range serverConfig.KafkaBridges { - kafkaBridge := kldkafka.NewKafkaBridge(&dontPrintYaml) + kafkaBridge := kafka.NewKafkaBridge(&dontPrintYaml) kafkaBridge.SetConf(conf) if err := kafkaBridge.ValidateConf(); err != nil { return err @@ -184,13 +184,13 @@ func startServer() (err error) { } // Merge in legacy named 'webbhooks' configs if serverConfig.RESTGateways == nil { - serverConfig.RESTGateways = make(map[string]*kldrest.RESTGatewayConf) + serverConfig.RESTGateways = make(map[string]*rest.RESTGatewayConf) } for name, conf := range serverConfig.Webhooks { serverConfig.RESTGateways[name] = conf } for name, conf := range serverConfig.RESTGateways { - restGateway := kldrest.NewRESTGateway(&dontPrintYaml) + restGateway := rest.NewRESTGateway(&dontPrintYaml) restGateway.SetConf(conf) if err := restGateway.ValidateConf(); err != nil { return err @@ -218,10 +218,10 @@ func init() { serverCmd := initServer() rootCmd.AddCommand(serverCmd) - kafkaBridge := kldkafka.NewKafkaBridge(&rootConfig.PrintYAML) + kafkaBridge := kafka.NewKafkaBridge(&rootConfig.PrintYAML) rootCmd.AddCommand(kafkaBridge.CobraInit()) - restGateway := kldrest.NewRESTGateway(&rootConfig.PrintYAML) + restGateway := rest.NewRESTGateway(&rootConfig.PrintYAML) rootCmd.AddCommand(restGateway.CobraInit("webhooks")) // for backwards compatibility rootCmd.AddCommand(restGateway.CobraInit("rest")) } diff --git a/cmd/plugins.go b/cmd/plugins.go index 736b7279..759d9c5c 100644 --- a/cmd/plugins.go +++ b/cmd/plugins.go @@ -17,9 +17,9 @@ package cmd import ( "plugin" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/pkg/kldplugins" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/pkg/plugins" log "github.com/sirupsen/logrus" ) @@ -45,14 +45,14 @@ func loadSecurityModulePlugin(conf *PluginConfig) error { log.Debugf("Loading SecurityModule plugin '%s'", modulePath) smPlugin, err := plugin.Open(modulePath) if err != nil { - return klderrors.Errorf(klderrors.SecurityModulePluginLoad, err) + return errors.Errorf(errors.SecurityModulePluginLoad, err) } smSymbol, err := smPlugin.Lookup("SecurityModule") if err != nil || smSymbol == nil { - return klderrors.Errorf(klderrors.SecurityModulePluginSymbol, modulePath, err) + return errors.Errorf(errors.SecurityModulePluginSymbol, modulePath, err) } - kldauth.RegisterSecurityModule(*smSymbol.(*kldplugins.SecurityModule)) + auth.RegisterSecurityModule(*smSymbol.(*plugins.SecurityModule)) return nil } diff --git a/codecov.yml b/codecov.yml index 25abbfec..1510c8d0 100644 --- a/codecov.yml +++ b/codecov.yml @@ -8,6 +8,6 @@ coverage: threshold: 0.1% ignore: - "internal/eth" # Dynamic dependency library loading - relied on by other tests - - "internal/kldkafka/mock_sarama" # Generated mock - - "internal/kldauth/kldauthtest" # Mock + - "internal/kafka/mock_sarama" # Generated mock + - "internal/auth/authtest" # Mock - "cmd/plugins.go" # Not testable with UTs diff --git a/internal/kldauth/auth.go b/internal/auth/auth.go similarity index 75% rename from internal/kldauth/auth.go rename to internal/auth/auth.go index bf67714e..dc5a35ff 100644 --- a/internal/kldauth/auth.go +++ b/internal/auth/auth.go @@ -12,38 +12,38 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldauth +package auth import ( "context" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/pkg/kldplugins" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/pkg/plugins" ) -type kldContextKey int +type ContextKey int const ( - kldContextKeySystemAuth kldContextKey = iota - kldContextKeyAuthContext - kldContextKeyAccessToken + ContextKeySystemAuth ContextKey = iota + ContextKeyAuthContext + ContextKeyAccessToken ) -var securityModule kldplugins.SecurityModule +var securityModule plugins.SecurityModule // RegisterSecurityModule is the plug point to register a security module -func RegisterSecurityModule(sm kldplugins.SecurityModule) { +func RegisterSecurityModule(sm plugins.SecurityModule) { securityModule = sm } // NewSystemAuthContext creates a system background context func NewSystemAuthContext() context.Context { - return context.WithValue(context.Background(), kldContextKeySystemAuth, true) + return context.WithValue(context.Background(), ContextKeySystemAuth, true) } // IsSystemContext checks if a context was created as a system context func IsSystemContext(ctx context.Context) bool { - b, ok := ctx.Value(kldContextKeySystemAuth).(bool) + b, ok := ctx.Value(ContextKeySystemAuth).(bool) return ok && b } @@ -54,8 +54,8 @@ func WithAuthContext(ctx context.Context, token string) (context.Context, error) if err != nil { return nil, err } - ctx = context.WithValue(ctx, kldContextKeyAccessToken, token) - ctx = context.WithValue(ctx, kldContextKeyAuthContext, ctxValue) + ctx = context.WithValue(ctx, ContextKeyAccessToken, token) + ctx = context.WithValue(ctx, ContextKeyAuthContext, ctxValue) return ctx, nil } return ctx, nil @@ -63,12 +63,12 @@ func WithAuthContext(ctx context.Context, token string) (context.Context, error) // GetAuthContext extracts a previously stored auth context from the context func GetAuthContext(ctx context.Context) interface{} { - return ctx.Value(kldContextKeyAuthContext) + return ctx.Value(ContextKeyAuthContext) } // GetAccessToken extracts a previously stored access token func GetAccessToken(ctx context.Context) string { - v, ok := ctx.Value(kldContextKeyAccessToken).(string) + v, ok := ctx.Value(ContextKeyAccessToken).(string) if ok { return v } @@ -80,7 +80,7 @@ func AuthRPC(ctx context.Context, method string, args ...interface{}) error { if securityModule != nil && !IsSystemContext(ctx) { authCtx := GetAuthContext(ctx) if authCtx == nil { - return klderrors.Errorf(klderrors.SecurityModuleNoAuthContext) + return errors.Errorf(errors.SecurityModuleNoAuthContext) } return securityModule.AuthRPC(authCtx, method, args...) } @@ -92,7 +92,7 @@ func AuthRPCSubscribe(ctx context.Context, namespace string, channel interface{} if securityModule != nil && !IsSystemContext(ctx) { authCtx := GetAuthContext(ctx) if authCtx == nil { - return klderrors.Errorf(klderrors.SecurityModuleNoAuthContext) + return errors.Errorf(errors.SecurityModuleNoAuthContext) } return securityModule.AuthRPCSubscribe(authCtx, namespace, channel, args...) } @@ -104,7 +104,7 @@ func AuthEventStreams(ctx context.Context) error { if securityModule != nil && !IsSystemContext(ctx) { authCtx := GetAuthContext(ctx) if authCtx == nil { - return klderrors.Errorf(klderrors.SecurityModuleNoAuthContext) + return errors.Errorf(errors.SecurityModuleNoAuthContext) } return securityModule.AuthEventStreams(authCtx) } @@ -116,7 +116,7 @@ func AuthListAsyncReplies(ctx context.Context) error { if securityModule != nil && !IsSystemContext(ctx) { authCtx := GetAuthContext(ctx) if authCtx == nil { - return klderrors.Errorf(klderrors.SecurityModuleNoAuthContext) + return errors.Errorf(errors.SecurityModuleNoAuthContext) } return securityModule.AuthListAsyncReplies(authCtx) } @@ -128,7 +128,7 @@ func AuthReadAsyncReplyByUUID(ctx context.Context) error { if securityModule != nil && !IsSystemContext(ctx) { authCtx := GetAuthContext(ctx) if authCtx == nil { - return klderrors.Errorf(klderrors.SecurityModuleNoAuthContext) + return errors.Errorf(errors.SecurityModuleNoAuthContext) } return securityModule.AuthReadAsyncReplyByUUID(authCtx) } diff --git a/internal/kldauth/auth_test.go b/internal/auth/auth_test.go similarity index 88% rename from internal/kldauth/auth_test.go rename to internal/auth/auth_test.go index 739a34df..d56e9e5f 100644 --- a/internal/kldauth/auth_test.go +++ b/internal/auth/auth_test.go @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldauth +package auth import ( "context" "testing" - "github.com/kaleido-io/ethconnect/internal/kldauth/kldauthtest" + "github.com/kaleido-io/ethconnect/internal/auth/authtest" "github.com/stretchr/testify/assert" ) @@ -27,8 +27,8 @@ func TestSystemContext(t *testing.T) { assert.True(IsSystemContext(NewSystemAuthContext())) assert.False(IsSystemContext(context.Background())) - assert.False(IsSystemContext(context.WithValue(context.Background(), kldContextKeySystemAuth, "false"))) - assert.False(IsSystemContext(context.WithValue(context.Background(), kldContextKeySystemAuth, false))) + assert.False(IsSystemContext(context.WithValue(context.Background(), ContextKeySystemAuth, "false"))) + assert.False(IsSystemContext(context.WithValue(context.Background(), ContextKeySystemAuth, false))) } @@ -40,7 +40,7 @@ func TestAccessToken(t *testing.T) { assert.Equal("", GetAccessToken(ctx)) assert.Equal(nil, GetAuthContext(ctx)) - RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + RegisterSecurityModule(&authtest.TestSecurityModule{}) ctx, err = WithAuthContext(context.Background(), "testat") assert.NoError(err) @@ -61,7 +61,7 @@ func TestAuthRPC(t *testing.T) { assert.NoError(AuthRPC(context.Background(), "anything")) - RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + RegisterSecurityModule(&authtest.TestSecurityModule{}) assert.EqualError(AuthRPC(context.Background(), "anything"), "No auth context") @@ -80,7 +80,7 @@ func TestAuthRPCSubscribe(t *testing.T) { assert.NoError(AuthRPCSubscribe(context.Background(), "anything", nil)) - RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + RegisterSecurityModule(&authtest.TestSecurityModule{}) assert.EqualError(AuthRPCSubscribe(context.Background(), "anything", nil), "No auth context") @@ -99,7 +99,7 @@ func TestAuthEventStreams(t *testing.T) { assert.NoError(AuthEventStreams(context.Background())) - RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + RegisterSecurityModule(&authtest.TestSecurityModule{}) assert.EqualError(AuthEventStreams(context.Background()), "No auth context") @@ -117,7 +117,7 @@ func TestAuthListAsyncReplies(t *testing.T) { assert.NoError(AuthListAsyncReplies(context.Background())) - RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + RegisterSecurityModule(&authtest.TestSecurityModule{}) assert.EqualError(AuthListAsyncReplies(context.Background()), "No auth context") @@ -135,7 +135,7 @@ func TestAuthReadAsyncReplyByUUID(t *testing.T) { assert.NoError(AuthReadAsyncReplyByUUID(context.Background())) - RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + RegisterSecurityModule(&authtest.TestSecurityModule{}) assert.EqualError(AuthReadAsyncReplyByUUID(context.Background()), "No auth context") diff --git a/internal/kldauth/kldauthtest/testsm.go b/internal/auth/authtest/testsm.go similarity index 99% rename from internal/kldauth/kldauthtest/testsm.go rename to internal/auth/authtest/testsm.go index 53da0b7f..f9d238e5 100644 --- a/internal/kldauth/kldauthtest/testsm.go +++ b/internal/auth/authtest/testsm.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldauthtest +package authtest import ( "fmt" diff --git a/internal/kldcontracts/kldparams.go b/internal/contracts/kldparams.go similarity index 75% rename from internal/kldcontracts/kldparams.go rename to internal/contracts/kldparams.go index a7d544ef..97d0527d 100644 --- a/internal/kldcontracts/kldparams.go +++ b/internal/contracts/kldparams.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "net/http" @@ -31,10 +31,10 @@ func getQueryParamNoCase(name string, req *http.Request) []string { return nil } -// getKLDParam standardizes how special 'kld' params are specified, in query params, or headers -func getKLDParam(name string, req *http.Request, isBool bool) string { +// getFlyParam standardizes how special 'fly' params are specified, in query params, or headers +func getFlyParam(name string, req *http.Request, isBool bool) string { valStr := "" - vs := getQueryParamNoCase("kld-"+name, req) + vs := getQueryParamNoCase("fly-"+name, req) if len(vs) > 0 { valStr = vs[0] } @@ -42,18 +42,18 @@ func getKLDParam(name string, req *http.Request, isBool bool) string { valStr = "true" } if valStr == "" { - valStr = req.Header.Get("x-kaleido-" + name) + valStr = req.Header.Get("x-firefly-" + name) } return valStr } -// getKLDParamMulti returns an array parameter, or nil if none specified. +// getFlyParamMulti returns an array parameter, or nil if none specified. // allows multiple query params / headers, or a single comma-separated query param / header -func getKLDParamMulti(name string, req *http.Request) (val []string) { +func getFlyParamMulti(name string, req *http.Request) (val []string) { req.ParseForm() - val = getQueryParamNoCase("kld-"+name, req) + val = getQueryParamNoCase("fly-"+name, req) if len(val) == 0 { - val = textproto.MIMEHeader(req.Header)[textproto.CanonicalMIMEHeaderKey("x-kaleido-"+name)] + val = textproto.MIMEHeader(req.Header)[textproto.CanonicalMIMEHeaderKey("x-firefly-"+name)] } if val != nil && len(val) == 1 { val = strings.Split(val[0], ",") diff --git a/internal/kldcontracts/remoteregistry.go b/internal/contracts/remoteregistry.go similarity index 84% rename from internal/kldcontracts/remoteregistry.go rename to internal/contracts/remoteregistry.go index a2b178fc..bb6ab43d 100644 --- a/internal/kldcontracts/remoteregistry.go +++ b/internal/contracts/remoteregistry.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "encoding/hex" @@ -21,10 +21,10 @@ import ( "strings" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldkvstore" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/kvstore" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) @@ -40,13 +40,13 @@ const ( ) type deployContractWithAddress struct { - kldmessages.DeployContract + messages.DeployContract Address string `json:"address"` } // RemoteRegistry lookup of ABI, ByteCode and DevDocs against a conformant REST API type RemoteRegistry interface { - loadFactoryForGateway(lookupStr string, refresh bool) (*kldmessages.DeployContract, error) + loadFactoryForGateway(lookupStr string, refresh bool) (*messages.DeployContract, error) loadFactoryForInstance(lookupStr string, refresh bool) (*deployContractWithAddress, error) registerInstance(lookupStr, address string) error init() error @@ -55,7 +55,7 @@ type RemoteRegistry interface { // RemoteRegistryConf configuration type RemoteRegistryConf struct { - kldutils.HTTPRequesterConf + utils.HTTPRequesterConf CacheDB string `json:"cacheDB"` GatewayURLPrefix string `json:"gatewayURLPrefix"` InstanceURLPrefix string `json:"instanceURLPrefix"` @@ -77,7 +77,7 @@ type RemoteRegistryPropNamesConf struct { func NewRemoteRegistry(conf *RemoteRegistryConf) RemoteRegistry { rr := &remoteRegistry{ conf: conf, - hr: kldutils.NewHTTPRequester("Contract registry", &conf.HTTPRequesterConf), + hr: utils.NewHTTPRequester("Contract registry", &conf.HTTPRequesterConf), } propNames := &conf.PropNames if propNames.ID == "" { @@ -112,14 +112,14 @@ func NewRemoteRegistry(conf *RemoteRegistryConf) RemoteRegistry { type remoteRegistry struct { conf *RemoteRegistryConf - hr *kldutils.HTTPRequester - db kldkvstore.KVStore + hr *utils.HTTPRequester + db kvstore.KVStore } func (rr *remoteRegistry) init() (err error) { if rr.conf.CacheDB != "" { - if rr.db, err = kldkvstore.NewLDBKeyValueStore(rr.conf.CacheDB); err != nil { - return klderrors.Errorf(klderrors.RemoteRegistryCacheInit, err) + if rr.db, err = kvstore.NewLDBKeyValueStore(rr.conf.CacheDB); err != nil { + return errors.Errorf(errors.RemoteRegistryCacheInit, err) } } return nil @@ -150,7 +150,7 @@ func (rr *remoteRegistry) loadFactoryFromURL(baseURL, ns, lookupStr string, refr err = json.Unmarshal([]byte(abiString), &abi) if err != nil { log.Errorf("GET %s <-- !Failed to decode ABI: %s\n%s", queryURL, err, abiString) - return nil, klderrors.Errorf(klderrors.RemoteRegistryLookupGenericProcessingFailed) + return nil, errors.Errorf(errors.RemoteRegistryLookupGenericProcessingFailed) } devdoc, err := rr.hr.GetResponseString(jsonRes, rr.conf.PropNames.Devdoc, true) if err != nil { @@ -163,15 +163,15 @@ func (rr *remoteRegistry) loadFactoryFromURL(baseURL, ns, lookupStr string, refr var bytecode []byte if bytecode, err = hex.DecodeString(strings.TrimPrefix(bytecodeStr, "0x")); err != nil { log.Errorf("GET %s <-- !Failed to parse bytecode: %s\n%s", queryURL, err, bytecodeStr) - return nil, klderrors.Errorf(klderrors.RemoteRegistryLookupGenericProcessingFailed) + return nil, errors.Errorf(errors.RemoteRegistryLookupGenericProcessingFailed) } addr, _ := rr.hr.GetResponseString(jsonRes, rr.conf.PropNames.Address, false) msg = &deployContractWithAddress{ - DeployContract: kldmessages.DeployContract{ - TransactionCommon: kldmessages.TransactionCommon{ - RequestCommon: kldmessages.RequestCommon{ - Headers: kldmessages.RequestHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ + DeployContract: messages.DeployContract{ + TransactionCommon: messages.TransactionCommon{ + RequestCommon: messages.RequestCommon{ + Headers: messages.RequestHeaders{ + CommonHeaders: messages.CommonHeaders{ ID: idString, Context: map[string]interface{}{ remoteRegistryContextKey: true, @@ -218,7 +218,7 @@ func (rr *remoteRegistry) storeFactoryToCacheDB(cacheKey string, msg *deployCont } } -func (rr *remoteRegistry) loadFactoryForGateway(lookupStr string, refresh bool) (*kldmessages.DeployContract, error) { +func (rr *remoteRegistry) loadFactoryForGateway(lookupStr string, refresh bool) (*messages.DeployContract, error) { if rr.conf.GatewayURLPrefix == "" { return nil, nil } @@ -239,7 +239,7 @@ func (rr *remoteRegistry) loadFactoryForInstance(lookupStr string, refresh bool) func (rr *remoteRegistry) registerInstance(lookupStr, address string) error { if rr.conf.InstanceURLPrefix == "" { - return klderrors.Errorf(klderrors.RemoteRegistryNotConfigured) + return errors.Errorf(errors.RemoteRegistryNotConfigured) } safeLookupStr := url.QueryEscape(lookupStr) requestURL := strings.TrimSuffix(rr.conf.InstanceURLPrefix, "/") @@ -249,7 +249,7 @@ func (rr *remoteRegistry) registerInstance(lookupStr, address string) error { log.Debugf("Registering contract: %+v", bodyMap) _, err := rr.hr.DoRequest("POST", requestURL, bodyMap) if err != nil { - return klderrors.Errorf(klderrors.RemoteRegistryRegistrationFailed, err) + return errors.Errorf(errors.RemoteRegistryRegistrationFailed, err) } return nil } diff --git a/internal/kldcontracts/remoteregsitry_test.go b/internal/contracts/remoteregsitry_test.go similarity index 98% rename from internal/kldcontracts/remoteregsitry_test.go rename to internal/contracts/remoteregsitry_test.go index 8370a9af..fe2df3d2 100644 --- a/internal/kldcontracts/remoteregsitry_test.go +++ b/internal/contracts/remoteregsitry_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "encoding/json" @@ -24,9 +24,9 @@ import ( "testing" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldkvstore" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/kvstore" + "github.com/kaleido-io/ethconnect/internal/messages" "github.com/stretchr/testify/assert" ) @@ -39,7 +39,7 @@ type mockRR struct { err error } -func (rr *mockRR) loadFactoryForGateway(id string, refresh bool) (*kldmessages.DeployContract, error) { +func (rr *mockRR) loadFactoryForGateway(id string, refresh bool) (*messages.DeployContract, error) { rr.idCapture = id rr.refreshCapture = refresh if rr.deployMsg == nil { @@ -165,7 +165,7 @@ func TestRemoteRegistryloadFactoryForGatewaySuccess(t *testing.T) { res, err := rr.loadFactoryForGateway("testid", false) assert.NoError(err) assert.NotEmpty(res.Compiled) - runtimeABI, err := eth.API.ABIMarshalingToABIRuntime(res.ABI) + runtimeABI, err := ethbind.API.ABIMarshalingToABIRuntime(res.ABI) assert.NoError(err) assert.Equal("set", runtimeABI.Methods["set"].Name) assert.Contains(res.DevDoc, "set") @@ -644,7 +644,7 @@ func TestRemoteRegistryLoadFactoryFromCacheDBBadBytes(t *testing.T) { func TestRemoteRegistryStoreFactoryToCacheDBBadObj(t *testing.T) { r := NewRemoteRegistry(&RemoteRegistryConf{}) rr := r.(*remoteRegistry) - mockKV := kldkvstore.NewMockKV(nil) + mockKV := kvstore.NewMockKV(nil) rr.db = mockKV mockKV.StoreErr = fmt.Errorf("pop") rr.storeFactoryToCacheDB("testid", nil) diff --git a/internal/kldcontracts/rest2eth.go b/internal/contracts/rest2eth.go similarity index 79% rename from internal/kldcontracts/rest2eth.go rename to internal/contracts/rest2eth.go index ff7799b8..1d90c675 100644 --- a/internal/kldcontracts/rest2eth.go +++ b/internal/contracts/rest2eth.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "context" @@ -28,46 +28,46 @@ import ( "github.com/julienschmidt/httprouter" ethbinding "github.com/kaleido-io/ethbinding/pkg" + "github.com/kaleido-io/ethconnect/internal/auth" + ethconnecterrors "github.com/kaleido-io/ethconnect/internal/errors" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldevents" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/events" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) // REST2EthAsyncDispatcher is passed in to process messages over a streaming system with -// a receipt store. Only used for POST methods, when kld-sync is not set to true +// a receipt store. Only used for POST methods, when fly-sync is not set to true type REST2EthAsyncDispatcher interface { - DispatchMsgAsync(ctx context.Context, msg map[string]interface{}, ack bool) (*kldmessages.AsyncSentMsg, error) + DispatchMsgAsync(ctx context.Context, msg map[string]interface{}, ack bool) (*messages.AsyncSentMsg, error) } // rest2EthSyncDispatcher abstracts the processing of the transactions and queries // synchronously. We perform those within this package. type rest2EthSyncDispatcher interface { - DispatchSendTransactionSync(ctx context.Context, msg *kldmessages.SendTransaction, replyProcessor rest2EthReplyProcessor) - DispatchDeployContractSync(ctx context.Context, msg *kldmessages.DeployContract, replyProcessor rest2EthReplyProcessor) + DispatchSendTransactionSync(ctx context.Context, msg *messages.SendTransaction, replyProcessor rest2EthReplyProcessor) + DispatchDeployContractSync(ctx context.Context, msg *messages.DeployContract, replyProcessor rest2EthReplyProcessor) } // rest2EthReplyProcessor interface type rest2EthReplyProcessor interface { ReplyWithError(err error) - ReplyWithReceipt(receipt kldmessages.ReplyWithHeaders) - ReplyWithReceiptAndError(receipt kldmessages.ReplyWithHeaders, err error) + ReplyWithReceipt(receipt messages.ReplyWithHeaders) + ReplyWithReceiptAndError(receipt messages.ReplyWithHeaders, err error) } -// rest2eth provides the HTTP <-> kldmessages translation and dispatches for processing +// rest2eth provides the HTTP <-> messages translation and dispatches for processing type rest2eth struct { gw smartContractGatewayInt - rpc kldeth.RPCClient - processor kldtx.TxnProcessor + rpc eth.RPCClient + processor tx.TxnProcessor asyncDispatcher REST2EthAsyncDispatcher syncDispatcher rest2EthSyncDispatcher - subMgr kldevents.SubscriptionManager + subMgr events.SubscriptionManager rr RemoteRegistry } @@ -81,7 +81,7 @@ type restAsyncMsg struct { type restReceiptAndError struct { Message string `json:"error"` - kldmessages.ReplyWithHeaders + messages.ReplyWithHeaders } // rest2EthInflight is instantiated for each async reply in flight @@ -102,7 +102,7 @@ func (i *rest2EthSyncResponder) ReplyWithError(err error) { return } -func (i *rest2EthSyncResponder) ReplyWithReceiptAndError(receipt kldmessages.ReplyWithHeaders, err error) { +func (i *rest2EthSyncResponder) ReplyWithReceiptAndError(receipt messages.ReplyWithHeaders, err error) { status := 500 reply, _ := json.MarshalIndent(&restReceiptAndError{err.Error(), receipt}, "", " ") log.Infof("<-- %s %s [%d]", i.req.Method, i.req.URL, status) @@ -115,7 +115,7 @@ func (i *rest2EthSyncResponder) ReplyWithReceiptAndError(receipt kldmessages.Rep return } -func (i *rest2EthSyncResponder) ReplyWithReceipt(receipt kldmessages.ReplyWithHeaders) { +func (i *rest2EthSyncResponder) ReplyWithReceipt(receipt messages.ReplyWithHeaders) { txReceiptMsg := receipt.IsReceipt() if txReceiptMsg != nil && txReceiptMsg.ContractAddress != nil { if err := i.r.gw.PostDeploy(txReceiptMsg); err != nil { @@ -125,7 +125,7 @@ func (i *rest2EthSyncResponder) ReplyWithReceipt(receipt kldmessages.ReplyWithHe } } status := 200 - if receipt.ReplyHeaders().MsgType != kldmessages.MsgTypeTransactionSuccess { + if receipt.ReplyHeaders().MsgType != messages.MsgTypeTransactionSuccess { status = 500 } reply, _ := json.MarshalIndent(receipt, "", " ") @@ -139,7 +139,7 @@ func (i *rest2EthSyncResponder) ReplyWithReceipt(receipt kldmessages.ReplyWithHe return } -func newREST2eth(gw smartContractGatewayInt, rpc kldeth.RPCClient, subMgr kldevents.SubscriptionManager, rr RemoteRegistry, processor kldtx.TxnProcessor, asyncDispatcher REST2EthAsyncDispatcher, syncDispatcher rest2EthSyncDispatcher) *rest2eth { +func newREST2eth(gw smartContractGatewayInt, rpc eth.RPCClient, subMgr events.SubscriptionManager, rr RemoteRegistry, processor tx.TxnProcessor, asyncDispatcher REST2EthAsyncDispatcher, syncDispatcher rest2EthSyncDispatcher) *rest2eth { return &rest2eth{ gw: gw, processor: processor, @@ -191,7 +191,7 @@ type restCmd struct { abiEvent *ethbinding.ABIEvent abiEventElem *ethbinding.ABIElementMarshaling isDeploy bool - deployMsg *kldmessages.DeployContract + deployMsg *messages.DeployContract body map[string]interface{} msgParams []interface{} blocknumber string @@ -214,7 +214,7 @@ func (r *rest2eth) resolveABI(res http.ResponseWriter, req *http.Request, params r.restErrReply(res, req, err, 500) return } else if c.deployMsg == nil { - err = klderrors.Errorf(klderrors.RESTGatewayGatewayNotFound) + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayGatewayNotFound) r.restErrReply(res, req, err, 404) return } @@ -225,7 +225,7 @@ func (r *rest2eth) resolveABI(res http.ResponseWriter, req *http.Request, params r.restErrReply(res, req, err, 500) return } else if msg == nil { - err = klderrors.Errorf(klderrors.RESTGatewayInstanceNotFound) + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayInstanceNotFound) r.restErrReply(res, req, err, 404) return } @@ -266,8 +266,8 @@ func (r *rest2eth) resolveMethod(res http.ResponseWriter, req *http.Request, c * for _, element := range a { if element.Type == "function" && element.Name == methodParam { c.abiMethodElem = &element - if c.abiMethod, err = eth.API.ABIElementMarshalingToABIMethod(&element); err != nil { - err = klderrors.Errorf(klderrors.RESTGatewayMethodABIInvalid, methodParam, err) + if c.abiMethod, err = ethbind.API.ABIElementMarshalingToABIMethod(&element); err != nil { + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayMethodABIInvalid, methodParam, err) r.restErrReply(res, req, err, 400) return } @@ -281,8 +281,8 @@ func (r *rest2eth) resolveConstructor(res http.ResponseWriter, req *http.Request for _, element := range a { if element.Type == "constructor" { c.abiMethodElem = &element - if c.abiMethod, err = eth.API.ABIElementMarshalingToABIMethod(&element); err != nil { - err = klderrors.Errorf(klderrors.RESTGatewayMethodABIInvalid, "constructor", err) + if c.abiMethod, err = ethbind.API.ABIElementMarshalingToABIMethod(&element); err != nil { + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayMethodABIInvalid, "constructor", err) r.restErrReply(res, req, err, 400) return } @@ -295,7 +295,7 @@ func (r *rest2eth) resolveConstructor(res http.ResponseWriter, req *http.Request c.abiMethodElem = ðbinding.ABIElementMarshaling{ Type: "constructor", } - c.abiMethod, _ = eth.API.ABIElementMarshalingToABIMethod(c.abiMethodElem) + c.abiMethod, _ = ethbind.API.ABIElementMarshalingToABIMethod(c.abiMethodElem) c.isDeploy = true } return @@ -318,8 +318,8 @@ func (r *rest2eth) resolveEvent(res http.ResponseWriter, req *http.Request, c *r } if eventDef != nil { c.abiEventElem = eventDef - if c.abiEvent, err = eth.API.ABIElementMarshalingToABIEvent(eventDef); err != nil { - err = klderrors.Errorf(klderrors.RESTGatewayEventABIInvalid, eventDef.Name, err) + if c.abiEvent, err = ethbind.API.ABIElementMarshalingToABIEvent(eventDef); err != nil { + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayEventABIInvalid, eventDef.Name, err) r.restErrReply(res, req, err, 400) return } @@ -369,11 +369,11 @@ func (r *rest2eth) resolveParams(res http.ResponseWriter, req *http.Request, par // If we didn't find the method or event, report to the user if c.abiMethod == nil && c.abiEvent == nil { if methodParamLC == "subscribe" { - err = klderrors.Errorf(klderrors.RESTGatewayEventNotDeclared, methodParam) + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayEventNotDeclared, methodParam) r.restErrReply(res, req, err, 404) return } - err = klderrors.Errorf(klderrors.RESTGatewayMethodNotDeclared, url.QueryEscape(methodParam), c.addr) + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayMethodNotDeclared, url.QueryEscape(methodParam), c.addr) r.restErrReply(res, req, err, 404) return } @@ -381,7 +381,7 @@ func (r *rest2eth) resolveParams(res http.ResponseWriter, req *http.Request, par // If we have an address, it must be valid if c.addr != "" && !validAddress { log.Errorf("Invalid to address: '%s'", params.ByName("address")) - err = klderrors.Errorf(klderrors.RESTGatewayInvalidToAddress) + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayInvalidToAddress) r.restErrReply(res, req, err, 404) return } @@ -390,23 +390,23 @@ func (r *rest2eth) resolveParams(res http.ResponseWriter, req *http.Request, par } // If we have a from, it needs to be a valid address - kldFrom := getKLDParam("from", req, false) - fromNo0xPrefix := strings.ToLower(strings.TrimPrefix(getKLDParam("from", req, false), "0x")) + From := getFlyParam("from", req, false) + fromNo0xPrefix := strings.ToLower(strings.TrimPrefix(getFlyParam("from", req, false), "0x")) if fromNo0xPrefix != "" { if addrCheck.MatchString(fromNo0xPrefix) { c.from = "0x" + fromNo0xPrefix - } else if kldtx.IsHDWalletRequest(fromNo0xPrefix) != nil { + } else if tx.IsHDWalletRequest(fromNo0xPrefix) != nil { c.from = fromNo0xPrefix } else { - log.Errorf("Invalid from address: '%s'", kldFrom) - err = klderrors.Errorf(klderrors.RESTGatewayInvalidFromAddress) + log.Errorf("Invalid from address: '%s'", From) + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayInvalidFromAddress) r.restErrReply(res, req, err, 404) return } } - c.value = json.Number(getKLDParam("ethvalue", req, false)) + c.value = json.Number(getFlyParam("ethvalue", req, false)) - c.body, err = kldutils.YAMLorJSONPayload(req) + c.body, err = utils.YAMLorJSONPayload(req) if err != nil { r.restErrReply(res, req, err, 400) return @@ -433,13 +433,13 @@ func (r *rest2eth) resolveParams(res http.ResponseWriter, req *http.Request, par } else if vs := queryParams[argName]; len(vs) > 0 { c.msgParams[i] = vs[0] } else { - err = klderrors.Errorf(klderrors.RESTGatewayMissingParameter, argName, c.abiMethod.Name) + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayMissingParameter, argName, c.abiMethod.Name) r.restErrReply(res, req, err, 400) return } } - c.blocknumber = getKLDParam("blocknumber", req, false) + c.blocknumber = getFlyParam("blocknumber", req, false) return } @@ -454,9 +454,9 @@ func (r *rest2eth) restHandler(res http.ResponseWriter, req *http.Request, param if c.abiEvent != nil { r.subscribeEvent(res, req, c.addr, c.abiEventElem, c.body) - } else if (req.Method == http.MethodPost && !c.abiMethod.IsConstant()) && strings.ToLower(getKLDParam("call", req, true)) != "true" { + } else if (req.Method == http.MethodPost && !c.abiMethod.IsConstant()) && strings.ToLower(getFlyParam("call", req, true)) != "true" { if c.from == "" { - err = klderrors.Errorf(klderrors.RESTGatewayMissingFromAddress) + err = ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayMissingFromAddress) r.restErrReply(res, req, err, 400) } else if c.isDeploy { r.deployContract(res, req, c.from, c.value, c.abiMethodElem, c.deployMsg, c.msgParams) @@ -479,10 +479,10 @@ func (r *rest2eth) fromBodyOrForm(req *http.Request, body map[string]interface{} func (r *rest2eth) subscribeEvent(res http.ResponseWriter, req *http.Request, addrStr string, abiEvent *ethbinding.ABIElementMarshaling, body map[string]interface{}) { - err := kldauth.AuthEventStreams(req.Context()) + err := auth.AuthEventStreams(req.Context()) if err != nil { log.Errorf("Unauthorized: %s", err) - r.restErrReply(res, req, klderrors.Errorf(klderrors.Unauthorized), 401) + r.restErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.Unauthorized), 401) return } @@ -492,13 +492,13 @@ func (r *rest2eth) subscribeEvent(res http.ResponseWriter, req *http.Request, ad } streamID := r.fromBodyOrForm(req, body, "stream") if streamID == "" { - r.restErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewaySubscribeMissingStreamParameter), 400) + r.restErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewaySubscribeMissingStreamParameter), 400) return } fromBlock := r.fromBodyOrForm(req, body, "fromBlock") var addr *ethbinding.Address if addrStr != "" { - address := eth.API.HexToAddress(addrStr) + address := ethbind.API.HexToAddress(addrStr) addr = &address } // if the end user provided a name for the subscription, use it @@ -527,39 +527,39 @@ func (r *rest2eth) doubleURLDecode(s string) string { return strings.ReplaceAll(doubleDecoded, " ", "+") } -func (r *rest2eth) addPrivateTx(msg *kldmessages.TransactionCommon, req *http.Request, res http.ResponseWriter) error { - msg.PrivateFrom = r.doubleURLDecode(getKLDParam("privatefrom", req, false)) - msg.PrivateFor = getKLDParamMulti("privatefor", req) +func (r *rest2eth) addPrivateTx(msg *messages.TransactionCommon, req *http.Request, res http.ResponseWriter) error { + msg.PrivateFrom = r.doubleURLDecode(getFlyParam("privatefrom", req, false)) + msg.PrivateFor = getFlyParamMulti("privatefor", req) for idx, val := range msg.PrivateFor { msg.PrivateFor[idx] = r.doubleURLDecode(val) } - msg.PrivacyGroupID = r.doubleURLDecode(getKLDParam("privacygroupid", req, false)) + msg.PrivacyGroupID = r.doubleURLDecode(getFlyParam("privacygroupid", req, false)) if len(msg.PrivateFor) > 0 && msg.PrivacyGroupID != "" { - return klderrors.Errorf(klderrors.RESTGatewayMixedPrivateForAndGroupID) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayMixedPrivateForAndGroupID) } return nil } -func (r *rest2eth) deployContract(res http.ResponseWriter, req *http.Request, from string, value json.Number, abiMethodElem *ethbinding.ABIElementMarshaling, deployMsg *kldmessages.DeployContract, msgParams []interface{}) { +func (r *rest2eth) deployContract(res http.ResponseWriter, req *http.Request, from string, value json.Number, abiMethodElem *ethbinding.ABIElementMarshaling, deployMsg *messages.DeployContract, msgParams []interface{}) { - deployMsg.Headers.MsgType = kldmessages.MsgTypeDeployContract + deployMsg.Headers.MsgType = messages.MsgTypeDeployContract deployMsg.From = from - deployMsg.Gas = json.Number(getKLDParam("gas", req, false)) - deployMsg.GasPrice = json.Number(getKLDParam("gasprice", req, false)) + deployMsg.Gas = json.Number(getFlyParam("gas", req, false)) + deployMsg.GasPrice = json.Number(getFlyParam("gasprice", req, false)) deployMsg.Value = value deployMsg.Parameters = msgParams if err := r.addPrivateTx(&deployMsg.TransactionCommon, req, res); err != nil { r.restErrReply(res, req, err, 400) return } - deployMsg.RegisterAs = getKLDParam("register", req, false) + deployMsg.RegisterAs = getFlyParam("register", req, false) if deployMsg.RegisterAs != "" { if err := r.gw.checkNameAvailable(deployMsg.RegisterAs, isRemote(deployMsg.Headers.CommonHeaders)); err != nil { r.restErrReply(res, req, err, 409) return } } - if strings.ToLower(getKLDParam("sync", req, true)) == "true" { + if strings.ToLower(getFlyParam("sync", req, true)) == "true" { responder := &rest2EthSyncResponder{ r: r, res: res, @@ -573,7 +573,7 @@ func (r *rest2eth) deployContract(res http.ResponseWriter, req *http.Request, fr responder.waiter.Wait() } } else { - ack := (getKLDParam("noack", req, true) != "true") // turn on ack's by default + ack := (getFlyParam("noack", req, true) != "true") // turn on ack's by default // Async messages are dispatched as generic map payloads. // We are confident in the re-serialization here as we've deserialized from JSON then built our own structure @@ -591,13 +591,13 @@ func (r *rest2eth) deployContract(res http.ResponseWriter, req *http.Request, fr func (r *rest2eth) sendTransaction(res http.ResponseWriter, req *http.Request, from, addr string, value json.Number, abiMethodElem *ethbinding.ABIElementMarshaling, msgParams []interface{}) { - msg := &kldmessages.SendTransaction{} - msg.Headers.MsgType = kldmessages.MsgTypeSendTransaction + msg := &messages.SendTransaction{} + msg.Headers.MsgType = messages.MsgTypeSendTransaction msg.Method = abiMethodElem msg.To = addr msg.From = from - msg.Gas = json.Number(getKLDParam("gas", req, false)) - msg.GasPrice = json.Number(getKLDParam("gasprice", req, false)) + msg.Gas = json.Number(getFlyParam("gas", req, false)) + msg.GasPrice = json.Number(getFlyParam("gasprice", req, false)) msg.Value = value msg.Parameters = msgParams if err := r.addPrivateTx(&msg.TransactionCommon, req, res); err != nil { @@ -605,7 +605,7 @@ func (r *rest2eth) sendTransaction(res http.ResponseWriter, req *http.Request, f return } - if strings.ToLower(getKLDParam("sync", req, true)) == "true" { + if strings.ToLower(getFlyParam("sync", req, true)) == "true" { responder := &rest2EthSyncResponder{ r: r, res: res, @@ -619,7 +619,7 @@ func (r *rest2eth) sendTransaction(res http.ResponseWriter, req *http.Request, f responder.waiter.Wait() } } else { - ack := (getKLDParam("noack", req, true) != "true") // turn on ack's by default + ack := (getFlyParam("noack", req, true) != "true") // turn on ack's by default // Async messages are dispatched as generic map payloads. // We are confident in the re-serialization here as we've deserialized from JSON then built our own structure @@ -642,7 +642,7 @@ func (r *rest2eth) callContract(res http.ResponseWriter, req *http.Request, from return } - resBody, err := kldeth.CallMethod(req.Context(), r.rpc, nil, from, addr, value, abiMethod, msgParams, blocknumber) + resBody, err := eth.CallMethod(req.Context(), r.rpc, nil, from, addr, value, abiMethod, msgParams, blocknumber) if err != nil { r.restErrReply(res, req, err, 500) return @@ -657,7 +657,7 @@ func (r *rest2eth) callContract(res http.ResponseWriter, req *http.Request, from return } -func (r *rest2eth) restAsyncReply(res http.ResponseWriter, req *http.Request, asyncResponse *kldmessages.AsyncSentMsg) { +func (r *rest2eth) restAsyncReply(res http.ResponseWriter, req *http.Request, asyncResponse *messages.AsyncSentMsg) { resBytes, _ := json.Marshal(asyncResponse) status := 202 // accepted log.Infof("<-- %s %s [%d]:\n%s", req.Method, req.URL, status, string(resBytes)) diff --git a/internal/kldcontracts/rest2eth_test.go b/internal/contracts/rest2eth_test.go similarity index 84% rename from internal/kldcontracts/rest2eth_test.go rename to internal/contracts/rest2eth_test.go index b9c41e59..572abcac 100644 --- a/internal/kldcontracts/rest2eth_test.go +++ b/internal/contracts/rest2eth_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "bytes" @@ -27,12 +27,12 @@ import ( "github.com/julienschmidt/httprouter" ethbinding "github.com/kaleido-io/ethbinding/pkg" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/auth/authtest" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldauth/kldauthtest" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldevents" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/events" + "github.com/kaleido-io/ethconnect/internal/messages" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -40,23 +40,23 @@ import ( type mockREST2EthDispatcher struct { asyncDispatchMsg map[string]interface{} asyncDispatchAck bool - asyncDispatchReply *kldmessages.AsyncSentMsg + asyncDispatchReply *messages.AsyncSentMsg asyncDispatchError error - sendTransactionMsg *kldmessages.SendTransaction - sendTransactionSyncReceipt *kldmessages.TransactionReceipt + sendTransactionMsg *messages.SendTransaction + sendTransactionSyncReceipt *messages.TransactionReceipt sendTransactionSyncError error - deployContractMsg *kldmessages.DeployContract - deployContractSyncReceipt *kldmessages.TransactionReceipt + deployContractMsg *messages.DeployContract + deployContractSyncReceipt *messages.TransactionReceipt deployContractSyncError error } -func (m *mockREST2EthDispatcher) DispatchMsgAsync(ctx context.Context, msg map[string]interface{}, ack bool) (*kldmessages.AsyncSentMsg, error) { +func (m *mockREST2EthDispatcher) DispatchMsgAsync(ctx context.Context, msg map[string]interface{}, ack bool) (*messages.AsyncSentMsg, error) { m.asyncDispatchMsg = msg m.asyncDispatchAck = ack return m.asyncDispatchReply, m.asyncDispatchError } -func (m *mockREST2EthDispatcher) DispatchSendTransactionSync(ctx context.Context, msg *kldmessages.SendTransaction, replyProcessor rest2EthReplyProcessor) { +func (m *mockREST2EthDispatcher) DispatchSendTransactionSync(ctx context.Context, msg *messages.SendTransaction, replyProcessor rest2EthReplyProcessor) { m.sendTransactionMsg = msg if m.sendTransactionSyncError != nil { replyProcessor.ReplyWithError(m.sendTransactionSyncError) @@ -65,7 +65,7 @@ func (m *mockREST2EthDispatcher) DispatchSendTransactionSync(ctx context.Context } } -func (m *mockREST2EthDispatcher) DispatchDeployContractSync(ctx context.Context, msg *kldmessages.DeployContract, replyProcessor rest2EthReplyProcessor) { +func (m *mockREST2EthDispatcher) DispatchDeployContractSync(ctx context.Context, msg *messages.DeployContract, replyProcessor rest2EthReplyProcessor) { m.deployContractMsg = msg if m.deployContractSyncError != nil { replyProcessor.ReplyWithError(m.deployContractSyncError) @@ -76,7 +76,7 @@ func (m *mockREST2EthDispatcher) DispatchDeployContractSync(ctx context.Context, type mockABILoader struct { loadABIError error - deployMsg *kldmessages.DeployContract + deployMsg *messages.DeployContract abiInfo *abiInfo contractInfo *contractInfo registeredContractAddr string @@ -90,7 +90,7 @@ func (m *mockABILoader) SendReply(message interface{}) { } -func (m *mockABILoader) loadDeployMsgForInstance(addrHexNo0x string) (*kldmessages.DeployContract, *contractInfo, error) { +func (m *mockABILoader) loadDeployMsgForInstance(addrHexNo0x string) (*messages.DeployContract, *contractInfo, error) { m.capturedAddr = addrHexNo0x return m.deployMsg, m.contractInfo, m.loadABIError } @@ -99,7 +99,7 @@ func (m *mockABILoader) resolveContractAddr(registeredName string) (string, erro return m.registeredContractAddr, m.resolveContractErr } -func (m *mockABILoader) loadDeployMsgByID(addrHexNo0x string) (*kldmessages.DeployContract, *abiInfo, error) { +func (m *mockABILoader) loadDeployMsgByID(addrHexNo0x string) (*messages.DeployContract, *abiInfo, error) { return m.deployMsg, m.abiInfo, m.loadABIError } @@ -107,8 +107,8 @@ func (m *mockABILoader) checkNameAvailable(name string, isRemote bool) error { return m.nameAvailableError } -func (m *mockABILoader) PreDeploy(msg *kldmessages.DeployContract) error { return nil } -func (m *mockABILoader) PostDeploy(msg *kldmessages.TransactionReceipt) error { +func (m *mockABILoader) PreDeploy(msg *messages.DeployContract) error { return nil } +func (m *mockABILoader) PostDeploy(msg *messages.TransactionReceipt) error { return m.postDeployError } func (m *mockABILoader) AddRoutes(router *httprouter.Router) { return } @@ -132,24 +132,24 @@ func (m *mockRPC) CallContext(ctx context.Context, result interface{}, method st type mockSubMgr struct { err error updateStreamErr error - sub *kldevents.SubscriptionInfo - stream *kldevents.StreamInfo - subs []*kldevents.SubscriptionInfo - streams []*kldevents.StreamInfo + sub *events.SubscriptionInfo + stream *events.StreamInfo + subs []*events.SubscriptionInfo + streams []*events.StreamInfo suspended bool resumed bool capturedAddr *ethbinding.Address } func (m *mockSubMgr) Init() error { return m.err } -func (m *mockSubMgr) AddStream(ctx context.Context, spec *kldevents.StreamInfo) (*kldevents.StreamInfo, error) { +func (m *mockSubMgr) AddStream(ctx context.Context, spec *events.StreamInfo) (*events.StreamInfo, error) { return spec, m.err } -func (m *mockSubMgr) UpdateStream(ctx context.Context, id string, spec *kldevents.StreamInfo) (*kldevents.StreamInfo, error) { +func (m *mockSubMgr) UpdateStream(ctx context.Context, id string, spec *events.StreamInfo) (*events.StreamInfo, error) { return m.stream, m.updateStreamErr } -func (m *mockSubMgr) Streams(ctx context.Context) []*kldevents.StreamInfo { return m.streams } -func (m *mockSubMgr) StreamByID(ctx context.Context, id string) (*kldevents.StreamInfo, error) { +func (m *mockSubMgr) Streams(ctx context.Context) []*events.StreamInfo { return m.streams } +func (m *mockSubMgr) StreamByID(ctx context.Context, id string) (*events.StreamInfo, error) { return m.stream, m.err } func (m *mockSubMgr) SuspendStream(ctx context.Context, id string) error { @@ -161,12 +161,12 @@ func (m *mockSubMgr) ResumeStream(ctx context.Context, id string) error { return m.err } func (m *mockSubMgr) DeleteStream(ctx context.Context, id string) error { return m.err } -func (m *mockSubMgr) AddSubscription(ctx context.Context, addr *ethbinding.Address, event *ethbinding.ABIElementMarshaling, streamID, initialBlock, name string) (*kldevents.SubscriptionInfo, error) { +func (m *mockSubMgr) AddSubscription(ctx context.Context, addr *ethbinding.Address, event *ethbinding.ABIElementMarshaling, streamID, initialBlock, name string) (*events.SubscriptionInfo, error) { m.capturedAddr = addr return m.sub, m.err } -func (m *mockSubMgr) Subscriptions(ctx context.Context) []*kldevents.SubscriptionInfo { return m.subs } -func (m *mockSubMgr) SubscriptionByID(ctx context.Context, id string) (*kldevents.SubscriptionInfo, error) { +func (m *mockSubMgr) Subscriptions(ctx context.Context) []*events.SubscriptionInfo { return m.subs } +func (m *mockSubMgr) SubscriptionByID(ctx context.Context, id string) (*events.SubscriptionInfo, error) { return m.sub, m.err } func (m *mockSubMgr) DeleteSubscription(ctx context.Context, id string) error { return m.err } @@ -176,10 +176,10 @@ func (m *mockSubMgr) ResetSubscription(ctx context.Context, id, initialBlock str func (m *mockSubMgr) Close() {} func newTestDeployMsg(t *testing.T, addr string) *deployContractWithAddress { - compiled, err := kldeth.CompileContract(simpleEventsSource(), "SimpleEvents", "", "") + compiled, err := eth.CompileContract(simpleEventsSource(), "SimpleEvents", "", "") assert.NoError(t, err) return &deployContractWithAddress{ - DeployContract: kldmessages.DeployContract{ABI: compiled.ABI}, + DeployContract: messages.DeployContract{ABI: compiled.ABI}, Address: addr, } } @@ -211,7 +211,7 @@ func newTestREST2EthCustomAbiLoader(dispatcher *mockREST2EthDispatcher, abiLoade func newTestREST2EthAndMsg(t *testing.T, dispatcher *mockREST2EthDispatcher, from, to string, bodyMap map[string]interface{}) (*rest2eth, *mockRPC, *httprouter.Router, *httptest.ResponseRecorder, *http.Request) { body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req.Header.Add("x-firefly-from", from) res := httptest.NewRecorder() r, mockRPC, router := newTestREST2Eth(t, dispatcher) @@ -227,7 +227,7 @@ func newTestREST2EthAndMsgPostDeployError(t *testing.T, dispatcher *mockREST2Eth } body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req.Header.Add("x-firefly-from", from) res := httptest.NewRecorder() r, mockRPC, router := newTestREST2EthCustomAbiLoader(dispatcher, abiLoader) @@ -246,18 +246,18 @@ func TestSendTransactionAsyncSuccess(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) - req.Header.Set("X-Kaleido-PrivateFrom", "0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90") - req.Header.Set("X-Kaleido-PrivateFor", "0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745,0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C") + req.Header.Set("X-Firefly-PrivateFrom", "0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90") + req.Header.Set("X-Firefly-PrivateFor", "0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745,0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C") router.ServeHTTP(res, req) assert.Equal(202, res.Result().StatusCode) - reply := kldmessages.AsyncSentMsg{} + reply := messages.AsyncSentMsg{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal(true, reply.Sent) @@ -281,19 +281,19 @@ func TestDeployContractAsyncSuccess(t *testing.T) { bodyMap["s"] = "testing" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/abis/abi1?kld-privateFrom=0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90&kld-privateFor=0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745&kld-privateFor=0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/abis/abi1?fly-privateFrom=0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90&fly-privateFor=0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745&fly-privateFor=0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(202, res.Result().StatusCode) - reply := kldmessages.AsyncSentMsg{} + reply := messages.AsyncSentMsg{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal(true, reply.Sent) @@ -316,7 +316,7 @@ func TestDeployContractAsyncHDWallet(t *testing.T) { bodyMap["s"] = "testing" from := "HD-u01234abcd-u01234abcd-12345" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, @@ -324,11 +324,11 @@ func TestDeployContractAsyncHDWallet(t *testing.T) { _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(202, res.Result().StatusCode) - reply := kldmessages.AsyncSentMsg{} + reply := messages.AsyncSentMsg{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal(true, reply.Sent) @@ -348,7 +348,7 @@ func TestDeployContractAsyncDuplicate(t *testing.T) { bodyMap["s"] = "testing" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, @@ -357,9 +357,9 @@ func TestDeployContractAsyncDuplicate(t *testing.T) { abiLoader := r.gw.(*mockABILoader) abiLoader.nameAvailableError = fmt.Errorf("spent already") body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/abis/abi1?kld-privateFrom=0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90&kld-privateFor=0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745&kld-privateFor=0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) - req.Header.Add("x-kaleido-register", "random") + req := httptest.NewRequest("POST", "/abis/abi1?fly-privateFrom=0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90&fly-privateFor=0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745&fly-privateFor=0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) + req.Header.Add("x-firefly-register", "random") router.ServeHTTP(res, req) assert.Equal(409, res.Result().StatusCode) @@ -378,11 +378,11 @@ func TestSendTransactionSyncSuccess(t *testing.T) { bodyMap["s"] = "testing" to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" - receipt := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeTransactionSuccess, + receipt := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeTransactionSuccess, }, }, }, @@ -392,8 +392,8 @@ func TestSendTransactionSyncSuccess(t *testing.T) { } _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/contracts/"+to+"/set?kld-sync&kld-ethvalue=1234", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(json.Number("1234"), dispatcher.sendTransactionMsg.Value) @@ -413,11 +413,11 @@ func TestSendTransactionSyncFailure(t *testing.T) { bodyMap["s"] = "testing" to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" - receipt := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeTransactionFailure, + receipt := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeTransactionFailure, }, }, }, @@ -427,8 +427,8 @@ func TestSendTransactionSyncFailure(t *testing.T) { } _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/contracts/"+to+"/set?kld-sync&kld-ethvalue=1234", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(json.Number("1234"), dispatcher.sendTransactionMsg.Value) @@ -448,12 +448,12 @@ func TestSendTransactionSyncPostDeployErr(t *testing.T) { bodyMap["s"] = "testing" to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" - contractAddr := eth.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") - receipt := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeTransactionSuccess, + contractAddr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") + receipt := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeTransactionSuccess, }, }, }, @@ -464,8 +464,8 @@ func TestSendTransactionSyncPostDeployErr(t *testing.T) { } _, _, router, res, _ := newTestREST2EthAndMsgPostDeployError(t, dispatcher, from, to, bodyMap) body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/contracts/"+to+"/set?kld-sync&kld-ethvalue=1234", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(json.Number("1234"), dispatcher.sendTransactionMsg.Value) @@ -487,11 +487,11 @@ func TestSendTransactionSyncViaABISuccess(t *testing.T) { abi := "69a8898a-b6ef-4092-43bf-6cbffac56939" to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" - receipt := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeTransactionSuccess, + receipt := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeTransactionSuccess, }, }, }, @@ -501,8 +501,8 @@ func TestSendTransactionSyncViaABISuccess(t *testing.T) { } _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/abis/"+abi+"/"+to+"/set?kld-sync&kld-ethvalue=1234", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/abis/"+abi+"/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(json.Number("1234"), dispatcher.sendTransactionMsg.Value) @@ -521,11 +521,11 @@ func TestDeployContractSyncSuccess(t *testing.T) { bodyMap["i"] = 12345 bodyMap["s"] = "testing" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" - receipt := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeTransactionSuccess, + receipt := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeTransactionSuccess, }, }, }, @@ -535,8 +535,8 @@ func TestDeployContractSyncSuccess(t *testing.T) { } _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/abis/abi1?kld-sync", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/abis/abi1?fly-sync", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) @@ -553,11 +553,11 @@ func TestDeployContractSyncRemoteRegitryInstance(t *testing.T) { bodyMap["s"] = "testing" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" - receipt := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeTransactionSuccess, + receipt := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeTransactionSuccess, Context: map[string]interface{}{ remoteRegistryContextKey: true, }, @@ -573,8 +573,8 @@ func TestDeployContractSyncRemoteRegitryInstance(t *testing.T) { deployMsg: newTestDeployMsg(t, strings.TrimPrefix(to, "0x")), } body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/instances/myinstance/set?kld-sync", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/instances/myinstance/set?fly-sync", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) @@ -593,7 +593,7 @@ func TestDeployContractSyncRemoteRegitryInstance500(t *testing.T) { err: fmt.Errorf("pop"), } body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/instances/myinstance/set?kld-sync", bytes.NewReader(body)) + req := httptest.NewRequest("POST", "/instances/myinstance/set?fly-sync", bytes.NewReader(body)) router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -608,7 +608,7 @@ func TestDeployContractSyncRemoteRegitryInstance404(t *testing.T) { r, _, router, res, _ := newTestREST2EthAndMsg(t, &mockREST2EthDispatcher{}, "", "", bodyMap) r.rr = &mockRR{} body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/instances/myinstance/set?kld-sync", bytes.NewReader(body)) + req := httptest.NewRequest("POST", "/instances/myinstance/set?fly-sync", bytes.NewReader(body)) router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) @@ -625,7 +625,7 @@ func TestDeployContractSyncRemoteRegitryGateway500(t *testing.T) { err: fmt.Errorf("pop"), } body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/g/mygw?kld-sync", bytes.NewReader(body)) + req := httptest.NewRequest("POST", "/g/mygw?fly-sync", bytes.NewReader(body)) router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -640,7 +640,7 @@ func TestDeployContractSyncRemoteRegitryGateway404(t *testing.T) { r, _, router, res, _ := newTestREST2EthAndMsg(t, &mockREST2EthDispatcher{}, "", "", bodyMap) r.rr = &mockRR{} body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/g/mygw?kld-sync", bytes.NewReader(body)) + req := httptest.NewRequest("POST", "/g/mygw?fly-sync", bytes.NewReader(body)) router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) @@ -656,11 +656,11 @@ func TestDeployContractSyncRemoteRegistryGateway(t *testing.T) { bodyMap["s"] = "testing" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" - receipt := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeTransactionSuccess, + receipt := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeTransactionSuccess, }, }, }, @@ -673,8 +673,8 @@ func TestDeployContractSyncRemoteRegistryGateway(t *testing.T) { deployMsg: newTestDeployMsg(t, strings.TrimPrefix(to, "0x")), } body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/g/mygateway/567a417717cb6c59ddc1035705f02c0fd1ab1872/set?kld-sync", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/g/mygateway/567a417717cb6c59ddc1035705f02c0fd1ab1872/set?fly-sync", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) @@ -696,7 +696,7 @@ func TestSendTransactionSyncFail(t *testing.T) { sendTransactionSyncError: fmt.Errorf("pop"), } _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) - req.Header.Set("x-kaleido-sync", "true") + req.Header.Set("x-firefly-sync", "true") router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -744,7 +744,7 @@ func TestDeployContractAsyncFail(t *testing.T) { _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req.Header.Add("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -842,7 +842,7 @@ func TestSendTransactionMissingContract(t *testing.T) { reply := restErrMsg{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) - assert.Equal("Please specify a valid address in the 'kld-from' query string parameter or x-kaleido-from HTTP header", reply.Message) + assert.Equal("Please specify a valid address in the 'fly-from' query string parameter or x-firefly-from HTTP header", reply.Message) } func TestSendTransactionBadMethodABI(t *testing.T) { @@ -850,13 +850,13 @@ func TestSendTransactionBadMethodABI(t *testing.T) { dir := tempdir() defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } abiLoader := &mockABILoader{ - deployMsg: &kldmessages.DeployContract{ + deployMsg: &messages.DeployContract{ ABI: ethbinding.ABIMarshaling{ { Name: "badmethod", Type: "function", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -868,7 +868,7 @@ func TestSendTransactionBadMethodABI(t *testing.T) { } _, _, router := newTestREST2EthCustomAbiLoader(dispatcher, abiLoader) req := httptest.NewRequest("GET", "/contracts/0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8/badmethod", bytes.NewReader([]byte{})) - req.Header.Add("x-kaleido-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") + req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") res := httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(400, res.Result().StatusCode) @@ -883,13 +883,13 @@ func TestSendTransactionBadEventABI(t *testing.T) { dir := tempdir() defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } abiLoader := &mockABILoader{ - deployMsg: &kldmessages.DeployContract{ + deployMsg: &messages.DeployContract{ ABI: ethbinding.ABIMarshaling{ { Name: "badevent", Type: "event", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -901,7 +901,7 @@ func TestSendTransactionBadEventABI(t *testing.T) { } _, _, router := newTestREST2EthCustomAbiLoader(dispatcher, abiLoader) req := httptest.NewRequest("POST", "/contracts/0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8/badevent/subscribe", bytes.NewReader([]byte{})) - req.Header.Add("x-kaleido-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") + req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") res := httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(400, res.Result().StatusCode) @@ -916,13 +916,13 @@ func TestSendTransactionBadConstructorABI(t *testing.T) { dir := tempdir() defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } abiLoader := &mockABILoader{ - deployMsg: &kldmessages.DeployContract{ + deployMsg: &messages.DeployContract{ ABI: ethbinding.ABIMarshaling{ { Name: "badevent", Type: "constructor", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -934,7 +934,7 @@ func TestSendTransactionBadConstructorABI(t *testing.T) { } _, _, router := newTestREST2EthCustomAbiLoader(dispatcher, abiLoader) req := httptest.NewRequest("POST", "/abis/testabi", bytes.NewReader([]byte{})) - req.Header.Add("x-kaleido-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") + req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") res := httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(400, res.Result().StatusCode) @@ -949,19 +949,19 @@ func TestSendTransactionDefaultConstructorABI(t *testing.T) { dir := tempdir() defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } abiLoader := &mockABILoader{ - deployMsg: &kldmessages.DeployContract{ + deployMsg: &messages.DeployContract{ ABI: ethbinding.ABIMarshaling{}, // completely empty ABI is ok }, } _, _, router := newTestREST2EthCustomAbiLoader(dispatcher, abiLoader) req := httptest.NewRequest("POST", "/abis/testabi", bytes.NewReader([]byte{})) - req.Header.Add("x-kaleido-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") + req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") res := httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(202, res.Result().StatusCode) @@ -972,13 +972,13 @@ func TestSendTransactionUnnamedParamsABI(t *testing.T) { dir := tempdir() defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } abiLoader := &mockABILoader{ - deployMsg: &kldmessages.DeployContract{ + deployMsg: &messages.DeployContract{ ABI: ethbinding.ABIMarshaling{ { Name: "unnamedparamsmethod", Type: "function", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -991,7 +991,7 @@ func TestSendTransactionUnnamedParamsABI(t *testing.T) { } _, _, router := newTestREST2EthCustomAbiLoader(dispatcher, abiLoader) req := httptest.NewRequest("POST", "/abis/testabi/0x29fb3f4f7cc82a1456903a506e88cdd63b1d74e8/unnamedparamsmethod", bytes.NewReader([]byte{})) - req.Header.Add("x-kaleido-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") + req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") q := req.URL.Query() q.Add("input", "105") q.Add("input1", "106") @@ -1034,7 +1034,7 @@ func TestSendTransactionInvalidContract(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, @@ -1061,15 +1061,15 @@ func TestDeployContractInvalidABI(t *testing.T) { bodyMap["s"] = "testing" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } r, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/abis/abi1?kld-sync", bytes.NewReader(body)) - req.Header.Add("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/abis/abi1?fly-sync", bytes.NewReader(body)) + req.Header.Add("x-firefly-from", from) abiLoader := r.gw.(*mockABILoader) abiLoader.loadABIError = fmt.Errorf("pop") router.ServeHTTP(res, req) @@ -1091,14 +1091,14 @@ func TestSendTransactionInvalidMethod(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/shazaam", bytes.NewReader([]byte("{}"))) - req.Header.Set("x-kaleido-from", from) + req.Header.Set("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) @@ -1117,14 +1117,14 @@ func TestSendTransactionParamInQuery(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) - req := httptest.NewRequest("POST", "/contracts/"+to+"/set?i=999&s=msg&kld-ethvalue=12345", bytes.NewReader([]byte("{}"))) - req.Header.Set("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/contracts/"+to+"/set?i=999&s=msg&fly-ethvalue=12345", bytes.NewReader([]byte("{}"))) + req.Header.Set("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(202, res.Result().StatusCode) @@ -1139,7 +1139,7 @@ func TestSendTransactionRegisteredName(t *testing.T) { to := "transponster" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, @@ -1147,8 +1147,8 @@ func TestSendTransactionRegisteredName(t *testing.T) { r, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) abiLoader := r.gw.(*mockABILoader) abiLoader.registeredContractAddr = "c6c572a18d31ff36d661d680c0060307e038dc47" - req := httptest.NewRequest("POST", "/contracts/"+to+"/set?i=999&s=msg&kld-ethvalue=12345", bytes.NewReader([]byte("{}"))) - req.Header.Set("x-kaleido-from", from) + req := httptest.NewRequest("POST", "/contracts/"+to+"/set?i=999&s=msg&fly-ethvalue=12345", bytes.NewReader([]byte("{}"))) + req.Header.Set("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal("c6c572a18d31ff36d661d680c0060307e038dc47", abiLoader.capturedAddr) @@ -1163,7 +1163,7 @@ func TestSendTransactionMissingParam(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, @@ -1187,14 +1187,14 @@ func TestSendTransactionBadBody(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{ - asyncDispatchReply: &kldmessages.AsyncSentMsg{ + asyncDispatchReply: &messages.AsyncSentMsg{ Sent: true, Request: "request1", }, } _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?x=999", bytes.NewReader([]byte(":not json or yaml"))) - req.Header.Set("x-kaleido-from", from) + req.Header.Set("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(400, res.Result().StatusCode) @@ -1240,7 +1240,7 @@ func TestCallMethodHDWalletSuccess(t *testing.T) { from := "HD-u01234abcd-u01234abcd-12345" r, mockRPC, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) r.processor.(*mockProcessor).resolvedFrom = "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" - req := httptest.NewRequest("GET", "/contracts/"+to+"/get?kld-from="+from, bytes.NewReader([]byte{})) + req := httptest.NewRequest("GET", "/contracts/"+to+"/get?fly-from="+from, bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) @@ -1268,7 +1268,7 @@ func TestCallMethodHDWalletFail(t *testing.T) { r, mockRPC, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) r.processor.(*mockProcessor).resolvedFrom = "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" r.processor.(*mockProcessor).err = fmt.Errorf("pop") - req := httptest.NewRequest("GET", "/contracts/"+to+"/get?kld-from="+from, bytes.NewReader([]byte{})) + req := httptest.NewRequest("GET", "/contracts/"+to+"/get?fly-from="+from, bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) @@ -1287,7 +1287,7 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} _, mockRPC, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) - req := httptest.NewRequest("POST", "/contracts/"+to+"/get?kld-blocknumber=12345", bytes.NewReader([]byte{})) + req := httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=12345", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) @@ -1305,7 +1305,7 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} _, mockRPC, router, res, _ = newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) - req = httptest.NewRequest("POST", "/contracts/"+to+"/get?kld-blocknumber=0xab1234", bytes.NewReader([]byte{})) + req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=0xab1234", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) @@ -1315,7 +1315,7 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} _, mockRPC, router, res, _ = newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) - req = httptest.NewRequest("POST", "/contracts/"+to+"/get?kld-blocknumber=pending", bytes.NewReader([]byte{})) + req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=pending", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) @@ -1345,7 +1345,7 @@ func TestCallMethodFail(t *testing.T) { to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} _, mockRPC, router, res, _ = newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) - req = httptest.NewRequest("POST", "/contracts/"+to+"/get?kld-blocknumber=ab1234", bytes.NewReader([]byte{})) + req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=ab1234", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -1416,7 +1416,7 @@ func TestSubscribeUnauthorized(t *testing.T) { dir := tempdir() defer cleanup(dir) - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) dispatcher := &mockREST2EthDispatcher{} _, _, router := newTestREST2Eth(t, dispatcher) @@ -1433,7 +1433,7 @@ func TestSubscribeUnauthorized(t *testing.T) { assert.NoError(err) assert.Equal("Unauthorized", reply.Message) - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } func TestSubscribeNoAddressMissingStream(t *testing.T) { @@ -1464,7 +1464,7 @@ func TestSubscribeNoAddressSuccess(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} r, _, router := newTestREST2Eth(t, dispatcher) sm := &mockSubMgr{ - sub: &kldevents.SubscriptionInfo{ID: "sub1", Name: "stream-without-address"}, + sub: &events.SubscriptionInfo{ID: "sub1", Name: "stream-without-address"}, } r.subMgr = sm bodyBytes, _ := json.Marshal(&map[string]string{ @@ -1475,7 +1475,7 @@ func TestSubscribeNoAddressSuccess(t *testing.T) { router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) - reply := kldevents.SubscriptionInfo{} + reply := events.SubscriptionInfo{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("sub1", reply.ID) @@ -1491,7 +1491,7 @@ func TestSubscribeWithAddressSuccess(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} r, _, router := newTestREST2Eth(t, dispatcher) sm := &mockSubMgr{ - sub: &kldevents.SubscriptionInfo{ID: "sub1"}, + sub: &events.SubscriptionInfo{ID: "sub1"}, } r.subMgr = sm bodyBytes, _ := json.Marshal(&map[string]string{ @@ -1502,7 +1502,7 @@ func TestSubscribeWithAddressSuccess(t *testing.T) { router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) - reply := kldevents.SubscriptionInfo{} + reply := events.SubscriptionInfo{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("sub1", reply.ID) @@ -1519,7 +1519,7 @@ func TestSubscribeWithAddressBadAddress(t *testing.T) { abiLoader := r.gw.(*mockABILoader) abiLoader.resolveContractErr = fmt.Errorf("unregistered") r.subMgr = &mockSubMgr{ - sub: &kldevents.SubscriptionInfo{ID: "sub1"}, + sub: &events.SubscriptionInfo{ID: "sub1"}, } bodyBytes, _ := json.Marshal(&map[string]string{ "stream": "stream1", diff --git a/internal/kldcontracts/smartcontractgw.go b/internal/contracts/smartcontractgw.go similarity index 79% rename from internal/kldcontracts/smartcontractgw.go rename to internal/contracts/smartcontractgw.go index 54536788..57d00b1d 100644 --- a/internal/kldcontracts/smartcontractgw.go +++ b/internal/contracts/smartcontractgw.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "bufio" @@ -42,16 +42,16 @@ import ( "github.com/spf13/cobra" ethbinding "github.com/kaleido-io/ethbinding/pkg" + "github.com/kaleido-io/ethconnect/internal/auth" + ethconnecterrors "github.com/kaleido-io/ethconnect/internal/errors" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldevents" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldopenapi" - "github.com/kaleido-io/ethconnect/internal/kldtx" - "github.com/kaleido-io/ethconnect/internal/kldutils" - "github.com/kaleido-io/ethconnect/internal/kldws" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/events" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/openapi" + "github.com/kaleido-io/ethconnect/internal/tx" + "github.com/kaleido-io/ethconnect/internal/utils" + "github.com/kaleido-io/ethconnect/internal/ws" ) const ( @@ -62,8 +62,8 @@ const ( // SmartContractGateway provides gateway functions for OpenAPI 2.0 processing of Solidity contracts type SmartContractGateway interface { - PreDeploy(msg *kldmessages.DeployContract) error - PostDeploy(msg *kldmessages.TransactionReceipt) error + PreDeploy(msg *messages.DeployContract) error + PostDeploy(msg *messages.TransactionReceipt) error AddRoutes(router *httprouter.Router) SendReply(message interface{}) Shutdown() @@ -72,14 +72,14 @@ type SmartContractGateway interface { type smartContractGatewayInt interface { SmartContractGateway resolveContractAddr(registeredName string) (string, error) - loadDeployMsgForInstance(addrHexNo0x string) (*kldmessages.DeployContract, *contractInfo, error) - loadDeployMsgByID(abi string) (*kldmessages.DeployContract, *abiInfo, error) + loadDeployMsgForInstance(addrHexNo0x string) (*messages.DeployContract, *contractInfo, error) + loadDeployMsgByID(abi string) (*messages.DeployContract, *abiInfo, error) checkNameAvailable(name string, isRemote bool) error } // SmartContractGatewayConf configuration type SmartContractGatewayConf struct { - kldevents.SubscriptionManagerConf + events.SubscriptionManagerConf StoragePath string `json:"storagePath"` BaseURL string `json:"baseURL"` RemoteRegistry RemoteRegistryConf `json:"registry,omitempty"` // JSON only config - no commandline @@ -89,15 +89,15 @@ type SmartContractGatewayConf struct { func CobraInitContractGateway(cmd *cobra.Command, conf *SmartContractGatewayConf) { cmd.Flags().StringVarP(&conf.StoragePath, "openapi-path", "I", "", "Path containing ABI + generated OpenAPI/Swagger 2.0 contact definitions") cmd.Flags().StringVarP(&conf.BaseURL, "openapi-baseurl", "U", "", "Base URL for generated OpenAPI/Swagger 2.0 contact definitions") - kldevents.CobraInitSubscriptionManager(cmd, &conf.SubscriptionManagerConf) + events.CobraInitSubscriptionManager(cmd, &conf.SubscriptionManagerConf) } func (g *smartContractGW) withEventsAuth(handler httprouter.Handle) httprouter.Handle { return func(res http.ResponseWriter, req *http.Request, params httprouter.Params) { - err := kldauth.AuthEventStreams(req.Context()) + err := auth.AuthEventStreams(req.Context()) if err != nil { log.Errorf("Unauthorized: %s", err) - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.Unauthorized), 401) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.Unauthorized), 401) return } handler(res, req, params) @@ -116,17 +116,17 @@ func (g *smartContractGW) AddRoutes(router *httprouter.Router) { router.GET("/i/:instance_lookup", g.getRemoteRegistrySwaggerOrABI) router.GET("/gateways/:gateway_lookup", g.getRemoteRegistrySwaggerOrABI) router.GET("/g/:gateway_lookup", g.getRemoteRegistrySwaggerOrABI) - router.POST(kldevents.StreamPathPrefix, g.withEventsAuth(g.createStream)) - router.PATCH(kldevents.StreamPathPrefix+"/:id", g.withEventsAuth(g.updateStream)) - router.GET(kldevents.StreamPathPrefix, g.withEventsAuth(g.listStreamsOrSubs)) - router.GET(kldevents.SubPathPrefix, g.withEventsAuth(g.listStreamsOrSubs)) - router.GET(kldevents.StreamPathPrefix+"/:id", g.withEventsAuth(g.getStreamOrSub)) - router.GET(kldevents.SubPathPrefix+"/:id", g.withEventsAuth(g.getStreamOrSub)) - router.DELETE(kldevents.StreamPathPrefix+"/:id", g.withEventsAuth(g.deleteStreamOrSub)) - router.DELETE(kldevents.SubPathPrefix+"/:id", g.withEventsAuth(g.deleteStreamOrSub)) - router.POST(kldevents.SubPathPrefix+"/:id/reset", g.withEventsAuth(g.resetSub)) - router.POST(kldevents.StreamPathPrefix+"/:id/suspend", g.withEventsAuth(g.suspendOrResumeStream)) - router.POST(kldevents.StreamPathPrefix+"/:id/resume", g.withEventsAuth(g.suspendOrResumeStream)) + router.POST(events.StreamPathPrefix, g.withEventsAuth(g.createStream)) + router.PATCH(events.StreamPathPrefix+"/:id", g.withEventsAuth(g.updateStream)) + router.GET(events.StreamPathPrefix, g.withEventsAuth(g.listStreamsOrSubs)) + router.GET(events.SubPathPrefix, g.withEventsAuth(g.listStreamsOrSubs)) + router.GET(events.StreamPathPrefix+"/:id", g.withEventsAuth(g.getStreamOrSub)) + router.GET(events.SubPathPrefix+"/:id", g.withEventsAuth(g.getStreamOrSub)) + router.DELETE(events.StreamPathPrefix+"/:id", g.withEventsAuth(g.deleteStreamOrSub)) + router.DELETE(events.SubPathPrefix+"/:id", g.withEventsAuth(g.deleteStreamOrSub)) + router.POST(events.SubPathPrefix+"/:id/reset", g.withEventsAuth(g.resetSub)) + router.POST(events.StreamPathPrefix+"/:id/suspend", g.withEventsAuth(g.suspendOrResumeStream)) + router.POST(events.StreamPathPrefix+"/:id/resume", g.withEventsAuth(g.suspendOrResumeStream)) } func (g *smartContractGW) SendReply(message interface{}) { @@ -134,7 +134,7 @@ func (g *smartContractGW) SendReply(message interface{}) { } // NewSmartContractGateway constructor -func NewSmartContractGateway(conf *SmartContractGatewayConf, txnConf *kldtx.TxnProcessorConf, rpc kldeth.RPCClient, processor kldtx.TxnProcessor, asyncDispatcher REST2EthAsyncDispatcher, ws kldws.WebSocketChannels) (SmartContractGateway, error) { +func NewSmartContractGateway(conf *SmartContractGatewayConf, txnConf *tx.TxnProcessorConf, rpc eth.RPCClient, processor tx.TxnProcessor, asyncDispatcher REST2EthAsyncDispatcher, ws ws.WebSocketChannels) (SmartContractGateway, error) { var baseURL *url.URL var err error if conf.BaseURL != "" { @@ -149,10 +149,10 @@ func NewSmartContractGateway(conf *SmartContractGatewayConf, txnConf *kldtx.TxnP gw := &smartContractGW{ conf: conf, rr: NewRemoteRegistry(&conf.RemoteRegistry), - contractIndex: make(map[string]kldmessages.TimeSortable), + contractIndex: make(map[string]messages.TimeSortable), contractRegistrations: make(map[string]*contractInfo), - abiIndex: make(map[string]kldmessages.TimeSortable), - baseSwaggerConf: &kldopenapi.ABI2SwaggerConf{ + abiIndex: make(map[string]messages.TimeSortable), + baseSwaggerConf: &openapi.ABI2SwaggerConf{ ExternalHost: baseURL.Host, ExternalRootPath: baseURL.Path, ExternalSchemes: []string{baseURL.Scheme}, @@ -166,10 +166,10 @@ func NewSmartContractGateway(conf *SmartContractGatewayConf, txnConf *kldtx.TxnP } syncDispatcher := newSyncDispatcher(processor) if conf.EventLevelDBPath != "" { - gw.sm = kldevents.NewSubscriptionManager(&conf.SubscriptionManagerConf, rpc, gw.ws) + gw.sm = events.NewSubscriptionManager(&conf.SubscriptionManagerConf, rpc, gw.ws) err = gw.sm.Init() if err != nil { - return nil, klderrors.Errorf(klderrors.RESTGatewayEventManagerInitFailed, err) + return nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayEventManagerInitFailed, err) } } gw.r2e = newREST2eth(gw, rpc, gw.sm, gw.rr, processor, asyncDispatcher, syncDispatcher) @@ -179,21 +179,21 @@ func NewSmartContractGateway(conf *SmartContractGatewayConf, txnConf *kldtx.TxnP type smartContractGW struct { conf *SmartContractGatewayConf - sm kldevents.SubscriptionManager + sm events.SubscriptionManager rr RemoteRegistry r2e *rest2eth - ws kldws.WebSocketChannels - contractIndex map[string]kldmessages.TimeSortable + ws ws.WebSocketChannels + contractIndex map[string]messages.TimeSortable contractRegistrations map[string]*contractInfo idxLock sync.Mutex - abiIndex map[string]kldmessages.TimeSortable - baseSwaggerConf *kldopenapi.ABI2SwaggerConf + abiIndex map[string]messages.TimeSortable + baseSwaggerConf *openapi.ABI2SwaggerConf } // contractInfo is the minimal data structure we keep in memory, indexed by address // ONLY used for local registry. Remote registry handles its own storage/caching type contractInfo struct { - kldmessages.TimeSorted + messages.TimeSorted Address string `json:"address"` Path string `json:"path"` ABI string `json:"abi"` @@ -203,7 +203,7 @@ type contractInfo struct { // abiInfo is the minimal data structure we keep in memory, indexed by our own UUID type abiInfo struct { - kldmessages.TimeSorted + messages.TimeSorted ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` @@ -235,7 +235,7 @@ func (g *smartContractGW) storeNewContractInfo(addrHexNo0x, abiID, pathName, reg Path: "/contracts/" + pathName, SwaggerURL: g.conf.BaseURL + "/contracts/" + pathName + "?swagger", RegisteredAs: registerAs, - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: time.Now().UTC().Format(time.RFC3339), }, } @@ -245,7 +245,7 @@ func (g *smartContractGW) storeNewContractInfo(addrHexNo0x, abiID, pathName, reg return contractInfo, nil } -func isRemote(msg kldmessages.CommonHeaders) bool { +func isRemote(msg messages.CommonHeaders) bool { ctxMap := msg.Context if isRemoteGeneric, ok := ctxMap[remoteRegistryContextKey]; ok { if isRemote, ok := isRemoteGeneric.(bool); ok { @@ -256,14 +256,14 @@ func isRemote(msg kldmessages.CommonHeaders) bool { } // PostDeploy callback processes the transaction receipt and generates the Swagger -func (g *smartContractGW) PostDeploy(msg *kldmessages.TransactionReceipt) error { +func (g *smartContractGW) PostDeploy(msg *messages.TransactionReceipt) error { requestID := msg.Headers.ReqID // We use the ethereum address of the contract, without the 0x prefix, and // all in lower case, as the name of the file and the path root of the Swagger operations if msg.ContractAddress == nil { - return klderrors.Errorf(klderrors.RESTGatewayPostDeployMissingAddress, requestID) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayPostDeployMissingAddress, requestID) } addrHexNo0x := strings.ToLower(msg.ContractAddress.Hex()[2:]) @@ -278,7 +278,7 @@ func (g *smartContractGW) PostDeploy(msg *kldmessages.TransactionReceipt) error registeredName = addrHexNo0x } - if msg.Headers.MsgType == kldmessages.MsgTypeTransactionSuccess { + if msg.Headers.MsgType == messages.MsgTypeTransactionSuccess { msg.ContractSwagger = g.conf.BaseURL + basePath + registeredName + "?openapi" msg.ContractUI = g.conf.BaseURL + basePath + registeredName + "?ui" @@ -295,7 +295,7 @@ func (g *smartContractGW) PostDeploy(msg *kldmessages.TransactionReceipt) error return nil } -func (g *smartContractGW) swaggerForRemoteRegistry(swaggerGen *kldopenapi.ABI2Swagger, apiName, addr string, factoryOnly bool, abi *ethbinding.RuntimeABI, devdoc, path string) *spec.Swagger { +func (g *smartContractGW) swaggerForRemoteRegistry(swaggerGen *openapi.ABI2Swagger, apiName, addr string, factoryOnly bool, abi *ethbinding.RuntimeABI, devdoc, path string) *spec.Swagger { var swagger *spec.Swagger if addr == "" { swagger = swaggerGen.Gen4Factory(path, apiName, factoryOnly, true, &abi.ABI, devdoc) @@ -305,7 +305,7 @@ func (g *smartContractGW) swaggerForRemoteRegistry(swaggerGen *kldopenapi.ABI2Sw return swagger } -func (g *smartContractGW) swaggerForABI(swaggerGen *kldopenapi.ABI2Swagger, abiID, apiName string, factoryOnly bool, abi *ethbinding.RuntimeABI, devdoc string, addrHexNo0x, registerAs string) *spec.Swagger { +func (g *smartContractGW) swaggerForABI(swaggerGen *openapi.ABI2Swagger, abiID, apiName string, factoryOnly bool, abi *ethbinding.RuntimeABI, devdoc string, addrHexNo0x, registerAs string) *spec.Swagger { // Ensure we have a contract name in all cases, as the Swagger // won't be valid without a title if apiName == "" { @@ -319,7 +319,7 @@ func (g *smartContractGW) swaggerForABI(swaggerGen *kldopenapi.ABI2Swagger, abiI } swagger = swaggerGen.Gen4Instance("/contracts/"+pathSuffix, apiName, &abi.ABI, devdoc) if registerAs != "" { - swagger.Info.AddExtension("x-kaleido-registered-name", pathSuffix) + swagger.Info.AddExtension("x-firefly-registered-name", pathSuffix) } } else { swagger = swaggerGen.Gen4Factory("/abis/"+abiID, apiName, factoryOnly, false, &abi.ABI, devdoc) @@ -327,7 +327,7 @@ func (g *smartContractGW) swaggerForABI(swaggerGen *kldopenapi.ABI2Swagger, abiI // Add in an extension to the Swagger that points back at the filename of the deployment info if abiID != "" { - swagger.Info.AddExtension("x-kaleido-deployment-id", abiID) + swagger.Info.AddExtension("x-firefly-deployment-id", abiID) } return swagger @@ -341,7 +341,7 @@ func (g *smartContractGW) storeContractInfo(info *contractInfo) error { instanceBytes, _ := json.MarshalIndent(info, "", " ") log.Infof("%s: Storing contract instance JSON to '%s'", info.ABI, infoFile) if err := ioutil.WriteFile(infoFile, instanceBytes, 0664); err != nil { - return klderrors.Errorf(klderrors.RESTGatewayLocalStoreContractSave, err) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayLocalStoreContractSave, err) } return nil } @@ -350,38 +350,38 @@ func (g *smartContractGW) resolveContractAddr(registeredName string) (string, er nameUnescaped, _ := url.QueryUnescape(registeredName) info, exists := g.contractRegistrations[nameUnescaped] if !exists { - return "", klderrors.Errorf(klderrors.RESTGatewayLocalStoreContractLoad, registeredName) + return "", ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayLocalStoreContractLoad, registeredName) } log.Infof("%s -> 0x%s", registeredName, info.Address) return info.Address, nil } -func (g *smartContractGW) loadDeployMsgForInstance(addrHex string) (*kldmessages.DeployContract, *contractInfo, error) { +func (g *smartContractGW) loadDeployMsgForInstance(addrHex string) (*messages.DeployContract, *contractInfo, error) { addrHexNo0x := strings.TrimPrefix(strings.ToLower(addrHex), "0x") info, exists := g.contractIndex[addrHexNo0x] if !exists { - return nil, nil, klderrors.Errorf(klderrors.RESTGatewayLocalStoreContractNotFound, addrHexNo0x) + return nil, nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayLocalStoreContractNotFound, addrHexNo0x) } deployMsg, _, err := g.loadDeployMsgByID(info.(*contractInfo).ABI) return deployMsg, info.(*contractInfo), err } -func (g *smartContractGW) loadDeployMsgByID(id string) (*kldmessages.DeployContract, *abiInfo, error) { +func (g *smartContractGW) loadDeployMsgByID(id string) (*messages.DeployContract, *abiInfo, error) { var info *abiInfo - var msg *kldmessages.DeployContract + var msg *messages.DeployContract ts, exists := g.abiIndex[id] if !exists { log.Infof("ABI with ID %s not found locally", id) - return nil, nil, klderrors.Errorf(klderrors.RESTGatewayLocalStoreABINotFound, id) + return nil, nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayLocalStoreABINotFound, id) } deployFile := path.Join(g.conf.StoragePath, "abi_"+id+".deploy.json") deployBytes, err := ioutil.ReadFile(deployFile) if err != nil { - return nil, nil, klderrors.Errorf(klderrors.RESTGatewayLocalStoreABILoad, id, err) + return nil, nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayLocalStoreABILoad, id, err) } - msg = &kldmessages.DeployContract{} + msg = &messages.DeployContract{} if err = json.Unmarshal(deployBytes, msg); err != nil { - return nil, nil, klderrors.Errorf(klderrors.RESTGatewayLocalStoreABIParse, id, err) + return nil, nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayLocalStoreABIParse, id, err) } info = ts.(*abiInfo) return msg, info, nil @@ -392,11 +392,11 @@ func (g *smartContractGW) loadDeployMsgByID(id string) (*kldmessages.DeployContr // - puts the code into the message to avoid a recompile later // - stores the ABI under the MsgID (can later be bound to an address) // *** caller is responsible for ensuring unique Header.ID *** -func (g *smartContractGW) PreDeploy(msg *kldmessages.DeployContract) (err error) { +func (g *smartContractGW) PreDeploy(msg *messages.DeployContract) (err error) { solidity := msg.Solidity - var compiled *kldeth.CompiledSolidity + var compiled *eth.CompiledSolidity if solidity != "" { - if compiled, err = kldeth.CompileContract(solidity, msg.ContractName, msg.CompilerVersion, msg.EVMVersion); err != nil { + if compiled, err = eth.CompileContract(solidity, msg.ContractName, msg.CompilerVersion, msg.EVMVersion); err != nil { return err } } @@ -406,7 +406,7 @@ func (g *smartContractGW) PreDeploy(msg *kldmessages.DeployContract) (err error) return err } -func (g *smartContractGW) storeDeployableABI(msg *kldmessages.DeployContract, compiled *kldeth.CompiledSolidity) (*abiInfo, error) { +func (g *smartContractGW) storeDeployableABI(msg *messages.DeployContract, compiled *eth.CompiledSolidity) (*abiInfo, error) { if compiled != nil { msg.Compiled = compiled.Compiled @@ -415,19 +415,19 @@ func (g *smartContractGW) storeDeployableABI(msg *kldmessages.DeployContract, co msg.ContractName = compiled.ContractName msg.CompilerVersion = compiled.ContractInfo.CompilerVersion } else if msg.ABI == nil { - return nil, klderrors.Errorf(klderrors.RESTGatewayLocalStoreMissingABI) + return nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayLocalStoreMissingABI) } - runtimeABI, err := eth.API.ABIMarshalingToABIRuntime(msg.ABI) + runtimeABI, err := ethbind.API.ABIMarshalingToABIRuntime(msg.ABI) if err != nil { - return nil, klderrors.Errorf(klderrors.RESTGatewayInvalidABI, err) + return nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayInvalidABI, err) } requestID := msg.Headers.ID // We store the swagger in a generic format that can be used to deploy // additional instances, or generically call other instances // Generate and store the swagger - swagger := g.swaggerForABI(kldopenapi.NewABI2Swagger(g.baseSwaggerConf), requestID, msg.ContractName, false, runtimeABI, msg.DevDoc, "", "") + swagger := g.swaggerForABI(openapi.NewABI2Swagger(g.baseSwaggerConf), requestID, msg.ContractName, false, runtimeABI, msg.DevDoc, "", "") msg.Description = swagger.Info.Description // Swagger generation parses the devdoc info := g.addToABIIndex(requestID, msg, time.Now().UTC()) @@ -451,14 +451,14 @@ func (g *smartContractGW) gatewayErrReply(res http.ResponseWriter, req *http.Req return } -func (g *smartContractGW) writeAbiInfo(requestID string, msg *kldmessages.DeployContract) error { +func (g *smartContractGW) writeAbiInfo(requestID string, msg *messages.DeployContract) error { // We store all the details from our compile, or the user-supplied // details, in a file under the message ID. infoFile := path.Join(g.conf.StoragePath, "abi_"+requestID+".deploy.json") infoBytes, _ := json.MarshalIndent(msg, "", " ") log.Infof("%s: Stashing deployment details to '%s'", requestID, infoFile) if err := ioutil.WriteFile(infoFile, infoBytes, 0664); err != nil { - return klderrors.Errorf(klderrors.RESTGatewayLocalStoreContractSavePostDeploy, requestID, err) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayLocalStoreContractSavePostDeploy, requestID, err) } return nil } @@ -507,10 +507,10 @@ func (g *smartContractGW) migrateLegacyContract(address, fileName string, create return } var registeredAs string - if ext, exists := swagger.Info.Extensions["x-kaleido-registered-name"]; exists { + if ext, exists := swagger.Info.Extensions["x-firefly-registered-name"]; exists { registeredAs = ext.(string) } - if ext, exists := swagger.Info.Extensions["x-kaleido-deployment-id"]; exists { + if ext, exists := swagger.Info.Extensions["x-firefly-deployment-id"]; exists { _, err := g.storeNewContractInfo(address, ext.(string), address, registeredAs) if err != nil { log.Errorf("Failed to write migrated instance file: %s", err) @@ -522,7 +522,7 @@ func (g *smartContractGW) migrateLegacyContract(address, fileName string, create } } else { - log.Warnf("Swagger cannot be migrated due to missing 'x-kaleido-deployment-id' extension: %s", fileName) + log.Warnf("Swagger cannot be migrated due to missing 'x-firefly-deployment-id' extension: %s", fileName) } } @@ -550,7 +550,7 @@ func (g *smartContractGW) addFileToABIIndex(id, fileName string, createdTime tim return } defer deployFile.Close() - var deployMsg kldmessages.DeployContract + var deployMsg messages.DeployContract err = json.NewDecoder(bufio.NewReader(deployFile)).Decode(&deployMsg) if err != nil { log.Errorf("Failed to parse ABI deployment file %s: %s", fileName, err) @@ -565,12 +565,12 @@ func (g *smartContractGW) checkNameAvailable(registerAs string, isRemote bool) e if err != nil { return err } else if msg != nil { - return klderrors.Errorf(klderrors.RESTGatewayFriendlyNameClash, msg.Address, registerAs) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayFriendlyNameClash, msg.Address, registerAs) } return nil } if existing, exists := g.contractRegistrations[registerAs]; exists { - return klderrors.Errorf(klderrors.RESTGatewayFriendlyNameClash, existing.Address, registerAs) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayFriendlyNameClash, existing.Address, registerAs) } return nil } @@ -590,7 +590,7 @@ func (g *smartContractGW) addToContractIndex(info *contractInfo) error { return nil } -func (g *smartContractGW) addToABIIndex(id string, deployMsg *kldmessages.DeployContract, createdTime time.Time) *abiInfo { +func (g *smartContractGW) addToABIIndex(id string, deployMsg *messages.DeployContract, createdTime time.Time) *abiInfo { g.idxLock.Lock() info := &abiInfo{ ID: id, @@ -600,7 +600,7 @@ func (g *smartContractGW) addToABIIndex(id string, deployMsg *kldmessages.Deploy CompilerVersion: deployMsg.CompilerVersion, Path: "/abis/" + id, SwaggerURL: g.conf.BaseURL + "/abis/" + id + "?swagger", - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: createdTime.UTC().Format(time.RFC3339), }, } @@ -613,7 +613,7 @@ func (g *smartContractGW) addToABIIndex(id string, deployMsg *kldmessages.Deploy func (g *smartContractGW) listContractsOrABIs(res http.ResponseWriter, req *http.Request, params httprouter.Params) { log.Infof("--> %s %s", req.Method, req.URL) - var index map[string]kldmessages.TimeSortable + var index map[string]messages.TimeSortable if strings.HasSuffix(req.URL.Path, "contracts") { index = g.contractIndex } else { @@ -622,7 +622,7 @@ func (g *smartContractGW) listContractsOrABIs(res http.ResponseWriter, req *http // Get an array copy of the current list g.idxLock.Lock() - retval := make([]kldmessages.TimeSortable, 0, len(index)) + retval := make([]messages.TimeSortable, 0, len(index)) for _, info := range index { retval = append(retval, info) } @@ -651,9 +651,9 @@ func (g *smartContractGW) createStream(res http.ResponseWriter, req *http.Reques return } - var spec kldevents.StreamInfo + var spec events.StreamInfo if err := json.NewDecoder(req.Body).Decode(&spec); err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayEventStreamInvalid, err), 400) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayEventStreamInvalid, err), 400) return } @@ -687,9 +687,9 @@ func (g *smartContractGW) updateStream(res http.ResponseWriter, req *http.Reques g.gatewayErrReply(res, req, err, 404) return } - var spec kldevents.StreamInfo + var spec events.StreamInfo if err := json.NewDecoder(req.Body).Decode(&spec); err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayEventStreamInvalid, err), 400) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayEventStreamInvalid, err), 400) return } newSpec, err := g.sm.UpdateStream(req.Context(), streamID, &spec) @@ -716,16 +716,16 @@ func (g *smartContractGW) listStreamsOrSubs(res http.ResponseWriter, req *http.R return } - var results []kldmessages.TimeSortable - if strings.HasPrefix(req.URL.Path, kldevents.SubPathPrefix) { + var results []messages.TimeSortable + if strings.HasPrefix(req.URL.Path, events.SubPathPrefix) { subs := g.sm.Subscriptions(req.Context()) - results = make([]kldmessages.TimeSortable, len(subs)) + results = make([]messages.TimeSortable, len(subs)) for i := range subs { results[i] = subs[i] } } else { streams := g.sm.Streams(req.Context()) - results = make([]kldmessages.TimeSortable, len(streams)) + results = make([]messages.TimeSortable, len(streams)) for i := range streams { results[i] = streams[i] } @@ -756,7 +756,7 @@ func (g *smartContractGW) getStreamOrSub(res http.ResponseWriter, req *http.Requ var retval interface{} var err error - if strings.HasPrefix(req.URL.Path, kldevents.SubPathPrefix) { + if strings.HasPrefix(req.URL.Path, events.SubPathPrefix) { retval, err = g.sm.SubscriptionByID(req.Context(), params.ByName("id")) } else { retval, err = g.sm.StreamByID(req.Context(), params.ByName("id")) @@ -785,7 +785,7 @@ func (g *smartContractGW) deleteStreamOrSub(res http.ResponseWriter, req *http.R } var err error - if strings.HasPrefix(req.URL.Path, kldevents.SubPathPrefix) { + if strings.HasPrefix(req.URL.Path, events.SubPathPrefix) { err = g.sm.DeleteSubscription(req.Context(), params.ByName("id")) } else { err = g.sm.DeleteStream(req.Context(), params.ByName("id")) @@ -854,7 +854,7 @@ func (g *smartContractGW) suspendOrResumeStream(res http.ResponseWriter, req *ht res.WriteHeader(status) } -func (g *smartContractGW) resolveAddressOrName(id string) (deployMsg *kldmessages.DeployContract, registeredName string, info *contractInfo, err error) { +func (g *smartContractGW) resolveAddressOrName(id string) (deployMsg *messages.DeployContract, registeredName string, info *contractInfo, err error) { deployMsg, info, err = g.loadDeployMsgForInstance(id) if err != nil { var origErr = err @@ -870,7 +870,7 @@ func (g *smartContractGW) resolveAddressOrName(id string) (deployMsg *kldmessage return deployMsg, registeredName, info, err } -func (g *smartContractGW) isSwaggerRequest(req *http.Request) (swaggerGen *kldopenapi.ABI2Swagger, uiRequest, factoryOnly, abiRequest, refreshABI bool, from string) { +func (g *smartContractGW) isSwaggerRequest(req *http.Request) (swaggerGen *openapi.ABI2Swagger, uiRequest, factoryOnly, abiRequest, refreshABI bool, from string) { req.ParseForm() var swaggerRequest bool if vs := req.Form["swagger"]; len(vs) > 0 { @@ -909,7 +909,7 @@ func (g *smartContractGW) isSwaggerRequest(req *http.Request) (swaggerGen *kldop } } } - swaggerGen = kldopenapi.NewABI2Swagger(&conf) + swaggerGen = openapi.NewABI2Swagger(&conf) } return } @@ -946,8 +946,8 @@ func (g *smartContractGW) getContractOrABI(res http.ResponseWriter, req *http.Re // For safety we always check our sanitized address index in memory, before checking the filesystem var registeredName string var err error - var deployMsg *kldmessages.DeployContract - var info kldmessages.TimeSortable + var deployMsg *messages.DeployContract + var info messages.TimeSortable var abiID string if prefix == "contract" { if deployMsg, registeredName, info, err = g.resolveAddressOrName(params.ByName("address")); err != nil { @@ -966,9 +966,9 @@ func (g *smartContractGW) getContractOrABI(res http.ResponseWriter, req *http.Re g.writeHTMLForUI(prefix, id, from, (prefix == "abi"), factoryOnly, res) } else if swaggerGen != nil { addr := params.ByName("address") - runtimeABI, err := eth.API.ABIMarshalingToABIRuntime(deployMsg.ABI) + runtimeABI, err := ethbind.API.ABIMarshalingToABIRuntime(deployMsg.ABI) if err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayInvalidABI, err), 404) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayInvalidABI, err), 404) return } swagger := g.swaggerForABI(swaggerGen, abiID, deployMsg.ContractName, factoryOnly, runtimeABI, deployMsg.DevDoc, addr, registeredName) @@ -995,7 +995,7 @@ func (g *smartContractGW) getRemoteRegistrySwaggerOrABI(res http.ResponseWriter, swaggerGen, uiRequest, factoryOnly, abiRequest, refreshABI, from := g.isSwaggerRequest(req) - var deployMsg *kldmessages.DeployContract + var deployMsg *messages.DeployContract var err error var isGateway = false var prefix, id, addr string @@ -1008,7 +1008,7 @@ func (g *smartContractGW) getRemoteRegistrySwaggerOrABI(res http.ResponseWriter, g.gatewayErrReply(res, req, err, 500) return } else if deployMsg == nil { - err = klderrors.Errorf(klderrors.RemoteRegistryLookupGatewayNotFound) + err = ethconnecterrors.Errorf(ethconnecterrors.RemoteRegistryLookupGatewayNotFound) g.gatewayErrReply(res, req, err, 404) return } @@ -1021,7 +1021,7 @@ func (g *smartContractGW) getRemoteRegistrySwaggerOrABI(res http.ResponseWriter, g.gatewayErrReply(res, req, err, 500) return } else if msg == nil { - err = klderrors.Errorf(klderrors.RemoteRegistryLookupInstanceNotFound) + err = ethconnecterrors.Errorf(ethconnecterrors.RemoteRegistryLookupInstanceNotFound) g.gatewayErrReply(res, req, err, 404) return } @@ -1032,9 +1032,9 @@ func (g *smartContractGW) getRemoteRegistrySwaggerOrABI(res http.ResponseWriter, if uiRequest { g.writeHTMLForUI(prefix, id, from, isGateway, factoryOnly, res) } else if swaggerGen != nil { - runtimeABI, err := eth.API.ABIMarshalingToABIRuntime(deployMsg.ABI) + runtimeABI, err := ethbind.API.ABIMarshalingToABIRuntime(deployMsg.ABI) if err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayInvalidABI, err), 400) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayInvalidABI, err), 400) return } swagger := g.swaggerForRemoteRegistry(swaggerGen, id, addr, factoryOnly, runtimeABI, deployMsg.DevDoc, req.URL.Path) @@ -1067,7 +1067,7 @@ func (g *smartContractGW) registerContract(res http.ResponseWriter, req *http.Re addrHexNo0x := strings.ToLower(strings.TrimPrefix(params.ByName("address"), "0x")) addrCheck, _ := regexp.Compile("^[0-9a-z]{40}$") if !addrCheck.MatchString(addrHexNo0x) { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayRegistrationSuppliedInvalidAddress), 404) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayRegistrationSuppliedInvalidAddress), 404) return } @@ -1080,7 +1080,7 @@ func (g *smartContractGW) registerContract(res http.ResponseWriter, req *http.Re return } - registerAs := getKLDParam("register", req, false) + registerAs := getFlyParam("register", req, false) registeredName := registerAs if registeredName == "" { registeredName = addrHexNo0x @@ -1100,7 +1100,7 @@ func (g *smartContractGW) registerContract(res http.ResponseWriter, req *http.Re } func tempdir() string { - dir, _ := ioutil.TempDir("", "kld") + dir, _ := ioutil.TempDir("", "fly") log.Infof("tmpdir/create: %s", dir) return dir } @@ -1114,7 +1114,7 @@ func (g *smartContractGW) addABI(res http.ResponseWriter, req *http.Request, par log.Infof("--> %s %s", req.Method, req.URL) if err := req.ParseMultipartForm(maxFormParsingMemory); err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayCompileContractInvalidFormData, err), 400) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractInvalidFormData, err), 400) return } @@ -1149,13 +1149,13 @@ func (g *smartContractGW) addABI(res http.ResponseWriter, req *http.Request, par abi, err := g.parseABI(req.Form) if err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayCompileContractInvalidFormData, err), 400) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractInvalidFormData, err), 400) return } bytecode, err := g.parseBytecode(req.Form) if err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayCompileContractInvalidFormData, err), 400) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractInvalidFormData, err), 400) return } @@ -1164,7 +1164,7 @@ func (g *smartContractGW) addABI(res http.ResponseWriter, req *http.Request, par var err error preCompiled, err = g.compileMultipartFormSolidity(tempdir, req) if err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayCompileContractCompileFailed, err), 400) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractCompileFailed, err), 400) return } } @@ -1181,15 +1181,15 @@ func (g *smartContractGW) addABI(res http.ResponseWriter, req *http.Request, par return } - msg := &kldmessages.DeployContract{} - msg.Headers.MsgType = kldmessages.MsgTypeSendTransaction - msg.Headers.ID = kldutils.UUIDv4() - var compiled *kldeth.CompiledSolidity + msg := &messages.DeployContract{} + msg.Headers.MsgType = messages.MsgTypeSendTransaction + msg.Headers.ID = utils.UUIDv4() + var compiled *eth.CompiledSolidity if bytecode == nil && abi == nil { var err error - compiled, err = kldeth.ProcessCompiled(preCompiled, req.FormValue("contract"), false) + compiled, err = eth.ProcessCompiled(preCompiled, req.FormValue("contract"), false) if err != nil { - g.gatewayErrReply(res, req, klderrors.Errorf(klderrors.RESTGatewayCompileContractPostCompileFailed, err), 400) + g.gatewayErrReply(res, req, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractPostCompileFailed, err), 400) return } } else { @@ -1243,7 +1243,7 @@ func (g *smartContractGW) compileMultipartFormSolidity(dir string, req *http.Req rootFiles, err := ioutil.ReadDir(dir) if err != nil { log.Errorf("Failed to read dir '%s': %s", dir, err) - return nil, klderrors.Errorf(klderrors.RESTGatewayCompileContractExtractedReadFailed) + return nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractExtractedReadFailed) } for _, file := range rootFiles { log.Debugf("multi-part: '%s' [dir=%t]", file.Name(), file.IsDir()) @@ -1253,18 +1253,18 @@ func (g *smartContractGW) compileMultipartFormSolidity(dir string, req *http.Req } evmVersion := req.FormValue("evm") - solcArgs := kldeth.GetSolcArgs(evmVersion) + solcArgs := eth.GetSolcArgs(evmVersion) if sourceFiles := req.Form["source"]; len(sourceFiles) > 0 { solcArgs = append(solcArgs, sourceFiles...) } else if len(solFiles) > 0 { solcArgs = append(solcArgs, solFiles...) } else { - return nil, klderrors.Errorf(klderrors.RESTGatewayCompileContractNoSOL) + return nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractNoSOL) } - solcVer, err := kldeth.GetSolc(req.FormValue("compiler")) + solcVer, err := eth.GetSolc(req.FormValue("compiler")) if err != nil { - return nil, klderrors.Errorf(klderrors.RESTGatewayCompileContractSolcVerFail, err) + return nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractSolcVerFail, err) } solOptionsString := strings.Join(append([]string{solcVer.Path}, solcArgs...), " ") log.Infof("Compiling: %s", solOptionsString) @@ -1275,12 +1275,12 @@ func (g *smartContractGW) compileMultipartFormSolidity(dir string, req *http.Req cmd.Stdout = &stdout cmd.Dir = dir if err := cmd.Run(); err != nil { - return nil, klderrors.Errorf(klderrors.RESTGatewayCompileContractCompileFailDetails, err, stderr.String()) + return nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractCompileFailDetails, err, stderr.String()) } - compiled, err := eth.API.ParseCombinedJSON(stdout.Bytes(), "", solcVer.Version, solcVer.Version, solOptionsString) + compiled, err := ethbind.API.ParseCombinedJSON(stdout.Bytes(), "", solcVer.Version, solcVer.Version, solOptionsString) if err != nil { - return nil, klderrors.Errorf(klderrors.RESTGatewayCompileContractSolcOutputProcessFail, err) + return nil, ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractSolcOutputProcessFail, err) } return compiled, nil @@ -1289,24 +1289,24 @@ func (g *smartContractGW) compileMultipartFormSolidity(dir string, req *http.Req func (g *smartContractGW) extractMultiPartFile(dir string, file *multipart.FileHeader) error { fileName := file.Filename if strings.ContainsAny(fileName, "/\\") { - return klderrors.Errorf(klderrors.RESTGatewayCompileContractSlashes) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractSlashes) } in, err := file.Open() if err != nil { log.Errorf("Failed opening '%s' for reading: %s", fileName, err) - return klderrors.Errorf(klderrors.RESTGatewayCompileContractUnzipRead) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractUnzipRead) } defer in.Close() outFileName := path.Join(dir, fileName) out, err := os.OpenFile(outFileName, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { log.Errorf("Failed opening '%s' for writing: %s", fileName, err) - return klderrors.Errorf(klderrors.RESTGatewayCompileContractUnzipWrite) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractUnzipWrite) } written, err := io.Copy(out, in) if err != nil { log.Errorf("Failed writing '%s' from multi-part form: %s", fileName, err) - return klderrors.Errorf(klderrors.RESTGatewayCompileContractUnzipCopy) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractUnzipCopy) } log.Debugf("multi-part: '%s' [%dKb]", fileName, written/1024) return g.processIfArchive(dir, outFileName) @@ -1320,7 +1320,7 @@ func (g *smartContractGW) processIfArchive(dir, fileName string) error { } err = z.(archiver.Unarchiver).Unarchive(fileName, dir) if err != nil { - return klderrors.Errorf(klderrors.RESTGatewayCompileContractUnzip, err) + return ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayCompileContractUnzip, err) } return nil } @@ -1349,12 +1349,12 @@ func (g *smartContractGW) writeHTMLForUI(prefix, id, from string, isGateway, fac factoryOnlyQuery = "&factory" helpHeader = `

Factory API to deploy contract instances

Use the [POST] panel below to set the input parameters for your constructor, and tick [TRY] to deploy a contract instance.

-

If you want to configure a friendly API path name to invoke your contract, then set the kld-register parameter.

` +

If you want to configure a friendly API path name to invoke your contract, then set the fly-register parameter.

` } else { hasMethodsMessage = `
  • GET actions never write to the chain. Even for actions that update state - so you can simulate execution
  • POST actions against /subscribe paths marked [event] add subscriptions to event streams
      -
    • Pre-configure your event streams with actions in the Kaleido console, or via the /eventstreams API route on Ethconnect
    • +
    • Pre-configure your event streams with actions via the /eventstreams API route on Ethconnect
    • Once you add a subscription, all matching events will be reliably read, batched and delivered over your event stream
  • Data type conversion is automatic for all actions an events. @@ -1382,27 +1382,29 @@ func (g *smartContractGW) writeHTMLForUI(prefix, id, from string, isGateway, fac theme="light" primary-color="#3842C1" > +
    ` + helpHeader + ` -

    Show additional instructions

    - diff --git a/internal/kldcontracts/smartcontractgw_test.go b/internal/contracts/smartcontractgw_test.go similarity index 88% rename from internal/kldcontracts/smartcontractgw_test.go rename to internal/contracts/smartcontractgw_test.go index 5e5ffec5..dc348cd9 100644 --- a/internal/kldcontracts/smartcontractgw_test.go +++ b/internal/contracts/smartcontractgw_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "archive/zip" @@ -29,16 +29,15 @@ import ( "testing" "time" - ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldauth/kldauthtest" - "github.com/go-openapi/spec" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/kldevents" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" + ethbinding "github.com/kaleido-io/ethbinding/pkg" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/auth/authtest" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/events" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" @@ -85,7 +84,7 @@ func TestNewSmartContractGatewayBadURL(t *testing.T) { &SmartContractGatewayConf{ BaseURL: " :", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -99,11 +98,11 @@ func TestNewSmartContractGatewayWithEvents(t *testing.T) { s, err := NewSmartContractGateway( &SmartContractGatewayConf{ BaseURL: "http://localhost/api/v1", - SubscriptionManagerConf: kldevents.SubscriptionManagerConf{ + SubscriptionManagerConf: events.SubscriptionManagerConf{ EventLevelDBPath: path.Join(dir, "db"), }, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -121,11 +120,11 @@ func TestNewSmartContractGatewayWithEventsFail(t *testing.T) { _, err := NewSmartContractGateway( &SmartContractGatewayConf{ BaseURL: "http://localhost/api/v1", - SubscriptionManagerConf: kldevents.SubscriptionManagerConf{ + SubscriptionManagerConf: events.SubscriptionManagerConf{ EventLevelDBPath: dbpath, }, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -136,7 +135,7 @@ func TestNewSmartContractGatewayWithEventsFail(t *testing.T) { func TestPreDeployCompileAndPostDeploy(t *testing.T) { // writes real files and tests end to end assert := assert.New(t) - msg := kldmessages.DeployContract{ + msg := messages.DeployContract{ Solidity: simpleEventsSource(), RegisterAs: "Test 1", } @@ -149,7 +148,7 @@ func TestPreDeployCompileAndPostDeploy(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -166,18 +165,18 @@ func TestPreDeployCompileAndPostDeploy(t *testing.T) { deployStashBytes, err := ioutil.ReadFile(path.Join(dir, "abi_message1.deploy.json")) assert.NoError(err) - var deployStash kldmessages.DeployContract + var deployStash messages.DeployContract err = json.Unmarshal(deployStashBytes, &deployStash) assert.NoError(err) assert.NotEmpty(deployStash.CompilerVersion) - contractAddr := eth.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") - receipt := kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ + contractAddr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") + receipt := messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ ID: "message2", - MsgType: kldmessages.MsgTypeTransactionSuccess, + MsgType: messages.MsgTypeTransactionSuccess, }, ReqID: "message1", }, @@ -191,7 +190,7 @@ func TestPreDeployCompileAndPostDeploy(t *testing.T) { deployMsg, abiID, err := scgw.(*smartContractGW).loadDeployMsgForInstance("0123456789abcdef0123456789abcdef01234567") assert.NoError(err) assert.NotEmpty(abiID) - runtimeABI, err := eth.API.ABIMarshalingToABIRuntime(deployMsg.ABI) + runtimeABI, err := ethbind.API.ABIMarshalingToABIRuntime(deployMsg.ABI) assert.NoError(err) assert.Equal("set", runtimeABI.Methods["set"].Name) @@ -297,7 +296,7 @@ func TestRegisterExistingContract(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -321,7 +320,7 @@ func TestRegisterExistingContract(t *testing.T) { json.NewDecoder(res.Body).Decode(&abi) assert.NotEmpty(abi.ID) - req = httptest.NewRequest("POST", "/abis/"+abi.ID+"/0x0123456789abcdef0123456789abcdef01234567?kld-register=testcontract", bytes.NewReader([]byte{})) + req = httptest.NewRequest("POST", "/abis/"+abi.ID+"/0x0123456789abcdef0123456789abcdef01234567?fly-register=testcontract", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) var contract contractInfo @@ -329,7 +328,7 @@ func TestRegisterExistingContract(t *testing.T) { assert.Equal(201, res.Code) assert.Equal("/contracts/testcontract", contract.Path) - req = httptest.NewRequest("POST", "/abis/"+abi.ID+"/0x0123456789abcdef0123456789abcdef01234567?kld-register=testcontract", bytes.NewReader([]byte{})) + req = httptest.NewRequest("POST", "/abis/"+abi.ID+"/0x0123456789abcdef0123456789abcdef01234567?fly-register=testcontract", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) var errBody map[string]interface{} @@ -343,7 +342,7 @@ func TestRegisterExistingContract(t *testing.T) { returnedSwagger := spec.Swagger{} assert.Equal(200, res.Code) json.NewDecoder(res.Body).Decode(&returnedSwagger) - assert.Equal("testcontract", returnedSwagger.Info.Extensions["x-kaleido-registered-name"]) + assert.Equal("testcontract", returnedSwagger.Info.Extensions["x-firefly-registered-name"]) assert.Equal("/api/v1/contracts/testcontract", returnedSwagger.BasePath) } @@ -355,7 +354,7 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { &SmartContractGatewayConf{ BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -463,7 +462,7 @@ func TestRemoteRegistryBadBI(t *testing.T) { &SmartContractGatewayConf{ BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -508,7 +507,7 @@ func TestRegisterContractBadAddress(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -536,7 +535,7 @@ func TestRegisterContractNoRegisteredName(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -581,7 +580,7 @@ func TestRegisterContractBadABI(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -606,13 +605,13 @@ func TestLoadDeployMsgOKNoABIInIndex(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, ) scgw := s.(*smartContractGW) - goodMsg := &kldmessages.DeployContract{} + goodMsg := &messages.DeployContract{} deployBytes, _ := json.Marshal(goodMsg) scgw.abiIndex["abi1"] = &abiInfo{} ioutil.WriteFile(path.Join(dir, "abi_abi1.deploy.json"), deployBytes, 0644) @@ -628,7 +627,7 @@ func TestLoadDeployMsgMissing(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -646,7 +645,7 @@ func TestLoadDeployMsgFailure(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -666,7 +665,7 @@ func TestLoadDeployMsgRemoteLookupNotFound(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -684,13 +683,13 @@ func TestPreDeployCompileFailure(t *testing.T) { &SmartContractGatewayConf{ StoragePath: "/anypath", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, ) scgw := s.(*smartContractGW) - msg := &kldmessages.DeployContract{ + msg := &messages.DeployContract{ Solidity: "bad solidity", } err := scgw.PreDeploy(msg) @@ -705,13 +704,13 @@ func TestPreDeployMsgWrite(t *testing.T) { &SmartContractGatewayConf{ StoragePath: path.Join(dir, "badpath"), }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, ) scgw := s.(*smartContractGW) - msg := &kldmessages.DeployContract{ + msg := &messages.DeployContract{ Solidity: simpleEventsSource(), } @@ -728,18 +727,18 @@ func TestPostDeployNoRegisteredName(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, ) - contractAddr := eth.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") + contractAddr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") scgw := s.(*smartContractGW) - replyMsg := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeTransactionSuccess, + replyMsg := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeTransactionSuccess, }, ReqID: "message1", }, @@ -748,7 +747,7 @@ func TestPostDeployNoRegisteredName(t *testing.T) { } deployFile := path.Join(dir, "abi_message1.deploy.json") - deployMsg := &kldmessages.DeployContract{} + deployMsg := &messages.DeployContract{} deployBytes, _ := json.Marshal(deployMsg) ioutil.WriteFile(deployFile, deployBytes, 0644) err := scgw.PostDeploy(replyMsg) @@ -768,7 +767,7 @@ func TestPostDeployRemoteRegisteredName(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -776,16 +775,16 @@ func TestPostDeployRemoteRegisteredName(t *testing.T) { rr := &mockRR{} s.(*smartContractGW).rr = rr - contractAddr := eth.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") + contractAddr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") scgw := s.(*smartContractGW) - replyMsg := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ + replyMsg := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ Context: map[string]interface{}{ remoteRegistryContextKey: true, }, - MsgType: kldmessages.MsgTypeTransactionSuccess, + MsgType: messages.MsgTypeTransactionSuccess, }, ReqID: "message1", }, @@ -795,7 +794,7 @@ func TestPostDeployRemoteRegisteredName(t *testing.T) { } deployFile := path.Join(dir, "abi_message1.deploy.json") - deployMsg := &kldmessages.DeployContract{} + deployMsg := &messages.DeployContract{} deployBytes, _ := json.Marshal(deployMsg) ioutil.WriteFile(deployFile, deployBytes, 0644) err := scgw.PostDeploy(replyMsg) @@ -814,7 +813,7 @@ func TestPostDeployRemoteRegisteredNameNotSuccess(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -822,16 +821,16 @@ func TestPostDeployRemoteRegisteredNameNotSuccess(t *testing.T) { rr := &mockRR{} s.(*smartContractGW).rr = rr - contractAddr := eth.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") + contractAddr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") scgw := s.(*smartContractGW) - replyMsg := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ + replyMsg := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ + CommonHeaders: messages.CommonHeaders{ Context: map[string]interface{}{ remoteRegistryContextKey: true, }, - MsgType: kldmessages.MsgTypeTransactionFailure, + MsgType: messages.MsgTypeTransactionFailure, }, ReqID: "message1", }, @@ -841,7 +840,7 @@ func TestPostDeployRemoteRegisteredNameNotSuccess(t *testing.T) { } deployFile := path.Join(dir, "abi_message1.deploy.json") - deployMsg := &kldmessages.DeployContract{} + deployMsg := &messages.DeployContract{} deployBytes, _ := json.Marshal(deployMsg) ioutil.WriteFile(deployFile, deployBytes, 0644) err := scgw.PostDeploy(replyMsg) @@ -859,15 +858,15 @@ func TestPostDeployMissingContractAddress(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, ) scgw := s.(*smartContractGW) - replyMsg := &kldmessages.TransactionReceipt{ - ReplyCommon: kldmessages.ReplyCommon{ - Headers: kldmessages.ReplyHeaders{ + replyMsg := &messages.TransactionReceipt{ + ReplyCommon: messages.ReplyCommon{ + Headers: messages.ReplyHeaders{ ReqID: "message1", }, }, @@ -886,7 +885,7 @@ func TestStoreABIWriteFail(t *testing.T) { &SmartContractGatewayConf{ StoragePath: path.Join(dir, "badpath"), }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -908,7 +907,7 @@ func TestLoadABIForInstanceUnknown(t *testing.T) { &SmartContractGatewayConf{ StoragePath: path.Join(dir, "badpath"), }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -927,7 +926,7 @@ func TestLoadABIBadData(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -959,7 +958,7 @@ func TestBuildIndex(t *testing.T) { }, }, } - okSwagger.Info.AddExtension("x-kaleido-deployment-id", "840b629f-2e46-413b-9671-553a886ca7bb") + okSwagger.Info.AddExtension("x-firefly-deployment-id", "840b629f-2e46-413b-9671-553a886ca7bb") swaggerBytes, _ = json.Marshal(&okSwagger) ioutil.WriteFile(path.Join(dir, "contract_123456789abcdef0123456789abcdef012345678.swagger.json"), swaggerBytes, 0644) @@ -972,8 +971,8 @@ func TestBuildIndex(t *testing.T) { }, }, } - regSwagger.Info.AddExtension("x-kaleido-deployment-id", "840b629f-2e46-413b-9671-553a886ca7bb") - regSwagger.Info.AddExtension("x-kaleido-registered-name", "migratedcontract") + regSwagger.Info.AddExtension("x-firefly-deployment-id", "840b629f-2e46-413b-9671-553a886ca7bb") + regSwagger.Info.AddExtension("x-firefly-registered-name", "migratedcontract") swaggerBytes, _ = json.Marshal(®Swagger) ioutil.WriteFile(path.Join(dir, "contract_23456789abcdef0123456789abcdef0123456789.swagger.json"), swaggerBytes, 0644) @@ -986,7 +985,7 @@ func TestBuildIndex(t *testing.T) { Path: "/contracts/456789abcdef0123456789abcdef012345678901", SwaggerURL: "http://localhost:8080/contracts/456789abcdef0123456789abcdef012345678901?swagger", RegisteredAs: "", - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: time.Now().UTC().Format(time.RFC3339), }, } @@ -998,14 +997,14 @@ func TestBuildIndex(t *testing.T) { Path: "/contracts/somecontract", SwaggerURL: "http://localhost:8080/contracts/somecontract?swagger", RegisteredAs: "somecontract", - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: time.Now().UTC().Format(time.RFC3339), }, } info2Bytes, _ := json.Marshal(info2) ioutil.WriteFile(path.Join(dir, "contract_56789abcdef0123456789abcdef0123456789012.instance.json"), info2Bytes, 0644) - deployMsg := &kldmessages.DeployContract{ + deployMsg := &messages.DeployContract{ ContractName: "abideployable", } deployBytes, _ := json.Marshal(&deployMsg) @@ -1017,7 +1016,7 @@ func TestBuildIndex(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1072,7 +1071,7 @@ func TestGetContractOrABIFail(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -1126,7 +1125,7 @@ func TestGetContractUI(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -1160,7 +1159,7 @@ func TestAddABISingleSolidity(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1197,7 +1196,7 @@ func TestAddABISingleSolidityBadContractName(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1229,7 +1228,7 @@ func TestAddABIZipNested(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1270,7 +1269,7 @@ func TestAddABIZipNestedListSolidity(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1312,7 +1311,7 @@ func TestAddABIZipNestedListContracts(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1354,7 +1353,7 @@ func TestAddABIBadZip(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1391,7 +1390,7 @@ func TestAddABIZipNestedNoSource(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1431,7 +1430,7 @@ func TestAddABIZiNotMultipart(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1461,7 +1460,7 @@ func TestCompileMultipartFormSolidityBadDir(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1482,19 +1481,19 @@ func TestCompileMultipartFormSolidityBadSolc(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, ) scgw := s.(*smartContractGW) - os.Setenv("KLD_SOLC_0_99", "badness") + os.Setenv("FLY_SOLC_0_99", "badness") ioutil.WriteFile(path.Join(dir, "solidity.sol"), []byte(simpleEventsSource()), 0644) req := httptest.NewRequest("POST", "/abis?compiler=0.99", bytes.NewReader([]byte{})) _, err := scgw.compileMultipartFormSolidity(dir, req) assert.Regexp("Failed checking solc version", err.Error()) - os.Unsetenv("KLD_SOLC_0_99") + os.Unsetenv("FLY_SOLC_0_99") } func TestCompileMultipartFormSolidityBadCompilerVerReq(t *testing.T) { @@ -1507,7 +1506,7 @@ func TestCompileMultipartFormSolidityBadCompilerVerReq(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -1530,7 +1529,7 @@ func TestCompileMultipartFormSolidityBadSolidity(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -1553,7 +1552,7 @@ func TestExtractMultiPartFileBadFile(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -1576,7 +1575,7 @@ func TestExtractMultiPartFileBadInput(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -1599,14 +1598,14 @@ func TestStoreDeployableABIMissingABI(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, ) scgw := s.(*smartContractGW) - _, err := scgw.storeDeployableABI(&kldmessages.DeployContract{}, nil) + _, err := scgw.storeDeployableABI(&messages.DeployContract{}, nil) assert.EqualError(err, "Must supply ABI to install an existing ABI into the REST Gateway") } @@ -1618,7 +1617,7 @@ func TestAddFileToContractIndexBadFileSwallowsError(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -1636,7 +1635,7 @@ func TestAddFileToContractIndexBadDataSwallowsError(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -1656,7 +1655,7 @@ func TestAddFileToABIIndexBadFileSwallowsError(t *testing.T) { &SmartContractGatewayConf{ StoragePath: dir, }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: true, }, nil, nil, nil, nil, @@ -1686,22 +1685,22 @@ func testGWPathBody(method, path string, results interface{}, sm *mockSubMgr, bo func TestAddStreamNoSubMgr(t *testing.T) { assert := assert.New(t) - res := testGWPath("POST", kldevents.StreamPathPrefix, nil, nil) + res := testGWPath("POST", events.StreamPathPrefix, nil, nil) assert.Equal(405, res.Result().StatusCode) } func TestAddStreamOK(t *testing.T) { assert := assert.New(t) - spec := &kldevents.StreamInfo{Type: "webhook", Name: "stream-1", Timestamps: true} + spec := &events.StreamInfo{Type: "webhook", Name: "stream-1", Timestamps: true} b, _ := json.Marshal(spec) - req := httptest.NewRequest("POST", kldevents.StreamPathPrefix, bytes.NewReader(b)) + req := httptest.NewRequest("POST", events.StreamPathPrefix, bytes.NewReader(b)) res := httptest.NewRecorder() s := &smartContractGW{} s.sm = &mockSubMgr{} r := &httprouter.Router{} s.AddRoutes(r) r.ServeHTTP(res, req) - var newSpec kldevents.StreamInfo + var newSpec events.StreamInfo json.NewDecoder(res.Body).Decode(&newSpec) assert.Equal(200, res.Result().StatusCode) assert.Equal("webhook", newSpec.Type) @@ -1712,16 +1711,16 @@ func TestAddStreamOK(t *testing.T) { func TestAddStreamDefaultNoTimestamps(t *testing.T) { assert := assert.New(t) - spec := &kldevents.StreamInfo{Type: "webhook", Name: "stream-no-timestamps"} + spec := &events.StreamInfo{Type: "webhook", Name: "stream-no-timestamps"} b, _ := json.Marshal(spec) - req := httptest.NewRequest("POST", kldevents.StreamPathPrefix, bytes.NewReader(b)) + req := httptest.NewRequest("POST", events.StreamPathPrefix, bytes.NewReader(b)) res := httptest.NewRecorder() s := &smartContractGW{} s.sm = &mockSubMgr{} r := &httprouter.Router{} s.AddRoutes(r) r.ServeHTTP(res, req) - var newSpec kldevents.StreamInfo + var newSpec events.StreamInfo json.NewDecoder(res.Body).Decode(&newSpec) assert.Equal(200, res.Result().StatusCode) assert.Equal("webhook", newSpec.Type) @@ -1732,7 +1731,7 @@ func TestAddStreamDefaultNoTimestamps(t *testing.T) { func TestAddStreamBadData(t *testing.T) { assert := assert.New(t) - req := httptest.NewRequest("POST", kldevents.StreamPathPrefix, bytes.NewReader([]byte(":bad json"))) + req := httptest.NewRequest("POST", events.StreamPathPrefix, bytes.NewReader([]byte(":bad json"))) res := httptest.NewRecorder() s := &smartContractGW{} s.sm = &mockSubMgr{} @@ -1747,9 +1746,9 @@ func TestAddStreamBadData(t *testing.T) { func TestAddStreamSubMgrError(t *testing.T) { assert := assert.New(t) - spec := &kldevents.StreamInfo{Type: "webhook"} + spec := &events.StreamInfo{Type: "webhook"} b, _ := json.Marshal(spec) - req := httptest.NewRequest("POST", kldevents.StreamPathPrefix, bytes.NewReader(b)) + req := httptest.NewRequest("POST", events.StreamPathPrefix, bytes.NewReader(b)) res := httptest.NewRecorder() s := &smartContractGW{} s.sm = &mockSubMgr{err: fmt.Errorf("pop")} @@ -1764,16 +1763,16 @@ func TestAddStreamSubMgrError(t *testing.T) { func TestUpdateStreamNoSubMgr(t *testing.T) { assert := assert.New(t) - res := testGWPath("PATCH", kldevents.StreamPathPrefix+"/123", nil, nil) + res := testGWPath("PATCH", events.StreamPathPrefix+"/123", nil, nil) assert.Equal(405, res.Result().StatusCode) } func TestUpdateStreamOK(t *testing.T) { assert := assert.New(t) - updatedSpec := &kldevents.StreamInfo{Type: "webhook", Name: "stream-new-name", ID: "123", Timestamps: true} - modSpec := &kldevents.StreamInfo{Timestamps: true} + updatedSpec := &events.StreamInfo{Type: "webhook", Name: "stream-new-name", ID: "123", Timestamps: true} + modSpec := &events.StreamInfo{Timestamps: true} b, _ := json.Marshal(modSpec) - req := httptest.NewRequest("PATCH", kldevents.StreamPathPrefix+"/123", bytes.NewReader(b)) + req := httptest.NewRequest("PATCH", events.StreamPathPrefix+"/123", bytes.NewReader(b)) res := httptest.NewRecorder() s := &smartContractGW{} s.sm = &mockSubMgr{ @@ -1782,7 +1781,7 @@ func TestUpdateStreamOK(t *testing.T) { r := &httprouter.Router{} s.AddRoutes(r) r.ServeHTTP(res, req) - var newSpec kldevents.StreamInfo + var newSpec events.StreamInfo json.NewDecoder(res.Body).Decode(&newSpec) assert.Equal(true, newSpec.Timestamps) assert.Equal(200, res.Result().StatusCode) @@ -1791,7 +1790,7 @@ func TestUpdateStreamOK(t *testing.T) { func TestUpdateStreamBadData(t *testing.T) { assert := assert.New(t) - req := httptest.NewRequest("PATCH", kldevents.StreamPathPrefix+"/123", bytes.NewReader([]byte(":bad json"))) + req := httptest.NewRequest("PATCH", events.StreamPathPrefix+"/123", bytes.NewReader([]byte(":bad json"))) res := httptest.NewRecorder() s := &smartContractGW{} s.sm = &mockSubMgr{} @@ -1806,9 +1805,9 @@ func TestUpdateStreamBadData(t *testing.T) { func TestUpdateStreamNotFoundError(t *testing.T) { assert := assert.New(t) - spec := &kldevents.StreamInfo{Type: "webhook", ID: "123"} + spec := &events.StreamInfo{Type: "webhook", ID: "123"} b, _ := json.Marshal(spec) - req := httptest.NewRequest("PATCH", kldevents.StreamPathPrefix+"/123", bytes.NewReader(b)) + req := httptest.NewRequest("PATCH", events.StreamPathPrefix+"/123", bytes.NewReader(b)) res := httptest.NewRecorder() s := &smartContractGW{} s.sm = &mockSubMgr{err: fmt.Errorf("pop")} @@ -1823,10 +1822,10 @@ func TestUpdateStreamNotFoundError(t *testing.T) { func TestUpdateStreamSubMgrError(t *testing.T) { assert := assert.New(t) - spec := &kldevents.StreamInfo{Type: "webhook", ID: "123"} - updatedSpec := &kldevents.StreamInfo{Timestamps: true} + spec := &events.StreamInfo{Type: "webhook", ID: "123"} + updatedSpec := &events.StreamInfo{Timestamps: true} b, _ := json.Marshal(updatedSpec) - req := httptest.NewRequest("PATCH", kldevents.StreamPathPrefix+"/123", bytes.NewReader(b)) + req := httptest.NewRequest("PATCH", events.StreamPathPrefix+"/123", bytes.NewReader(b)) res := httptest.NewRecorder() s := &smartContractGW{} s.sm = &mockSubMgr{ @@ -1845,7 +1844,7 @@ func TestUpdateStreamSubMgrError(t *testing.T) { func TestListStreamsNoSubMgr(t *testing.T) { assert := assert.New(t) - res := testGWPath("GET", kldevents.StreamPathPrefix, nil, nil) + res := testGWPath("GET", events.StreamPathPrefix, nil, nil) assert.Equal(405, res.Result().StatusCode) } @@ -1853,21 +1852,21 @@ func TestListStreams(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{ - streams: []*kldevents.StreamInfo{ + streams: []*events.StreamInfo{ { - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: time.Now().UTC().Format(time.RFC3339), }, ID: "earlier", Name: "stream-1", }, { - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: time.Now().UTC().Add(1 * time.Hour).Format(time.RFC3339), }, ID: "later", Name: "stream-2", }, }, } - var results []*kldevents.StreamInfo - res := testGWPath("GET", kldevents.StreamPathPrefix, &results, mockSubMgr) + var results []*events.StreamInfo + res := testGWPath("GET", events.StreamPathPrefix, &results, mockSubMgr) assert.Equal(200, res.Result().StatusCode) assert.Equal(2, len(results)) assert.Equal("later", results[0].ID) @@ -1880,21 +1879,21 @@ func TestListSubs(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{ - subs: []*kldevents.SubscriptionInfo{ + subs: []*events.SubscriptionInfo{ { - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: time.Now().UTC().Format(time.RFC3339), }, ID: "earlier", }, { - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: time.Now().UTC().Add(1 * time.Hour).Format(time.RFC3339), }, ID: "later", }, }, } - var results []*kldevents.SubscriptionInfo - res := testGWPath("GET", kldevents.SubPathPrefix, &results, mockSubMgr) + var results []*events.SubscriptionInfo + res := testGWPath("GET", events.SubPathPrefix, &results, mockSubMgr) assert.Equal(200, res.Result().StatusCode) assert.Equal(2, len(results)) assert.Equal("later", results[0].ID) @@ -1905,10 +1904,10 @@ func TestGetSub(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{ - sub: &kldevents.SubscriptionInfo{ID: "123"}, + sub: &events.SubscriptionInfo{ID: "123"}, } - var result kldevents.SubscriptionInfo - res := testGWPath("GET", kldevents.SubPathPrefix+"/123", &result, mockSubMgr) + var result events.SubscriptionInfo + res := testGWPath("GET", events.SubPathPrefix+"/123", &result, mockSubMgr) assert.Equal(200, res.Result().StatusCode) assert.Equal("123", result.ID) } @@ -1917,10 +1916,10 @@ func TestGetStream(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{ - stream: &kldevents.StreamInfo{ID: "123"}, + stream: &events.StreamInfo{ID: "123"}, } - var result kldevents.StreamInfo - res := testGWPath("GET", kldevents.StreamPathPrefix+"/123", &result, mockSubMgr) + var result events.StreamInfo + res := testGWPath("GET", events.StreamPathPrefix+"/123", &result, mockSubMgr) assert.Equal(200, res.Result().StatusCode) assert.Equal("123", result.ID) } @@ -1928,8 +1927,8 @@ func TestGetStream(t *testing.T) { func TestGetSubNoSubMgr(t *testing.T) { assert := assert.New(t) - var result kldevents.SubscriptionInfo - res := testGWPath("GET", kldevents.SubPathPrefix+"/123", &result, nil) + var result events.SubscriptionInfo + res := testGWPath("GET", events.SubPathPrefix+"/123", &result, nil) assert.Equal(405, res.Result().StatusCode) } @@ -1937,8 +1936,8 @@ func TestGetSubNotFound(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{err: fmt.Errorf("not found")} - var result kldevents.SubscriptionInfo - res := testGWPath("GET", kldevents.SubPathPrefix+"/123", &result, mockSubMgr) + var result events.SubscriptionInfo + res := testGWPath("GET", events.SubPathPrefix+"/123", &result, mockSubMgr) assert.Equal(404, res.Result().StatusCode) } @@ -1946,7 +1945,7 @@ func TestDeleteSub(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{} - res := testGWPath("DELETE", kldevents.SubPathPrefix+"/123", nil, mockSubMgr) + res := testGWPath("DELETE", events.SubPathPrefix+"/123", nil, mockSubMgr) assert.Equal(204, res.Result().StatusCode) } @@ -1958,7 +1957,7 @@ func TestResetSub(t *testing.T) { } b, _ := json.Marshal(&reqData) mockSubMgr := &mockSubMgr{} - res := testGWPathBody("POST", kldevents.SubPathPrefix+"/123/reset", nil, mockSubMgr, bytes.NewReader(b)) + res := testGWPathBody("POST", events.SubPathPrefix+"/123/reset", nil, mockSubMgr, bytes.NewReader(b)) assert.Equal(204, res.Result().StatusCode) } @@ -1972,13 +1971,13 @@ func TestResetSubFail(t *testing.T) { mockSubMgr := &mockSubMgr{ err: fmt.Errorf("pop"), } - res := testGWPathBody("POST", kldevents.SubPathPrefix+"/123/reset", nil, mockSubMgr, bytes.NewReader(b)) + res := testGWPathBody("POST", events.SubPathPrefix+"/123/reset", nil, mockSubMgr, bytes.NewReader(b)) assert.Equal(500, res.Result().StatusCode) } func TestResetSubNoManager(t *testing.T) { assert := assert.New(t) - res := testGWPath("POST", kldevents.SubPathPrefix+"/123/reset", nil, nil) + res := testGWPath("POST", events.SubPathPrefix+"/123/reset", nil, nil) assert.Equal(405, res.Result().StatusCode) } @@ -1986,14 +1985,14 @@ func TestDeleteStream(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{} - res := testGWPath("DELETE", kldevents.StreamPathPrefix+"/123", nil, mockSubMgr) + res := testGWPath("DELETE", events.StreamPathPrefix+"/123", nil, mockSubMgr) assert.Equal(204, res.Result().StatusCode) } func TestDeleteSubNoSubMgr(t *testing.T) { assert := assert.New(t) - res := testGWPath("DELETE", kldevents.SubPathPrefix+"/123", nil, nil) + res := testGWPath("DELETE", events.SubPathPrefix+"/123", nil, nil) assert.Equal(405, res.Result().StatusCode) } @@ -2002,7 +2001,7 @@ func TestDeleteSubError(t *testing.T) { mockSubMgr := &mockSubMgr{err: fmt.Errorf("not found")} var errInfo = restErrMsg{} - res := testGWPath("DELETE", kldevents.SubPathPrefix+"/123", &errInfo, mockSubMgr) + res := testGWPath("DELETE", events.SubPathPrefix+"/123", &errInfo, mockSubMgr) assert.Equal(500, res.Result().StatusCode) assert.Equal("not found", errInfo.Message) } @@ -2011,7 +2010,7 @@ func TestSuspendStream(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{} - res := testGWPath("POST", kldevents.StreamPathPrefix+"/123/suspend", nil, mockSubMgr) + res := testGWPath("POST", events.StreamPathPrefix+"/123/suspend", nil, mockSubMgr) assert.Equal(204, res.Result().StatusCode) assert.True(mockSubMgr.suspended) } @@ -2020,7 +2019,7 @@ func TestResumeStream(t *testing.T) { assert := assert.New(t) mockSubMgr := &mockSubMgr{} - res := testGWPath("POST", kldevents.StreamPathPrefix+"/123/resume", nil, mockSubMgr) + res := testGWPath("POST", events.StreamPathPrefix+"/123/resume", nil, mockSubMgr) assert.Equal(204, res.Result().StatusCode) assert.True(mockSubMgr.resumed) } @@ -2030,7 +2029,7 @@ func TestResumeStreamFail(t *testing.T) { mockSubMgr := &mockSubMgr{err: fmt.Errorf("pop")} var errInfo = restErrMsg{} - res := testGWPath("POST", kldevents.StreamPathPrefix+"/123/resume", &errInfo, mockSubMgr) + res := testGWPath("POST", events.StreamPathPrefix+"/123/resume", &errInfo, mockSubMgr) assert.Equal(500, res.Result().StatusCode) assert.Equal("pop", errInfo.Message) } @@ -2038,7 +2037,7 @@ func TestResumeStreamFail(t *testing.T) { func TestSuspendNoSubMgr(t *testing.T) { assert := assert.New(t) - res := testGWPath("POST", kldevents.StreamPathPrefix+"/123/resume", nil, nil) + res := testGWPath("POST", events.StreamPathPrefix+"/123/resume", nil, nil) assert.Equal(405, res.Result().StatusCode) } @@ -2049,7 +2048,7 @@ func TestCheckNameAvailableRRDuplicate(t *testing.T) { &SmartContractGatewayConf{ BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -2071,7 +2070,7 @@ func TestCheckNameAvailableRRFail(t *testing.T) { &SmartContractGatewayConf{ BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -2089,13 +2088,13 @@ func TestCheckNameAvailableRRFail(t *testing.T) { func TestWithEventsAuthRequiresAuth(t *testing.T) { assert := assert.New(t) - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) scgw, _ := NewSmartContractGateway( &SmartContractGatewayConf{ BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -2114,7 +2113,7 @@ func TestWithEventsAuthRequiresAuth(t *testing.T) { assert.Equal(res.Code, 401) - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } func TestSendReplyBroadcast(t *testing.T) { @@ -2129,7 +2128,7 @@ func TestSendReplyBroadcast(t *testing.T) { &SmartContractGatewayConf{ BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, ws, @@ -2151,7 +2150,7 @@ func TestPublishBadABI(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -2186,7 +2185,7 @@ func TestPublishBadBytecode(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -2221,7 +2220,7 @@ func TestPublishPreCompiled(t *testing.T) { StoragePath: dir, BaseURL: "http://localhost/api/v1", }, - &kldtx.TxnProcessorConf{ + &tx.TxnProcessorConf{ OrionPrivateAPIS: false, }, nil, nil, nil, nil, @@ -2251,7 +2250,7 @@ func TestPublishPreCompiled(t *testing.T) { deployedJson, err := ioutil.ReadFile(path.Join(dir, files[0].Name())) assert.NoError(err) - var deployStash kldmessages.DeployContract + var deployStash messages.DeployContract err = json.Unmarshal(deployedJson, &deployStash) assert.NoError(err) assert.NotEmpty(deployStash.ABI) diff --git a/internal/kldcontracts/syncdispatcher.go b/internal/contracts/syncdispatcher.go similarity index 75% rename from internal/kldcontracts/syncdispatcher.go rename to internal/contracts/syncdispatcher.go index 5f0ed365..74b7be0f 100644 --- a/internal/kldcontracts/syncdispatcher.go +++ b/internal/contracts/syncdispatcher.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "context" @@ -20,19 +20,19 @@ import ( "reflect" "time" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) type syncDispatcher struct { - processor kldtx.TxnProcessor + processor tx.TxnProcessor } -func newSyncDispatcher(processor kldtx.TxnProcessor) rest2EthSyncDispatcher { +func newSyncDispatcher(processor tx.TxnProcessor) rest2EthSyncDispatcher { return &syncDispatcher{ processor: processor, } @@ -43,15 +43,15 @@ type syncTxInflight struct { d *syncDispatcher replyProcessor rest2EthReplyProcessor timeReceived time.Time - sendMsg *kldmessages.SendTransaction - deployMsg *kldmessages.DeployContract + sendMsg *messages.SendTransaction + deployMsg *messages.DeployContract } func (t *syncTxInflight) Context() context.Context { return t.ctx } -func (t *syncTxInflight) Headers() *kldmessages.CommonHeaders { +func (t *syncTxInflight) Headers() *messages.CommonHeaders { if t.deployMsg != nil { return &t.deployMsg.Headers.CommonHeaders } @@ -67,7 +67,7 @@ func (t *syncTxInflight) Unmarshal(msg interface{}) error { } if reflect.TypeOf(msg) != reflect.TypeOf(retMsg) { log.Errorf("Type mismatch: %s != %s", reflect.TypeOf(msg), reflect.TypeOf(retMsg)) - return klderrors.Errorf(klderrors.RESTGatewaySyncMsgTypeMismatch) + return errors.Errorf(errors.RESTGatewaySyncMsgTypeMismatch) } reflect.ValueOf(msg).Elem().Set(reflect.ValueOf(retMsg).Elem()) return nil @@ -82,13 +82,13 @@ func (t *syncTxInflight) SendErrorReplyWithGapFill(status int, err error, gapFil } func (t *syncTxInflight) SendErrorReplyWithTX(status int, err error, txHash string) { - t.SendErrorReply(status, klderrors.Errorf(klderrors.RESTGatewaySyncWrapErrorWithTXDetail, txHash, err)) + t.SendErrorReply(status, errors.Errorf(errors.RESTGatewaySyncWrapErrorWithTXDetail, txHash, err)) } -func (t *syncTxInflight) Reply(replyMessage kldmessages.ReplyWithHeaders) { +func (t *syncTxInflight) Reply(replyMessage messages.ReplyWithHeaders) { headers := t.Headers() replyHeaders := replyMessage.ReplyHeaders() - replyHeaders.ID = kldutils.UUIDv4() + replyHeaders.ID = utils.UUIDv4() replyHeaders.Context = headers.Context replyHeaders.ReqID = headers.ID replyHeaders.Received = t.timeReceived.UTC().Format(time.RFC3339Nano) @@ -102,7 +102,7 @@ func (t *syncTxInflight) String() string { return fmt.Sprintf("MsgContext[%s/%s]", headers.MsgType, headers.ID) } -func (d *syncDispatcher) DispatchSendTransactionSync(ctx context.Context, msg *kldmessages.SendTransaction, replyProcessor rest2EthReplyProcessor) { +func (d *syncDispatcher) DispatchSendTransactionSync(ctx context.Context, msg *messages.SendTransaction, replyProcessor rest2EthReplyProcessor) { syncCtx := &syncTxInflight{ replyProcessor: replyProcessor, timeReceived: time.Now().UTC(), @@ -112,7 +112,7 @@ func (d *syncDispatcher) DispatchSendTransactionSync(ctx context.Context, msg *k d.processor.OnMessage(syncCtx) } -func (d *syncDispatcher) DispatchDeployContractSync(ctx context.Context, msg *kldmessages.DeployContract, replyProcessor rest2EthReplyProcessor) { +func (d *syncDispatcher) DispatchDeployContractSync(ctx context.Context, msg *messages.DeployContract, replyProcessor rest2EthReplyProcessor) { syncCtx := &syncTxInflight{ replyProcessor: replyProcessor, timeReceived: time.Now().UTC(), diff --git a/internal/kldcontracts/syncdispatcher_test.go b/internal/contracts/syncdispatcher_test.go similarity index 74% rename from internal/kldcontracts/syncdispatcher_test.go rename to internal/contracts/syncdispatcher_test.go index c566f2c5..4bd6d8ff 100644 --- a/internal/kldcontracts/syncdispatcher_test.go +++ b/internal/contracts/syncdispatcher_test.go @@ -12,24 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldcontracts +package contracts import ( "context" "fmt" "testing" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" "github.com/stretchr/testify/assert" ) type mockProcessor struct { t *testing.T - headers *kldmessages.CommonHeaders + headers *messages.CommonHeaders err error - reply kldmessages.ReplyWithHeaders + reply messages.ReplyWithHeaders unmarshalErr error badUnmarshal bool resolvedFrom string @@ -39,12 +39,12 @@ func (p *mockProcessor) ResolveAddress(from string) (resolvedFrom string, err er return p.resolvedFrom, p.err } -func (p *mockProcessor) OnMessage(c kldtx.TxnContext) { +func (p *mockProcessor) OnMessage(c tx.TxnContext) { p.headers = c.Headers() ctx := c.(*syncTxInflight) if p.badUnmarshal { // Send something unexpected - p.unmarshalErr = c.Unmarshal(&kldmessages.ErrorReply{}) + p.unmarshalErr = c.Unmarshal(&messages.ErrorReply{}) } else if ctx.sendMsg != nil { p.unmarshalErr = c.Unmarshal(ctx.sendMsg) } else { @@ -57,22 +57,22 @@ func (p *mockProcessor) OnMessage(c kldtx.TxnContext) { c.Reply(p.reply) } } -func (p *mockProcessor) Init(kldeth.RPCClient) {} +func (p *mockProcessor) Init(eth.RPCClient) {} type mockReplyProcessor struct { err error - receipt kldmessages.ReplyWithHeaders + receipt messages.ReplyWithHeaders } func (p *mockReplyProcessor) ReplyWithError(err error) { p.err = err } -func (p *mockReplyProcessor) ReplyWithReceipt(receipt kldmessages.ReplyWithHeaders) { +func (p *mockReplyProcessor) ReplyWithReceipt(receipt messages.ReplyWithHeaders) { p.receipt = receipt } -func (p *mockReplyProcessor) ReplyWithReceiptAndError(receipt kldmessages.ReplyWithHeaders, err error) { +func (p *mockReplyProcessor) ReplyWithReceiptAndError(receipt messages.ReplyWithHeaders, err error) { p.receipt = receipt } @@ -81,10 +81,10 @@ func TestDispatchSendTransactionSync(t *testing.T) { processor := &mockProcessor{ t: t, - reply: &kldmessages.TransactionReceipt{}, + reply: &messages.TransactionReceipt{}, } d := newSyncDispatcher(processor) - sendTx := &kldmessages.SendTransaction{} + sendTx := &messages.SendTransaction{} sendTx.Headers.ID = "request1" r := &mockReplyProcessor{} d.DispatchSendTransactionSync(context.Background(), sendTx, r) @@ -98,10 +98,10 @@ func TestDispatchDeployContractSync(t *testing.T) { processor := &mockProcessor{ t: t, - reply: &kldmessages.TransactionReceipt{}, + reply: &messages.TransactionReceipt{}, } d := newSyncDispatcher(processor) - deployTx := &kldmessages.DeployContract{} + deployTx := &messages.DeployContract{} deployTx.Headers.ID = "request1" r := &mockReplyProcessor{} d.DispatchDeployContractSync(context.Background(), deployTx, r) @@ -115,11 +115,11 @@ func TestDispatchSendTransactionBadUnmarshal(t *testing.T) { processor := &mockProcessor{ t: t, - reply: &kldmessages.TransactionReceipt{}, + reply: &messages.TransactionReceipt{}, badUnmarshal: true, } d := newSyncDispatcher(processor) - sendTx := &kldmessages.SendTransaction{} + sendTx := &messages.SendTransaction{} sendTx.Headers.ID = "request1" r := &mockReplyProcessor{} d.DispatchSendTransactionSync(context.Background(), sendTx, r) @@ -132,11 +132,11 @@ func TestDispatchSendTransactionError(t *testing.T) { processor := &mockProcessor{ t: t, - reply: &kldmessages.TransactionReceipt{}, + reply: &messages.TransactionReceipt{}, err: fmt.Errorf("pop"), } d := newSyncDispatcher(processor) - sendTx := &kldmessages.SendTransaction{} + sendTx := &messages.SendTransaction{} sendTx.Headers.ID = "request1" r := &mockReplyProcessor{} d.DispatchSendTransactionSync(context.Background(), sendTx, r) diff --git a/internal/klderrors/errors.go b/internal/errors/errors.go similarity index 99% rename from internal/klderrors/errors.go rename to internal/errors/errors.go index 55724927..ca8e4b4a 100644 --- a/internal/klderrors/errors.go +++ b/internal/errors/errors.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package klderrors +package errors import ( "fmt" @@ -232,11 +232,11 @@ const ( // RESTGatewayMissingParameter did not supply a parameter required by the method RESTGatewayMissingParameter = "Parameter '%s' of method '%s' was not specified in body or query parameters" // RESTGatewayMissingFromAddress did not supply a signing address for the transaction - RESTGatewayMissingFromAddress = "Please specify a valid address in the 'kld-from' query string parameter or x-kaleido-from HTTP header" + RESTGatewayMissingFromAddress = "Please specify a valid address in the 'fly-from' query string parameter or x-firefly-from HTTP header" // RESTGatewaySubscribeMissingStreamParameter missed the ID of the stream when registering RESTGatewaySubscribeMissingStreamParameter = "Must supply a 'stream' parameter in the body or query" // RESTGatewayMixedPrivateForAndGroupID confused privacy group info, using simple/Tessera style as well as pre-defined/Orion style - RESTGatewayMixedPrivateForAndGroupID = "kld-privatefor and kld-privacygroupid are mutually exclusive" + RESTGatewayMixedPrivateForAndGroupID = "fly-privatefor and fly-privacygroupid are mutually exclusive" // RESTGatewayEventManagerInitFailed constructor failure for event manager RESTGatewayEventManagerInitFailed = "Event-stream subscription manager: %s" // RESTGatewayEventStreamInvalid attempt to create an event stream with invalid parameters @@ -442,14 +442,14 @@ const ( WebhooksDirectBadHeaders = "Failed to process headers in message" ) -type kldError string +type Error string -func (e kldError) Error() string { +func (e Error) Error() string { return string(e) } // Errorf creates an error (not yet translated, but an extensible interface for that using simple sprintf formatting rather than named i18n inserts) func Errorf(msg ErrorID, inserts ...interface{}) error { - var err error = kldError(fmt.Sprintf(string(msg), inserts...)) + var err error = Error(fmt.Sprintf(string(msg), inserts...)) return errors.WithStack(err) } diff --git a/internal/kldeth/compiler.go b/internal/eth/compiler.go similarity index 78% rename from internal/kldeth/compiler.go rename to internal/eth/compiler.go index 332d467a..3b82519c 100644 --- a/internal/kldeth/compiler.go +++ b/internal/eth/compiler.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "bytes" @@ -24,9 +24,8 @@ import ( "strings" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/ethbind" log "github.com/sirupsen/logrus" ) @@ -53,7 +52,7 @@ func getSolcExecutable(requestedVersion string) (string, error) { solcVerChecker, _ = regexp.Compile("^([0-9]+)\\.?([0-9]+)") } if defaultSolc == "" { - if envVar := os.Getenv("KLD_SOLC_DEFAULT"); envVar != "" { + if envVar := os.Getenv("FLY_SOLC_DEFAULT"); envVar != "" { defaultSolc = envVar } else { defaultSolc = "solc" @@ -61,14 +60,14 @@ func getSolcExecutable(requestedVersion string) (string, error) { } solc := defaultSolc if v := solcVerChecker.FindStringSubmatch(requestedVersion); v != nil { - envVarName := "KLD_SOLC_" + v[1] + "_" + v[2] + envVarName := "FLY_SOLC_" + v[1] + "_" + v[2] if envVar := os.Getenv(envVarName); envVar != "" { solc = envVar } else { - return "", klderrors.Errorf(klderrors.CompilerVersionNotFound, v[1], v[2]) + return "", errors.Errorf(errors.CompilerVersionNotFound, v[1], v[2]) } } else if requestedVersion != "" { - return "", klderrors.Errorf(klderrors.CompilerVersionBadRequest) + return "", errors.Errorf(errors.CompilerVersionBadRequest) } log.Debugf("Solidity compiler solc binary: %s", solc) return solc, nil @@ -81,7 +80,7 @@ func GetSolc(requestedVersion string) (*ethbinding.Solidity, error) { if err != nil { return nil, err } - return eth.API.SolidityVersion(solc) + return ethbind.API.SolidityVersion(solc) } // GetSolcArgs get the correct solc args @@ -112,9 +111,9 @@ func CompileContract(soliditySource, contractName, requestedVersion, evmVersion cmd.Stderr = &stderr cmd.Stdout = &stdout if err := cmd.Run(); err != nil { - return nil, klderrors.Errorf(klderrors.CompilerFailedSolc, err, stderr.String()) + return nil, errors.Errorf(errors.CompilerFailedSolc, err, stderr.String()) } - c, _ := eth.API.ParseCombinedJSON(stdout.Bytes(), soliditySource, s.Version, s.Version, strings.Join(solcArgs, " ")) + c, _ := ethbind.API.ParseCombinedJSON(stdout.Bytes(), soliditySource, s.Version, s.Version, strings.Join(solcArgs, " ")) return ProcessCompiled(c, contractName, true) } @@ -128,11 +127,11 @@ func ProcessCompiled(compiled map[string]*ethbinding.Contract, contractName stri contractName = ":" + contractName } if _, ok := compiled[contractName]; !ok { - return nil, klderrors.Errorf(klderrors.CompilerOutputMissingContract, contractName, contractNames) + return nil, errors.Errorf(errors.CompilerOutputMissingContract, contractName, contractNames) } contract = compiled[contractName] } else if len(contractNames) != 1 { - return nil, klderrors.Errorf(klderrors.CompilerOutputMultipleContracts, contractNames) + return nil, errors.Errorf(errors.CompilerOutputMultipleContracts, contractNames) } else { contractName = contractNames[0].String() contract = compiled[contractName] @@ -151,27 +150,27 @@ func packContract(contractName string, contract *ethbinding.Contract) (c *Compil ContractName: contractName, ContractInfo: &contract.Info, } - c.Compiled, err = eth.API.HexDecode(contract.Code) + c.Compiled, err = ethbind.API.HexDecode(contract.Code) if err != nil { - return nil, klderrors.Errorf(klderrors.CompilerBytecodeInvalid, err) + return nil, errors.Errorf(errors.CompilerBytecodeInvalid, err) } if len(c.Compiled) == 0 { - return nil, klderrors.Errorf(klderrors.CompilerBytecodeEmpty, contractName) + return nil, errors.Errorf(errors.CompilerBytecodeEmpty, contractName) } // Pack the arguments for calling the contract abiJSON, err := json.Marshal(contract.Info.AbiDefinition) if err != nil { - return nil, klderrors.Errorf(klderrors.CompilerABISerialize, err) + return nil, errors.Errorf(errors.CompilerABISerialize, err) } var abi ethbinding.ABIMarshaling err = json.Unmarshal(abiJSON, &abi) if err != nil { - return nil, klderrors.Errorf(klderrors.CompilerABIReRead, err) + return nil, errors.Errorf(errors.CompilerABIReRead, err) } c.ABI = abi devdocBytes, err := json.Marshal(contract.Info.DeveloperDoc) if err != nil { - return nil, klderrors.Errorf(klderrors.CompilerSerializeDevDocs, err) + return nil, errors.Errorf(errors.CompilerSerializeDevDocs, err) } c.DevDoc = string(devdocBytes) return c, nil diff --git a/internal/kldeth/compiler_test.go b/internal/eth/compiler_test.go similarity index 94% rename from internal/kldeth/compiler_test.go rename to internal/eth/compiler_test.go index 2a7df2b7..ebc29498 100644 --- a/internal/kldeth/compiler_test.go +++ b/internal/eth/compiler_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "os" @@ -100,27 +100,27 @@ func TestPackContractFailSerializingDevDoc(t *testing.T) { func TestSolcDefaultVersion(t *testing.T) { assert := assert.New(t) - os.Setenv("KLD_SOLC_DEFAULT", "") + os.Setenv("FLY_SOLC_DEFAULT", "") defaultSolc = "" solc, err := getSolcExecutable("") assert.NoError(err) assert.Equal("solc", solc) - os.Unsetenv("KLD_SOLC_DEFAULT") + os.Unsetenv("FLY_SOLC_DEFAULT") } func TestSolcDefaultVersionEnvVar(t *testing.T) { assert := assert.New(t) - os.Setenv("KLD_SOLC_DEFAULT", "solc123") + os.Setenv("FLY_SOLC_DEFAULT", "solc123") defaultSolc = "" solc, err := getSolcExecutable("") assert.NoError(err) assert.Equal("solc123", solc) - os.Unsetenv("KLD_SOLC_DEFAULT") + os.Unsetenv("FLY_SOLC_DEFAULT") } func TestSolcCustomVersionValidMajor(t *testing.T) { assert := assert.New(t) - os.Setenv("KLD_SOLC_0_4", "solc04") + os.Setenv("FLY_SOLC_0_4", "solc04") defaultSolc = "" solc, err := getSolcExecutable("0.4") assert.NoError(err) @@ -129,7 +129,7 @@ func TestSolcCustomVersionValidMajor(t *testing.T) { func TestSolcCustomVersionValidMinor(t *testing.T) { assert := assert.New(t) - os.Setenv("KLD_SOLC_0_4", "solc04") + os.Setenv("FLY_SOLC_0_4", "solc04") defaultSolc = "" solc, err := getSolcExecutable("0.4.23.some interesting things") assert.NoError(err) diff --git a/internal/kldeth/getreceipt.go b/internal/eth/getreceipt.go similarity index 84% rename from internal/kldeth/getreceipt.go rename to internal/eth/getreceipt.go index be223a81..b4b4c9b3 100644 --- a/internal/kldeth/getreceipt.go +++ b/internal/eth/getreceipt.go @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" "time" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" log "github.com/sirupsen/logrus" ) @@ -30,7 +30,7 @@ func (tx *Txn) GetTXReceipt(ctx context.Context, rpc RPCClient) (bool, error) { defer cancel() if err := rpc.CallContext(ctx, &tx.Receipt, "eth_getTransactionReceipt", tx.Hash); err != nil { - return false, klderrors.Errorf(klderrors.RPCCallReturnedError, "eth_getTransactionReceipt", err) + return false, errors.Errorf(errors.RPCCallReturnedError, "eth_getTransactionReceipt", err) } callTime := time.Now().UTC().Sub(start) isMined := tx.Receipt.BlockNumber != nil && tx.Receipt.BlockNumber.ToInt().Uint64() > 0 @@ -39,7 +39,7 @@ func (tx *Txn) GetTXReceipt(ctx context.Context, rpc RPCClient) (bool, error) { if tx.PrivacyGroupID != "" { // priv_getTransactionReceipt expects the txHash and the public key of enclave (privateFrom) if err := rpc.CallContext(ctx, &tx.Receipt, "priv_getTransactionReceipt", tx.Hash, tx.PrivateFrom); err != nil { - return false, klderrors.Errorf(klderrors.RPCCallReturnedError, "priv_getTransactionReceipt", err) + return false, errors.Errorf(errors.RPCCallReturnedError, "priv_getTransactionReceipt", err) } } diff --git a/internal/kldeth/getreceipt_test.go b/internal/eth/getreceipt_test.go similarity index 99% rename from internal/kldeth/getreceipt_test.go rename to internal/eth/getreceipt_test.go index e74ef30c..5ff4e3b9 100644 --- a/internal/kldeth/getreceipt_test.go +++ b/internal/eth/getreceipt_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" diff --git a/internal/kldeth/privacygroup.go b/internal/eth/privacygroup.go similarity index 86% rename from internal/kldeth/privacygroup.go rename to internal/eth/privacygroup.go index 27b3b7fd..6bed1165 100644 --- a/internal/kldeth/privacygroup.go +++ b/internal/eth/privacygroup.go @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" "time" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" ) // OrionPrivacyGroup is the result of the priv_findPrivacyGroup call @@ -41,11 +41,11 @@ func GetOrionPrivacyGroup(ctx context.Context, rpc RPCClient, addr *ethbinding.A var privacyGroups []OrionPrivacyGroup var privacyGroup string if err := rpc.CallContext(ctx, &privacyGroups, "priv_findPrivacyGroup", allMembers); err != nil { - return "", klderrors.Errorf(klderrors.RPCCallReturnedError, "priv_findPrivacyGroup", err) + return "", errors.Errorf(errors.RPCCallReturnedError, "priv_findPrivacyGroup", err) } if len(privacyGroups) == 0 { if err := rpc.CallContext(ctx, &privacyGroup, "priv_createPrivacyGroup", params); err != nil { - return "", klderrors.Errorf(klderrors.RPCCallReturnedError, "priv_createPrivacyGroup", err) + return "", errors.Errorf(errors.RPCCallReturnedError, "priv_createPrivacyGroup", err) } } else { privacyGroup = privacyGroups[0].PrivacyGroupID diff --git a/internal/kldeth/privacygroup_test.go b/internal/eth/privacygroup_test.go similarity index 87% rename from internal/kldeth/privacygroup_test.go rename to internal/eth/privacygroup_test.go index cef765a4..52131052 100644 --- a/internal/kldeth/privacygroup_test.go +++ b/internal/eth/privacygroup_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" @@ -20,7 +20,7 @@ import ( "reflect" "testing" - "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/ethbind" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -44,7 +44,7 @@ func TestGetOrionPrivacyGroupExists(t *testing.T) { }, } - addr := eth.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") + addr := ethbind.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") privacyGroupID, err := GetOrionPrivacyGroup(context.Background(), &r, &addr, "jO6dpqnMhmnrCHqUumyK09+18diF7quq/rROGs2HFWI=", []string{"2QiZG7rYPzRvRsioEn6oYUff1DOvPA22EZr0+/o3RUg="}) @@ -61,7 +61,7 @@ func TestGetOrionPrivacyGroupDoesNotExist(t *testing.T) { r := testRPCClient{} - addr := eth.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") + addr := ethbind.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") _, err := GetOrionPrivacyGroup(context.Background(), &r, &addr, "jO6dpqnMhmnrCHqUumyK09+18diF7quq/rROGs2HFWI=", []string{"2QiZG7rYPzRvRsioEn6oYUff1DOvPA22EZr0+/o3RUg="}) @@ -79,7 +79,7 @@ func TestGetOrionPrivacyGroupErrFind(t *testing.T) { mockError: fmt.Errorf("pop"), } - addr := eth.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") + addr := ethbind.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") _, err := GetOrionPrivacyGroup(context.Background(), &r, &addr, "jO6dpqnMhmnrCHqUumyK09+18diF7quq/rROGs2HFWI=", []string{"2QiZG7rYPzRvRsioEn6oYUff1DOvPA22EZr0+/o3RUg="}) @@ -95,7 +95,7 @@ func TestGetOrionPrivacyGroupErrCreate(t *testing.T) { mockError2: fmt.Errorf("pop"), } - addr := eth.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") + addr := ethbind.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") _, err := GetOrionPrivacyGroup(context.Background(), &r, &addr, "jO6dpqnMhmnrCHqUumyK09+18diF7quq/rROGs2HFWI=", []string{"2QiZG7rYPzRvRsioEn6oYUff1DOvPA22EZr0+/o3RUg="}) diff --git a/internal/kldeth/rpc.go b/internal/eth/rpc.go similarity index 88% rename from internal/kldeth/rpc.go rename to internal/eth/rpc.go index 1127f76a..b5fdcc6f 100644 --- a/internal/kldeth/rpc.go +++ b/internal/eth/rpc.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" @@ -20,9 +20,9 @@ import ( "os" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/ethbind" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -47,9 +47,9 @@ func RPCConnect(conf *RPCConnOpts) (RPCClientAll, error) { if u.User != nil { u.User = url.UserPassword(u.User.Username(), "xxxxxx") } - rpcClient, err := eth.API.Dial(conf.URL) + rpcClient, err := ethbind.API.Dial(conf.URL) if err != nil { - return nil, klderrors.Errorf(klderrors.RPCConnectFailed, u, err) + return nil, errors.Errorf(errors.RPCConnectFailed, u, err) } log.Infof("New JSON/RPC connection established") log.Debugf("JSON/RPC connected to %s", u) @@ -93,9 +93,9 @@ func (sw *subWrapper) Unsubscribe() { } func (w *rpcWrapper) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { - if err := kldauth.AuthRPC(ctx, method, args...); err != nil { + if err := auth.AuthRPC(ctx, method, args...); err != nil { log.Errorf("JSON/RPC %s - not authorized: %s", method, err) - return klderrors.Errorf(klderrors.Unauthorized) + return errors.Errorf(errors.Unauthorized) } log.Tracef("RPC [%s] --> %+v", method, args) err := w.rpc.CallContext(ctx, result, method, args...) @@ -104,9 +104,9 @@ func (w *rpcWrapper) CallContext(ctx context.Context, result interface{}, method } func (w *rpcWrapper) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (RPCClientSubscription, error) { - if err := kldauth.AuthRPCSubscribe(ctx, namespace, channel, args...); err != nil { + if err := auth.AuthRPCSubscribe(ctx, namespace, channel, args...); err != nil { log.Errorf("JSON/RPC Subscribe - not authorized: %s", err) - return nil, klderrors.Errorf(klderrors.Unauthorized) + return nil, errors.Errorf(errors.Unauthorized) } tSub, err := w.rpc.Subscribe(ctx, namespace, channel, args...) return &subWrapper{s: tSub}, err diff --git a/internal/kldeth/rpc_test.go b/internal/eth/rpc_test.go similarity index 94% rename from internal/kldeth/rpc_test.go rename to internal/eth/rpc_test.go index 701d4c3e..c974fbcb 100644 --- a/internal/kldeth/rpc_test.go +++ b/internal/eth/rpc_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" @@ -24,8 +24,8 @@ import ( "github.com/spf13/cobra" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldauth/kldauthtest" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/auth/authtest" "github.com/stretchr/testify/assert" ) @@ -132,7 +132,7 @@ func TestCallContextWrapper(t *testing.T) { func TestCallContextWrapperAuth(t *testing.T) { assert := assert.New(t) - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) w := &rpcWrapper{rpc: &mockEthClient{}} _, err := w.Subscribe(context.Background(), "", nil) @@ -140,5 +140,5 @@ func TestCallContextWrapperAuth(t *testing.T) { err = w.CallContext(context.Background(), nil, "") assert.EqualError(err, "Unauthorized") - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } diff --git a/internal/kldeth/rpcmock.go b/internal/eth/rpcmock.go similarity index 99% rename from internal/kldeth/rpcmock.go rename to internal/eth/rpcmock.go index e518c0e7..8207dbe9 100644 --- a/internal/kldeth/rpcmock.go +++ b/internal/eth/rpcmock.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" diff --git a/internal/kldeth/send.go b/internal/eth/send.go similarity index 87% rename from internal/kldeth/send.go rename to internal/eth/send.go index c8b7a5f6..2290bdf3 100644 --- a/internal/kldeth/send.go +++ b/internal/eth/send.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" @@ -22,8 +22,9 @@ import ( "time" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" + + "github.com/kaleido-io/ethconnect/internal/ethbind" log "github.com/sirupsen/logrus" ) @@ -39,7 +40,7 @@ func (tx *Txn) calculateGas(ctx context.Context, rpc RPCClient, txArgs *SendTXAr if err := rpc.CallContext(ctx, &gas, "eth_estimateGas", txArgs); err != nil { // Now we attempt a call of the transaction, because that will return us a useful error in the case, of a revert. - estError := klderrors.Errorf(klderrors.TransactionSendGasEstimateFailed, err) + estError := errors.Errorf(errors.TransactionSendGasEstimateFailed, err) log.Errorf(estError.Error()) if _, err := tx.Call(ctx, rpc, "latest"); err != nil { return err @@ -70,7 +71,7 @@ func (tx *Txn) Call(ctx context.Context, rpc RPCClient, blocknumber string) (res var hexString string if err = rpc.CallContext(ctx, &hexString, "eth_call", txArgs, blocknumber); err != nil { - return nil, klderrors.Errorf(klderrors.TransactionSendCallFailedNoRevert, err) + return nil, errors.Errorf(errors.TransactionSendCallFailedNoRevert, err) } if len(hexString) == 0 || hexString == "0x" { return nil, nil @@ -90,12 +91,12 @@ func (tx *Txn) Call(ctx context.Context, rpc RPCClient, blocknumber string) (res errorStringBytes, err := hex.DecodeString(errorStringHex) log.Warnf("EVM Reverted. Message='%s' Offset='%s'", errorStringBytes, dataOffsetHex.Text(10)) if err != nil { - return nil, klderrors.Errorf(klderrors.TransactionSendCallFailedRevertNoMessage) + return nil, errors.Errorf(errors.TransactionSendCallFailedRevertNoMessage) } - return nil, klderrors.Errorf(klderrors.TransactionSendCallFailedRevertMessage, errorStringBytes) + return nil, errors.Errorf(errors.TransactionSendCallFailedRevertMessage, errorStringBytes) } log.Debugf("eth_call response: %s", hexString) - res = eth.API.FromHex(hexString) + res = ethbind.API.FromHex(hexString) return } @@ -121,9 +122,9 @@ func (tx *Txn) Send(ctx context.Context, rpc RPCClient) (err error) { } // Re-encode the EthTX (for external HD Wallet signing) if to != nil { - tx.EthTX = eth.API.NewTransaction(tx.EthTX.Nonce(), *tx.EthTX.To(), tx.EthTX.Value(), uint64(gas), tx.EthTX.GasPrice(), tx.EthTX.Data()) + tx.EthTX = ethbind.API.NewTransaction(tx.EthTX.Nonce(), *tx.EthTX.To(), tx.EthTX.Value(), uint64(gas), tx.EthTX.GasPrice(), tx.EthTX.Data()) } else { - tx.EthTX = eth.API.NewContractCreation(tx.EthTX.Nonce(), tx.EthTX.Value(), uint64(gas), tx.EthTX.GasPrice(), tx.EthTX.Data()) + tx.EthTX = ethbind.API.NewContractCreation(tx.EthTX.Nonce(), tx.EthTX.Value(), uint64(gas), tx.EthTX.GasPrice(), tx.EthTX.Data()) } } txArgs.Gas = &gas @@ -180,7 +181,7 @@ func (tx *Txn) submitTXtoNode(ctx context.Context, rpc RPCClient, txArgs *SendTX txArgs.Restriction = "restricted" // PrivateFrom is requires for Orion transactions if txArgs.PrivateFrom == "" { - return "", klderrors.Errorf(klderrors.TransactionSendMissingPrivateFromOrion) + return "", errors.Errorf(errors.TransactionSendMissingPrivateFromOrion) } isPrivate = true } else if len(tx.PrivateFor) > 0 { @@ -193,7 +194,7 @@ func (tx *Txn) submitTXtoNode(ctx context.Context, rpc RPCClient, txArgs *SendTX var callParam0 interface{} = txArgs if tx.Signer != nil { if isPrivate { - return "", klderrors.Errorf(klderrors.TransactionSendPrivateTXWithExternalSigner, tx.Signer.Type()) + return "", errors.Errorf(errors.TransactionSendPrivateTXWithExternalSigner, tx.Signer.Type()) } // Sign the transaction and get the bytes, which we pass to eth_sendRawTransaction jsonRPCMethod = "eth_sendRawTransaction" @@ -201,7 +202,7 @@ func (tx *Txn) submitTXtoNode(ctx context.Context, rpc RPCClient, txArgs *SendTX if err != nil { return "", err } - callParam0 = eth.API.HexEncode(signed) + callParam0 = ethbind.API.HexEncode(signed) } var txHash string diff --git a/internal/kldeth/signer.go b/internal/eth/signer.go similarity index 95% rename from internal/kldeth/signer.go rename to internal/eth/signer.go index 12b20f0a..8352c8e1 100644 --- a/internal/kldeth/signer.go +++ b/internal/eth/signer.go @@ -1,6 +1,6 @@ // Copyright 2018, 2019 Kaleido -package kldeth +package eth import ( ethbinding "github.com/kaleido-io/ethbinding/pkg" diff --git a/internal/kldeth/signer_test.go b/internal/eth/signer_test.go similarity index 96% rename from internal/kldeth/signer_test.go rename to internal/eth/signer_test.go index 3d654d6f..00cfaac2 100644 --- a/internal/kldeth/signer_test.go +++ b/internal/eth/signer_test.go @@ -1,6 +1,6 @@ // Copyright 2018, 2019 Kaleido -package kldeth +package eth import ( ethbinding "github.com/kaleido-io/ethbinding/pkg" diff --git a/internal/kldeth/txn.go b/internal/eth/txn.go similarity index 78% rename from internal/kldeth/txn.go rename to internal/eth/txn.go index b0d26836..820c4287 100644 --- a/internal/kldeth/txn.go +++ b/internal/eth/txn.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" @@ -26,10 +26,10 @@ import ( "strings" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) @@ -65,7 +65,7 @@ type TxnReceipt struct { // NewContractDeployTxn builds a new ethereum transaction from the supplied // SendTranasction message -func NewContractDeployTxn(msg *kldmessages.DeployContract, signer TXSigner) (tx *Txn, err error) { +func NewContractDeployTxn(msg *messages.DeployContract, signer TXSigner) (tx *Txn, err error) { tx = &Txn{Signer: signer} @@ -82,13 +82,13 @@ func NewContractDeployTxn(msg *kldmessages.DeployContract, signer TXSigner) (tx return } } else { - err = klderrors.Errorf(klderrors.DeployTransactionMissingCode) + err = errors.Errorf(errors.DeployTransactionMissingCode) return } // Build a runtime ABI from the serialized one var typedArgs []interface{} - abi, err := eth.API.ABIMarshalingToABIRuntime(compiled.ABI) + abi, err := ethbind.API.ABIMarshalingToABIRuntime(compiled.ABI) if err == nil { // Build correctly typed args for the ethereum call typedArgs, err = tx.generateTypedArgs(msg.Parameters, &abi.Constructor) @@ -100,7 +100,7 @@ func NewContractDeployTxn(msg *kldmessages.DeployContract, signer TXSigner) (tx // Pack the arguments packedCall, err := abi.Pack("", typedArgs...) if err != nil { - err = klderrors.Errorf(klderrors.TransactionSendConstructorPackArgs, err) + err = errors.Errorf(errors.TransactionSendConstructorPackArgs, err) return } @@ -133,7 +133,7 @@ func CallMethod(ctx context.Context, rpc RPCClient, signer TXSigner, from, addr } callOption := "latest" // only allowed values are "earliest/latest/pending", "", a number string "12345" or a hex number "0xab23" - // "latest" and "" (no kld-blocknumber given) are equivalent + // "latest" and "" (no fly-blocknumber given) are equivalent if blocknumber != "" && blocknumber != "latest" { isHex, _ := regexp.MatchString(`^0x[0-9a-fA-F]+$`, blocknumber) if isHex || blocknumber == "earliest" || blocknumber == "pending" { @@ -142,9 +142,9 @@ func CallMethod(ctx context.Context, rpc RPCClient, signer TXSigner, from, addr n := new(big.Int) n, ok := n.SetString(blocknumber, 10) if !ok { - return nil, klderrors.Errorf(klderrors.TransactionCallInvalidBlockNumber) + return nil, errors.Errorf(errors.TransactionCallInvalidBlockNumber) } - callOption = eth.API.EncodeBig(n) + callOption = ethbind.API.EncodeBig(n) } } @@ -169,7 +169,7 @@ func ProcessRLPBytes(args ethbinding.ABIArguments, retBytes []byte) map[string]i rawRetval, unpackErr := args.UnpackValues(retBytes) var err error if unpackErr != nil { - err = klderrors.Errorf(klderrors.UnpackOutputsFailed, unpackErr) + err = errors.Errorf(errors.UnpackOutputsFailed, unpackErr) } else { err = processOutputs(args, rawRetval, retval) } @@ -183,7 +183,7 @@ func processOutputs(args ethbinding.ABIArguments, rawRetval []interface{}, retva numOutputs := len(args) if numOutputs > 0 { if len(rawRetval) != numOutputs { - return klderrors.Errorf(klderrors.UnpackOutputsMismatchCount, numOutputs, len(rawRetval), rawRetval) + return errors.Errorf(errors.UnpackOutputsMismatchCount, numOutputs, len(rawRetval), rawRetval) } for idx, output := range args { if err := genOutput(idx, retval, output, rawRetval[idx]); err != nil { @@ -191,7 +191,7 @@ func processOutputs(args ethbinding.ABIArguments, rawRetval []interface{}, retva } } } else if rawRetval != nil { - return klderrors.Errorf(klderrors.UnpackOutputsMismatchNil, rawRetval) + return errors.Errorf(errors.UnpackOutputsMismatchNil, rawRetval) } return nil } @@ -229,24 +229,24 @@ func mapOutput(argName, argType string, t *ethbinding.ABIType, rawValue interfac kind == reflect.Uint64 { return strconv.FormatUint(reflect.ValueOf(rawValue).Uint(), 10), nil } else { - return nil, klderrors.Errorf(klderrors.UnpackOutputsMismatchType, "number", + return nil, errors.Errorf(errors.UnpackOutputsMismatchType, "number", argName, argType, rawType.Kind()) } case ethbinding.BoolTy: if rawType.Kind() != reflect.Bool { - return nil, klderrors.Errorf(klderrors.UnpackOutputsMismatchType, "boolean", + return nil, errors.Errorf(errors.UnpackOutputsMismatchType, "boolean", argName, argType, rawType.Kind()) } return rawValue, nil case ethbinding.StringTy: if rawType.Kind() != reflect.String { - return nil, klderrors.Errorf(klderrors.UnpackOutputsMismatchType, "string array", + return nil, errors.Errorf(errors.UnpackOutputsMismatchType, "string array", argName, argType, rawType.Kind()) } return reflect.ValueOf(rawValue).Interface().(string), nil case ethbinding.BytesTy, ethbinding.FixedBytesTy, ethbinding.AddressTy: if (rawType.Kind() != reflect.Array && rawType.Kind() != reflect.Slice) || rawType.Elem().Kind() != reflect.Uint8 { - return nil, klderrors.Errorf(klderrors.UnpackOutputsMismatchType, "[]byte", + return nil, errors.Errorf(errors.UnpackOutputsMismatchType, "[]byte", argName, argType, rawType.Kind()) } s := reflect.ValueOf(rawValue) @@ -254,10 +254,10 @@ func mapOutput(argName, argType string, t *ethbinding.ABIType, rawValue interfac for i := 0; i < s.Len(); i++ { arrayVal[i] = byte(s.Index(i).Uint()) } - return eth.API.HexEncode(arrayVal), nil + return ethbind.API.HexEncode(arrayVal), nil case ethbinding.SliceTy, ethbinding.ArrayTy: if rawType.Kind() != reflect.Slice { - return nil, klderrors.Errorf(klderrors.UnpackOutputsMismatchType, "slice", + return nil, errors.Errorf(errors.UnpackOutputsMismatchType, "slice", argName, argType, rawType.Kind()) } s := reflect.ValueOf(rawValue) @@ -273,7 +273,7 @@ func mapOutput(argName, argType string, t *ethbinding.ABIType, rawValue interfac case ethbinding.TupleTy: return genTupleMapOutput(argName, argType, t, rawValue) default: - return nil, klderrors.Errorf(klderrors.UnpackOutputsUnknownType, + return nil, errors.Errorf(errors.UnpackOutputsUnknownType, argName, argType, rawType.Kind()) } } @@ -281,11 +281,11 @@ func mapOutput(argName, argType string, t *ethbinding.ABIType, rawValue interfac func genTupleMapOutput(argName, argType string, t *ethbinding.ABIType, rawValue interface{}) (r map[string]interface{}, err error) { reflectValue := reflect.ValueOf(rawValue) if reflectValue.Kind() != reflect.Struct || reflectValue.Type() != t.TupleType { - return nil, klderrors.Errorf(klderrors.UnpackOutputsMismatchTupleType, + return nil, errors.Errorf(errors.UnpackOutputsMismatchTupleType, argName, argType, t.TupleType, rawValue) } if len(t.TupleRawNames) != reflectValue.NumField() { - return nil, klderrors.Errorf(klderrors.UnpackOutputsMismatchTupleFieldCount, + return nil, errors.Errorf(errors.UnpackOutputsMismatchTupleFieldCount, argName, argType, len(t.TupleRawNames), reflectValue.NumField()) } returnMap := make(map[string]interface{}) @@ -300,25 +300,25 @@ func genTupleMapOutput(argName, argType string, t *ethbinding.ABIType, rawValue // NewSendTxn builds a new ethereum transaction from the supplied // SendTranasction message -func NewSendTxn(msg *kldmessages.SendTransaction, signer TXSigner) (tx *Txn, err error) { +func NewSendTxn(msg *messages.SendTransaction, signer TXSigner) (tx *Txn, err error) { var methodABI *ethbinding.ABIMethod if msg.Method == nil || msg.Method.Name == "" { if msg.MethodName == "" { - err = klderrors.Errorf(klderrors.TransactionSendMissingMethod) + err = errors.Errorf(errors.TransactionSendMissingMethod) return } var abiInputs ethbinding.ABIArguments msg.Parameters, err = flattenParams(msg.Parameters, &abiInputs, true) if err == nil { - abiMethod := eth.API.NewMethod(msg.MethodName, msg.MethodName, ethbinding.Function, "payable", false, true, abiInputs, ethbinding.ABIArguments{}) + abiMethod := ethbind.API.NewMethod(msg.MethodName, msg.MethodName, ethbinding.Function, "payable", false, true, abiInputs, ethbinding.ABIArguments{}) methodABI = &abiMethod } if err != nil { return } } else { - methodABI, err = eth.API.ABIElementMarshalingToABIMethod(msg.Method) + methodABI, err = ethbind.API.ABIElementMarshalingToABIMethod(msg.Method) if err != nil { return } @@ -360,7 +360,7 @@ func buildTX(signer TXSigner, msgFrom, msgTo string, msgNonce, msgValue, msgGas, // Pack the arguments packedArgs, err := methodABI.Inputs.Pack(typedArgs...) if err != nil { - err = klderrors.Errorf(klderrors.TransactionSendMethodPackArgs, methodABI.RawName, err) + err = errors.Errorf(errors.TransactionSendMethodPackArgs, methodABI.RawName, err) log.Errorf("Attempted to pack args %+v: %s", typedArgs, err) return } @@ -381,7 +381,7 @@ func buildTX(signer TXSigner, msgFrom, msgTo string, msgNonce, msgValue, msgGas, func (tx *Txn) genEthTransaction(msgFrom, msgTo string, msgNonce, msgValue, msgGas, msgGasPrice json.Number, data []byte) (err error) { if msgFrom != "" { - tx.From, err = kldutils.StrToAddress("from", msgFrom) + tx.From, err = utils.StrToAddress("from", msgFrom) if err != nil { return } @@ -391,7 +391,7 @@ func (tx *Txn) genEthTransaction(msgFrom, msgTo string, msgNonce, msgValue, msgG if msgNonce != "" { nonce, err = msgNonce.Int64() if err != nil { - err = klderrors.Errorf(klderrors.TransactionSendBadNonce, err) + err = errors.Errorf(errors.TransactionSendBadNonce, err) return } } @@ -399,7 +399,7 @@ func (tx *Txn) genEthTransaction(msgFrom, msgTo string, msgNonce, msgValue, msgG value := big.NewInt(0) if msgValue.String() != "" { if _, ok := value.SetString(msgValue.String(), 10); !ok { - err = klderrors.Errorf(klderrors.TransactionSendBadValue, err) + err = errors.Errorf(errors.TransactionSendBadValue, err) return } } @@ -408,7 +408,7 @@ func (tx *Txn) genEthTransaction(msgFrom, msgTo string, msgNonce, msgValue, msgG if msgGas != "" { gas, err = msgGas.Int64() if err != nil { - err = klderrors.Errorf(klderrors.TransactionSendBadGas, err) + err = errors.Errorf(errors.TransactionSendBadGas, err) return } } @@ -416,7 +416,7 @@ func (tx *Txn) genEthTransaction(msgFrom, msgTo string, msgNonce, msgValue, msgG gasPrice := big.NewInt(0) if msgGasPrice.String() != "" { if _, ok := gasPrice.SetString(msgGasPrice.String(), 10); !ok { - err = klderrors.Errorf(klderrors.TransactionSendBadGasPrice) + err = errors.Errorf(errors.TransactionSendBadGasPrice) return } } @@ -424,13 +424,13 @@ func (tx *Txn) genEthTransaction(msgFrom, msgTo string, msgNonce, msgValue, msgG var toAddr ethbinding.Address var toStr string if msgTo != "" { - if toAddr, err = kldutils.StrToAddress("to", msgTo); err != nil { + if toAddr, err = utils.StrToAddress("to", msgTo); err != nil { return } - tx.EthTX = eth.API.NewTransaction(uint64(nonce), toAddr, value, uint64(gas), gasPrice, data) + tx.EthTX = ethbind.API.NewTransaction(uint64(nonce), toAddr, value, uint64(gas), gasPrice, data) toStr = toAddr.Hex() } else { - tx.EthTX = eth.API.NewContractCreation(uint64(nonce), value, uint64(gas), gasPrice, data) + tx.EthTX = ethbind.API.NewContractCreation(uint64(nonce), value, uint64(gas), gasPrice, data) toStr = "" } etx := tx.EthTX @@ -442,13 +442,13 @@ func (tx *Txn) genEthTransaction(msgFrom, msgTo string, msgNonce, msgValue, msgG func (tx *Txn) getInteger(methodName string, path string, requiredType *ethbinding.ABIType, suppliedType reflect.Type, param interface{}) (val int64, err error) { if suppliedType.Kind() == reflect.String { if val, err = strconv.ParseInt(param.(string), 10, 64); err != nil { - err = klderrors.Errorf(klderrors.TransactionSendInputTypeBadNumber, methodName, path) + err = errors.Errorf(errors.TransactionSendInputTypeBadNumber, methodName, path) return } } else if suppliedType.Kind() == reflect.Float64 { val = int64(param.(float64)) } else { - err = klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForNumber, methodName, path, requiredType, suppliedType) + err = errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForNumber, methodName, path, requiredType, suppliedType) } return } @@ -456,13 +456,13 @@ func (tx *Txn) getInteger(methodName string, path string, requiredType *ethbindi func (tx *Txn) getUnsignedInteger(methodName string, path string, requiredType *ethbinding.ABIType, suppliedType reflect.Type, param interface{}) (val uint64, err error) { if suppliedType.Kind() == reflect.String { if val, err = strconv.ParseUint(param.(string), 10, 64); err != nil { - err = klderrors.Errorf(klderrors.TransactionSendInputTypeBadNumber, methodName, path) + err = errors.Errorf(errors.TransactionSendInputTypeBadNumber, methodName, path) return } } else if suppliedType.Kind() == reflect.Float64 { val = uint64(param.(float64)) } else { - err = klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForNumber, methodName, path, requiredType, suppliedType) + err = errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForNumber, methodName, path, requiredType, suppliedType) } return } @@ -471,19 +471,19 @@ func (tx *Txn) getBigInteger(methodName string, path string, requiredType *ethbi bigInt = big.NewInt(0) if suppliedType.Kind() == reflect.String { if _, ok := bigInt.SetString(param.(string), 10); !ok { - err = klderrors.Errorf(klderrors.TransactionSendInputTypeBadNumber, methodName, path) + err = errors.Errorf(errors.TransactionSendInputTypeBadNumber, methodName, path) } } else if suppliedType.Kind() == reflect.Float64 { bigInt.SetInt64(int64(param.(float64))) } else { - err = klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForNumber, methodName, path, requiredType, suppliedType) + err = errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForNumber, methodName, path, requiredType, suppliedType) } return } func (tx *Txn) generateTypedArrayOrSlice(methodName string, path string, requiredType *ethbinding.ABIType, suppliedType reflect.Type, param interface{}) (interface{}, error) { if suppliedType.Kind() != reflect.Slice { - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForArray, methodName, path, requiredType, suppliedType) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForArray, methodName, path, requiredType, suppliedType) } paramV := reflect.ValueOf(param) var genericSlice reflect.Value @@ -522,10 +522,10 @@ func (tx *Txn) generateTupleFromMap(methodName string, path string, requiredType tupleField := tuple.Field(i) if suppliedType == nil { // No known cases where nil can be assigned - return nil, klderrors.Errorf(klderrors.TransactionSendInputNotAssignable, methodName, path, typedVal, inputElemName, requiredType.TupleElems[i]) + return nil, errors.Errorf(errors.TransactionSendInputNotAssignable, methodName, path, typedVal, inputElemName, requiredType.TupleElems[i]) } if !suppliedType.AssignableTo(tupleField.Type()) { - return nil, klderrors.Errorf(klderrors.TransactionSendInputNotAssignable, methodName, path, typedVal, inputElemName, requiredType.TupleElems[i]) + return nil, errors.Errorf(errors.TransactionSendInputNotAssignable, methodName, path, typedVal, inputElemName, requiredType.TupleElems[i]) } tupleField.Set(reflect.ValueOf(typedVal)) } @@ -535,7 +535,7 @@ func (tx *Txn) generateTupleFromMap(methodName string, path string, requiredType func (tx *Txn) generateTypedArg(requiredType *ethbinding.ABIType, param interface{}, methodName string, path string) (interface{}, error) { suppliedType := reflect.TypeOf(param) if suppliedType == nil { - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadNull, methodName, path) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadNull, methodName, path) } switch requiredType.T { case ethbinding.IntTy, ethbinding.UintTy: @@ -580,20 +580,20 @@ func (tx *Txn) generateTypedArg(requiredType *ethbinding.ABIType, param interfac } else if suppliedType.Kind() == reflect.Bool { return param.(bool), nil } - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForBoolean, methodName, path, requiredType, suppliedType) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForBoolean, methodName, path, requiredType, suppliedType) case ethbinding.StringTy: if suppliedType.Kind() == reflect.String { return param.(string), nil } - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForString, methodName, path, suppliedType) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForString, methodName, path, suppliedType) case ethbinding.AddressTy: if suppliedType.Kind() == reflect.String { - if !eth.API.IsHexAddress(param.(string)) { - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeAddress, methodName, path, suppliedType) + if !ethbind.API.IsHexAddress(param.(string)) { + return nil, errors.Errorf(errors.TransactionSendInputTypeAddress, methodName, path, suppliedType) } - return eth.API.HexToAddress(param.(string)), nil + return ethbind.API.HexToAddress(param.(string)), nil } - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForAddress, methodName, path, requiredType, suppliedType) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForAddress, methodName, path, requiredType, suppliedType) case ethbinding.BytesTy, ethbinding.FixedBytesTy: var bSlice []byte if suppliedType.Kind() == reflect.Slice { @@ -606,18 +606,18 @@ func (tx *Txn) generateTypedArg(requiredType *ethbinding.ABIType, param interfac valV = valV.Elem() } if valV.Kind() != reflect.Float64 { - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeInNumericArray, methodName, path, requiredType, i, valV.Kind()) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeInNumericArray, methodName, path, requiredType, i, valV.Kind()) } floatVal := valV.Float() if floatVal > 255 || floatVal < 0 { - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadByteOutsideRange, methodName, path, requiredType) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadByteOutsideRange, methodName, path, requiredType) } bSlice[i] = byte(floatVal) } } else if suppliedType.Kind() == reflect.String { - bSlice = eth.API.FromHex(param.(string)) + bSlice = ethbind.API.FromHex(param.(string)) } else { - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForBytes, methodName, path, requiredType, suppliedType) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForBytes, methodName, path, requiredType, suppliedType) } if len(bSlice) == 0 { return [0]byte{}, nil @@ -633,11 +633,11 @@ func (tx *Txn) generateTypedArg(requiredType *ethbinding.ABIType, param interfac return tx.generateTypedArrayOrSlice(methodName, path, requiredType, suppliedType, param) case ethbinding.TupleTy: if suppliedType.Kind() != reflect.Map || suppliedType.Key().Kind() != reflect.String { - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeBadJSONTypeForTuple, methodName, path, requiredType, suppliedType) + return nil, errors.Errorf(errors.TransactionSendInputTypeBadJSONTypeForTuple, methodName, path, requiredType, suppliedType) } return tx.generateTupleFromMap(methodName, path, requiredType, param.(map[string]interface{})) default: - return nil, klderrors.Errorf(klderrors.TransactionSendInputTypeNotSupported, requiredType) + return nil, errors.Errorf(errors.TransactionSendInputTypeNotSupported, requiredType) } } @@ -657,7 +657,7 @@ func (tx *Txn) generateTypedArgs(origParams []interface{}, method *ethbinding.AB var typedArgs []interface{} for idx, inputArg := range method.Inputs { if idx >= len(params) { - err = klderrors.Errorf(klderrors.TransactionSendInputCountMismatch, methodName, len(method.Inputs), len(params)) + err = errors.Errorf(errors.TransactionSendInputCountMismatch, methodName, len(method.Inputs), len(params)) return nil, err } param := params[idx] @@ -682,7 +682,7 @@ func (tx *Txn) generateTypedArgs(origParams []interface{}, method *ethbinding.AB // A mix is tollerated by the code, but no usecase is known for that. func flattenParams(origParams []interface{}, inputs *ethbinding.ABIArguments, lazyTyping bool) (params []interface{}, err error) { if !lazyTyping && len(origParams) > len(*inputs) { - err = klderrors.Errorf(klderrors.TransactionSendInputTooManyParams, len(origParams), len(*inputs)) + err = errors.Errorf(errors.TransactionSendInputTooManyParams, len(origParams), len(*inputs)) } // Allows us to support params = make([]interface{}, len(origParams)) @@ -704,18 +704,18 @@ func flattenParams(origParams []interface{}, inputs *ethbinding.ABIArguments, la typeStr, exists = mapParam["type"] } if !exists { - err = klderrors.Errorf(klderrors.TransactionSendInputStructureWrong, i) + err = errors.Errorf(errors.TransactionSendInputStructureWrong, i) return } if reflect.TypeOf(typeStr).Kind() != reflect.String { - err = klderrors.Errorf(klderrors.TransactionSendInputInLineTypeArrayNotString, i) + err = errors.Errorf(errors.TransactionSendInputInLineTypeArrayNotString, i) return } params[i] = value // Set the type var ethType ethbinding.ABIType - if ethType, err = eth.API.ABITypeFor(typeStr.(string)); err != nil { - err = klderrors.Errorf(klderrors.TransactionSendInputInLineTypeUnknown, i, typeStr, err) + if ethType, err = ethbind.API.ABITypeFor(typeStr.(string)); err != nil { + err = errors.Errorf(errors.TransactionSendInputInLineTypeUnknown, i, typeStr, err) return } for len(*inputs) <= i { diff --git a/internal/kldeth/txn_test.go b/internal/eth/txn_test.go similarity index 94% rename from internal/kldeth/txn_test.go rename to internal/eth/txn_test.go index 847b9915..3a458e05 100644 --- a/internal/kldeth/txn_test.go +++ b/internal/eth/txn_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" @@ -24,8 +24,8 @@ import ( "testing" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/messages" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -66,7 +66,7 @@ const ( func TestNewContractDeployTxnSimpleStorage(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -97,7 +97,7 @@ func TestNewContractDeployTxnSimpleStorage(t *testing.T) { func TestNewContractDeployTxnSimpleStorageCalcGas(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -128,7 +128,7 @@ func TestNewContractDeployTxnSimpleStorageCalcGas(t *testing.T) { func TestNewContractDeployTxnSimpleStoragePrivate(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -159,7 +159,7 @@ func TestNewContractDeployTxnSimpleStoragePrivate(t *testing.T) { func TestNewContractDeployTxnSimpleStoragePrivateOrion(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -190,7 +190,7 @@ func TestNewContractDeployTxnSimpleStoragePrivateOrion(t *testing.T) { func TestNewContractDeployTxnSimpleStoragePrivateOrionMissingPrivateFrom(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -209,7 +209,7 @@ func TestNewContractDeployTxnSimpleStoragePrivateOrionMissingPrivateFrom(t *test func TestNewContractDeployTxnSimpleStorageCalcGasFailAndCallSucceeds(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -228,7 +228,7 @@ func TestNewContractDeployTxnSimpleStorageCalcGasFailAndCallSucceeds(t *testing. func TestNewContractDeployTxnSimpleStorageCalcGasFailAndCallFailsAsExpected(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -248,7 +248,7 @@ func TestNewContractDeployTxnSimpleStorageCalcGasFailAndCallFailsAsExpected(t *t func TestNewContractDeployMissingCompiledOrSolidity(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" msg.Nonce = "123" @@ -265,7 +265,7 @@ func TestNewContractDeployPrecompiledSimpleStorage(t *testing.T) { c, err := CompileContract(simpleStorage, "simplestorage", "", "") assert.NoError(err) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Compiled = c.Compiled msg.ABI = c.ABI msg.Parameters = []interface{}{float64(999999)} @@ -297,7 +297,7 @@ func TestNewContractDeployPrecompiledSimpleStorage(t *testing.T) { func TestNewContractDeployTxnBadNonce(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -312,7 +312,7 @@ func TestNewContractDeployTxnBadNonce(t *testing.T) { func TestNewContractDeployBadValue(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -327,7 +327,7 @@ func TestNewContractDeployBadValue(t *testing.T) { func TestNewContractDeployBadGas(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -342,7 +342,7 @@ func TestNewContractDeployBadGas(t *testing.T) { func TestNewContractDeployBadGasPrice(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{float64(999999)} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -357,7 +357,7 @@ func TestNewContractDeployBadGasPrice(t *testing.T) { func TestNewContractDeployTxnBadContract(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = "badness" _, err := NewContractDeployTxn(&msg, nil) assert.Regexp("Solidity compilation failed", err.Error()) @@ -366,7 +366,7 @@ func TestNewContractDeployTxnBadContract(t *testing.T) { func TestNewContractDeployStringForNumber(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{"123"} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -381,7 +381,7 @@ func TestNewContractDeployStringForNumber(t *testing.T) { func TestNewContractDeployTxnBadContractName(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.ContractName = "wrongun" _, err := NewContractDeployTxn(&msg, nil) @@ -390,7 +390,7 @@ func TestNewContractDeployTxnBadContractName(t *testing.T) { func TestNewContractDeploySpecificContractName(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = twoContracts msg.ContractName = "contract1" msg.Parameters = []interface{}{} @@ -406,7 +406,7 @@ func TestNewContractDeploySpecificContractName(t *testing.T) { func TestNewContractDeployMissingNameMultipleContracts(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = twoContracts _, err := NewContractDeployTxn(&msg, nil) assert.Regexp("More than one contract in Solidity file", err.Error()) @@ -415,7 +415,7 @@ func TestNewContractDeployMissingNameMultipleContracts(t *testing.T) { func TestNewContractDeployBadNumber(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{"ABCD"} _, err := NewContractDeployTxn(&msg, nil) @@ -425,7 +425,7 @@ func TestNewContractDeployBadNumber(t *testing.T) { func TestNewContractDeployBadTypeForNumber(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{false} _, err := NewContractDeployTxn(&msg, nil) @@ -435,7 +435,7 @@ func TestNewContractDeployBadTypeForNumber(t *testing.T) { func TestNewContractDeployMissingParam(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = simpleStorage msg.Parameters = []interface{}{} _, err := NewContractDeployTxn(&msg, nil) @@ -445,7 +445,7 @@ func TestNewContractDeployMissingParam(t *testing.T) { func testComplexParam(t *testing.T, solidityType string, val interface{}, expectedErr string) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Solidity = "pragma solidity >=0.4.22 <=0.7; contract test {constructor(" + solidityType + " p1) public {}}" msg.Parameters = []interface{}{val} msg.From = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" @@ -574,7 +574,7 @@ func TestTypeNotYetSupported(t *testing.T) { assert := assert.New(t) var tx Txn var m ethbinding.ABIMethod - functionType, err := eth.API.NewType("function", "uint256") + functionType, err := ethbind.API.NewType("function", "uint256") assert.NoError(err) m.Inputs = append(m.Inputs, ethbinding.ABIArgument{Name: "functionType", Type: functionType}) _, err = tx.generateTypedArgs([]interface{}{"abc"}, &m) @@ -584,7 +584,7 @@ func TestTypeNotYetSupported(t *testing.T) { func TestSendTxnABIParam(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{"123", float64(123), "abc", "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c", "0xfeedbeef"} msg.Method = ðbinding.ABIElementMarshaling{ Name: "testFunc", @@ -646,7 +646,7 @@ func TestSendTxnABIParam(t *testing.T) { func TestSendTxnInlineParam(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} param1 := make(map[string]interface{}) @@ -699,7 +699,7 @@ func TestSendTxnInlineParam(t *testing.T) { func TestSendTxnNilParam(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} param1 := make(map[string]interface{}) @@ -721,8 +721,8 @@ func TestSendTxnNilParam(t *testing.T) { func TestNewSendTxnMissingParamTypes(t *testing.T) { assert := assert.New(t) - _, err := NewSendTxn(&kldmessages.SendTransaction{ - TransactionCommon: kldmessages.TransactionCommon{ + _, err := NewSendTxn(&messages.SendTransaction{ + TransactionCommon: messages.TransactionCommon{ Parameters: []interface{}{ map[string]interface{}{ "wrong": "stuff", @@ -760,16 +760,16 @@ func TestCallMethod(t *testing.T) { param4["value"] = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" genMethod := func(params []interface{}) *ethbinding.ABIMethod { - uint256Type, _ := eth.API.ABITypeFor("uint256") + uint256Type, _ := ethbind.API.ABITypeFor("uint256") inputs := make(ethbinding.ABIArguments, len(params)) for i := range params { - abiType, _ := eth.API.ABITypeFor(params[i].(map[string]interface{})["type"].(string)) + abiType, _ := ethbind.API.ABITypeFor(params[i].(map[string]interface{})["type"].(string)) inputs[i] = ethbinding.ABIArgument{ Type: abiType, } } outputs := ethbinding.ABIArguments{ethbinding.ABIArgument{Name: "retval1", Type: uint256Type}} - method := eth.API.NewMethod("testFunc", "testFunc", ethbinding.Function, "payable", false, true, inputs, outputs) + method := ethbind.API.NewMethod("testFunc", "testFunc", ethbinding.Function, "payable", false, true, inputs, outputs) return &method } @@ -957,7 +957,7 @@ func TestCallMethodBadArgs(t *testing.T) { func TestSendTxnNodeAssignNonce(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} param1 := make(map[string]interface{}) @@ -1010,7 +1010,7 @@ func TestSendTxnNodeAssignNonce(t *testing.T) { func TestSendWithTXSignerContractOK(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} signer := &mockTXSigner{ @@ -1038,7 +1038,7 @@ func TestSendWithTXSignerContractOK(t *testing.T) { func TestSendWithTXSignerOK(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} signer := &mockTXSigner{ @@ -1068,7 +1068,7 @@ func TestSendWithTXSignerOK(t *testing.T) { func TestSendWithTXSignerFail(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} signer := &mockTXSigner{ @@ -1097,7 +1097,7 @@ func TestSendWithTXSignerFail(t *testing.T) { func TestSendWithTXSignerFailPrivate(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} signer := &mockTXSigner{ @@ -1127,7 +1127,7 @@ func TestSendWithTXSignerFailPrivate(t *testing.T) { func TestNewContractWithTXSignerOK(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Parameters = []interface{}{} signer := &mockTXSigner{ @@ -1157,7 +1157,7 @@ func TestNewContractWithTXSignerOK(t *testing.T) { func TestNewNilTXSignerOK(t *testing.T) { assert := assert.New(t) - var msg kldmessages.DeployContract + var msg messages.DeployContract msg.Parameters = []interface{}{} signer := &mockTXSigner{ @@ -1185,7 +1185,7 @@ func TestNewNilTXSignerOK(t *testing.T) { func TestSendTxnRPFError(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} msg.MethodName = "testFunc" @@ -1211,7 +1211,7 @@ func TestSendTxnRPFError(t *testing.T) { func TestSendTxnInlineBadParamType(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} param1 := make(map[string]interface{}) @@ -1235,7 +1235,7 @@ func TestSendTxnInlineBadParamType(t *testing.T) { func TestSendTxnInlineMissingParamType(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} param1 := make(map[string]interface{}) @@ -1258,7 +1258,7 @@ func TestSendTxnInlineMissingParamType(t *testing.T) { func TestSendTxnInlineMissingParamValue(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} param1 := make(map[string]interface{}) @@ -1281,7 +1281,7 @@ func TestSendTxnInlineMissingParamValue(t *testing.T) { func TestSendTxnInlineBadTypeType(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{} param1 := make(map[string]interface{}) @@ -1304,7 +1304,7 @@ func TestSendTxnInlineBadTypeType(t *testing.T) { func TestSendTxnBadInputType(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Method = ðbinding.ABIElementMarshaling{ Name: "testFunc", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -1327,7 +1327,7 @@ func TestSendTxnBadInputType(t *testing.T) { func TestSendTxnMissingMethod(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{"123"} msg.Method = ðbinding.ABIElementMarshaling{} msg.To = "0x2b8c0ECc76d0759a8F50b2E14A6881367D805832" @@ -1342,7 +1342,7 @@ func TestSendTxnMissingMethod(t *testing.T) { func TestSendTxnBadFrom(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{"123"} msg.Method = ðbinding.ABIElementMarshaling{ Name: "testFunc", @@ -1372,7 +1372,7 @@ func TestSendTxnBadFrom(t *testing.T) { func TestSendTxnBadTo(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{"123"} msg.Method = ðbinding.ABIElementMarshaling{ Name: "testFunc", @@ -1402,7 +1402,7 @@ func TestSendTxnBadTo(t *testing.T) { func TestSendTxnBadOutputType(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Method = ðbinding.ABIElementMarshaling{ Name: "testFunc", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -1425,7 +1425,7 @@ func TestSendTxnBadOutputType(t *testing.T) { func TestSendBadParams(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{"abc"} msg.Method = ðbinding.ABIElementMarshaling{ Name: "testFunc", @@ -1449,7 +1449,7 @@ func TestSendBadParams(t *testing.T) { func TestSendTxnPackError(t *testing.T) { assert := assert.New(t) - var msg kldmessages.SendTransaction + var msg messages.SendTransaction msg.Parameters = []interface{}{""} msg.Method = ðbinding.ABIElementMarshaling{ Name: "testFunc", @@ -1473,15 +1473,15 @@ func TestSendTxnPackError(t *testing.T) { func TestProcessRLPBytesValidTypes(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("string") - t2, _ := eth.API.ABITypeFor("int256[]") - t3, _ := eth.API.ABITypeFor("bool") - t4, _ := eth.API.ABITypeFor("bytes1") - t5, _ := eth.API.ABITypeFor("address") - t6, _ := eth.API.ABITypeFor("bytes4") - t7, _ := eth.API.ABITypeFor("uint256") - t8, _ := eth.API.ABITypeFor("int32[]") - t9, _ := eth.API.ABITypeFor("uint32[]") + t1, _ := ethbind.API.ABITypeFor("string") + t2, _ := ethbind.API.ABITypeFor("int256[]") + t3, _ := ethbind.API.ABITypeFor("bool") + t4, _ := ethbind.API.ABITypeFor("bytes1") + t5, _ := ethbind.API.ABITypeFor("address") + t6, _ := ethbind.API.ABITypeFor("bytes4") + t7, _ := ethbind.API.ABITypeFor("uint256") + t8, _ := ethbind.API.ABITypeFor("int32[]") + t9, _ := ethbind.API.ABITypeFor("uint32[]") methodABI := ðbinding.ABIMethod{ Name: "echoTypes2", Inputs: []ethbinding.ABIArgument{}, @@ -1654,7 +1654,7 @@ func TestGenerateTupleFromMapBadStructType(t *testing.T) { assert := assert.New(t) tx := Txn{} type random struct{ stuff string } - tUint, _ := eth.API.ABITypeFor("uint256") + tUint, _ := ethbind.API.ABITypeFor("uint256") _, err := tx.generateTupleFromMap("method1", "test", ðbinding.ABIType{ TupleType: reflect.TypeOf((*random)(nil)).Elem(), // random type that should never happen TupleRawNames: []string{"field1"}, @@ -1683,7 +1683,7 @@ func TestGenTupleMapOutputBadTypeCountMismatch(t *testing.T) { func TestGenTupleMapOutputBadTypeValMismatch(t *testing.T) { assert := assert.New(t) type random struct{ Field1 string } - tUint, _ := eth.API.ABITypeFor("uint256") + tUint, _ := ethbind.API.ABITypeFor("uint256") _, err := genTupleMapOutput("test", "random", ðbinding.ABIType{ TupleType: reflect.TypeOf((*random)(nil)).Elem(), TupleRawNames: []string{"field1"}, @@ -1695,7 +1695,7 @@ func TestGenTupleMapOutputBadTypeValMismatch(t *testing.T) { func TestProcessRLPBytesInvalidNumber(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("int32") + t1, _ := ethbind.API.ABITypeFor("int32") _, err := mapOutput("test1", "int256", &t1, "not an int") assert.EqualError(err, "Expected number type in JSON/RPC response for test1 (int256). Received string") } @@ -1703,7 +1703,7 @@ func TestProcessRLPBytesInvalidNumber(t *testing.T) { func TestProcessRLPBytesInvalidBool(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("bool") + t1, _ := ethbind.API.ABITypeFor("bool") _, err := mapOutput("test1", "bool", &t1, "not a bool") assert.EqualError(err, "Expected boolean type in JSON/RPC response for test1 (bool). Received string") } @@ -1711,7 +1711,7 @@ func TestProcessRLPBytesInvalidBool(t *testing.T) { func TestProcessRLPBytesInvalidString(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("string") + t1, _ := ethbind.API.ABITypeFor("string") _, err := mapOutput("test1", "string", &t1, 42) assert.EqualError(err, "Expected string array type in JSON/RPC response for test1 (string). Received int") } @@ -1719,7 +1719,7 @@ func TestProcessRLPBytesInvalidString(t *testing.T) { func TestProcessRLPBytesInvalidByteArray(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("address") + t1, _ := ethbind.API.ABITypeFor("address") _, err := mapOutput("test1", "address", &t1, 42) assert.EqualError(err, "Expected []byte type in JSON/RPC response for test1 (address). Received int") } @@ -1727,7 +1727,7 @@ func TestProcessRLPBytesInvalidByteArray(t *testing.T) { func TestProcessRLPBytesInvalidArray(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("int32[]") + t1, _ := ethbind.API.ABITypeFor("int32[]") _, err := mapOutput("test1", "int32[]", &t1, 42) assert.EqualError(err, "Expected slice type in JSON/RPC response for test1 (int32[]). Received int") } @@ -1735,7 +1735,7 @@ func TestProcessRLPBytesInvalidArray(t *testing.T) { func TestProcessRLPBytesInvalidArrayType(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("int32[]") + t1, _ := ethbind.API.ABITypeFor("int32[]") _, err := mapOutput("test1", "int32[]", &t1, []string{"wrong"}) assert.EqualError(err, "Expected number type in JSON/RPC response for test1[0] (int32[]). Received string") } @@ -1743,7 +1743,7 @@ func TestProcessRLPBytesInvalidArrayType(t *testing.T) { func TestProcessRLPBytesInvalidTypeByte(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("bool") + t1, _ := ethbind.API.ABITypeFor("bool") t1.T = 42 _, err := mapOutput("test1", "randomness", &t1, 42) assert.EqualError(err, "Unable to process type for test1 (randomness). Received int") @@ -1752,7 +1752,7 @@ func TestProcessRLPBytesInvalidTypeByte(t *testing.T) { func TestProcessRLPBytesUnpackFailure(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("string") + t1, _ := ethbind.API.ABITypeFor("string") methodABI := ðbinding.ABIMethod{ Name: "echoTypes2", Inputs: []ethbinding.ABIArgument{}, @@ -1768,7 +1768,7 @@ func TestProcessRLPBytesUnpackFailure(t *testing.T) { func TestProcessOutputsTooFew(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("string") + t1, _ := ethbind.API.ABITypeFor("string") methodABI := ðbinding.ABIMethod{ Name: "echoTypes2", Inputs: []ethbinding.ABIArgument{}, @@ -1797,7 +1797,7 @@ func TestProcessOutputsTooMany(t *testing.T) { func TestProcessOutputsDefaultName(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("string") + t1, _ := ethbind.API.ABITypeFor("string") methodABI := ðbinding.ABIMethod{ Name: "anonReturn", Inputs: []ethbinding.ABIArgument{}, @@ -1816,7 +1816,7 @@ func TestProcessOutputsDefaultName(t *testing.T) { func TestProcessOutputsBadArgs(t *testing.T) { assert := assert.New(t) - t1, _ := eth.API.ABITypeFor("int32[]") + t1, _ := ethbind.API.ABITypeFor("int32[]") methodABI := ðbinding.ABIMethod{ Name: "echoTypes2", Inputs: []ethbinding.ABIArgument{}, diff --git a/internal/kldeth/txncount.go b/internal/eth/txncount.go similarity index 88% rename from internal/kldeth/txncount.go rename to internal/eth/txncount.go index 4b6d593a..0c0b94b6 100644 --- a/internal/kldeth/txncount.go +++ b/internal/eth/txncount.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" @@ -21,7 +21,7 @@ import ( log "github.com/sirupsen/logrus" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" ) // GetOrionTXCount uses the special Pantheon/Orion interface to check the @@ -34,7 +34,7 @@ func GetOrionTXCount(ctx context.Context, rpc RPCClient, addr *ethbinding.Addres var txnCount ethbinding.HexUint64 if err := rpc.CallContext(ctx, &txnCount, "priv_getTransactionCount", addr, privacyGroup); err != nil { - return 0, klderrors.Errorf(klderrors.TransactionSendNonceFailWithPrivacyGroup, privacyGroup, err) + return 0, errors.Errorf(errors.TransactionSendNonceFailWithPrivacyGroup, privacyGroup, err) } callTime := time.Now().UTC().Sub(start) log.Debugf("priv_getTransactionCount(%x,%s)=%d [%.2fs]", addr, privacyGroup, txnCount, callTime.Seconds()) @@ -51,7 +51,7 @@ func GetTransactionCount(ctx context.Context, rpc RPCClient, addr *ethbinding.Ad var txnCount ethbinding.HexUint64 if err := rpc.CallContext(ctx, &txnCount, "eth_getTransactionCount", addr, blockNumber); err != nil { - return 0, klderrors.Errorf(klderrors.RPCCallReturnedError, "eth_getTransactionCount", err) + return 0, errors.Errorf(errors.RPCCallReturnedError, "eth_getTransactionCount", err) } callTime := time.Now().UTC().Sub(start) log.Debugf("eth_getTransactionCount(%x,latest)=%d [%.2fs]", addr, txnCount, callTime.Seconds()) diff --git a/internal/kldeth/txncount_test.go b/internal/eth/txncount_test.go similarity index 84% rename from internal/kldeth/txncount_test.go rename to internal/eth/txncount_test.go index 8503e6d2..9841b306 100644 --- a/internal/kldeth/txncount_test.go +++ b/internal/eth/txncount_test.go @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldeth +package eth import ( "context" "fmt" "testing" - "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/ethbind" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -30,7 +30,7 @@ func TestGetTransactionCount(t *testing.T) { r := testRPCClient{} - addr := eth.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") + addr := ethbind.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") _, err := GetTransactionCount(context.Background(), &r, &addr, "latest") assert.Equal(nil, err) @@ -45,7 +45,7 @@ func TestGetTransactionCountErr(t *testing.T) { mockError: fmt.Errorf("pop"), } - addr := eth.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") + addr := ethbind.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") _, err := GetTransactionCount(context.Background(), &r, &addr, "latest") assert.EqualError(err, "eth_getTransactionCount returned: pop") @@ -57,7 +57,7 @@ func TestGetOrionPrivateTransactionCount(t *testing.T) { r := testRPCClient{} - addr := eth.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") + addr := ethbind.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") _, err := GetOrionTXCount(context.Background(), &r, &addr, "negmDcN2P4ODpqn/6WkJ02zT/0w0bjhGpkZ8UP6vARk=") assert.Equal(nil, err) @@ -72,7 +72,7 @@ func TestGetOrionPrivateTransactionCountErr(t *testing.T) { mockError: fmt.Errorf("pop"), } - addr := eth.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") + addr := ethbind.API.HexToAddress("0xD50ce736021D9F7B0B2566a3D2FA7FA3136C003C") _, err := GetOrionTXCount(context.Background(), &r, &addr, "negmDcN2P4ODpqn/6WkJ02zT/0w0bjhGpkZ8UP6vARk=") assert.EqualError(err, "priv_getTransactionCount for privacy group 'negmDcN2P4ODpqn/6WkJ02zT/0w0bjhGpkZ8UP6vARk=' returned: pop") diff --git a/internal/eth/ethbinding.go b/internal/ethbind/ethbinding.go similarity index 99% rename from internal/eth/ethbinding.go rename to internal/ethbind/ethbinding.go index 6fa8d871..c68ba8c2 100644 --- a/internal/eth/ethbinding.go +++ b/internal/ethbind/ethbinding.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package eth +package ethbind import ( "fmt" diff --git a/internal/kldevents/eventstream.go b/internal/events/eventstream.go similarity index 95% rename from internal/kldevents/eventstream.go rename to internal/events/eventstream.go index 102dfdeb..36f5ee24 100644 --- a/internal/kldevents/eventstream.go +++ b/internal/events/eventstream.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "container/list" @@ -24,10 +24,10 @@ import ( "sync" "time" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldws" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/ws" lru "github.com/hashicorp/golang-lru" log "github.com/sirupsen/logrus" @@ -59,7 +59,7 @@ const ( // StreamInfo configures the stream to perform an action for each event type StreamInfo struct { - kldmessages.TimeSorted + messages.TimeSorted ID string `json:"id"` Name string `json:"name,omitempty"` Path string `json:"path"` @@ -108,7 +108,7 @@ type eventStream struct { updateWG *sync.WaitGroup // Wait group for the go routines to reply back after they have stopped blockTimestampCache *lru.Cache action eventStreamAction - wsChannels kldws.WebSocketChannels + wsChannels ws.WebSocketChannels } type eventStreamAction interface { @@ -117,7 +117,7 @@ type eventStreamAction interface { func validateWebSocket(w *webSocketActionInfo) error { if w.DistributionMode != "" && w.DistributionMode != DistributionModeBroadcast && w.DistributionMode != DistributionModeWLD { - return klderrors.Errorf(klderrors.EventStreamsInvalidDistributionMode, w.DistributionMode) + return errors.Errorf(errors.EventStreamsInvalidDistributionMode, w.DistributionMode) } return nil } @@ -126,9 +126,9 @@ func validateWebSocket(w *webSocketActionInfo) error { // off the event batch processor, and blockHWM will be // initialied to that supplied (zero on initial, or the // value from the checkpoint) -func newEventStream(sm subscriptionManager, spec *StreamInfo, wsChannels kldws.WebSocketChannels) (a *eventStream, err error) { +func newEventStream(sm subscriptionManager, spec *StreamInfo, wsChannels ws.WebSocketChannels) (a *eventStream, err error) { if spec == nil || spec.GetID() == "" { - return nil, klderrors.Errorf(klderrors.EventStreamsNoID) + return nil, errors.Errorf(errors.EventStreamsNoID) } if spec.BatchSize == 0 { @@ -165,7 +165,7 @@ func newEventStream(sm subscriptionManager, spec *StreamInfo, wsChannels kldws.W } if a.blockTimestampCache, err = lru.New(spec.TimestampCacheSize); err != nil { - return nil, klderrors.Errorf(klderrors.EventStreamsCreateStreamResourceErr, err) + return nil, errors.Errorf(errors.EventStreamsCreateStreamResourceErr, err) } if a.pollingInterval == 0 { // Let's us do this from UTs, without exposing it @@ -190,7 +190,7 @@ func newEventStream(sm subscriptionManager, spec *StreamInfo, wsChannels kldws.W return nil, err } default: - return nil, klderrors.Errorf(klderrors.EventStreamsInvalidActionType, spec.Type) + return nil, errors.Errorf(errors.EventStreamsInvalidActionType, spec.Type) } a.startEventHandlers(false) @@ -248,14 +248,14 @@ func (a *eventStream) update(newSpec *StreamInfo) (spec *StreamInfo, err error) a.updateWG.Wait() if newSpec.Type != "" && newSpec.Type != a.spec.Type { - return nil, klderrors.Errorf(klderrors.EventStreamsCannotUpdateType) + return nil, errors.Errorf(errors.EventStreamsCannotUpdateType) } if a.spec.Type == "webhook" && newSpec.Webhook != nil { if newSpec.Webhook.URL == "" { - return nil, klderrors.Errorf(klderrors.EventStreamsWebhookNoURL) + return nil, errors.Errorf(errors.EventStreamsWebhookNoURL) } if _, err = url.Parse(newSpec.Webhook.URL); err != nil { - return nil, klderrors.Errorf(klderrors.EventStreamsWebhookInvalidURL) + return nil, errors.Errorf(errors.EventStreamsWebhookInvalidURL) } if newSpec.Webhook.RequestTimeoutSec == 0 { newSpec.Webhook.RequestTimeoutSec = 120 @@ -326,7 +326,7 @@ func (a *eventStream) resume() error { a.batchCond.L.Lock() defer a.batchCond.L.Unlock() if !a.processorDone || !a.pollerDone { - return klderrors.Errorf(klderrors.EventStreamsWebhookResumeActive, a.spec.Suspended) + return errors.Errorf(errors.EventStreamsWebhookResumeActive, a.spec.Suspended) } a.spec.Suspended = false a.processorDone = false @@ -365,7 +365,7 @@ func (a *eventStream) markAllSubscriptionsStale(ctx context.Context) { func (a *eventStream) eventPoller() { defer a.updateWG.Done() - ctx := kldauth.NewSystemAuthContext() + ctx := auth.NewSystemAuthContext() defer func() { a.pollerDone = true }() var checkpoint map[string]*big.Int diff --git a/internal/kldevents/eventstream_test.go b/internal/events/eventstream_test.go similarity index 94% rename from internal/kldevents/eventstream_test.go rename to internal/events/eventstream_test.go index 827f30d9..d5fc6cad 100644 --- a/internal/kldevents/eventstream_test.go +++ b/internal/events/eventstream_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "context" @@ -27,10 +27,10 @@ import ( "time" ethbinding "github.com/kaleido-io/ethbinding/pkg" + "github.com/kaleido-io/ethconnect/internal/errors" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldkvstore" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/kvstore" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -91,7 +91,7 @@ func testEvent(subID string) *eventData { } } -func newTestStreamForBatching(spec *StreamInfo, db kldkvstore.KVStore, status ...int) (*subscriptionMGR, *eventStream, *httptest.Server, chan []*eventData) { +func newTestStreamForBatching(spec *StreamInfo, db kvstore.KVStore, status ...int) (*subscriptionMGR, *eventStream, *httptest.Server, chan []*eventData) { mux := http.NewServeMux() eventStream := make(chan []*eventData) count := 0 @@ -123,7 +123,7 @@ func newTestStreamForBatching(spec *StreamInfo, db kldkvstore.KVStore, status .. return sm, sm.streams[stream.ID], svr, eventStream } -func newTestStreamForWebSocket(spec *StreamInfo, db kldkvstore.KVStore, status ...int) (*subscriptionMGR, *eventStream, *mockWebSocket) { +func newTestStreamForWebSocket(spec *StreamInfo, db kvstore.KVStore, status ...int) (*subscriptionMGR, *eventStream, *mockWebSocket) { sm := newTestSubscriptionManager() sm.config().EventPollingIntervalSec = 0 if db != nil { @@ -430,7 +430,7 @@ func setupTestSubscription(assert *assert.Assertions, sm *subscriptionMGR, strea testBlock.Time = uint64(ts) callCount := 0 - rpc := kldeth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { + rpc := eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { callCount++ if method == "eth_blockNumber" || method == "eth_newFilter" { } else if method == "eth_getFilterLogs" { @@ -474,7 +474,7 @@ func setupTestSubscription(assert *assert.Assertions, sm *subscriptionMGR, strea }, }, } - addr := eth.API.HexToAddress("0x167f57a13a9c35ff92f0649d2be0e52b4f8ac3ca") + addr := ethbind.API.HexToAddress("0x167f57a13a9c35ff92f0649d2be0e52b4f8ac3ca") ctx := context.Background() s, _ := sm.AddSubscription(ctx, &addr, event, stream.spec.ID, "", subscriptionName) return s @@ -485,7 +485,7 @@ func TestProcessEventsEnd2EndWebhook(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ BatchSize: 1, @@ -534,7 +534,7 @@ func TestProcessEventsEnd2EndWebSocket(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, mockWebSocket := newTestStreamForWebSocket( &StreamInfo{ BatchSize: 1, @@ -586,7 +586,7 @@ func TestProcessEventsEnd2EndWithTimestamps(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ BatchSize: 1, @@ -638,7 +638,7 @@ func TestProcessEventsEnd2EndWithReset(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ BatchSize: 1, @@ -811,7 +811,7 @@ func TestCheckpointRecovery(t *testing.T) { var newFilterBlock uint64 sub := sm.subscriptions[s.ID] sub.filterStale = true - sub.rpc = kldeth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { + sub.rpc = eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { if method == "eth_newFilter" { newFilterBlock = args[0].(*ethFilter).FromBlock.ToInt().Uint64() t.Logf("New filter block after checkpoint recovery: %d", newFilterBlock) @@ -854,7 +854,7 @@ func TestWithoutCheckpointRecovery(t *testing.T) { var initialEndBlock string sub := sm.subscriptions[s.ID] sub.filterStale = true - sub.rpc = kldeth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { + sub.rpc = eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { if method == "eth_blockNumber" { } else if method == "eth_newFilter" { initialEndBlock = args[0].(*ethFilter).ToBlock @@ -896,7 +896,7 @@ func TestMarkStaleOnError(t *testing.T) { sm.subscriptions[s.ID].filterStale = false sub := sm.subscriptions[s.ID] - sub.rpc = kldeth.NewMockRPCClientForSync(fmt.Errorf("filter not found"), nil) + sub.rpc = eth.NewMockRPCClientForSync(fmt.Errorf("filter not found"), nil) stream.resume() for stream.pollerDone { @@ -914,7 +914,7 @@ func TestStoreCheckpointLoadError(t *testing.T) { ErrorHandling: ErrorHandlingBlock, Webhook: &webhookActionInfo{}, }, nil, 200) - mockKV := kldkvstore.NewMockKV(fmt.Errorf("pop")) + mockKV := kvstore.NewMockKV(fmt.Errorf("pop")) sm.db = mockKV defer close(eventStream) defer svr.Close() @@ -937,7 +937,7 @@ func TestStoreCheckpointStoreError(t *testing.T) { ErrorHandling: ErrorHandlingBlock, Webhook: &webhookActionInfo{}, }, nil, 200) - mockKV := kldkvstore.NewMockKV(nil) + mockKV := kvstore.NewMockKV(nil) mockKV.StoreErr = fmt.Errorf("pop") defer close(eventStream) defer svr.Close() @@ -966,7 +966,7 @@ func TestProcessBatchEmptyArray(t *testing.T) { ErrorHandling: ErrorHandlingBlock, Webhook: &webhookActionInfo{}, }, nil, 200) - mockKV := kldkvstore.NewMockKV(nil) + mockKV := kvstore.NewMockKV(nil) mockKV.StoreErr = fmt.Errorf("pop") sm.db = mockKV defer close(eventStream) @@ -986,7 +986,7 @@ func TestUpdateStream(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ ErrorHandling: ErrorHandlingBlock, @@ -1035,7 +1035,7 @@ func TestUpdateStreamSwapType(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ ErrorHandling: ErrorHandlingBlock, @@ -1062,7 +1062,7 @@ func TestUpdateWebSocketBadDistributionMode(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ ErrorHandling: ErrorHandlingBlock, @@ -1093,7 +1093,7 @@ func TestUpdateWebSocket(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ ErrorHandling: ErrorHandlingBlock, @@ -1125,7 +1125,7 @@ func TestWebSocketClientClosedOnSend(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) _, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ ErrorHandling: ErrorHandlingBlock, @@ -1158,7 +1158,7 @@ func TestWebSocketClientClosedOnReceive(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) _, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ ErrorHandling: ErrorHandlingBlock, @@ -1193,7 +1193,7 @@ func TestUpdateStreamMissingWebhookURL(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ ErrorHandling: ErrorHandlingBlock, @@ -1225,7 +1225,7 @@ func TestUpdateStreamMissingWebhookURL(t *testing.T) { }, } _, err := sm.UpdateStream(ctx, stream.spec.ID, updateSpec) - assert.EqualError(err, klderrors.EventStreamsWebhookNoURL) + assert.EqualError(err, errors.EventStreamsWebhookNoURL) err = sm.DeleteSubscription(ctx, s.ID) assert.NoError(err) err = sm.DeleteStream(ctx, stream.spec.ID) @@ -1238,7 +1238,7 @@ func TestUpdateStreamInvalidWebhookURL(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) - db, _ := kldkvstore.NewLDBKeyValueStore(dir) + db, _ := kvstore.NewLDBKeyValueStore(dir) sm, stream, svr, eventStream := newTestStreamForBatching( &StreamInfo{ ErrorHandling: ErrorHandlingBlock, @@ -1270,7 +1270,7 @@ func TestUpdateStreamInvalidWebhookURL(t *testing.T) { }, } _, err := sm.UpdateStream(ctx, stream.spec.ID, updateSpec) - assert.EqualError(err, klderrors.EventStreamsWebhookInvalidURL) + assert.EqualError(err, errors.EventStreamsWebhookInvalidURL) err = sm.DeleteSubscription(ctx, s.ID) assert.NoError(err) err = sm.DeleteStream(ctx, stream.spec.ID) diff --git a/internal/kldevents/logprocessor.go b/internal/events/logprocessor.go similarity index 89% rename from internal/kldevents/logprocessor.go rename to internal/events/logprocessor.go index 30ef0189..07a7109c 100644 --- a/internal/kldevents/logprocessor.go +++ b/internal/events/logprocessor.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "math/big" @@ -21,9 +21,9 @@ import ( "sync" ethbinding "github.com/kaleido-io/ethbinding/pkg" + "github.com/kaleido-io/ethconnect/internal/errors" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" + "github.com/kaleido-io/ethconnect/internal/ethbind" log "github.com/sirupsen/logrus" ) @@ -96,9 +96,9 @@ func (lp *logProcessor) processLogEntry(subInfo string, entry *logEntry, idx int var data []byte if strings.HasPrefix(entry.Data, "0x") { - data, err = eth.API.HexDecode(entry.Data) + data, err = ethbind.API.HexDecode(entry.Data) if err != nil { - return klderrors.Errorf(klderrors.EventStreamsLogDecode, subInfo, err) + return errors.Errorf(errors.EventStreamsLogDecode, subInfo, err) } } @@ -107,7 +107,7 @@ func (lp *logProcessor) processLogEntry(subInfo string, entry *logEntry, idx int BlockNumber: entry.BlockNumber.ToInt().String(), TransactionIndex: entry.TransactionIndex.String(), TransactionHash: entry.TransactionHash.String(), - Signature: eth.API.ABIEventSignature(lp.event), + Signature: ethbind.API.ABIEventSignature(lp.event), Data: make(map[string]interface{}), SubID: lp.subID, LogIndex: strconv.Itoa(idx), @@ -128,7 +128,7 @@ func (lp *logProcessor) processLogEntry(subInfo string, entry *logEntry, idx int var val interface{} if input.Indexed { if topicIdx >= len(entry.Topics) { - return klderrors.Errorf(klderrors.EventStreamsLogDecodeInsufficientTopics, subInfo, idx, eth.API.ABIEventSignature(lp.event)) + return errors.Errorf(errors.EventStreamsLogDecodeInsufficientTopics, subInfo, idx, ethbind.API.ABIEventSignature(lp.event)) } topic := entry.Topics[topicIdx] topicIdx++ @@ -145,7 +145,7 @@ func (lp *logProcessor) processLogEntry(subInfo string, entry *logEntry, idx int // Retrieve the data args from the RLP and merge the results if len(dataArgs) > 0 { - dataMap := kldeth.ProcessRLPBytes(dataArgs, data) + dataMap := eth.ProcessRLPBytes(dataArgs, data) for k, v := range dataMap { result.Data[k] = v } @@ -162,10 +162,10 @@ func topicToValue(topic *ethbinding.Hash, input *ethbinding.ABIArgument) interfa case ethbinding.IntTy, ethbinding.UintTy, ethbinding.BoolTy: h := ethbinding.HexBigInt{} h.UnmarshalText([]byte(topic.Hex())) - bI, _ := eth.API.ParseBig256(topic.Hex()) + bI, _ := ethbind.API.ParseBig256(topic.Hex()) if input.Type.T == ethbinding.IntTy { // It will be a two's complement number, so needs to be interpretted - bI = eth.API.S256(bI) + bI = ethbind.API.S256(bI) return bI.String() } else if input.Type.T == ethbinding.BoolTy { return (bI.Uint64() != 0) @@ -174,7 +174,7 @@ func topicToValue(topic *ethbinding.Hash, input *ethbinding.ABIArgument) interfa case ethbinding.AddressTy: topicBytes := topic.Bytes() addrBytes := topicBytes[len(topicBytes)-20:] - return eth.API.BytesToAddress(addrBytes) + return ethbind.API.BytesToAddress(addrBytes) default: // For all other types it is just a hash of the output for indexing, so we can only // logically return it as a hex string. The Solidity developer has to include diff --git a/internal/kldevents/logprocessor_test.go b/internal/events/logprocessor_test.go similarity index 73% rename from internal/kldevents/logprocessor_test.go rename to internal/events/logprocessor_test.go index 05e6a025..587e51ad 100644 --- a/internal/kldevents/logprocessor_test.go +++ b/internal/events/logprocessor_test.go @@ -12,15 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "encoding/json" "testing" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" - + "github.com/kaleido-io/ethconnect/internal/ethbind" "github.com/stretchr/testify/assert" ) @@ -61,28 +60,28 @@ const sampleEventABIAllIndexedNoData = ` func TestTopicToValue(t *testing.T) { assert := assert.New(t) - h := eth.API.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffcfc7") - v := topicToValue(&h, ðbinding.ABIArgument{Type: eth.API.ABITypeKnown("int64")}) + h := ethbind.API.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffcfc7") + v := topicToValue(&h, ðbinding.ABIArgument{Type: ethbind.API.ABITypeKnown("int64")}) assert.Equal("-12345", v) - h = eth.API.HexToHash("0x000000000000000000000000000000000000000001d2d490d572353317a01f8d") - v = topicToValue(&h, ðbinding.ABIArgument{Type: eth.API.ABITypeKnown("uint256")}) + h = ethbind.API.HexToHash("0x000000000000000000000000000000000000000001d2d490d572353317a01f8d") + v = topicToValue(&h, ðbinding.ABIArgument{Type: ethbind.API.ABITypeKnown("uint256")}) assert.Equal("564363245346346345353453453", v) - h = eth.API.HexToHash("0x0000000000000000000000003924d1d6423f88148a4fcc0417a33b27a61d595f") - v = topicToValue(&h, ðbinding.ABIArgument{Type: eth.API.ABITypeKnown("address")}) - assert.Equal(eth.API.HexToAddress("0x3924d1D6423F88148A4fcc0417A33B27a61d595f"), v) + h = ethbind.API.HexToHash("0x0000000000000000000000003924d1d6423f88148a4fcc0417a33b27a61d595f") + v = topicToValue(&h, ðbinding.ABIArgument{Type: ethbind.API.ABITypeKnown("address")}) + assert.Equal(ethbind.API.HexToAddress("0x3924d1D6423F88148A4fcc0417A33B27a61d595f"), v) - h = eth.API.HexToHash("0xdc47fb175244491f21a29733a67d2e07647d59d2f36f2603d339299587182f19") - v = topicToValue(&h, ðbinding.ABIArgument{Type: eth.API.ABITypeKnown("string")}) + h = ethbind.API.HexToHash("0xdc47fb175244491f21a29733a67d2e07647d59d2f36f2603d339299587182f19") + v = topicToValue(&h, ðbinding.ABIArgument{Type: ethbind.API.ABITypeKnown("string")}) assert.Equal("0xdc47fb175244491f21a29733a67d2e07647d59d2f36f2603d339299587182f19", v) - h = eth.API.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000") - v = topicToValue(&h, ðbinding.ABIArgument{Type: eth.API.ABITypeKnown("bool")}) + h = ethbind.API.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000") + v = topicToValue(&h, ðbinding.ABIArgument{Type: ethbind.API.ABITypeKnown("bool")}) assert.Equal(false, v) - h = eth.API.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000001") - v = topicToValue(&h, ðbinding.ABIArgument{Type: eth.API.ABITypeKnown("bool")}) + h = ethbind.API.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000001") + v = topicToValue(&h, ðbinding.ABIArgument{Type: ethbind.API.ABITypeKnown("bool")}) assert.Equal(true, v) } @@ -107,7 +106,7 @@ func TestProcessLogEntryNillAndTooFewFields(t *testing.T) { }` var marshaling ethbinding.ABIElementMarshaling json.Unmarshal([]byte(eventABI), &marshaling) - event, err := eth.API.ABIElementMarshalingToABIEvent(&marshaling) + event, err := ethbind.API.ABIElementMarshalingToABIEvent(&marshaling) assert.NoError(err) lp := &logProcessor{ @@ -141,7 +140,7 @@ func TestProcessLogBadRLPData(t *testing.T) { var marshaling ethbinding.ABIElementMarshaling err := json.Unmarshal([]byte(eventABI), &marshaling) assert.NoError(err) - event, _ := eth.API.ABIElementMarshalingToABIEvent(&marshaling) + event, _ := ethbind.API.ABIElementMarshalingToABIEvent(&marshaling) lp := &logProcessor{ event: event, stream: stream, @@ -167,7 +166,7 @@ func TestProcessLogSampleEvent(t *testing.T) { } var marshaling ethbinding.ABIElementMarshaling json.Unmarshal([]byte(sampleEventABIAllIndexedNoData), &marshaling) - event, _ := eth.API.ABIElementMarshalingToABIEvent(&marshaling) + event, _ := ethbind.API.ABIElementMarshalingToABIEvent(&marshaling) lp := &logProcessor{ event: event, stream: stream, diff --git a/internal/kldevents/submanager.go b/internal/events/submanager.go similarity index 90% rename from internal/kldevents/submanager.go rename to internal/events/submanager.go index 96f5e7cc..addccf9d 100644 --- a/internal/kldevents/submanager.go +++ b/internal/events/submanager.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "context" @@ -24,12 +24,12 @@ import ( "github.com/spf13/cobra" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldkvstore" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldutils" - "github.com/kaleido-io/ethconnect/internal/kldws" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/kvstore" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/utils" + "github.com/kaleido-io/ethconnect/internal/ws" log "github.com/sirupsen/logrus" "github.com/syndtr/goleveldb/leveldb" ) @@ -80,13 +80,13 @@ type SubscriptionManagerConf struct { type subscriptionMGR struct { conf *SubscriptionManagerConf - rpcConf *kldeth.RPCConnOpts - db kldkvstore.KVStore - rpc kldeth.RPCClient + rpcConf *eth.RPCConnOpts + db kvstore.KVStore + rpc eth.RPCClient subscriptions map[string]*subscription streams map[string]*eventStream closed bool - wsChannels kldws.WebSocketChannels + wsChannels ws.WebSocketChannels } // CobraInitSubscriptionManager standard naming for cobra command params @@ -97,7 +97,7 @@ func CobraInitSubscriptionManager(cmd *cobra.Command, conf *SubscriptionManagerC } // NewSubscriptionManager constructor -func NewSubscriptionManager(conf *SubscriptionManagerConf, rpc kldeth.RPCClient, wsChannels kldws.WebSocketChannels) SubscriptionManager { +func NewSubscriptionManager(conf *SubscriptionManagerConf, rpc eth.RPCClient, wsChannels ws.WebSocketChannels) SubscriptionManager { sm := &subscriptionMGR{ conf: conf, rpc: rpc, @@ -136,7 +136,7 @@ func (s *subscriptionMGR) setInitialBlock(i *SubscriptionInfo, initialBlock stri } else { var bi big.Int if _, ok := bi.SetString(initialBlock, 0); !ok { - return klderrors.Errorf(klderrors.EventStreamsSubscribeBadBlock) + return errors.Errorf(errors.EventStreamsSubscribeBadBlock) } i.FromBlock = bi.Text(10) } @@ -146,10 +146,10 @@ func (s *subscriptionMGR) setInitialBlock(i *SubscriptionInfo, initialBlock stri // AddSubscription adds a new subscription func (s *subscriptionMGR) AddSubscription(ctx context.Context, addr *ethbinding.Address, event *ethbinding.ABIElementMarshaling, streamID, initialBlock, name string) (*SubscriptionInfo, error) { i := &SubscriptionInfo{ - TimeSorted: kldmessages.TimeSorted{ + TimeSorted: messages.TimeSorted{ CreatedISO8601: time.Now().UTC().Format(time.RFC3339), }, - ID: subIDPrefix + kldutils.UUIDv4(), + ID: subIDPrefix + utils.UUIDv4(), Event: event, Stream: streamID, } @@ -218,7 +218,7 @@ func (s *subscriptionMGR) deleteSubscription(ctx context.Context, sub *subscript func (s *subscriptionMGR) storeSubscription(info *SubscriptionInfo) (*SubscriptionInfo, error) { infoBytes, _ := json.MarshalIndent(info, "", " ") if err := s.db.Put(info.ID, infoBytes); err != nil { - return nil, klderrors.Errorf(klderrors.EventStreamsSubscribeStoreFailed, err) + return nil, errors.Errorf(errors.EventStreamsSubscribeStoreFailed, err) } return info, nil } @@ -243,7 +243,7 @@ func (s *subscriptionMGR) Streams(ctx context.Context) []*StreamInfo { // AddStream adds a new stream func (s *subscriptionMGR) AddStream(ctx context.Context, spec *StreamInfo) (*StreamInfo, error) { - spec.ID = streamIDPrefix + kldutils.UUIDv4() + spec.ID = streamIDPrefix + utils.UUIDv4() spec.CreatedISO8601 = time.Now().UTC().Format(time.RFC3339) spec.Path = StreamPathPrefix + "/" + spec.ID stream, err := newEventStream(s, spec, s.wsChannels) @@ -270,7 +270,7 @@ func (s *subscriptionMGR) UpdateStream(ctx context.Context, id string, spec *Str func (s *subscriptionMGR) storeStream(spec *StreamInfo) (*StreamInfo, error) { infoBytes, _ := json.MarshalIndent(spec, "", " ") if err := s.db.Put(spec.ID, infoBytes); err != nil { - return nil, klderrors.Errorf(klderrors.EventStreamsCreateStreamStoreFailed, err) + return nil, errors.Errorf(errors.EventStreamsCreateStreamStoreFailed, err) } return spec, nil } @@ -336,7 +336,7 @@ func (s *subscriptionMGR) ResumeStream(ctx context.Context, id string) error { func (s *subscriptionMGR) subscriptionByID(id string) (*subscription, error) { sub, exists := s.subscriptions[id] if !exists { - return nil, klderrors.Errorf(klderrors.EventStreamsSubscriptionNotFound, id) + return nil, errors.Errorf(errors.EventStreamsSubscriptionNotFound, id) } return sub, nil } @@ -345,7 +345,7 @@ func (s *subscriptionMGR) subscriptionByID(id string) (*subscription, error) { func (s *subscriptionMGR) streamByID(id string) (*eventStream, error) { stream, exists := s.streams[id] if !exists { - return nil, klderrors.Errorf(klderrors.EventStreamsStreamNotFound, id) + return nil, errors.Errorf(errors.EventStreamsStreamNotFound, id) } return stream, nil } @@ -380,8 +380,8 @@ func (s *subscriptionMGR) deleteCheckpoint(streamID string) { } func (s *subscriptionMGR) Init() (err error) { - if s.db, err = kldkvstore.NewLDBKeyValueStore(s.conf.EventLevelDBPath); err != nil { - return klderrors.Errorf(klderrors.EventStreamsDBLoad, s.conf.EventLevelDBPath, err) + if s.db, err = kvstore.NewLDBKeyValueStore(s.conf.EventLevelDBPath); err != nil { + return errors.Errorf(errors.EventStreamsDBLoad, s.conf.EventLevelDBPath, err) } s.recoverStreams() s.recoverSubscriptions() diff --git a/internal/kldevents/submanager_test.go b/internal/events/submanager_test.go similarity index 91% rename from internal/kldevents/submanager_test.go rename to internal/events/submanager_test.go index 98a6f7ad..ddd301d6 100644 --- a/internal/kldevents/submanager_test.go +++ b/internal/events/submanager_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "context" @@ -28,8 +28,8 @@ import ( "github.com/julienschmidt/httprouter" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldkvstore" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/kvstore" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" ) @@ -64,7 +64,7 @@ func (m *mockWebSocket) GetChannels(namespace string) (chan<- interface{}, chan< func (m *mockWebSocket) SendReply(message interface{}) {} func tempdir(t *testing.T) string { - dir, _ := ioutil.TempDir("", "kld") + dir, _ := ioutil.TempDir("", "fly") t.Logf("tmpdir/create: %s", dir) return dir } @@ -86,8 +86,8 @@ func newMockWebSocket() *mockWebSocket { func newTestSubscriptionManager() *subscriptionMGR { smconf := &SubscriptionManagerConf{} sm := NewSubscriptionManager(smconf, nil, newMockWebSocket()).(*subscriptionMGR) - sm.rpc = kldeth.NewMockRPCClientForSync(nil, nil) - sm.db = kldkvstore.NewMockKV(nil) + sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.db = kvstore.NewMockKV(nil) sm.config().WebhooksAllowPrivateIPs = true sm.config().EventPollingIntervalSec = 0 return sm @@ -135,8 +135,8 @@ func TestActionAndSubscriptionLifecyle(t *testing.T) { subscriptionName := "testSub" defer cleanup(t, dir) sm := newTestSubscriptionManager() - sm.rpc = kldeth.NewMockRPCClientForSync(nil, nil) - sm.db, _ = kldkvstore.NewLDBKeyValueStore(path.Join(dir, "db")) + sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.db, _ = kvstore.NewLDBKeyValueStore(path.Join(dir, "db")) defer sm.db.Close() ctx := context.Background() @@ -189,7 +189,7 @@ func TestActionAndSubscriptionLifecyle(t *testing.T) { defer svr.Close() sm = newTestSubscriptionManager() sm.conf.EventLevelDBPath = path.Join(dir, "db") - sm.rpcConf = &kldeth.RPCConnOpts{URL: svr.URL} + sm.rpcConf = ð.RPCConnOpts{URL: svr.URL} err = sm.Init() assert.NoError(err) @@ -213,8 +213,8 @@ func TestActionChildCleanup(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) sm := newTestSubscriptionManager() - sm.rpc = kldeth.NewMockRPCClientForSync(nil, nil) - sm.db, _ = kldkvstore.NewLDBKeyValueStore(path.Join(dir, "db")) + sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.db, _ = kvstore.NewLDBKeyValueStore(path.Join(dir, "db")) defer sm.db.Close() ctx := context.Background() @@ -239,8 +239,8 @@ func TestStreamAndSubscriptionErrors(t *testing.T) { subscriptionName := "testSub" defer cleanup(t, dir) sm := newTestSubscriptionManager() - sm.rpc = kldeth.NewMockRPCClientForSync(nil, nil) - sm.db, _ = kldkvstore.NewLDBKeyValueStore(path.Join(dir, "db")) + sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.db, _ = kvstore.NewLDBKeyValueStore(path.Join(dir, "db")) defer sm.db.Close() ctx := context.Background() @@ -271,8 +271,8 @@ func TestResetSubscriptionErrors(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) sm := newTestSubscriptionManager() - sm.rpc = kldeth.NewMockRPCClientForSync(nil, nil) - sm.db = kldkvstore.NewMockKV(fmt.Errorf("pop")) + sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.db = kvstore.NewMockKV(fmt.Errorf("pop")) defer sm.db.Close() ctx := context.Background() @@ -313,7 +313,7 @@ func TestRecoverErrors(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) sm := newTestSubscriptionManager() - sm.db, _ = kldkvstore.NewLDBKeyValueStore(path.Join(dir, "db")) + sm.db, _ = kvstore.NewLDBKeyValueStore(path.Join(dir, "db")) defer sm.db.Close() sm.db.Put(streamIDPrefix+"esid1", []byte(":bad json")) diff --git a/internal/kldevents/subscription.go b/internal/events/subscription.go similarity index 87% rename from internal/kldevents/subscription.go rename to internal/events/subscription.go index 025e640b..d81118b8 100644 --- a/internal/kldevents/subscription.go +++ b/internal/events/subscription.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "context" @@ -21,10 +21,10 @@ import ( "time" ethbinding "github.com/kaleido-io/ethbinding/pkg" + "github.com/kaleido-io/ethconnect/internal/errors" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/messages" log "github.com/sirupsen/logrus" ) @@ -43,7 +43,7 @@ type ethFilter struct { // SubscriptionInfo is the persisted data for the subscription type SubscriptionInfo struct { - kldmessages.TimeSorted + messages.TimeSorted ID string `json:"id,omitempty"` Path string `json:"path"` Summary string `json:"-"` // System generated name for the subscription @@ -57,7 +57,7 @@ type SubscriptionInfo struct { // subscription is the runtime that manages the subscription type subscription struct { info *SubscriptionInfo - rpc kldeth.RPCClient + rpc eth.RPCClient lp *logProcessor logName string filterID ethbinding.HexBigInt @@ -67,12 +67,12 @@ type subscription struct { resetRequested bool } -func newSubscription(sm subscriptionManager, rpc kldeth.RPCClient, addr *ethbinding.Address, i *SubscriptionInfo) (*subscription, error) { +func newSubscription(sm subscriptionManager, rpc eth.RPCClient, addr *ethbinding.Address, i *SubscriptionInfo) (*subscription, error) { stream, err := sm.streamByID(i.Stream) if err != nil { return nil, err } - event, err := eth.API.ABIElementMarshalingToABIEvent(i.Event) + event, err := ethbind.API.ABIElementMarshalingToABIEvent(i.Event) if err != nil { return nil, err } @@ -80,7 +80,7 @@ func newSubscription(sm subscriptionManager, rpc kldeth.RPCClient, addr *ethbind info: i, rpc: rpc, lp: newLogProcessor(i.ID, event, stream), - logName: i.ID + ":" + eth.API.ABIEventSignature(event), + logName: i.ID + ":" + ethbind.API.ABIEventSignature(event), filterStale: true, } f := &i.Filter @@ -89,14 +89,14 @@ func newSubscription(sm subscriptionManager, rpc kldeth.RPCClient, addr *ethbind f.Addresses = []ethbinding.Address{*addr} addrStr = addr.String() } - i.Summary = addrStr + ":" + eth.API.ABIEventSignature(event) + i.Summary = addrStr + ":" + ethbind.API.ABIEventSignature(event) // If a name was not provided by the end user, set it to the system generated summary if i.Name == "" { log.Debugf("No name provided for subscription, using auto-generated summary:%s", i.Summary) i.Name = i.Summary } if event == nil || event.Name == "" { - return nil, klderrors.Errorf(klderrors.EventStreamsSubscribeNoEvent) + return nil, errors.Errorf(errors.EventStreamsSubscribeNoEvent) } // For now we only support filtering on the event type f.Topics = [][]ethbinding.Hash{{event.ID}} @@ -109,15 +109,15 @@ func (info *SubscriptionInfo) GetID() string { return info.ID } -func restoreSubscription(sm subscriptionManager, rpc kldeth.RPCClient, i *SubscriptionInfo) (*subscription, error) { +func restoreSubscription(sm subscriptionManager, rpc eth.RPCClient, i *SubscriptionInfo) (*subscription, error) { if i.GetID() == "" { - return nil, klderrors.Errorf(klderrors.EventStreamsNoID) + return nil, errors.Errorf(errors.EventStreamsNoID) } stream, err := sm.streamByID(i.Stream) if err != nil { return nil, err } - event, err := eth.API.ABIElementMarshalingToABIEvent(i.Event) + event, err := ethbind.API.ABIElementMarshalingToABIEvent(i.Event) if err != nil { return nil, err } @@ -125,7 +125,7 @@ func restoreSubscription(sm subscriptionManager, rpc kldeth.RPCClient, i *Subscr rpc: rpc, info: i, lp: newLogProcessor(i.ID, event, stream), - logName: i.ID + ":" + eth.API.ABIEventSignature(event), + logName: i.ID + ":" + ethbind.API.ABIEventSignature(event), filterStale: true, } return s, nil @@ -135,7 +135,7 @@ func (s *subscription) setInitialBlockHeight(ctx context.Context) (*big.Int, err if s.info.FromBlock != "" && s.info.FromBlock != FromBlockLatest { var i big.Int if _, ok := i.SetString(s.info.FromBlock, 10); !ok { - return nil, klderrors.Errorf(klderrors.EventStreamsSubscribeBadBlock) + return nil, errors.Errorf(errors.EventStreamsSubscribeBadBlock) } return &i, nil } @@ -144,7 +144,7 @@ func (s *subscription) setInitialBlockHeight(ctx context.Context) (*big.Int, err blockHeight := ethbinding.HexBigInt{} err := s.rpc.CallContext(ctx, &blockHeight, "eth_blockNumber") if err != nil { - return nil, klderrors.Errorf(klderrors.RPCCallReturnedError, "eth_blockNumber", err) + return nil, errors.Errorf(errors.RPCCallReturnedError, "eth_blockNumber", err) } i := blockHeight.ToInt() s.lp.initBlockHWM(i) @@ -166,7 +166,7 @@ func (s *subscription) restartFilter(ctx context.Context, since *big.Int) error defer cancel() err := s.rpc.CallContext(ctx, &s.filterID, "eth_newFilter", f) if err != nil { - return klderrors.Errorf(klderrors.RPCCallReturnedError, "eth_newFilter", err) + return errors.Errorf(errors.RPCCallReturnedError, "eth_newFilter", err) } s.filteredOnce = false s.markFilterStale(ctx, false) diff --git a/internal/kldevents/subscription_test.go b/internal/events/subscription_test.go similarity index 89% rename from internal/kldevents/subscription_test.go rename to internal/events/subscription_test.go index b1c99d71..3e42f33c 100644 --- a/internal/kldevents/subscription_test.go +++ b/internal/events/subscription_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "context" @@ -22,8 +22,8 @@ import ( ethbinding "github.com/kaleido-io/ethbinding/pkg" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldkvstore" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/kvstore" "github.com/stretchr/testify/assert" ) @@ -73,7 +73,7 @@ func testSubInfo(event *ethbinding.ABIElementMarshaling) *SubscriptionInfo { func TestCreateWebhookSub(t *testing.T) { assert := assert.New(t) - rpc := kldeth.NewMockRPCClientForSync(nil, nil) + rpc := eth.NewMockRPCClientForSync(nil, nil) event := ðbinding.ABIElementMarshaling{ Name: "glastonbury", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -113,14 +113,14 @@ func TestCreateWebhookSub(t *testing.T) { func TestCreateWebhookSubWithAddr(t *testing.T) { assert := assert.New(t) - rpc := kldeth.NewMockRPCClientForSync(nil, nil) + rpc := eth.NewMockRPCClientForSync(nil, nil) m := &mockSubMgr{stream: newTestStream()} event := ðbinding.ABIElementMarshaling{ Name: "devcon", Anonymous: true, } - addr := eth.API.HexToAddress("0x0123456789abcDEF0123456789abCDef01234567") + addr := ethbind.API.HexToAddress("0x0123456789abcDEF0123456789abCDef01234567") subInfo := testSubInfo(event) subInfo.Name = "mySubscription" s, err := newSubscription(m, rpc, &addr, subInfo) @@ -182,7 +182,7 @@ func TestRestoreSubscriptionBadType(t *testing.T) { func TestProcessEventsStaleFilter(t *testing.T) { assert := assert.New(t) s := &subscription{ - rpc: kldeth.NewMockRPCClientForSync(fmt.Errorf("filter not found"), nil), + rpc: eth.NewMockRPCClientForSync(fmt.Errorf("filter not found"), nil), } err := s.processNewEvents(context.Background()) assert.EqualError(err, "filter not found") @@ -192,7 +192,7 @@ func TestProcessEventsStaleFilter(t *testing.T) { func TestProcessEventsCannotProcess(t *testing.T) { assert := assert.New(t) s := &subscription{ - rpc: kldeth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { + rpc: eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { les := res.(*[]*logEntry) *les = append(*les, &logEntry{ Data: "0x no hex here sorry", @@ -209,7 +209,7 @@ func TestInitialFilterFail(t *testing.T) { assert := assert.New(t) s := &subscription{ info: &SubscriptionInfo{}, - rpc: kldeth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), } _, err := s.setInitialBlockHeight(context.Background()) assert.EqualError(err, "eth_blockNumber returned: pop") @@ -221,7 +221,7 @@ func TestInitialFilterBadInitialBlock(t *testing.T) { info: &SubscriptionInfo{ FromBlock: "!integer", }, - rpc: kldeth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), } _, err := s.setInitialBlockHeight(context.Background()) assert.EqualError(err, "FromBlock cannot be parsed as a BigInt") @@ -243,7 +243,7 @@ func TestRestartFilterFail(t *testing.T) { assert := assert.New(t) s := &subscription{ info: &SubscriptionInfo{}, - rpc: kldeth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), } err := s.restartFilter(context.Background(), big.NewInt(0)) assert.EqualError(err, "eth_newFilter returned: pop") @@ -257,7 +257,7 @@ func TestEventTimestampFail(t *testing.T) { s := &subscription{ lp: lp, info: &SubscriptionInfo{}, - rpc: kldeth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), } l := &logEntry{Timestamp: 100} // set it to a fake value, should get overwritten s.getEventTimestamp(context.Background(), l) @@ -267,7 +267,7 @@ func TestEventTimestampFail(t *testing.T) { func TestUnsubscribe(t *testing.T) { assert := assert.New(t) s := &subscription{ - rpc: kldeth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { + rpc: eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { *(res.(*bool)) = true }), } @@ -279,7 +279,7 @@ func TestUnsubscribe(t *testing.T) { func TestLoadCheckpointBadJSON(t *testing.T) { assert := assert.New(t) sm := newTestSubscriptionManager() - mockKV := kldkvstore.NewMockKV(nil) + mockKV := kvstore.NewMockKV(nil) sm.db = mockKV mockKV.KVS[checkpointIDPrefix+"id1"] = []byte(":bad json") _, err := sm.loadCheckpoint("id1") diff --git a/internal/kldevents/webhooks.go b/internal/events/webhooks.go similarity index 88% rename from internal/kldevents/webhooks.go rename to internal/events/webhooks.go index 5b90e8ef..bc38984b 100644 --- a/internal/kldevents/webhooks.go +++ b/internal/events/webhooks.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( "bytes" @@ -24,7 +24,7 @@ import ( "net/url" "time" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" log "github.com/sirupsen/logrus" ) @@ -36,10 +36,10 @@ type webhookAction struct { func newWebhookAction(es *eventStream, spec *webhookActionInfo) (*webhookAction, error) { if spec == nil || spec.URL == "" { - return nil, klderrors.Errorf(klderrors.EventStreamsWebhookNoURL) + return nil, errors.Errorf(errors.EventStreamsWebhookNoURL) } if _, err := url.Parse(spec.URL); err != nil { - return nil, klderrors.Errorf(klderrors.EventStreamsWebhookInvalidURL) + return nil, errors.Errorf(errors.EventStreamsWebhookInvalidURL) } if spec.RequestTimeoutSec == 0 { spec.RequestTimeoutSec = 120 @@ -60,7 +60,7 @@ func (w *webhookAction) attemptBatch(batchNumber, attempt uint64, events []*even return err } if w.es.isAddressUnsafe(addr) { - err := klderrors.Errorf(klderrors.EventStreamsWebhookProhibitedAddress, u.Hostname()) + err := errors.Errorf(errors.EventStreamsWebhookProhibitedAddress, u.Hostname()) log.Errorf(err.Error()) return err } @@ -105,7 +105,7 @@ func (w *webhookAction) attemptBatch(batchNumber, attempt uint64, events []*even log.Infof("%s: Response body: %s", esID, string(bodyBytes)) } if !ok { - err = klderrors.Errorf(klderrors.EventStreamsWebhookFailedHTTPStatus, esID, res.StatusCode) + err = errors.Errorf(errors.EventStreamsWebhookFailedHTTPStatus, esID, res.StatusCode) } } } diff --git a/internal/kldevents/websockets.go b/internal/events/websockets.go similarity index 81% rename from internal/kldevents/websockets.go rename to internal/events/websockets.go index 66e8afb4..d7e489ee 100644 --- a/internal/kldevents/websockets.go +++ b/internal/events/websockets.go @@ -12,10 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldevents +package events import ( - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" ) type webSocketAction struct { @@ -25,7 +25,7 @@ type webSocketAction struct { func newWebSocketAction(es *eventStream, spec *webSocketActionInfo) (*webSocketAction, error) { if es.wsChannels == nil { - return nil, klderrors.Errorf(klderrors.EventStreamsWebSocketNotConfigured) + return nil, errors.Errorf(errors.EventStreamsWebSocketNotConfigured) } return &webSocketAction{ es: es, @@ -59,9 +59,9 @@ func (w *webSocketAction) attemptBatch(batchNumber, attempt uint64, events []*ev case channel <- events: break case <-w.es.updateInterrupt: - return klderrors.Errorf(klderrors.EventStreamsWebSocketInterruptedSend) + return errors.Errorf(errors.EventStreamsWebSocketInterruptedSend) case <-closing: - return klderrors.Errorf(klderrors.EventStreamsWebSocketInterruptedSend) + return errors.Errorf(errors.EventStreamsWebSocketInterruptedSend) } // If we ever add more distribution modes, we may want to change this logic from a simple if statement @@ -71,9 +71,9 @@ func (w *webSocketAction) attemptBatch(batchNumber, attempt uint64, events []*ev case err = <-receiver: break case <-w.es.updateInterrupt: - return klderrors.Errorf(klderrors.EventStreamsWebSocketInterruptedReceive) + return errors.Errorf(errors.EventStreamsWebSocketInterruptedReceive) case <-closing: - return klderrors.Errorf(klderrors.EventStreamsWebSocketInterruptedReceive) + return errors.Errorf(errors.EventStreamsWebSocketInterruptedReceive) } // Pass back any exception from the client } diff --git a/internal/kldkafka/client.go b/internal/kafka/client.go similarity index 99% rename from internal/kldkafka/client.go rename to internal/kafka/client.go index 9b48dbc2..69142c0a 100644 --- a/internal/kldkafka/client.go +++ b/internal/kafka/client.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkafka +package kafka import ( "context" diff --git a/internal/kldkafka/client_test.go b/internal/kafka/client_test.go similarity index 98% rename from internal/kldkafka/client_test.go rename to internal/kafka/client_test.go index ffa79be9..6a6069d7 100644 --- a/internal/kldkafka/client_test.go +++ b/internal/kafka/client_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkafka +package kafka import ( "context" @@ -22,7 +22,7 @@ import ( "github.com/Shopify/sarama" "github.com/golang/mock/gomock" - "github.com/kaleido-io/ethconnect/internal/kldkafka/mock_sarama" + "github.com/kaleido-io/ethconnect/internal/kafka/mock_sarama" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) diff --git a/internal/kldkafka/clientmock.go b/internal/kafka/clientmock.go similarity index 99% rename from internal/kldkafka/clientmock.go rename to internal/kafka/clientmock.go index d58f518f..83aca441 100644 --- a/internal/kldkafka/clientmock.go +++ b/internal/kafka/clientmock.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkafka +package kafka import ( "sync" diff --git a/internal/kldkafka/kafkabridge.go b/internal/kafka/kafkabridge.go similarity index 88% rename from internal/kldkafka/kafkabridge.go rename to internal/kafka/kafkabridge.go index 42399813..c5b8e91d 100644 --- a/internal/kldkafka/kafkabridge.go +++ b/internal/kafka/kafkabridge.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkafka +package kafka import ( "context" @@ -23,12 +23,12 @@ import ( "time" "github.com/Shopify/sarama" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -37,8 +37,8 @@ import ( type KafkaBridgeConf struct { Kafka KafkaCommonConf `json:"kafka"` MaxInFlight int `json:"maxInFlight"` - kldtx.TxnProcessorConf - kldeth.RPCConf + tx.TxnProcessorConf + eth.RPCConf } // KafkaBridge receives messages from Kafka and dispatches them to go-ethereum over JSON/RPC @@ -46,8 +46,8 @@ type KafkaBridge struct { printYAML *bool conf KafkaBridgeConf kafka KafkaCommon - rpc kldeth.RPCClient - processor kldtx.TxnProcessor + rpc eth.RPCClient + processor tx.TxnProcessor inFlight map[string]*msgContext inFlightCond *sync.Cond } @@ -65,7 +65,7 @@ func (k *KafkaBridge) SetConf(conf *KafkaBridgeConf) { // ValidateConf validates the configuration func (k *KafkaBridge) ValidateConf() (err error) { if k.conf.RPC.URL == "" { - return klderrors.Errorf(klderrors.ConfigNoRPC) + return errors.Errorf(errors.ConfigNoRPC) } if k.conf.MaxTXWaitTime < 10 { if k.conf.MaxTXWaitTime > 0 { @@ -98,9 +98,9 @@ func (k *KafkaBridge) CobraInit() (cmd *cobra.Command) { }, } k.kafka.CobraInit(cmd) - kldeth.CobraInitRPC(cmd, &k.conf.RPCConf) - kldtx.CobraInitTxnProcessor(cmd, &k.conf.TxnProcessorConf) - cmd.Flags().IntVarP(&k.conf.MaxInFlight, "maxinflight", "m", kldutils.DefInt("KAFKA_MAX_INFLIGHT", 0), "Maximum messages to hold in-flight") + eth.CobraInitRPC(cmd, &k.conf.RPCConf) + tx.CobraInitTxnProcessor(cmd, &k.conf.TxnProcessorConf) + cmd.Flags().IntVarP(&k.conf.MaxInFlight, "maxinflight", "m", utils.DefInt("KAFKA_MAX_INFLIGHT", 0), "Maximum messages to hold in-flight") return } @@ -108,7 +108,7 @@ type msgContext struct { timeReceived time.Time ctx context.Context producer KafkaProducer - requestCommon kldmessages.RequestCommon + requestCommon messages.RequestCommon reqOffset string saramaMsg *sarama.ConsumerMessage key string @@ -158,19 +158,19 @@ func (k *KafkaBridge) addInflightMsg(msg *sarama.ConsumerMessage, producer Kafka headers := &ctx.requestCommon.Headers accessToken := "" for _, header := range msg.Headers { - if string(header.Key) == kldmessages.RecordHeaderAccessToken { + if string(header.Key) == messages.RecordHeaderAccessToken { accessToken = string(header.Value) } } - authCtx, err := kldauth.WithAuthContext(context.Background(), accessToken) + authCtx, err := auth.WithAuthContext(context.Background(), accessToken) if err != nil { log.Errorf("Unauthorized: %s - Message=%+v", err, ctx.requestCommon) - err = klderrors.Errorf(klderrors.Unauthorized) + err = errors.Errorf(errors.Unauthorized) return } ctx.ctx = authCtx if headers.ID == "" { - headers.ID = kldutils.UUIDv4() + headers.ID = utils.UUIDv4() } // Use the account as the partitioning key, or fallback to the ID, which we ensure is non-null if headers.Account != "" { @@ -241,7 +241,7 @@ func (c *msgContext) Context() context.Context { return c.ctx } -func (c *msgContext) Headers() *kldmessages.CommonHeaders { +func (c *msgContext) Headers() *messages.CommonHeaders { return &c.requestCommon.Headers.CommonHeaders } @@ -258,7 +258,7 @@ func (c *msgContext) SendErrorReply(status int, err error) { func (c *msgContext) SendErrorReplyWithGapFill(status int, err error, gapFillTxHash string, gapFillSucceeded bool) { log.Warnf("Failed to process message %s: %s", c, err) - errMsg := kldmessages.NewErrorReply(err, c.saramaMsg.Value) + errMsg := messages.NewErrorReply(err, c.saramaMsg.Value) errMsg.GapFillTxHash = gapFillTxHash var bGap = gapFillSucceeded errMsg.GapFillSucceeded = &bGap @@ -267,16 +267,16 @@ func (c *msgContext) SendErrorReplyWithGapFill(status int, err error, gapFillTxH func (c *msgContext) SendErrorReplyWithTX(status int, err error, txHash string) { log.Warnf("Failed to process message %s: %s", c, err) - errMsg := kldmessages.NewErrorReply(err, c.saramaMsg.Value) + errMsg := messages.NewErrorReply(err, c.saramaMsg.Value) errMsg.TXHash = txHash c.Reply(errMsg) } -func (c *msgContext) Reply(replyMessage kldmessages.ReplyWithHeaders) { +func (c *msgContext) Reply(replyMessage messages.ReplyWithHeaders) { replyHeaders := replyMessage.ReplyHeaders() c.replyType = replyHeaders.MsgType - replyHeaders.ID = kldutils.UUIDv4() + replyHeaders.ID = utils.UUIDv4() replyHeaders.Context = c.requestCommon.Headers.Context replyHeaders.ReqID = c.requestCommon.Headers.ID replyHeaders.ReqOffset = c.reqOffset @@ -324,7 +324,7 @@ func NewKafkaBridge(printYAML *bool) *KafkaBridge { inFlight: make(map[string]*msgContext), inFlightCond: sync.NewCond(&sync.Mutex{}), } - k.processor = kldtx.NewTxnProcessor(&k.conf.TxnProcessorConf, &k.conf.RPCConf) + k.processor = tx.NewTxnProcessor(&k.conf.TxnProcessorConf, &k.conf.RPCConf) k.kafka = NewKafkaCommon(&SaramaKafkaFactory{}, &k.conf.Kafka, k) return k } @@ -353,7 +353,7 @@ func (k *KafkaBridge) ConsumerMessagesLoop(consumer KafkaConsumer, producer Kafk k.processor.OnMessage(msgCtx) } else { // Dispatch a generic 'bad data' reply - errMsg := kldmessages.NewErrorReply(err, msg.Value) + errMsg := messages.NewErrorReply(err, msg.Value) msgCtx.Reply(errMsg) } } @@ -395,7 +395,7 @@ func (k *KafkaBridge) ProducerSuccessLoop(consumer KafkaConsumer, producer Kafka k.inFlightCond.Broadcast() } else { // This should never happen. Represents a logic bug that must be diagnosed. - err := klderrors.Errorf(klderrors.KakfaProducerConfirmMsgUnknown, reqOffset) + err := errors.Errorf(errors.KakfaProducerConfirmMsgUnknown, reqOffset) panic(err) } k.inFlightCond.L.Unlock() @@ -404,7 +404,7 @@ func (k *KafkaBridge) ProducerSuccessLoop(consumer KafkaConsumer, producer Kafka func (k *KafkaBridge) connect() (err error) { // Connect the client - if k.rpc, err = kldeth.RPCConnect(&k.conf.RPC); err != nil { + if k.rpc, err = eth.RPCConnect(&k.conf.RPC); err != nil { return } k.processor.Init(k.rpc) @@ -415,7 +415,7 @@ func (k *KafkaBridge) connect() (err error) { func (k *KafkaBridge) Start() (err error) { if *k.printYAML { - b, err := kldutils.MarshalToYAML(&k.conf) + b, err := utils.MarshalToYAML(&k.conf) print("# YAML Configuration snippet for Kafka->Ethereum bridge\n" + string(b)) return err } diff --git a/internal/kldkafka/kafkabridge_test.go b/internal/kafka/kafkabridge_test.go similarity index 90% rename from internal/kldkafka/kafkabridge_test.go rename to internal/kafka/kafkabridge_test.go index f8d7caff..fbed0fcc 100644 --- a/internal/kldkafka/kafkabridge_test.go +++ b/internal/kafka/kafkabridge_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkafka +package kafka import ( "crypto/tls" @@ -24,11 +24,11 @@ import ( "time" "github.com/Shopify/sarama" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldauth/kldauthtest" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/auth/authtest" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" @@ -75,19 +75,19 @@ func (k *testKafkaCommon) Producer() KafkaProducer { } type testKafkaMsgProcessor struct { - messages chan kldtx.TxnContext - rpc kldeth.RPCClient + messages chan tx.TxnContext + rpc eth.RPCClient } func (p *testKafkaMsgProcessor) ResolveAddress(from string) (resolvedFrom string, err error) { return from, nil } -func (p *testKafkaMsgProcessor) Init(rpc kldeth.RPCClient) { +func (p *testKafkaMsgProcessor) Init(rpc eth.RPCClient) { p.rpc = rpc } -func (p *testKafkaMsgProcessor) OnMessage(msg kldtx.TxnContext) { +func (p *testKafkaMsgProcessor) OnMessage(msg tx.TxnContext) { log.Infof("Dispatched message context to processor: %s", msg) p.messages <- msg return @@ -112,7 +112,7 @@ func newTestKafkaBridge() (k *KafkaBridge, kafkaCmd *cobra.Command) { k = NewKafkaBridge(&printYAML) k.kafka = &testKafkaCommon{} k.processor = &testKafkaMsgProcessor{ - messages: make(chan kldtx.TxnContext), + messages: make(chan tx.TxnContext), } kafkaCmd = k.CobraInit() return k, kafkaCmd @@ -215,12 +215,12 @@ func setupMocks() (*KafkaBridge, *testKafkaMsgProcessor, *MockKafkaConsumer, *Mo func TestSingleMessageWithReply(t *testing.T) { assert := assert.New(t) - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) _, processor, mockConsumer, mockProducer, wg := setupMocks() // Send a minimal test message - msg1 := kldmessages.RequestCommon{} + msg1 := messages.RequestCommon{} msg1.Headers.MsgType = "TestSingleMessageWithReply" msg1Ctx := map[string]interface{}{ "some": "data", @@ -237,7 +237,7 @@ func TestSingleMessageWithReply(t *testing.T) { Value: msg1bytes, Headers: []*sarama.RecordHeader{ { - Key: []byte(kldmessages.RecordHeaderAccessToken), + Key: []byte(messages.RecordHeaderAccessToken), Value: []byte("testat"), }, }, @@ -245,19 +245,19 @@ func TestSingleMessageWithReply(t *testing.T) { // Get the message via the processor msgContext1 := <-processor.messages - assert.Equal("testat", kldauth.GetAccessToken(msgContext1.Context())) - assert.Equal("verified", kldauth.GetAuthContext(msgContext1.Context())) + assert.Equal("testat", auth.GetAccessToken(msgContext1.Context())) + assert.Equal("verified", auth.GetAuthContext(msgContext1.Context())) assert.NotEmpty(msgContext1.Headers().ID) // Generated one as not supplied assert.Equal(msg1.Headers.MsgType, msgContext1.Headers().MsgType) assert.Equal("data", msgContext1.Headers().Context["some"]) assert.Equal(len(msgContext1.(*msgContext).replyBytes), msgContext1.(*msgContext).Length()) - var msgUnmarshaled kldmessages.RequestCommon + var msgUnmarshaled messages.RequestCommon msgContext1.Unmarshal(&msgUnmarshaled) assert.Equal(msg1.Headers.MsgType, msgUnmarshaled.Headers.MsgType) // Send the reply in a go routine go func() { - reply1 := kldmessages.ReplyCommon{} + reply1 := messages.ReplyCommon{} reply1.Headers.MsgType = "TestReply" msgContext1.Reply(&reply1) }() @@ -270,7 +270,7 @@ func TestSingleMessageWithReply(t *testing.T) { assert.Fail("Could not get bytes from reply: %s", err) return } - var replySent kldmessages.ReplyCommon + var replySent messages.ReplyCommon err = json.Unmarshal(replyBytes, &replySent) if err != nil { assert.Fail("Could not unmarshal reply: %s", err) @@ -287,17 +287,17 @@ func TestSingleMessageWithReply(t *testing.T) { mockConsumer.Close() wg.Wait() - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } func TestSingleMessageWithNotAuthorizedReply(t *testing.T) { assert := assert.New(t) - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) _, _, mockConsumer, mockProducer, wg := setupMocks() // Send a minimal test message - msg1 := kldmessages.RequestCommon{} + msg1 := messages.RequestCommon{} msg1.Headers.MsgType = "TestSingleMessageWithErrorReply" msg1.Headers.Account = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" msg1bytes, _ := json.Marshal(&msg1) @@ -312,7 +312,7 @@ func TestSingleMessageWithNotAuthorizedReply(t *testing.T) { assert.Fail("Could not get bytes from reply: %s", err) return } - var errorReply kldmessages.ErrorReply + var errorReply messages.ErrorReply err = json.Unmarshal(replyBytes, &errorReply) if err != nil { assert.Fail("Could not unmarshal reply: %s", err) @@ -325,7 +325,7 @@ func TestSingleMessageWithNotAuthorizedReply(t *testing.T) { mockConsumer.Close() wg.Wait() - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } func TestSingleMessageWithErrorReply(t *testing.T) { @@ -334,7 +334,7 @@ func TestSingleMessageWithErrorReply(t *testing.T) { _, processor, mockConsumer, mockProducer, wg := setupMocks() // Send a minimal test message - msg1 := kldmessages.RequestCommon{} + msg1 := messages.RequestCommon{} msg1.Headers.MsgType = "TestSingleMessageWithErrorReply" msg1.Headers.Account = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" msg1bytes, _ := json.Marshal(&msg1) @@ -356,7 +356,7 @@ func TestSingleMessageWithErrorReply(t *testing.T) { assert.Fail("Could not get bytes from reply: %s", err) return } - var errorReply kldmessages.ErrorReply + var errorReply messages.ErrorReply err = json.Unmarshal(replyBytes, &errorReply) if err != nil { assert.Fail("Could not unmarshal reply: %s", err) @@ -376,7 +376,7 @@ func TestSingleMessageWithErrorReplyWithGapFillDetail(t *testing.T) { _, processor, mockConsumer, mockProducer, wg := setupMocks() // Send a minimal test message - msg1 := kldmessages.RequestCommon{} + msg1 := messages.RequestCommon{} msg1.Headers.MsgType = "TestSingleMessageWithErrorReply" msg1.Headers.Account = "0xAA983AD2a0e0eD8ac639277F37be42F2A5d2618c" msg1bytes, _ := json.Marshal(&msg1) @@ -394,7 +394,7 @@ func TestSingleMessageWithErrorReplyWithGapFillDetail(t *testing.T) { replyKafkaMsg := <-mockProducer.MockInput mockProducer.MockSuccesses <- replyKafkaMsg replyBytes, _ := replyKafkaMsg.Value.Encode() - var errorReply kldmessages.ErrorReply + var errorReply messages.ErrorReply json.Unmarshal(replyBytes, &errorReply) assert.Equal("bang", errorReply.ErrorMessage) assert.Equal("txhash", errorReply.GapFillTxHash) @@ -414,7 +414,7 @@ func TestMoreMessagesThanMaxInFlight(t *testing.T) { // Send 20 messages (10 is the max inflight) go func() { for i := 0; i < 20; i++ { - msg := kldmessages.RequestCommon{} + msg := messages.RequestCommon{} msg.Headers.MsgType = "TestAddInflightMsg" msg.Headers.ID = fmt.Sprintf("msg%d", i) msg1bytes, _ := json.Marshal(&msg) @@ -424,7 +424,7 @@ func TestMoreMessagesThanMaxInFlight(t *testing.T) { }() // 10 messages should be sent into the processor - var msgContexts []kldtx.TxnContext + var msgContexts []tx.TxnContext for i := 0; i < 10; i++ { msgContext := <-processor.messages log.Infof("Processor passed %s", msgContext.Headers().ID) @@ -434,9 +434,9 @@ func TestMoreMessagesThanMaxInFlight(t *testing.T) { assert.Equal(10, len(k.inFlight)) // Send the replies for the first 10 - go func(msgContexts []kldtx.TxnContext) { + go func(msgContexts []tx.TxnContext) { for _, msgContext := range msgContexts { - reply := kldmessages.ReplyCommon{} + reply := messages.ReplyCommon{} msgContext.Reply(&reply) log.Infof("Sent reply for %s", msgContext.Headers().ID) } @@ -448,7 +448,7 @@ func TestMoreMessagesThanMaxInFlight(t *testing.T) { } // 10 more messages should be sent into the processor - msgContexts = []kldtx.TxnContext{} + msgContexts = []tx.TxnContext{} for i := 10; i < 20; i++ { msgContext := <-processor.messages log.Infof("Processor passed %s", msgContext.Headers().ID) @@ -460,10 +460,10 @@ func TestMoreMessagesThanMaxInFlight(t *testing.T) { // Send the replies for the next 10 - in reverse order var wg1 sync.WaitGroup wg1.Add(1) - go func(msgContexts []kldtx.TxnContext) { + go func(msgContexts []tx.TxnContext) { for i := (len(msgContexts) - 1); i >= 0; i-- { msgContext := msgContexts[i] - reply := kldmessages.ReplyCommon{} + reply := messages.ReplyCommon{} msgContext.Reply(&reply) log.Infof("Sent reply for %s", msgContext.Headers().ID) } diff --git a/internal/kldkafka/kafkacommon.go b/internal/kafka/kafkacommon.go similarity index 92% rename from internal/kldkafka/kafkacommon.go rename to internal/kafka/kafkacommon.go index aa945b43..1d735a1a 100644 --- a/internal/kldkafka/kafkacommon.go +++ b/internal/kafka/kafkacommon.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkafka +package kafka import ( "crypto/tls" @@ -26,8 +26,8 @@ import ( "github.com/Shopify/sarama" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -48,7 +48,7 @@ type KafkaCommonConf struct { Username string Password string } `json:"sasl"` - TLS kldutils.TLSConfig `json:"tls"` + TLS utils.TLSConfig `json:"tls"` } // KafkaCommon is the base interface for bridges that interact with Kafka @@ -102,16 +102,16 @@ func (k *kafkaCommon) ValidateConf() error { // KafkaValidateConf validates supplied configuration func KafkaValidateConf(kconf *KafkaCommonConf) (err error) { if kconf.TopicOut == "" { - return klderrors.Errorf(klderrors.ConfigKafkaMissingOutputTopic) + return errors.Errorf(errors.ConfigKafkaMissingOutputTopic) } if kconf.TopicIn == "" { - return klderrors.Errorf(klderrors.ConfigKafkaMissingInputTopic) + return errors.Errorf(errors.ConfigKafkaMissingInputTopic) } if kconf.ConsumerGroup == "" { - return klderrors.Errorf(klderrors.ConfigKafkaMissingConsumerGroup) + return errors.Errorf(errors.ConfigKafkaMissingConsumerGroup) } - if !kldutils.AllOrNoneReqd(kconf.SASL.Username, kconf.SASL.Password) { - err = klderrors.Errorf(klderrors.ConfigKafkaMissingBadSASL) + if !utils.AllOrNoneReqd(kconf.SASL.Username, kconf.SASL.Password) { + err = errors.Errorf(errors.ConfigKafkaMissingBadSASL) return } return @@ -166,7 +166,7 @@ func (k *kafkaCommon) connect() (err error) { log.Debugf("Kafka Bootstrap brokers: %s", k.conf.Brokers) if len(k.conf.Brokers) == 0 || k.conf.Brokers[0] == "" { - err = klderrors.Errorf(klderrors.ConfigKafkaMissingBrokers) + err = errors.Errorf(errors.ConfigKafkaMissingBrokers) return } @@ -174,7 +174,7 @@ func (k *kafkaCommon) connect() (err error) { clientConf := sarama.NewConfig() var tlsConfig *tls.Config - if tlsConfig, err = kldutils.CreateTLSConfiguration(&k.conf.TLS); err != nil { + if tlsConfig, err = utils.CreateTLSConfiguration(&k.conf.TLS); err != nil { return } @@ -197,7 +197,7 @@ func (k *kafkaCommon) connect() (err error) { clientConf.Net.TLS.Config = tlsConfig clientConf.ClientID = k.conf.ClientID if clientConf.ClientID == "" { - clientConf.ClientID = kldutils.UUIDv4() + clientConf.ClientID = utils.UUIDv4() } log.Debugf("Kafka ClientID: %s", clientConf.ClientID) diff --git a/internal/kldkafka/kafkacommon_test.go b/internal/kafka/kafkacommon_test.go similarity index 99% rename from internal/kldkafka/kafkacommon_test.go rename to internal/kafka/kafkacommon_test.go index 4a8e99f0..2b979398 100644 --- a/internal/kldkafka/kafkacommon_test.go +++ b/internal/kafka/kafkacommon_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkafka +package kafka import ( "crypto/tls" diff --git a/internal/kldkafka/mock_sarama/sarama_mocks.go b/internal/kafka/mock_sarama/sarama_mocks.go similarity index 100% rename from internal/kldkafka/mock_sarama/sarama_mocks.go rename to internal/kafka/mock_sarama/sarama_mocks.go diff --git a/internal/kldkvstore/kvstore.go b/internal/kvstore/kvstore.go similarity index 94% rename from internal/kldkvstore/kvstore.go rename to internal/kvstore/kvstore.go index 2cdb9780..0442a16c 100644 --- a/internal/kldkvstore/kvstore.go +++ b/internal/kvstore/kvstore.go @@ -12,10 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkvstore +package kvstore import ( - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" log "github.com/sirupsen/logrus" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/iterator" @@ -103,7 +103,7 @@ func NewLDBKeyValueStore(ldbPath string) (kv KVStore, err error) { path: ldbPath, } if store.db, err = leveldb.OpenFile(ldbPath, nil); err != nil { - return nil, klderrors.Errorf(klderrors.KVStoreDBLoad, ldbPath, err) + return nil, errors.Errorf(errors.KVStoreDBLoad, ldbPath, err) } kv = store return diff --git a/internal/kldkvstore/kvstore_test.go b/internal/kvstore/kvstore_test.go similarity index 97% rename from internal/kldkvstore/kvstore_test.go rename to internal/kvstore/kvstore_test.go index 88490751..4c10a3dc 100644 --- a/internal/kldkvstore/kvstore_test.go +++ b/internal/kvstore/kvstore_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkvstore +package kvstore import ( "fmt" @@ -25,7 +25,7 @@ import ( ) func tempdir(t *testing.T) string { - dir, _ := ioutil.TempDir("", "kld") + dir, _ := ioutil.TempDir("", "fly") t.Logf("tmpdir/create: %s", dir) return dir } diff --git a/internal/kldkvstore/memkv.go b/internal/kvstore/memkv.go similarity index 98% rename from internal/kldkvstore/memkv.go rename to internal/kvstore/memkv.go index a66db046..6cd2aac5 100644 --- a/internal/kldkvstore/memkv.go +++ b/internal/kvstore/memkv.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkvstore +package kvstore import ( "github.com/syndtr/goleveldb/leveldb" diff --git a/internal/kldkvstore/memkv_test.go b/internal/kvstore/memkv_test.go similarity index 98% rename from internal/kldkvstore/memkv_test.go rename to internal/kvstore/memkv_test.go index f393dbe7..089a34be 100644 --- a/internal/kldkvstore/memkv_test.go +++ b/internal/kvstore/memkv_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldkvstore +package kvstore import ( "testing" diff --git a/internal/kldmessages/messages.go b/internal/messages/messages.go similarity index 99% rename from internal/kldmessages/messages.go rename to internal/messages/messages.go index a410ea86..d31d1447 100644 --- a/internal/kldmessages/messages.go +++ b/internal/messages/messages.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldmessages +package messages import ( "encoding/json" @@ -33,7 +33,7 @@ const ( // MsgTypeTransactionFailure - a transaction receipt where status is 0 MsgTypeTransactionFailure = "TransactionFailure" // RecordHeaderAccessToken - record header name for passing JWT token over messaging - RecordHeaderAccessToken = "kld-accesstoken" + RecordHeaderAccessToken = "fly-accesstoken" ) // AsyncSentMsg is a standard response for async requests diff --git a/internal/kldmessages/messages_test.go b/internal/messages/messages_test.go similarity index 99% rename from internal/kldmessages/messages_test.go rename to internal/messages/messages_test.go index 52d66cbb..f92ff4df 100644 --- a/internal/kldmessages/messages_test.go +++ b/internal/messages/messages_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldmessages +package messages import ( "encoding/json" diff --git a/internal/kldmessages/timesorted.go b/internal/messages/timesorted.go similarity index 98% rename from internal/kldmessages/timesorted.go rename to internal/messages/timesorted.go index 56bb9b0d..c99ca2bd 100644 --- a/internal/kldmessages/timesorted.go +++ b/internal/messages/timesorted.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldmessages +package messages // TimeSorted base structure for time sortable things type TimeSorted struct { diff --git a/internal/kldmessages/timesorted_test.go b/internal/messages/timesorted_test.go similarity index 98% rename from internal/kldmessages/timesorted_test.go rename to internal/messages/timesorted_test.go index 2fc83703..506a5ba2 100644 --- a/internal/kldmessages/timesorted_test.go +++ b/internal/messages/timesorted_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldmessages +package messages import ( "sort" diff --git a/internal/kldopenapi/abi2swagger.go b/internal/openapi/abi2swagger.go similarity index 94% rename from internal/kldopenapi/abi2swagger.go rename to internal/openapi/abi2swagger.go index 12b0bea0..51397131 100644 --- a/internal/kldopenapi/abi2swagger.go +++ b/internal/openapi/abi2swagger.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldopenapi +package openapi import ( "net/url" @@ -40,7 +40,7 @@ type ABI2Swagger struct { } const ( - kaleidoAppCredential = "KaleidoAppCredential" + fireflyAppCredential = "FireflyAppCredential" inputSchemaNameSuffix = "_inputs" outputSchemaNameSuffix = "_outputs" ) @@ -98,7 +98,7 @@ func (c *ABI2Swagger) convert(basePath, name string, abi *ethbinding.ABI, devdoc } if c.conf.BasicAuth { swagger.SwaggerProps.SecurityDefinitions = map[string]*spec.SecurityScheme{ - kaleidoAppCredential: { + fireflyAppCredential: { SecuritySchemeProps: spec.SecuritySchemeProps{ Type: "basic", }, @@ -252,8 +252,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { params := make(map[string]spec.Parameter) params["fromParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "The 'from' address (header: x-kaleido-from)", - Name: "kld-from", + Description: "The 'from' address (header: x-firefly-from)", + Name: "fly-from", In: "query", Required: false, }, @@ -263,8 +263,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["valueParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Ether value to send with the transaction (header: x-kaleido-ethvalue)", - Name: "kld-ethvalue", + Description: "Ether value to send with the transaction (header: x-firefly-ethvalue)", + Name: "fly-ethvalue", In: "query", Required: false, AllowEmptyValue: true, @@ -275,8 +275,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["gasParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Gas to send with the transaction (auto-calculated if not set) (header: x-kaleido-gas)", - Name: "kld-gas", + Description: "Gas to send with the transaction (auto-calculated if not set) (header: x-firefly-gas)", + Name: "fly-gas", In: "query", Required: false, AllowEmptyValue: true, @@ -287,8 +287,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["gaspriceParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Gas Price offered (header: x-kaleido-gasprice)", - Name: "kld-gasprice", + Description: "Gas Price offered (header: x-firefly-gasprice)", + Name: "fly-gasprice", In: "query", Required: false, AllowEmptyValue: true, @@ -299,8 +299,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["syncParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-kaleido-sync)", - Name: "kld-sync", + Description: "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-firefly-sync)", + Name: "fly-sync", In: "query", Required: false, AllowEmptyValue: true, @@ -312,8 +312,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["callParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-kaleido-call)", - Name: "kld-call", + Description: "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-firefly-call)", + Name: "fly-call", In: "query", Required: false, AllowEmptyValue: true, @@ -324,8 +324,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["privateFromParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Private transaction sender (header: x-kaleido-privatefrom)", - Name: "kld-privatefrom", + Description: "Private transaction sender (header: x-firefly-privatefrom)", + Name: "fly-privatefrom", In: "query", Required: false, AllowEmptyValue: false, @@ -336,8 +336,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["privateForParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Private transaction recipients (comma separated or multiple params) (header: x-kaleido-privatefor)", - Name: "kld-privatefor", + Description: "Private transaction recipients (comma separated or multiple params) (header: x-firefly-privatefor)", + Name: "fly-privatefor", In: "query", Required: false, AllowEmptyValue: false, @@ -348,8 +348,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["privacyGroupIdParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Private transaction group ID (header: x-kaleido-privacyGroupId)", - Name: "kld-privacygroupid", + Description: "Private transaction group ID (header: x-firefly-privacyGroupId)", + Name: "fly-privacygroupid", In: "query", Required: false, AllowEmptyValue: false, @@ -360,8 +360,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["registerParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "Register the installed contract on a friendly path (overwrites existing) (header: x-kaleido-register)", - Name: "kld-register", + Description: "Register the installed contract on a friendly path (overwrites existing) (header: x-firefly-register)", + Name: "fly-register", In: "query", Required: false, AllowEmptyValue: false, @@ -372,8 +372,8 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { } params["blocknumberParam"] = spec.Parameter{ ParamProps: spec.ParamProps{ - Description: "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-kaleido-blocknumber)", - Name: "kld-blocknumber", + Description: "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-firefly-blocknumber)", + Name: "fly-blocknumber", In: "query", Required: false, AllowEmptyValue: false, @@ -388,7 +388,7 @@ func (c *ABI2Swagger) getCommonParameters() map[string]spec.Parameter { func (c *ABI2Swagger) addCommonParams(op *spec.Operation, isPOST bool, isConstructor bool) { if c.conf.BasicAuth { - op.Security = append(op.Security, map[string][]string{kaleidoAppCredential: {}}) + op.Security = append(op.Security, map[string][]string{fireflyAppCredential: {}}) } fromParam, _ := spec.NewRef("#/parameters/fromParam") diff --git a/internal/kldopenapi/abi2swagger_test.go b/internal/openapi/abi2swagger_test.go similarity index 97% rename from internal/kldopenapi/abi2swagger_test.go rename to internal/openapi/abi2swagger_test.go index fb59cbba..5a085d76 100644 --- a/internal/kldopenapi/abi2swagger_test.go +++ b/internal/openapi/abi2swagger_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldopenapi +package openapi import ( "bufio" @@ -22,7 +22,7 @@ import ( "strings" "testing" - "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/ethbind" "github.com/stretchr/testify/assert" ) @@ -44,7 +44,7 @@ func TestABI2SwaggerERC20(t *testing.T) { OrionPrivateAPI: true, BasicAuth: true, }) - abi, err := eth.API.JSON(strings.NewReader(erc20ABI)) + abi, err := ethbind.API.JSON(strings.NewReader(erc20ABI)) assert.NoError(err) swagger := c.Gen4Factory("/erc20", "erc20", false, false, &abi, erc20DevDocs) @@ -69,7 +69,7 @@ func TestABI2SwaggerERC20actoryOnlyNoAuthCustomScheme(t *testing.T) { OrionPrivateAPI: false, BasicAuth: false, }) - abi, err := eth.API.JSON(strings.NewReader(erc20ABI)) + abi, err := ethbind.API.JSON(strings.NewReader(erc20ABI)) assert.NoError(err) swagger := c.Gen4Factory("/erc20", "erc20", true, false, &abi, erc20DevDocs) @@ -89,7 +89,7 @@ func TestABI2SwaggerLotsOfTypesInstance(t *testing.T) { OrionPrivateAPI: true, BasicAuth: true, }) - abi, err := eth.API.JSON(strings.NewReader(lotsOfTypesABI)) + abi, err := ethbind.API.JSON(strings.NewReader(lotsOfTypesABI)) assert.NoError(err) swagger := c.Gen4Instance("/0x0123456789abcdef0123456789abcdef0123456", "lotsOfTypes", &abi, lotsOfTypesDevDocs) @@ -111,7 +111,7 @@ func TestABI2SwaggerV2ABIEncoder(t *testing.T) { }) f, err := os.Open("../../test/abicoderv2_example.abi.json") assert.NoError(err) - abi, err := eth.API.JSON(bufio.NewReader(f)) + abi, err := ethbind.API.JSON(bufio.NewReader(f)) assert.NoError(err) swagger := c.Gen4Instance("/0x0123456789abcdef0123456789abcdef0123456", "abicoderv2", &abi, lotsOfTypesDevDocs) @@ -134,7 +134,7 @@ func TestABI2SwaggerUnnamedInputsABI(t *testing.T) { OrionPrivateAPI: true, BasicAuth: true, }) - abi, err := eth.API.JSON(strings.NewReader(unnamedInputsABI)) + abi, err := ethbind.API.JSON(strings.NewReader(unnamedInputsABI)) assert.NoError(err) swagger := c.Gen4Factory("/simplestorage", "ssunnamed", false, false, &abi, "") diff --git a/internal/kldrest/memreceipts.go b/internal/rest/memreceipts.go similarity index 93% rename from internal/kldrest/memreceipts.go rename to internal/rest/memreceipts.go index f2cf782b..4f388807 100644 --- a/internal/kldrest/memreceipts.go +++ b/internal/rest/memreceipts.go @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "container/list" "sync" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" log "github.com/sirupsen/logrus" ) @@ -42,7 +42,7 @@ func (m *memoryReceipts) GetReceipts(skip, limit int, ids []string, sinceEpochMS defer m.mux.Unlock() if len(ids) > 0 || sinceEpochMS != 0 || from != "" || to != "" { - return nil, klderrors.Errorf(klderrors.KVStoreMemFilteringUnsupported) + return nil, errors.Errorf(errors.KVStoreMemFilteringUnsupported) } results := make([]map[string]interface{}, 0, limit) diff --git a/internal/kldrest/memreceipts_test.go b/internal/rest/memreceipts_test.go similarity index 98% rename from internal/kldrest/memreceipts_test.go rename to internal/rest/memreceipts_test.go index 4354c888..fa5b21a0 100644 --- a/internal/kldrest/memreceipts_test.go +++ b/internal/rest/memreceipts_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "fmt" diff --git a/internal/kldrest/mongoreceipts.go b/internal/rest/mongoreceipts.go similarity index 94% rename from internal/kldrest/mongoreceipts.go rename to internal/rest/mongoreceipts.go index a9d1a95b..c302936a 100644 --- a/internal/kldrest/mongoreceipts.go +++ b/internal/rest/mongoreceipts.go @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "time" "github.com/globalsign/mgo" "github.com/globalsign/mgo/bson" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" log "github.com/sirupsen/logrus" ) @@ -47,7 +47,7 @@ func (m *mongoReceipts) connect() (err error) { } err = m.mgo.Connect(m.conf.URL, time.Duration(m.conf.ConnectTimeoutMS)*time.Millisecond) if err != nil { - err = klderrors.Errorf(klderrors.ReceiptStoreMongoDBConnect, err) + err = errors.Errorf(errors.ReceiptStoreMongoDBConnect, err) return } m.collection = m.mgo.GetCollection(m.conf.Database, m.conf.Collection) @@ -66,7 +66,7 @@ func (m *mongoReceipts) connect() (err error) { Sparse: true, } if err = m.collection.EnsureIndex(index); err != nil { - err = klderrors.Errorf(klderrors.ReceiptStoreMongoDBIndex, err) + err = errors.Errorf(errors.ReceiptStoreMongoDBIndex, err) return } diff --git a/internal/kldrest/mongoreceipts_test.go b/internal/rest/mongoreceipts_test.go similarity index 99% rename from internal/kldrest/mongoreceipts_test.go rename to internal/rest/mongoreceipts_test.go index 3d9e91b9..ea9e8685 100644 --- a/internal/kldrest/mongoreceipts_test.go +++ b/internal/rest/mongoreceipts_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "fmt" diff --git a/internal/kldrest/mongwrapper.go b/internal/rest/mongwrapper.go similarity index 99% rename from internal/kldrest/mongwrapper.go rename to internal/rest/mongwrapper.go index 910df86c..29532f31 100644 --- a/internal/kldrest/mongwrapper.go +++ b/internal/rest/mongwrapper.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest // github.com/globalsign/mgo seems to be the most popular mgo fork. It seems // a key feature we need is missing from the official Golang library. diff --git a/internal/kldrest/receiptstore.go b/internal/rest/receiptstore.go similarity index 79% rename from internal/kldrest/receiptstore.go rename to internal/rest/receiptstore.go index 8088d8f6..b2f7f688 100644 --- a/internal/kldrest/receiptstore.go +++ b/internal/rest/receiptstore.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "encoding/json" @@ -22,11 +22,11 @@ import ( "time" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldcontracts" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/contracts" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) @@ -48,10 +48,10 @@ type ReceiptStorePersistence interface { type receiptStore struct { conf *ReceiptStoreConf persistence ReceiptStorePersistence - smartContractGW kldcontracts.SmartContractGateway + smartContractGW contracts.SmartContractGateway } -func newReceiptStore(conf *ReceiptStoreConf, persistence ReceiptStorePersistence, smartContractGW kldcontracts.SmartContractGateway) *receiptStore { +func newReceiptStore(conf *ReceiptStoreConf, persistence ReceiptStorePersistence, smartContractGW contracts.SmartContractGateway) *receiptStore { if conf.RetryTimeoutMS <= 0 { conf.RetryTimeoutMS = defaultRetryTimeout } @@ -97,24 +97,24 @@ func (r *receiptStore) processReply(msgBytes []byte) { } // The one field we require is the original ID (as it's the key in MongoDB) - requestID := kldutils.GetMapString(headers, "requestId") + requestID := utils.GetMapString(headers, "requestId") if requestID == "" { log.Errorf("Failed to extract headers.requestId from '%+v'", parsedMsg) return } - reqOffset := kldutils.GetMapString(headers, "reqOffset") - msgType := kldutils.GetMapString(headers, "type") - contractAddr := kldutils.GetMapString(parsedMsg, "contractAddress") + reqOffset := utils.GetMapString(headers, "reqOffset") + msgType := utils.GetMapString(headers, "type") + contractAddr := utils.GetMapString(parsedMsg, "contractAddress") result := "" - if msgType == kldmessages.MsgTypeError { - result = kldutils.GetMapString(parsedMsg, "errorMessage") + if msgType == messages.MsgTypeError { + result = utils.GetMapString(parsedMsg, "errorMessage") } else { - result = kldutils.GetMapString(parsedMsg, "transactionHash") + result = utils.GetMapString(parsedMsg, "transactionHash") } log.Infof("Received reply message. requestId='%s' reqOffset='%s' type='%s': %s", requestID, reqOffset, msgType, result) - if r.smartContractGW != nil && msgType == kldmessages.MsgTypeTransactionSuccess && contractAddr != "" { - var receipt kldmessages.TransactionReceipt + if r.smartContractGW != nil && msgType == messages.MsgTypeTransactionSuccess && contractAddr != "" { + var receipt messages.TransactionReceipt if err := json.Unmarshal(msgBytes, &receipt); err == nil { if err = r.smartContractGW.PostDeploy(&receipt); err != nil { log.Errorf("Failed to process receipt in smart contract gateway: %s", err) @@ -179,7 +179,7 @@ func (r *receiptStore) marshalAndReply(res http.ResponseWriter, req *http.Reques resBytes, err := json.MarshalIndent(result, "", " ") if err != nil { log.Errorf("Error serializing receipts: %s", err) - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreSerializeResponse), 500) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreSerializeResponse), 500) return } status := 200 @@ -193,16 +193,16 @@ func (r *receiptStore) marshalAndReply(res http.ResponseWriter, req *http.Reques func (r *receiptStore) getReplies(res http.ResponseWriter, req *http.Request, params httprouter.Params) { log.Infof("--> %s %s", req.Method, req.URL) - err := kldauth.AuthListAsyncReplies(req.Context()) + err := auth.AuthListAsyncReplies(req.Context()) if err != nil { log.Errorf("Error querying replies: %s", err) - sendRESTError(res, req, klderrors.Errorf(klderrors.Unauthorized), 401) + sendRESTError(res, req, errors.Errorf(errors.Unauthorized), 401) return } res.Header().Set("Content-Type", "application/json") if r.persistence == nil { - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreDisabled), 405) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreDisabled), 405) return } @@ -215,7 +215,7 @@ func (r *receiptStore) getReplies(res http.ResponseWriter, req *http.Request, pa for idx, id := range ids { if !uuidCharsVerifier.MatchString(id) { log.Errorf("Invalid id '%s' %d", id, idx) - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreInvalidRequestID), 400) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreInvalidRequestID), 400) return } } @@ -227,14 +227,14 @@ func (r *receiptStore) getReplies(res http.ResponseWriter, req *http.Request, pa if customLimit, err := strconv.ParseInt(limitStr, 10, 32); err == nil { if int(customLimit) > r.conf.QueryLimit { log.Errorf("Invalid limit value: %s", err) - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreInvalidRequestMaxLimit, r.conf.QueryLimit), 400) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreInvalidRequestMaxLimit, r.conf.QueryLimit), 400) return } else if customLimit > 0 { limit = int(customLimit) } } else { log.Errorf("Invalid limit value: %s", err) - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreInvalidRequestBadLimit), 400) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreInvalidRequestBadLimit), 400) return } } @@ -247,7 +247,7 @@ func (r *receiptStore) getReplies(res http.ResponseWriter, req *http.Request, pa skip = int(skipI64) } else { log.Errorf("Invalid skip value: %s", err) - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreInvalidRequestBadSkip), 400) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreInvalidRequestBadSkip), 400) return } } @@ -261,7 +261,7 @@ func (r *receiptStore) getReplies(res http.ResponseWriter, req *http.Request, pa } else { if sinceEpochMS, err = strconv.ParseInt(since, 10, 64); err != nil { log.Errorf("since '%s' cannot be parsed as RFC3339 or millisecond timestamp: %s", since, err) - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreInvalidRequestBadSince), 400) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreInvalidRequestBadSince), 400) } } } @@ -273,7 +273,7 @@ func (r *receiptStore) getReplies(res http.ResponseWriter, req *http.Request, pa results, err := r.persistence.GetReceipts(skip, limit, ids, sinceEpochMS, from, to) if err != nil { log.Errorf("Error querying replies: %s", err) - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreFailedQuery, err), 500) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreFailedQuery, err), 500) return } log.Debugf("Replies query: skip=%d limit=%d replies=%d", skip, limit, len(*results)) @@ -285,10 +285,10 @@ func (r *receiptStore) getReplies(res http.ResponseWriter, req *http.Request, pa func (r *receiptStore) getReply(res http.ResponseWriter, req *http.Request, params httprouter.Params) { log.Infof("--> %s %s", req.Method, req.URL) - err := kldauth.AuthReadAsyncReplyByUUID(req.Context()) + err := auth.AuthReadAsyncReplyByUUID(req.Context()) if err != nil { log.Errorf("Error querying reply: %s", err) - sendRESTError(res, req, klderrors.Errorf(klderrors.Unauthorized), 401) + sendRESTError(res, req, errors.Errorf(errors.Unauthorized), 401) return } @@ -297,10 +297,10 @@ func (r *receiptStore) getReply(res http.ResponseWriter, req *http.Request, para result, err := r.persistence.GetReceipt(requestID) if err != nil { log.Errorf("Error querying reply: %s", err) - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreFailedQuerySingle, err), 500) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreFailedQuerySingle, err), 500) return } else if result == nil { - sendRESTError(res, req, klderrors.Errorf(klderrors.ReceiptStoreFailedNotFound), 404) + sendRESTError(res, req, errors.Errorf(errors.ReceiptStoreFailedNotFound), 404) log.Infof("Reply not found") return } diff --git a/internal/kldrest/receiptstore_test.go b/internal/rest/receiptstore_test.go similarity index 84% rename from internal/kldrest/receiptstore_test.go rename to internal/rest/receiptstore_test.go index 1261295c..919815b2 100644 --- a/internal/kldrest/receiptstore_test.go +++ b/internal/rest/receiptstore_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "encoding/json" @@ -25,11 +25,11 @@ import ( "net/http/httptest" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldauth/kldauthtest" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/auth/authtest" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/utils" ) type mockReceiptErrs struct { @@ -92,12 +92,12 @@ func TestReplyProcessorWithValidReply(t *testing.T) { r, p := newReceiptsTestStore(nil) - replyMsg := &kldmessages.TransactionReceipt{} - replyMsg.Headers.MsgType = kldmessages.MsgTypeTransactionSuccess - replyMsg.Headers.ID = kldutils.UUIDv4() - replyMsg.Headers.ReqID = kldutils.UUIDv4() + replyMsg := &messages.TransactionReceipt{} + replyMsg.Headers.MsgType = messages.MsgTypeTransactionSuccess + replyMsg.Headers.ID = utils.UUIDv4() + replyMsg.Headers.ReqID = utils.UUIDv4() replyMsg.Headers.ReqOffset = "topic:1:2" - txHash := eth.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") + txHash := ethbind.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") replyMsg.TransactionHash = &txHash replyMsgBytes, _ := json.Marshal(&replyMsg) @@ -115,14 +115,14 @@ func TestReplyProcessorWithContractGWSuccess(t *testing.T) { r, p := newReceiptsTestStore(nil) r.smartContractGW = &mockContractGW{} - replyMsg := &kldmessages.TransactionReceipt{} - replyMsg.Headers.MsgType = kldmessages.MsgTypeTransactionSuccess - replyMsg.Headers.ID = kldutils.UUIDv4() - replyMsg.Headers.ReqID = kldutils.UUIDv4() + replyMsg := &messages.TransactionReceipt{} + replyMsg.Headers.MsgType = messages.MsgTypeTransactionSuccess + replyMsg.Headers.ID = utils.UUIDv4() + replyMsg.Headers.ReqID = utils.UUIDv4() replyMsg.Headers.ReqOffset = "topic:1:2" - txHash := eth.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") + txHash := ethbind.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") replyMsg.TransactionHash = &txHash - addr := eth.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef0123456") + addr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef0123456") replyMsg.ContractAddress = &addr replyMsgBytes, _ := json.Marshal(&replyMsg) @@ -142,14 +142,14 @@ func TestReplyProcessorWithContractGWFailure(t *testing.T) { postDeployErr: fmt.Errorf("pop"), } - replyMsg := &kldmessages.TransactionReceipt{} - replyMsg.Headers.MsgType = kldmessages.MsgTypeTransactionSuccess - replyMsg.Headers.ID = kldutils.UUIDv4() - replyMsg.Headers.ReqID = kldutils.UUIDv4() + replyMsg := &messages.TransactionReceipt{} + replyMsg.Headers.MsgType = messages.MsgTypeTransactionSuccess + replyMsg.Headers.ID = utils.UUIDv4() + replyMsg.Headers.ReqID = utils.UUIDv4() replyMsg.Headers.ReqOffset = "topic:1:2" - txHash := eth.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") + txHash := ethbind.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") replyMsg.TransactionHash = &txHash - addr := eth.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef0123456") + addr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef0123456") replyMsg.ContractAddress = &addr replyMsgBytes, _ := json.Marshal(&replyMsg) @@ -167,7 +167,7 @@ func TestReplyProcessorWithContractGWBadReceipt(t *testing.T) { replyMsg := map[string]interface{}{ "headers": map[string]interface{}{ - "type": kldmessages.MsgTypeTransactionSuccess, + "type": messages.MsgTypeTransactionSuccess, "requestId": "123", }, "contractAddress": "bad address", // cannot parse as address @@ -190,12 +190,12 @@ func TestReplyProcessorWithPeristenceErrorPanics(t *testing.T) { addReceiptErr: fmt.Errorf("pop"), }, nil) - replyMsg := &kldmessages.TransactionReceipt{} - replyMsg.Headers.MsgType = kldmessages.MsgTypeTransactionSuccess - replyMsg.Headers.ID = kldutils.UUIDv4() - replyMsg.Headers.ReqID = kldutils.UUIDv4() + replyMsg := &messages.TransactionReceipt{} + replyMsg.Headers.MsgType = messages.MsgTypeTransactionSuccess + replyMsg.Headers.ID = utils.UUIDv4() + replyMsg.Headers.ReqID = utils.UUIDv4() replyMsg.Headers.ReqOffset = "topic:1:2" - txHash := eth.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") + txHash := ethbind.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") replyMsg.TransactionHash = &txHash replyMsgBytes, _ := json.Marshal(&replyMsg) @@ -216,12 +216,12 @@ func TestReplyProcessorWithPeristenceErrorDuplicateSwallows(t *testing.T) { RetryInitialDelayMS: 1, }, mr, nil) - replyMsg := &kldmessages.TransactionReceipt{} - replyMsg.Headers.MsgType = kldmessages.MsgTypeTransactionSuccess - replyMsg.Headers.ID = kldutils.UUIDv4() - replyMsg.Headers.ReqID = kldutils.UUIDv4() + replyMsg := &messages.TransactionReceipt{} + replyMsg.Headers.MsgType = messages.MsgTypeTransactionSuccess + replyMsg.Headers.ID = utils.UUIDv4() + replyMsg.Headers.ReqID = utils.UUIDv4() replyMsg.Headers.ReqOffset = "topic:1:2" - txHash := eth.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") + txHash := ethbind.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") replyMsg.TransactionHash = &txHash replyMsgBytes, _ := json.Marshal(&replyMsg) @@ -236,10 +236,10 @@ func TestReplyProcessorWithErrorReply(t *testing.T) { r, p := newReceiptsTestStore(nil) - replyMsg := &kldmessages.ErrorReply{} - replyMsg.Headers.MsgType = kldmessages.MsgTypeError - replyMsg.Headers.ID = kldutils.UUIDv4() - replyMsg.Headers.ReqID = kldutils.UUIDv4() + replyMsg := &messages.ErrorReply{} + replyMsg.Headers.MsgType = messages.MsgTypeError + replyMsg.Headers.ID = utils.UUIDv4() + replyMsg.Headers.ReqID = utils.UUIDv4() replyMsg.Headers.ReqOffset = "topic:1:2" replyMsg.OriginalMessage = "{\"badness\": true}" replyMsg.ErrorMessage = "pop" @@ -271,7 +271,7 @@ func TestReplyProcessorMissingRequestId(t *testing.T) { r, p := newReceiptsTestStore(nil) - replyMsg := &kldmessages.ErrorReply{} + replyMsg := &messages.ErrorReply{} replyMsgBytes, _ := json.Marshal(&replyMsg) r.processReply(replyMsgBytes) @@ -284,8 +284,8 @@ func TestReplyProcessorInsertError(t *testing.T) { r, p := newReceiptsTestStore(nil) - replyMsg := &kldmessages.ErrorReply{} - replyMsg.Headers.ReqID = kldutils.UUIDv4() + replyMsg := &messages.ErrorReply{} + replyMsg.Headers.ReqID = utils.UUIDv4() replyMsgBytes, _ := json.Marshal(&replyMsg) r.processReply(replyMsgBytes) @@ -546,7 +546,7 @@ func TestGetRepliesExcessiveLimit(t *testing.T) { } func TestGetRepliesUnauthorized(t *testing.T) { - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) assert := assert.New(t) _, _, ts := newReceiptsTestServer() @@ -557,11 +557,11 @@ func TestGetRepliesUnauthorized(t *testing.T) { assert.Equal(401, status) assert.Equal("Unauthorized", respJSON["error"]) - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } func TestGetReplyUnauthorized(t *testing.T) { - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) assert := assert.New(t) _, _, ts := newReceiptsTestServer() @@ -572,7 +572,7 @@ func TestGetReplyUnauthorized(t *testing.T) { assert.Equal(401, status) assert.Equal("Unauthorized", respJSON["error"]) - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } func TestSendReplyBroadcast(t *testing.T) { @@ -581,12 +581,12 @@ func TestSendReplyBroadcast(t *testing.T) { assert.NotNil(message) }) - replyMsg := &kldmessages.TransactionReceipt{} - replyMsg.Headers.MsgType = kldmessages.MsgTypeTransactionSuccess - replyMsg.Headers.ID = kldutils.UUIDv4() - replyMsg.Headers.ReqID = kldutils.UUIDv4() + replyMsg := &messages.TransactionReceipt{} + replyMsg.Headers.MsgType = messages.MsgTypeTransactionSuccess + replyMsg.Headers.ID = utils.UUIDv4() + replyMsg.Headers.ReqID = utils.UUIDv4() replyMsg.Headers.ReqOffset = "topic:1:2" - txHash := eth.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") + txHash := ethbind.API.HexToHash("0x02587104e9879911bea3d5bf6ccd7e1a6cb9a03145b8a1141804cebd6aa67c5c") replyMsg.TransactionHash = &txHash replyMsgBytes, _ := json.Marshal(&replyMsg) diff --git a/internal/kldrest/resterror.go b/internal/rest/resterror.go similarity index 98% rename from internal/kldrest/resterror.go rename to internal/rest/resterror.go index e3ba49dd..63c78a65 100644 --- a/internal/kldrest/resterror.go +++ b/internal/rest/resterror.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "encoding/json" diff --git a/internal/kldrest/restgateway.go b/internal/rest/restgateway.go similarity index 75% rename from internal/kldrest/restgateway.go rename to internal/rest/restgateway.go index df9c7fd8..61eb029e 100644 --- a/internal/kldrest/restgateway.go +++ b/internal/rest/restgateway.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "context" @@ -26,15 +26,15 @@ import ( "syscall" "time" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldcontracts" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldkafka" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" - "github.com/kaleido-io/ethconnect/internal/kldutils" - "github.com/kaleido-io/ethconnect/internal/kldws" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/contracts" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/kafka" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" + "github.com/kaleido-io/ethconnect/internal/utils" + "github.com/kaleido-io/ethconnect/internal/ws" "github.com/Shopify/sarama" "github.com/julienschmidt/httprouter" @@ -66,14 +66,14 @@ type MongoDBReceiptStoreConf struct { // RESTGatewayConf defines the YAML config structure for a webhooks bridge instance type RESTGatewayConf struct { - Kafka kldkafka.KafkaCommonConf `json:"kafka"` - MongoDB MongoDBReceiptStoreConf `json:"mongodb"` - MemStore ReceiptStoreConf `json:"memstore"` - OpenAPI kldcontracts.SmartContractGatewayConf `json:"openapi"` + Kafka kafka.KafkaCommonConf `json:"kafka"` + MongoDB MongoDBReceiptStoreConf `json:"mongodb"` + MemStore ReceiptStoreConf `json:"memstore"` + OpenAPI contracts.SmartContractGatewayConf `json:"openapi"` HTTP struct { - LocalAddr string `json:"localAddr"` - Port int `json:"port"` - TLS kldutils.TLSConfig `json:"tls"` + LocalAddr string `json:"localAddr"` + Port int `json:"port"` + TLS utils.TLSConfig `json:"tls"` } `json:"http"` WebhooksDirectConf } @@ -82,7 +82,7 @@ type RESTGatewayConf struct { type RESTGateway struct { printYAML *bool conf RESTGatewayConf - kafka kldkafka.KafkaCommon + kafka kafka.KafkaCommon srv *http.Server sendCond *sync.Cond pendingMsgs map[string]bool @@ -90,8 +90,8 @@ type RESTGateway struct { failedMsgs map[string]error receipts *receiptStore webhooks *webhooks - smartContractGW kldcontracts.SmartContractGateway - ws kldws.WebSocketServer + smartContractGW contracts.SmartContractGateway + ws ws.WebSocketServer } // Conf gets the config for this bridge @@ -106,15 +106,15 @@ func (g *RESTGateway) SetConf(conf *RESTGatewayConf) { // ValidateConf validates the config func (g *RESTGateway) ValidateConf() (err error) { - if !kldutils.AllOrNoneReqd(g.conf.MongoDB.URL, g.conf.MongoDB.Database, g.conf.MongoDB.Collection) { - err = klderrors.Errorf(klderrors.ConfigRESTGatewayRequiredReceiptStore) + if !utils.AllOrNoneReqd(g.conf.MongoDB.URL, g.conf.MongoDB.Database, g.conf.MongoDB.Collection) { + err = errors.Errorf(errors.ConfigRESTGatewayRequiredReceiptStore) return } if g.conf.MongoDB.QueryLimit < 1 { g.conf.MongoDB.QueryLimit = 100 } if g.conf.OpenAPI.StoragePath != "" && g.conf.RPC.URL == "" { - err = klderrors.Errorf(klderrors.ConfigRESTGatewayRequiredRPC) + err = errors.Errorf(errors.ConfigRESTGatewayRequiredRPC) return } return @@ -128,7 +128,7 @@ func NewRESTGateway(printYAML *bool) (g *RESTGateway) { pendingMsgs: make(map[string]bool), successMsgs: make(map[string]*sarama.ProducerMessage), failedMsgs: make(map[string]error), - ws: kldws.NewWebSocketServer(), + ws: ws.NewWebSocketServer(), } return } @@ -144,7 +144,7 @@ func (g *RESTGateway) CobraInit(cmdName string) (cmd *cobra.Command) { }, PreRunE: func(cmd *cobra.Command, args []string) (err error) { if len(g.conf.Kafka.Brokers) > 0 { - if err = kldkafka.KafkaValidateConf(&g.conf.Kafka); err != nil { + if err = kafka.KafkaValidateConf(&g.conf.Kafka); err != nil { return } } else { @@ -162,20 +162,20 @@ func (g *RESTGateway) CobraInit(cmdName string) (cmd *cobra.Command) { return }, } - kldkafka.KafkaCommonCobraInit(cmd, &g.conf.Kafka) - kldeth.CobraInitRPC(cmd, &g.conf.RPCConf) - kldtx.CobraInitTxnProcessor(cmd, &g.conf.TxnProcessorConf) - kldcontracts.CobraInitContractGateway(cmd, &g.conf.OpenAPI) - cmd.Flags().IntVarP(&g.conf.MaxInFlight, "maxinflight", "m", kldutils.DefInt("WEBHOOKS_MAX_INFLIGHT", 0), "Maximum messages to hold in-flight") + kafka.KafkaCommonCobraInit(cmd, &g.conf.Kafka) + eth.CobraInitRPC(cmd, &g.conf.RPCConf) + tx.CobraInitTxnProcessor(cmd, &g.conf.TxnProcessorConf) + contracts.CobraInitContractGateway(cmd, &g.conf.OpenAPI) + cmd.Flags().IntVarP(&g.conf.MaxInFlight, "maxinflight", "m", utils.DefInt("WEBHOOKS_MAX_INFLIGHT", 0), "Maximum messages to hold in-flight") cmd.Flags().StringVarP(&g.conf.HTTP.LocalAddr, "listen-addr", "L", os.Getenv("WEBHOOKS_LISTEN_ADDR"), "Local address to listen on") - cmd.Flags().IntVarP(&g.conf.HTTP.Port, "listen-port", "l", kldutils.DefInt("WEBHOOKS_LISTEN_PORT", 8080), "Port to listen on") + cmd.Flags().IntVarP(&g.conf.HTTP.Port, "listen-port", "l", utils.DefInt("WEBHOOKS_LISTEN_PORT", 8080), "Port to listen on") cmd.Flags().StringVarP(&g.conf.MongoDB.URL, "mongodb-url", "M", os.Getenv("MONGODB_URL"), "MongoDB URL for a receipt store") cmd.Flags().StringVarP(&g.conf.MongoDB.Database, "mongodb-database", "D", os.Getenv("MONGODB_DATABASE"), "MongoDB receipt store database") cmd.Flags().StringVarP(&g.conf.MongoDB.Collection, "mongodb-receipt-collection", "R", os.Getenv("MONGODB_COLLECTION"), "MongoDB receipt store collection") - cmd.Flags().IntVarP(&g.conf.MongoDB.MaxDocs, "mongodb-receipt-maxdocs", "X", kldutils.DefInt("MONGODB_MAXDOCS", 0), "Receipt store capped size (new collections only)") - cmd.Flags().IntVarP(&g.conf.MongoDB.QueryLimit, "mongodb-query-limit", "Q", kldutils.DefInt("MONGODB_QUERYLIM", 0), "Maximum docs to return on a rest call (cap on limit)") - cmd.Flags().IntVarP(&g.conf.MemStore.MaxDocs, "memstore-receipt-maxdocs", "v", kldutils.DefInt("MEMSTORE_MAXDOCS", 10), "In-memory receipt store capped size") - cmd.Flags().IntVarP(&g.conf.MemStore.QueryLimit, "memstore-query-limit", "V", kldutils.DefInt("MEMSTORE_QUERYLIM", 0), "In-memory maximum docs to return on a rest call") + cmd.Flags().IntVarP(&g.conf.MongoDB.MaxDocs, "mongodb-receipt-maxdocs", "X", utils.DefInt("MONGODB_MAXDOCS", 0), "Receipt store capped size (new collections only)") + cmd.Flags().IntVarP(&g.conf.MongoDB.QueryLimit, "mongodb-query-limit", "Q", utils.DefInt("MONGODB_QUERYLIM", 0), "Maximum docs to return on a rest call (cap on limit)") + cmd.Flags().IntVarP(&g.conf.MemStore.MaxDocs, "memstore-receipt-maxdocs", "v", utils.DefInt("MEMSTORE_MAXDOCS", 10), "In-memory receipt store capped size") + cmd.Flags().IntVarP(&g.conf.MemStore.QueryLimit, "memstore-query-limit", "V", utils.DefInt("MEMSTORE_QUERYLIM", 0), "In-memory maximum docs to return on a rest call") return } @@ -204,7 +204,7 @@ func (g *RESTGateway) sendError(res http.ResponseWriter, msg string, code int) { } // DispatchMsgAsync is the rest2eth interface method for async dispatching of messages (via our webhook logic) -func (g *RESTGateway) DispatchMsgAsync(ctx context.Context, msg map[string]interface{}, ack bool) (*kldmessages.AsyncSentMsg, error) { +func (g *RESTGateway) DispatchMsgAsync(ctx context.Context, msg map[string]interface{}, ack bool) (*messages.AsyncSentMsg, error) { reply, _, err := g.webhooks.processMsg(ctx, msg, ack) return reply, err } @@ -218,7 +218,7 @@ func (g *RESTGateway) newAccessTokenContextHandler(parent http.Handler) http.Han if len(hSplit) == 2 && strings.ToLower(hSplit[0]) == "bearer" { accessToken = hSplit[1] } - authCtx, err := kldauth.WithAuthContext(req.Context(), accessToken) + authCtx, err := auth.WithAuthContext(req.Context(), accessToken) if err != nil { log.Errorf("Error getting auth context: %s", err) g.sendError(res, "Unauthorized", 401) @@ -233,33 +233,33 @@ func (g *RESTGateway) newAccessTokenContextHandler(parent http.Handler) http.Han func (g *RESTGateway) Start() (err error) { if *g.printYAML { - b, err := kldutils.MarshalToYAML(&g.conf) + b, err := utils.MarshalToYAML(&g.conf) print("# YAML Configuration snippet for REST Gateway\n" + string(b)) return err } - tlsConfig, err := kldutils.CreateTLSConfiguration(&g.conf.HTTP.TLS) + tlsConfig, err := utils.CreateTLSConfiguration(&g.conf.HTTP.TLS) if err != nil { return } router := httprouter.New() - var processor kldtx.TxnProcessor - var rpcClient kldeth.RPCClient + var processor tx.TxnProcessor + var rpcClient eth.RPCClient if g.conf.RPC.URL != "" || g.conf.OpenAPI.StoragePath != "" { - rpcClient, err = kldeth.RPCConnect(&g.conf.RPC) + rpcClient, err = eth.RPCConnect(&g.conf.RPC) if err != nil { return err } - processor = kldtx.NewTxnProcessor(&g.conf.TxnProcessorConf, &g.conf.RPCConf) + processor = tx.NewTxnProcessor(&g.conf.TxnProcessorConf, &g.conf.RPCConf) processor.Init(rpcClient) } g.ws.AddRoutes(router) if g.conf.OpenAPI.StoragePath != "" { - g.smartContractGW, err = kldcontracts.NewSmartContractGateway(&g.conf.OpenAPI, &g.conf.TxnProcessorConf, rpcClient, processor, g, g.ws) + g.smartContractGW, err = contracts.NewSmartContractGateway(&g.conf.OpenAPI, &g.conf.TxnProcessorConf, rpcClient, processor, g, g.ws) if err != nil { return err } diff --git a/internal/kldrest/restgateway_test.go b/internal/rest/restgateway_test.go similarity index 96% rename from internal/kldrest/restgateway_test.go rename to internal/rest/restgateway_test.go index 9d84eff0..fc91af16 100644 --- a/internal/kldrest/restgateway_test.go +++ b/internal/rest/restgateway_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "context" @@ -26,8 +26,8 @@ import ( "time" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldauth/kldauthtest" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/auth/authtest" "github.com/stretchr/testify/assert" ) @@ -64,7 +64,7 @@ func TestValidateConfInvalidOpenAPIArgs(t *testing.T) { func TestStartStatusStopNoKafkaWebhooksAccessToken(t *testing.T) { assert := assert.New(t) - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) router := &httprouter.Router{} fakeRPC := httptest.NewServer(router) // Add username/pass to confirm we don't log @@ -108,14 +108,14 @@ func TestStartStatusStopNoKafkaWebhooksAccessToken(t *testing.T) { wg.Wait() assert.EqualError(err, "http: Server closed") - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } func TestStartStatusStopNoKafkaWebhooksMissingToken(t *testing.T) { assert := assert.New(t) - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) router := &httprouter.Router{} fakeRPC := httptest.NewServer(router) @@ -160,7 +160,7 @@ func TestStartStatusStopNoKafkaWebhooksMissingToken(t *testing.T) { wg.Wait() assert.EqualError(err, "http: Server closed") - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } diff --git a/internal/kldrest/webhooks.go b/internal/rest/webhooks.go similarity index 80% rename from internal/kldrest/webhooks.go rename to internal/rest/webhooks.go index 91b4bf14..d7467391 100644 --- a/internal/kldrest/webhooks.go +++ b/internal/rest/webhooks.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "context" @@ -21,10 +21,10 @@ import ( "reflect" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/kldcontracts" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/contracts" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) @@ -36,11 +36,11 @@ type webhooksHandler interface { // webhooks provides the async HTTP to eth TX bridge type webhooks struct { - smartContractGW kldcontracts.SmartContractGateway + smartContractGW contracts.SmartContractGateway handler webhooksHandler } -func newWebhooks(handler webhooksHandler, smartContractGW kldcontracts.SmartContractGateway) *webhooks { +func newWebhooks(handler webhooksHandler, smartContractGW contracts.SmartContractGateway) *webhooks { return &webhooks{ handler: handler, smartContractGW: smartContractGW, @@ -61,7 +61,7 @@ func (w *webhooks) hookErrReply(res http.ResponseWriter, req *http.Request, err return } -func (w *webhooks) msgSentReply(res http.ResponseWriter, req *http.Request, replyMsg *kldmessages.AsyncSentMsg) { +func (w *webhooks) msgSentReply(res http.ResponseWriter, req *http.Request, replyMsg *messages.AsyncSentMsg) { reply, _ := json.Marshal(replyMsg) status := 200 log.Infof("<-- %s %s [%d]: Webhook RequestID=%s", req.Method, req.URL, status, replyMsg.Request) @@ -88,7 +88,7 @@ func (w *webhooks) webhookHandlerNoAck(res http.ResponseWriter, req *http.Reques func (w *webhooks) webhookHandler(res http.ResponseWriter, req *http.Request, ack bool) { log.Infof("--> %s %s", req.Method, req.URL) - msg, err := kldutils.YAMLorJSONPayload(req) + msg, err := utils.YAMLorJSONPayload(req) if err != nil { w.hookErrReply(res, req, err, 400) return @@ -102,35 +102,35 @@ func (w *webhooks) webhookHandler(res http.ResponseWriter, req *http.Request, ac w.msgSentReply(res, req, reply) } -func (w *webhooks) processMsg(ctx context.Context, msg map[string]interface{}, ack bool) (*kldmessages.AsyncSentMsg, int, error) { +func (w *webhooks) processMsg(ctx context.Context, msg map[string]interface{}, ack bool) (*messages.AsyncSentMsg, int, error) { // Check we understand the type, and can get the key. // The rest of the validation is performed by the bridge listening to Kafka headers, exists := msg["headers"] if !exists || reflect.TypeOf(headers).Kind() != reflect.Map { - return nil, 400, klderrors.Errorf(klderrors.WebhooksInvalidMsgHeaders) + return nil, 400, errors.Errorf(errors.WebhooksInvalidMsgHeaders) } msgType, exists := headers.(map[string]interface{})["type"] if !exists || reflect.TypeOf(msgType).Kind() != reflect.String { - return nil, 400, klderrors.Errorf(klderrors.WebhooksInvalidMsgTypeMissing) + return nil, 400, errors.Errorf(errors.WebhooksInvalidMsgTypeMissing) } var key string switch msgType { - case kldmessages.MsgTypeDeployContract, kldmessages.MsgTypeSendTransaction: + case messages.MsgTypeDeployContract, messages.MsgTypeSendTransaction: from, exists := msg["from"] if !exists || reflect.TypeOf(from).Kind() != reflect.String { - return nil, 400, klderrors.Errorf(klderrors.WebhooksInvalidMsgFromMissing) + return nil, 400, errors.Errorf(errors.WebhooksInvalidMsgFromMissing) } key = from.(string) break default: - return nil, 400, klderrors.Errorf(klderrors.WebhooksInvalidMsgType, msgType) + return nil, 400, errors.Errorf(errors.WebhooksInvalidMsgType, msgType) } // We always generate the ID. It cannot be set by the user - msgID := kldutils.UUIDv4() + msgID := utils.UUIDv4() headers.(map[string]interface{})["id"] = msgID - if w.smartContractGW != nil && msgType == kldmessages.MsgTypeDeployContract { + if w.smartContractGW != nil && msgType == messages.MsgTypeDeployContract { var err error if msg, err = w.contractGWHandler(msg); err != nil { return nil, 500, err @@ -143,7 +143,7 @@ func (w *webhooks) processMsg(ctx context.Context, msg map[string]interface{}, a if err != nil { return nil, status, err } - return &kldmessages.AsyncSentMsg{ + return &messages.AsyncSentMsg{ Sent: true, Request: msgID, Msg: msgAck, @@ -154,7 +154,7 @@ func (w *webhooks) contractGWHandler(msg map[string]interface{}) (map[string]int // We have to fully parse, then re-serialize, the message in the case of a contract deployment // where we are performing OpenAPI gateway processing msgBytes, _ := json.Marshal(&msg) - var deployMsg kldmessages.DeployContract + var deployMsg messages.DeployContract if err := json.Unmarshal(msgBytes, &deployMsg); err != nil { return nil, err } diff --git a/internal/kldrest/webhooks_test.go b/internal/rest/webhooks_test.go similarity index 78% rename from internal/kldrest/webhooks_test.go rename to internal/rest/webhooks_test.go index d6e2714f..9438e6bf 100644 --- a/internal/kldrest/webhooks_test.go +++ b/internal/rest/webhooks_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "bytes" @@ -24,7 +24,7 @@ import ( "testing" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/messages" "github.com/stretchr/testify/assert" ) @@ -41,9 +41,9 @@ type mockContractGW struct { replyCallback func(message interface{}) } -func (m *mockContractGW) PreDeploy(*kldmessages.DeployContract) error { return m.preDeployErr } +func (m *mockContractGW) PreDeploy(*messages.DeployContract) error { return m.preDeployErr } -func (m *mockContractGW) PostDeploy(*kldmessages.TransactionReceipt) error { return m.postDeployErr } +func (m *mockContractGW) PostDeploy(*messages.TransactionReceipt) error { return m.postDeployErr } func (m *mockContractGW) AddRoutes(*httprouter.Router) {} @@ -82,12 +82,12 @@ func TestWebhookHandlerBadRequest(t *testing.T) { func TestWebhookHandlerContractGWSuccess(t *testing.T) { assert := assert.New(t) - deployMsg := kldmessages.DeployContract{ - TransactionCommon: kldmessages.TransactionCommon{ - RequestCommon: kldmessages.RequestCommon{ - Headers: kldmessages.RequestHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeDeployContract, + deployMsg := messages.DeployContract{ + TransactionCommon: messages.TransactionCommon{ + RequestCommon: messages.RequestCommon{ + Headers: messages.RequestHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeDeployContract, }, }, }, @@ -107,12 +107,12 @@ func TestWebhookHandlerContractGWSuccess(t *testing.T) { func TestWebhookHandlerContractGWFail(t *testing.T) { assert := assert.New(t) - deployMsg := kldmessages.DeployContract{ - TransactionCommon: kldmessages.TransactionCommon{ - RequestCommon: kldmessages.RequestCommon{ - Headers: kldmessages.RequestHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeDeployContract, + deployMsg := messages.DeployContract{ + TransactionCommon: messages.TransactionCommon{ + RequestCommon: messages.RequestCommon{ + Headers: messages.RequestHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeDeployContract, }, }, }, diff --git a/internal/kldrest/webhooksdirect.go b/internal/rest/webhooksdirect.go similarity index 81% rename from internal/kldrest/webhooksdirect.go rename to internal/rest/webhooksdirect.go index 332bf1bd..cac6c82b 100644 --- a/internal/kldrest/webhooksdirect.go +++ b/internal/rest/webhooksdirect.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "context" @@ -21,19 +21,19 @@ import ( "sync" "time" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) // WebhooksDirectConf defines the YAML structore for a Webhooks direct to RPC bridge type WebhooksDirectConf struct { MaxInFlight int `json:"maxInFlight"` - kldtx.TxnProcessorConf - kldeth.RPCConf + tx.TxnProcessorConf + eth.RPCConf } // webhooksDirect provides the HTTP -> Kafka bridge functionality for ethconnect @@ -41,13 +41,13 @@ type webhooksDirect struct { initialized bool receipts *receiptStore conf *WebhooksDirectConf - processor kldtx.TxnProcessor + processor tx.TxnProcessor inFlightMutex sync.Mutex inFlight map[string]*msgContext stopChan chan error } -func newWebhooksDirect(conf *WebhooksDirectConf, processor kldtx.TxnProcessor, receipts *receiptStore) *webhooksDirect { +func newWebhooksDirect(conf *WebhooksDirectConf, processor tx.TxnProcessor, receipts *receiptStore) *webhooksDirect { return &webhooksDirect{ processor: processor, receipts: receipts, @@ -64,14 +64,14 @@ type msgContext struct { key string msgID string msg map[string]interface{} - headers *kldmessages.CommonHeaders + headers *messages.CommonHeaders } func (t *msgContext) Context() context.Context { return t.ctx } -func (t *msgContext) Headers() *kldmessages.CommonHeaders { +func (t *msgContext) Headers() *messages.CommonHeaders { return t.headers } @@ -94,17 +94,17 @@ func (t *msgContext) SendErrorReplyWithGapFill(status int, err error, gapFillTxH func (t *msgContext) SendErrorReplyWithTX(status int, err error, txHash string) { log.Warnf("Failed to process message %s: %s", t, err) origBytes, _ := json.Marshal(t.msg) - errMsg := kldmessages.NewErrorReply(err, origBytes) + errMsg := messages.NewErrorReply(err, origBytes) errMsg.TXHash = txHash t.Reply(errMsg) } -func (t *msgContext) Reply(replyMessage kldmessages.ReplyWithHeaders) { +func (t *msgContext) Reply(replyMessage messages.ReplyWithHeaders) { t.w.inFlightMutex.Lock() defer t.w.inFlightMutex.Unlock() replyHeaders := replyMessage.ReplyHeaders() - replyHeaders.ID = kldutils.UUIDv4() + replyHeaders.ID = utils.UUIDv4() replyHeaders.Context = t.headers.Context replyHeaders.ReqID = t.headers.ID replyHeaders.Received = t.timeReceived.UTC().Format(time.RFC3339Nano) @@ -126,10 +126,10 @@ func (w *webhooksDirect) sendWebhookMsg(ctx context.Context, key, msgID string, if numInFlight >= w.conf.MaxInFlight { w.inFlightMutex.Unlock() log.Errorf("Failed to dispatch mesage from '%s': %d/%d already in-flight", key, numInFlight, w.conf.MaxInFlight) - return "", 429, klderrors.Errorf(klderrors.WebhooksDirectTooManyInflight) + return "", 429, errors.Errorf(errors.WebhooksDirectTooManyInflight) } - var headers kldmessages.CommonHeaders + var headers messages.CommonHeaders var headerBytes []byte var err error headersMap := msg["headers"] @@ -139,7 +139,7 @@ func (w *webhooksDirect) sendWebhookMsg(ctx context.Context, key, msgID string, if err != nil { w.inFlightMutex.Unlock() log.Errorf("Unable to unmarshal headers from map payload: %+v: %s", msg, err) - return "", 400, klderrors.Errorf(klderrors.WebhooksDirectBadHeaders) + return "", 400, errors.Errorf(errors.WebhooksDirectBadHeaders) } msgContext := &msgContext{ ctx: context.Background(), @@ -159,7 +159,7 @@ func (w *webhooksDirect) sendWebhookMsg(ctx context.Context, key, msgID string, func validateWebhooksDirectConf(conf *WebhooksDirectConf) error { if conf.RPC.URL == "" { - return klderrors.Errorf(klderrors.ConfigWebhooksDirectRPC) + return errors.Errorf(errors.ConfigWebhooksDirectRPC) } if conf.MaxTXWaitTime < 10 { if conf.MaxTXWaitTime > 0 { diff --git a/internal/kldrest/webhooksdirect_test.go b/internal/rest/webhooksdirect_test.go similarity index 86% rename from internal/kldrest/webhooksdirect_test.go rename to internal/rest/webhooksdirect_test.go index daa4278e..ac432b5a 100644 --- a/internal/kldrest/webhooksdirect_test.go +++ b/internal/rest/webhooksdirect_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "bytes" @@ -25,9 +25,9 @@ import ( "testing" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldtx" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/tx" "github.com/stretchr/testify/assert" ) @@ -37,10 +37,10 @@ type mockProcessor struct { } func (p *mockProcessor) ResolveAddress(from string) (string, error) { return "", nil } -func (p *mockProcessor) OnMessage(ctx kldtx.TxnContext) { +func (p *mockProcessor) OnMessage(ctx tx.TxnContext) { p.capturedCtx = ctx.(*msgContext) } -func (p *mockProcessor) Init(kldeth.RPCClient) {} +func (p *mockProcessor) Init(eth.RPCClient) {} func newTestWebhooksDirect(maxMsgs int) (*webhooksDirect, *memoryReceipts, *mockProcessor) { rsc := &ReceiptStoreConf{} @@ -64,13 +64,13 @@ func newTestWebhooksDirectServer(maxMsgs int) (*webhooksDirect, *httptest.Server return wd, ts, r, p } -func newTestMsg() kldmessages.SendTransaction { - return kldmessages.SendTransaction{ - TransactionCommon: kldmessages.TransactionCommon{ - RequestCommon: kldmessages.RequestCommon{ - Headers: kldmessages.RequestHeaders{ - CommonHeaders: kldmessages.CommonHeaders{ - MsgType: kldmessages.MsgTypeSendTransaction, +func newTestMsg() messages.SendTransaction { + return messages.SendTransaction{ + TransactionCommon: messages.TransactionCommon{ + RequestCommon: messages.RequestCommon{ + Headers: messages.RequestHeaders{ + CommonHeaders: messages.CommonHeaders{ + MsgType: messages.MsgTypeSendTransaction, }, }, }, @@ -99,7 +99,7 @@ func TestWebhooksDirectSubmitSendTransaction(t *testing.T) { assert.Equal(200, resp.StatusCode) replyBytes, _ := ioutil.ReadAll(resp.Body) t.Logf("Received reply: %s", string(replyBytes)) - reply := kldmessages.AsyncSentMsg{} + reply := messages.AsyncSentMsg{} json.Unmarshal(replyBytes, &reply) assert.True(reply.Sent) assert.NotEmpty(reply.Request) @@ -108,7 +108,7 @@ func TestWebhooksDirectSubmitSendTransaction(t *testing.T) { headers := p.capturedCtx.Headers() assert.Equal(reply.Request, headers.ID) - reconstructed := &kldmessages.SendTransaction{} + reconstructed := &messages.SendTransaction{} err = p.capturedCtx.Unmarshal(&reconstructed) assert.NoError(err) assert.Equal("0xd912641Eb51a311A1C6BD32c1ED200C2a5abD7FE", reconstructed.From) @@ -129,7 +129,7 @@ func TestWebhooksDirectMsgLimit(t *testing.T) { assert.Equal(200, resp.StatusCode) replyBytes, _ := ioutil.ReadAll(resp.Body) t.Logf("Received reply: %s", string(replyBytes)) - reply1 := kldmessages.AsyncSentMsg{} + reply1 := messages.AsyncSentMsg{} json.Unmarshal(replyBytes, &reply1) msgID1 := reply1.Request diff --git a/internal/kldrest/webhookskafka.go b/internal/rest/webhookskafka.go similarity index 78% rename from internal/kldrest/webhookskafka.go rename to internal/rest/webhookskafka.go index 1da0350e..4c8a6618 100644 --- a/internal/kldrest/webhookskafka.go +++ b/internal/rest/webhookskafka.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "context" @@ -21,16 +21,16 @@ import ( "sync" "github.com/Shopify/sarama" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldkafka" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/kafka" + "github.com/kaleido-io/ethconnect/internal/messages" log "github.com/sirupsen/logrus" ) // webhooksKafka provides the HTTP -> Kafka bridge functionality for ethconnect type webhooksKafka struct { - kafka kldkafka.KafkaCommon + kafka kafka.KafkaCommon receipts *receiptStore sendCond *sync.Cond pendingMsgs map[string]bool @@ -50,10 +50,10 @@ func newWebhooksKafkaBase(receipts *receiptStore) *webhooksKafka { } // newWebhooksKafka constructor -func newWebhooksKafka(kconf *kldkafka.KafkaCommonConf, receipts *receiptStore) (w *webhooksKafka) { +func newWebhooksKafka(kconf *kafka.KafkaCommonConf, receipts *receiptStore) (w *webhooksKafka) { w = newWebhooksKafkaBase(receipts) - kf := &kldkafka.SaramaKafkaFactory{} - w.kafka = kldkafka.NewKafkaCommon(kf, kconf, w) + kf := &kafka.SaramaKafkaFactory{} + w.kafka = kafka.NewKafkaCommon(kf, kconf, w) return } @@ -80,7 +80,7 @@ func (w *webhooksKafka) waitForSend(msgID string) (msg *sarama.ProducerMessage, } // ConsumerMessagesLoop - consume replies -func (w *webhooksKafka) ConsumerMessagesLoop(consumer kldkafka.KafkaConsumer, producer kldkafka.KafkaProducer, wg *sync.WaitGroup) { +func (w *webhooksKafka) ConsumerMessagesLoop(consumer kafka.KafkaConsumer, producer kafka.KafkaProducer, wg *sync.WaitGroup) { for msg := range consumer.Messages() { w.receipts.processReply(msg.Value) @@ -91,13 +91,13 @@ func (w *webhooksKafka) ConsumerMessagesLoop(consumer kldkafka.KafkaConsumer, pr } // ProducerErrorLoop - consume errors -func (w *webhooksKafka) ProducerErrorLoop(consumer kldkafka.KafkaConsumer, producer kldkafka.KafkaProducer, wg *sync.WaitGroup) { +func (w *webhooksKafka) ProducerErrorLoop(consumer kafka.KafkaConsumer, producer kafka.KafkaProducer, wg *sync.WaitGroup) { log.Debugf("Webhooks listening for errors sending to Kafka") for err := range producer.Errors() { log.Errorf("Error sending message: %s", err) if err.Msg == nil || err.Msg.Metadata == nil { // This should not be possible - panic(klderrors.Errorf(klderrors.WebhooksKafkaUnexpectedErrFmt, err)) + panic(errors.Errorf(errors.WebhooksKafkaUnexpectedErrFmt, err)) } msgID := err.Msg.Metadata.(string) w.sendCond.L.Lock() @@ -112,13 +112,13 @@ func (w *webhooksKafka) ProducerErrorLoop(consumer kldkafka.KafkaConsumer, produ } // ProducerSuccessLoop - consume successes -func (w *webhooksKafka) ProducerSuccessLoop(consumer kldkafka.KafkaConsumer, producer kldkafka.KafkaProducer, wg *sync.WaitGroup) { +func (w *webhooksKafka) ProducerSuccessLoop(consumer kafka.KafkaConsumer, producer kafka.KafkaProducer, wg *sync.WaitGroup) { log.Debugf("Webhooks listening for successful sends to Kafka") for msg := range producer.Successes() { log.Infof("Webhooks sent message ok: %s", msg.Metadata) if msg.Metadata == nil { // This should not be possible - panic(klderrors.Errorf(klderrors.WebhooksKafkaDeliveryReportNoMeta, msg)) + panic(errors.Errorf(errors.WebhooksKafkaDeliveryReportNoMeta, msg)) } msgID := msg.Metadata.(string) w.sendCond.L.Lock() @@ -137,7 +137,7 @@ func (w *webhooksKafka) sendWebhookMsg(ctx context.Context, key, msgID string, m // Reseialize back to JSON with the headers payloadToForward, err := json.Marshal(&msg) if err != nil { - return "", 500, klderrors.Errorf(klderrors.WebhooksKafkaYAMLtoJSON, err) + return "", 500, errors.Errorf(errors.WebhooksKafkaYAMLtoJSON, err) } if ack { w.setMsgPending(msgID) @@ -150,11 +150,11 @@ func (w *webhooksKafka) sendWebhookMsg(ctx context.Context, key, msgID string, m Value: sarama.ByteEncoder(payloadToForward), Metadata: msgID, } - accessToken := kldauth.GetAccessToken(ctx) + accessToken := auth.GetAccessToken(ctx) if accessToken != "" { sentMsg.Headers = []sarama.RecordHeader{ { - Key: []byte(kldmessages.RecordHeaderAccessToken), + Key: []byte(messages.RecordHeaderAccessToken), Value: []byte(accessToken), }, } @@ -165,7 +165,7 @@ func (w *webhooksKafka) sendWebhookMsg(ctx context.Context, key, msgID string, m if ack { successMsg, err := w.waitForSend(msgID) if err != nil { - return "", 502, klderrors.Errorf(klderrors.WebhooksKafkaErr, err) + return "", 502, errors.Errorf(errors.WebhooksKafkaErr, err) } msgAck = fmt.Sprintf("%s:%d:%d", successMsg.Topic, successMsg.Partition, successMsg.Offset) } diff --git a/internal/kldrest/webhookskafka_test.go b/internal/rest/webhookskafka_test.go similarity index 82% rename from internal/kldrest/webhookskafka_test.go rename to internal/rest/webhookskafka_test.go index 28bc4886..2a00524f 100644 --- a/internal/kldrest/webhookskafka_test.go +++ b/internal/rest/webhookskafka_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldrest +package rest import ( "bytes" @@ -31,10 +31,10 @@ import ( "github.com/Shopify/sarama" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/kldauth" - "github.com/kaleido-io/ethconnect/internal/kldauth/kldauthtest" - "github.com/kaleido-io/ethconnect/internal/kldkafka" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/auth" + "github.com/kaleido-io/ethconnect/internal/auth/authtest" + "github.com/kaleido-io/ethconnect/internal/kafka" + "github.com/kaleido-io/ethconnect/internal/messages" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" @@ -46,7 +46,7 @@ type testKafkaCommon struct { startErr error cobraInitCalled bool validateConfErr error - kafkaFactory *kldkafka.MockKafkaFactory + kafkaFactory *kafka.MockKafkaFactory kafkaInitDelay int startTime time.Time } @@ -77,12 +77,12 @@ func (k *testKafkaCommon) CreateTLSConfiguration() (t *tls.Config, err error) { return nil, nil } -func (k *testKafkaCommon) Conf() *kldkafka.KafkaCommonConf { - return &kldkafka.KafkaCommonConf{} +func (k *testKafkaCommon) Conf() *kafka.KafkaCommonConf { + return &kafka.KafkaCommonConf{} } -func (k *testKafkaCommon) Producer() kldkafka.KafkaProducer { - var producer kldkafka.KafkaProducer +func (k *testKafkaCommon) Producer() kafka.KafkaProducer { + var producer kafka.KafkaProducer timeSinceStart := time.Now().Sub(k.startTime) if timeSinceStart > time.Duration(k.kafkaInitDelay)*time.Millisecond { producer = k.kafkaFactory.Producer @@ -92,13 +92,13 @@ func (k *testKafkaCommon) Producer() kldkafka.KafkaProducer { func newTestKafkaComon() *testKafkaCommon { log.SetLevel(log.DebugLevel) - kafka := &testKafkaCommon{} - kafka.startTime = time.Now().UTC() - kafka.stop = make(chan bool) - kafka.kafkaFactory = kldkafka.NewMockKafkaFactory() - kafka.kafkaFactory.NewProducer(kafka) - kafka.kafkaFactory.NewConsumer(kafka) - return kafka + k := &testKafkaCommon{} + k.startTime = time.Now().UTC() + k.stop = make(chan bool) + k.kafkaFactory = kafka.NewMockKafkaFactory() + k.kafkaFactory.NewProducer(k) + k.kafkaFactory.NewConsumer(k) + return k } func newTestWebhooks() (*webhooks, *webhooksKafka, *testKafkaCommon, *httptest.Server) { @@ -112,7 +112,7 @@ func newTestWebhooks() (*webhooks, *webhooksKafka, *testKafkaCommon, *httptest.S w.addRoutes(router) ts := httptest.NewUnstartedServer(router) ts.Config.BaseContext = func(l net.Listener) context.Context { - ctx, _ := kldauth.WithAuthContext(context.Background(), "testat") + ctx, _ := auth.WithAuthContext(context.Background(), "testat") return ctx } ts.Start() @@ -128,7 +128,7 @@ func assertSentResp(assert *assert.Assertions, resp *http.Response, ack bool) { replyBytes, err := ioutil.ReadAll(resp.Body) assert.Nil(err) if resp.StatusCode == 200 { - var replyMsg kldmessages.AsyncSentMsg + var replyMsg messages.AsyncSentMsg err = json.Unmarshal(replyBytes, &replyMsg) assert.Nil(err) assert.Equal(true, replyMsg.Sent) @@ -219,37 +219,37 @@ func sendTestTransaction(assert *assert.Assertions, msgBytes []byte, contentType func TestWebhookHandlerJSONSendTransaction(t *testing.T) { assert := assert.New(t) - msg := kldmessages.SendTransaction{} - msg.Headers.MsgType = kldmessages.MsgTypeSendTransaction + msg := messages.SendTransaction{} + msg.Headers.MsgType = messages.MsgTypeSendTransaction msgBytes, _ := json.Marshal(&msg) resp, replyMsgs := sendTestTransaction(assert, msgBytes, "application/json", nil, true) assertSentResp(assert, resp, true) assert.Equal(1, len(replyMsgs)) - forwardedMessage := kldmessages.SendTransaction{} + forwardedMessage := messages.SendTransaction{} json.Unmarshal(replyMsgs[0], &forwardedMessage) - assert.Equal(kldmessages.MsgTypeSendTransaction, forwardedMessage.Headers.MsgType) + assert.Equal(messages.MsgTypeSendTransaction, forwardedMessage.Headers.MsgType) assert.NotEmpty(forwardedMessage.Headers.ID) } func TestWebhookHandlerJSONSendnWithAccessToken(t *testing.T) { - kldauth.RegisterSecurityModule(&kldauthtest.TestSecurityModule{}) + auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) assert := assert.New(t) - msg := kldmessages.SendTransaction{} - msg.Headers.MsgType = kldmessages.MsgTypeSendTransaction + msg := messages.SendTransaction{} + msg.Headers.MsgType = messages.MsgTypeSendTransaction msgBytes, _ := json.Marshal(&msg) resp, replyMsgs := sendTestTransaction(assert, msgBytes, "application/json", nil, true) assertSentResp(assert, resp, true) assert.Equal(1, len(replyMsgs)) - forwardedMessage := kldmessages.SendTransaction{} + forwardedMessage := messages.SendTransaction{} json.Unmarshal(replyMsgs[0], &forwardedMessage) - assert.Equal(kldmessages.MsgTypeSendTransaction, forwardedMessage.Headers.MsgType) + assert.Equal(messages.MsgTypeSendTransaction, forwardedMessage.Headers.MsgType) assert.NotEmpty(forwardedMessage.Headers.ID) - kldauth.RegisterSecurityModule(nil) + auth.RegisterSecurityModule(nil) } @@ -257,24 +257,24 @@ func TestWebhookHandlerJSONSendTransactionNoAck(t *testing.T) { assert := assert.New(t) - msg := kldmessages.SendTransaction{} - msg.Headers.MsgType = kldmessages.MsgTypeSendTransaction + msg := messages.SendTransaction{} + msg.Headers.MsgType = messages.MsgTypeSendTransaction msgBytes, _ := json.Marshal(&msg) resp, replyMsgs := sendTestTransaction(assert, msgBytes, "application/json", nil, false) assertSentResp(assert, resp, false) assert.Equal(1, len(replyMsgs)) - forwardedMessage := kldmessages.SendTransaction{} + forwardedMessage := messages.SendTransaction{} json.Unmarshal(replyMsgs[0], &forwardedMessage) - assert.Equal(kldmessages.MsgTypeSendTransaction, forwardedMessage.Headers.MsgType) + assert.Equal(messages.MsgTypeSendTransaction, forwardedMessage.Headers.MsgType) } func TestWebhookHandlerJSONSendFailedToKafka(t *testing.T) { assert := assert.New(t) - msg := kldmessages.SendTransaction{} - msg.Headers.MsgType = kldmessages.MsgTypeSendTransaction + msg := messages.SendTransaction{} + msg.Headers.MsgType = messages.MsgTypeSendTransaction msgBytes, _ := json.Marshal(&msg) resp, _ := sendTestTransaction(assert, msgBytes, "application/json", fmt.Errorf("pop"), true) assertErrResp(assert, resp, 502, "Failed to deliver message to Kafka.*pop") @@ -284,17 +284,17 @@ func TestWebhookHandlerJSONSendFailedToKafkaNoAck(t *testing.T) { assert := assert.New(t) - msg := kldmessages.SendTransaction{} - msg.Headers.MsgType = kldmessages.MsgTypeSendTransaction + msg := messages.SendTransaction{} + msg.Headers.MsgType = messages.MsgTypeSendTransaction msgBytes, _ := json.Marshal(&msg) resp, replyMsgs := sendTestTransaction(assert, msgBytes, "application/json", fmt.Errorf("pop"), false) // Error is swallowed assertSentResp(assert, resp, false) assert.Equal(1, len(replyMsgs)) - forwardedMessage := kldmessages.SendTransaction{} + forwardedMessage := messages.SendTransaction{} json.Unmarshal(replyMsgs[0], &forwardedMessage) - assert.Equal(kldmessages.MsgTypeSendTransaction, forwardedMessage.Headers.MsgType) + assert.Equal(messages.MsgTypeSendTransaction, forwardedMessage.Headers.MsgType) } func TestProducerErrorLoopPanicsOnBadErrStructure(t *testing.T) { @@ -352,17 +352,17 @@ func TestWebhookHandlerJSONDeployContract(t *testing.T) { assert := assert.New(t) - msg := kldmessages.DeployContract{} - msg.Headers.MsgType = kldmessages.MsgTypeDeployContract + msg := messages.DeployContract{} + msg.Headers.MsgType = messages.MsgTypeDeployContract msg.From = "any string" msgBytes, _ := json.Marshal(&msg) resp, replyMsgs := sendTestTransaction(assert, msgBytes, "application/json", nil, true) assertSentResp(assert, resp, true) assert.Equal(1, len(replyMsgs)) - forwardedMessage := kldmessages.SendTransaction{} + forwardedMessage := messages.SendTransaction{} json.Unmarshal(replyMsgs[0], &forwardedMessage) - assert.Equal(kldmessages.MsgTypeDeployContract, forwardedMessage.Headers.MsgType) + assert.Equal(messages.MsgTypeDeployContract, forwardedMessage.Headers.MsgType) } func TestWebhookHandlerYAMLDeployContract(t *testing.T) { @@ -397,9 +397,9 @@ func TestWebhookHandlerYAMLDeployContract(t *testing.T) { assertSentResp(assert, resp, true) assert.Equal(1, len(replyMsgs)) - forwardedMessage := kldmessages.SendTransaction{} + forwardedMessage := messages.SendTransaction{} json.Unmarshal(replyMsgs[0], &forwardedMessage) - assert.Equal(kldmessages.MsgTypeDeployContract, forwardedMessage.Headers.MsgType) + assert.Equal(messages.MsgTypeDeployContract, forwardedMessage.Headers.MsgType) } func TestWebhookHandlerYAMLBadHeaders(t *testing.T) { @@ -466,7 +466,7 @@ func TestWebhookHandlerBadMsgType(t *testing.T) { assert := assert.New(t) - msg := kldmessages.RequestCommon{} + msg := messages.RequestCommon{} msg.Headers.MsgType = "badness" msgBytes, _ := json.Marshal(&msg) resp, replyMsgs := sendTestTransaction(assert, msgBytes, "application/json", nil, true) @@ -502,7 +502,7 @@ func TestConsumerMessagesLoopCallsReplyProcessorWithEmptyPayload(t *testing.T) { wk.ConsumerMessagesLoop(consumer, producer, wg) }() - consumer.(*kldkafka.MockKafkaConsumer).MockMessages <- &sarama.ConsumerMessage{ + consumer.(*kafka.MockKafkaConsumer).MockMessages <- &sarama.ConsumerMessage{ Partition: 3, Offset: 12345, Value: []byte(""), @@ -511,6 +511,6 @@ func TestConsumerMessagesLoopCallsReplyProcessorWithEmptyPayload(t *testing.T) { k.stop <- true wg.Wait() - assert.Equal(int64(12345), consumer.(*kldkafka.MockKafkaConsumer).OffsetsByPartition[3]) + assert.Equal(int64(12345), consumer.(*kafka.MockKafkaConsumer).OffsetsByPartition[3]) } diff --git a/internal/kldtx/addressbook.go b/internal/tx/addressbook.go similarity index 81% rename from internal/kldtx/addressbook.go rename to internal/tx/addressbook.go index 441f9d57..3e08af0d 100644 --- a/internal/kldtx/addressbook.go +++ b/internal/tx/addressbook.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldtx +package tx import ( "context" @@ -21,9 +21,9 @@ import ( "sync" "time" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) @@ -34,12 +34,12 @@ const ( // AddressBook looks up RPC URLs based on a remote registry, and optionally // resolves hostnames to IP addresses using a hosts file type AddressBook interface { - lookup(ctx context.Context, addr string) (kldeth.RPCClient, error) + lookup(ctx context.Context, addr string) (eth.RPCClient, error) } // AddressBookConf configuration type AddressBookConf struct { - kldutils.HTTPRequesterConf + utils.HTTPRequesterConf AddressbookURLPrefix string `json:"urlPrefix"` HostsFile string `json:"hostsFile"` PropNames AddressBookPropNamesConf `json:"propNames"` @@ -51,13 +51,13 @@ type AddressBookPropNamesConf struct { } // NewAddressBook construtor -func NewAddressBook(conf *AddressBookConf, rpcConf *kldeth.RPCConf) AddressBook { +func NewAddressBook(conf *AddressBookConf, rpcConf *eth.RPCConf) AddressBook { ab := &addressBook{ conf: conf, fallbackRPCEndpoint: rpcConf.RPC.URL, - hr: kldutils.NewHTTPRequester("Addressbook", &conf.HTTPRequesterConf), + hr: utils.NewHTTPRequester("Addressbook", &conf.HTTPRequesterConf), addrToHost: make(map[string]string), - hostToRPC: make(map[string]kldeth.RPCClientAll), + hostToRPC: make(map[string]eth.RPCClientAll), } propNames := &conf.PropNames if propNames.RPCEndpoint == "" { @@ -71,15 +71,15 @@ func NewAddressBook(conf *AddressBookConf, rpcConf *kldeth.RPCConf) AddressBook type addressBook struct { conf *AddressBookConf - hr *kldutils.HTTPRequester + hr *utils.HTTPRequester mtx sync.Mutex fallbackRPCEndpoint string addrToHost map[string]string - hostToRPC map[string]kldeth.RPCClientAll + hostToRPC map[string]eth.RPCClientAll } // testRPC uses a simple net_version JSON/RPC call to test the health of a cached connection -func (ab *addressBook) testRPC(ctx context.Context, rpc kldeth.RPCClient) bool { +func (ab *addressBook) testRPC(ctx context.Context, rpc eth.RPCClient) bool { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() @@ -96,14 +96,14 @@ func (ab *addressBook) resolveHost(endpoint string) (*url.URL, error) { url, err := url.Parse(endpoint) if err != nil { log.Errorf("Invalid URL '%s': %s", endpoint, err) - return nil, klderrors.Errorf(klderrors.AddressBookLookupBadURL) + return nil, errors.Errorf(errors.AddressBookLookupBadURL) } if ab.conf.HostsFile != "" { - hostsMap, err := kldutils.ParseHosts(ab.conf.HostsFile) + hostsMap, err := utils.ParseHosts(ab.conf.HostsFile) if err != nil { log.Errorf("Failed to parse hosts file: %s", err) - return nil, klderrors.Errorf(klderrors.AddressBookLookupBadHostsFile) + return nil, errors.Errorf(errors.AddressBookLookupBadHostsFile) } splitHostPort := strings.Split(url.Host, ":") if mappedHost, ok := hostsMap[splitHostPort[0]]; ok && mappedHost != "" { @@ -119,7 +119,7 @@ func (ab *addressBook) resolveHost(endpoint string) (*url.URL, error) { // mapEndpoint takes an RPC connect endpoint (prior to host resolution) and maps // it to a cached RPC connection. Or creates a new connection and caches it. -func (ab *addressBook) mapEndpoint(ctx context.Context, endpoint string) (kldeth.RPCClient, error) { +func (ab *addressBook) mapEndpoint(ctx context.Context, endpoint string) (eth.RPCClient, error) { // Simple locking on our cache for now (covers long-lived async test+connect operations) ab.mtx.Lock() @@ -143,7 +143,7 @@ func (ab *addressBook) mapEndpoint(ctx context.Context, endpoint string) (kldeth } // Connect and cache the RPC connection - if rpc, err = kldeth.RPCConnect(&kldeth.RPCConnOpts{ + if rpc, err = eth.RPCConnect(ð.RPCConnOpts{ URL: url.String(), }); err != nil { return nil, err @@ -154,7 +154,7 @@ func (ab *addressBook) mapEndpoint(ctx context.Context, endpoint string) (kldeth // lookup the RPC URL to use for a given from address, performing hostname resolution // based on a custom hosts file (if configured) -func (ab *addressBook) lookup(ctx context.Context, fromAddr string) (kldeth.RPCClient, error) { +func (ab *addressBook) lookup(ctx context.Context, fromAddr string) (eth.RPCClient, error) { // First check if we already know the base (non host translated) endpoint // to use for this address log.Infof("Resolving signing address: %s", fromAddr) @@ -167,7 +167,7 @@ func (ab *addressBook) lookup(ctx context.Context, fromAddr string) (kldeth.RPCC } if body == nil { if ab.fallbackRPCEndpoint == "" { - return nil, klderrors.Errorf(klderrors.AddressBookLookupNotFound) + return nil, errors.Errorf(errors.AddressBookLookupNotFound) } endpoint = ab.fallbackRPCEndpoint } else { diff --git a/internal/kldtx/addressbook_test.go b/internal/tx/addressbook_test.go similarity index 95% rename from internal/kldtx/addressbook_test.go rename to internal/tx/addressbook_test.go index 8a204884..1c8dcd5a 100644 --- a/internal/kldtx/addressbook_test.go +++ b/internal/tx/addressbook_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldtx +package tx import ( "context" @@ -21,7 +21,7 @@ import ( "testing" "github.com/julienschmidt/httprouter" - "github.com/kaleido-io/ethconnect/internal/kldeth" + "github.com/kaleido-io/ethconnect/internal/eth" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -31,7 +31,7 @@ func TestNewAddressBookDefaultPropNames(t *testing.T) { a := NewAddressBook(&AddressBookConf{ AddressbookURLPrefix: "http://localhost:12345/", - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) assert.Equal("http://localhost:12345/", ab.conf.AddressbookURLPrefix) assert.Equal(defaultRPCEndpointProp, ab.conf.PropNames.RPCEndpoint) @@ -45,7 +45,7 @@ func TestNewAddressBookCustomPropNames(t *testing.T) { PropNames: AddressBookPropNamesConf{ RPCEndpoint: "rpcEndpointProp", }, - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) assert.Equal("http://localhost:12345/", ab.conf.AddressbookURLPrefix) assert.Equal("rpcEndpointProp", ab.conf.PropNames.RPCEndpoint) @@ -78,7 +78,7 @@ func TestLookupWithCaching(t *testing.T) { PropNames: AddressBookPropNamesConf{ RPCEndpoint: "rpcEndpointProp", }, - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) log.SetLevel(log.DebugLevel) @@ -125,7 +125,7 @@ func TestLookupBadURL(t *testing.T) { PropNames: AddressBookPropNamesConf{ RPCEndpoint: "rpcEndpointProp", }, - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) ctx := context.Background() @@ -151,8 +151,8 @@ func TestLookupFallbackAddress(t *testing.T) { PropNames: AddressBookPropNamesConf{ RPCEndpoint: "rpcEndpointProp", }, - }, &kldeth.RPCConf{ - RPC: kldeth.RPCConnOpts{ + }, ð.RPCConf{ + RPC: eth.RPCConnOpts{ URL: serverURL, }, }) @@ -184,7 +184,7 @@ func TestLookupNoFallbackAddress(t *testing.T) { PropNames: AddressBookPropNamesConf{ RPCEndpoint: "rpcEndpointProp", }, - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) log.SetLevel(log.DebugLevel) @@ -213,7 +213,7 @@ func TestLookupBadResponse(t *testing.T) { PropNames: AddressBookPropNamesConf{ RPCEndpoint: "rpcEndpointProp", }, - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) log.SetLevel(log.DebugLevel) @@ -241,7 +241,7 @@ func TestLookupFailureResponse(t *testing.T) { PropNames: AddressBookPropNamesConf{ RPCEndpoint: "rpcEndpointProp", }, - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) log.SetLevel(log.DebugLevel) @@ -256,7 +256,7 @@ func TestResolveHostOK(t *testing.T) { a := NewAddressBook(&AddressBookConf{ HostsFile: "../../test/hosts_example", - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) url, err := ab.resolveHost("http://foo.bar:12345") @@ -271,7 +271,7 @@ func TestResolveHostMissing(t *testing.T) { a := NewAddressBook(&AddressBookConf{ HostsFile: "../../test/hosts_example", - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) url, err := ab.resolveHost("http://another") @@ -286,7 +286,7 @@ func TestResolveHostBadFile(t *testing.T) { a := NewAddressBook(&AddressBookConf{ HostsFile: "badhostsfile", - }, &kldeth.RPCConf{}) + }, ð.RPCConf{}) ab := a.(*addressBook) _, err := ab.resolveHost("http://any") diff --git a/internal/kldtx/hdwallet.go b/internal/tx/hdwallet.go similarity index 80% rename from internal/kldtx/hdwallet.go rename to internal/tx/hdwallet.go index 3b3bf7cf..27ac4d53 100644 --- a/internal/kldtx/hdwallet.go +++ b/internal/tx/hdwallet.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldtx +package tx import ( "bytes" @@ -24,10 +24,10 @@ import ( "github.com/alecthomas/template" ethbinding "github.com/kaleido-io/ethbinding/pkg" + "github.com/kaleido-io/ethconnect/internal/errors" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) @@ -41,7 +41,7 @@ var hdWalletFromAddressMatcher = regexp.MustCompile("(?i)^hd-([^-]+)-([^-]+)-(\\ // HDWalletConf configuration type HDWalletConf struct { - kldutils.HTTPRequesterConf + utils.HTTPRequesterConf // URLTemplate is a go template such as: "https://someconstant-{{.InstanceID}}/api/v1/{{.WalletID}}/{{.Index}}" URLTemplate string `json:"urlTemplate"` ChainID string `json:"chainID"` @@ -58,7 +58,7 @@ type hdWallet struct { conf *HDWalletConf urlTemplate *template.Template chainID big.Int - hr *kldutils.HTTPRequester + hr *utils.HTTPRequester } // HDWalletRequest is the struct that is extracted from a specially formatted 'from' string, by IsHDWalletRequest @@ -70,7 +70,7 @@ type HDWalletRequest struct { // HDWallet interface type HDWallet interface { - SignerFor(request *HDWalletRequest) (kldeth.TXSigner, error) + SignerFor(request *HDWalletRequest) (eth.TXSigner, error) } type hdwalletSigner struct { @@ -84,7 +84,7 @@ func newHDWallet(conf *HDWalletConf) HDWallet { hd := &hdWallet{ conf: conf, urlTemplate: template.Must(template.New("urlTemplate").Parse(conf.URLTemplate)), - hr: kldutils.NewHTTPRequester("HDWallet", &conf.HTTPRequesterConf), + hr: utils.NewHTTPRequester("HDWallet", &conf.HTTPRequesterConf), } propNames := &conf.PropNames if propNames.Address == "" { @@ -109,7 +109,7 @@ func IsHDWalletRequest(fromAddr string) *HDWalletRequest { return nil } -func (hd *hdWallet) SignerFor(request *HDWalletRequest) (kldeth.TXSigner, error) { +func (hd *hdWallet) SignerFor(request *HDWalletRequest) (eth.TXSigner, error) { urlStr := &strings.Builder{} hd.urlTemplate.Execute(urlStr, request) @@ -117,27 +117,27 @@ func (hd *hdWallet) SignerFor(request *HDWalletRequest) (kldeth.TXSigner, error) result, err := hd.hr.DoRequest("GET", urlStr.String(), nil) if err != nil { log.Errorf("HDWallet request failed: %s", err) - return nil, klderrors.Errorf(klderrors.HDWalletSigningFailed) + return nil, errors.Errorf(errors.HDWalletSigningFailed) } address, err := hd.hr.GetResponseString(result, hd.conf.PropNames.Address, false) if err != nil { log.Errorf("Missing address in response: %s", err) - return nil, klderrors.Errorf(klderrors.HDWalletSigningBadData) + return nil, errors.Errorf(errors.HDWalletSigningBadData) } keyStr, ok := result[hd.conf.PropNames.PrivateKey].(string) if !ok { log.Errorf("Missing entry in response") - return nil, klderrors.Errorf(klderrors.HDWalletSigningBadData) + return nil, errors.Errorf(errors.HDWalletSigningBadData) } - key, err := eth.API.HexToECDSA(strings.TrimPrefix(keyStr, "0x")) + key, err := ethbind.API.HexToECDSA(strings.TrimPrefix(keyStr, "0x")) if err != nil { log.Errorf("Bad hex value in response '%s': %s", keyStr, err) - return nil, klderrors.Errorf(klderrors.HDWalletSigningBadData) + return nil, errors.Errorf(errors.HDWalletSigningBadData) } return &hdwalletSigner{ - address: eth.API.HexToAddress(address), + address: ethbind.API.HexToAddress(address), key: key, chainID: &hd.chainID, }, nil @@ -153,8 +153,8 @@ func (s *hdwalletSigner) Address() string { } func (s *hdwalletSigner) Sign(tx *ethbinding.Transaction) ([]byte, error) { - ethSigner := eth.API.NewEIP155Signer(s.chainID) - signedTX, _ := eth.API.SignTx(tx, ethSigner, s.key) + ethSigner := ethbind.API.NewEIP155Signer(s.chainID) + signedTX, _ := ethbind.API.SignTx(tx, ethSigner, s.key) signedRLP := new(bytes.Buffer) signedTX.EncodeRLP(signedRLP) return signedRLP.Bytes(), nil diff --git a/internal/kldtx/hdwallet_test.go b/internal/tx/hdwallet_test.go similarity index 91% rename from internal/kldtx/hdwallet_test.go rename to internal/tx/hdwallet_test.go index e5d48188..c97eb3b8 100644 --- a/internal/kldtx/hdwallet_test.go +++ b/internal/tx/hdwallet_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldtx +package tx import ( "bytes" @@ -23,7 +23,7 @@ import ( "testing" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/ethbind" "github.com/stretchr/testify/assert" ) @@ -39,8 +39,8 @@ func TestHDWalletDefaults(t *testing.T) { func TestHDWalletSignOK(t *testing.T) { assert := assert.New(t) - key, _ := eth.API.GenerateKey() - addr := eth.API.PubkeyToAddress(key.PublicKey) + key, _ := ethbind.API.GenerateKey() + addr := ethbind.API.PubkeyToAddress(key.PublicKey) svr := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { assert.Equal("/testinst/api/v1/testwallet/1234", req.URL.Path) @@ -49,7 +49,7 @@ func TestHDWalletSignOK(t *testing.T) { res.Write([]byte(` { "addr": "` + addr.String() + `", - "key": "` + hex.EncodeToString(eth.API.FromECDSA(key)) + `" + "key": "` + hex.EncodeToString(ethbind.API.FromECDSA(key)) + `" }`)) })) defer svr.Close() @@ -72,14 +72,14 @@ func TestHDWalletSignOK(t *testing.T) { assert.Equal(s.Type(), "HD Wallet") assert.Equal(addr.String(), s.Address()) - tx := eth.API.NewContractCreation(12345, big.NewInt(0), 0, big.NewInt(0), []byte("hello world")) + tx := ethbind.API.NewContractCreation(12345, big.NewInt(0), 0, big.NewInt(0), []byte("hello world")) signed, err := s.Sign(tx) assert.NoError(err) - eip155 := eth.API.NewEIP155Signer(big.NewInt(12345)) + eip155 := ethbind.API.NewEIP155Signer(big.NewInt(12345)) tx2 := ðbinding.Transaction{} - err = tx2.DecodeRLP(eth.API.NewStream(bytes.NewReader(signed), 0)) + err = tx2.DecodeRLP(ethbind.API.NewStream(bytes.NewReader(signed), 0)) assert.NoError(err) sender, err := eip155.Sender(tx2) assert.NoError(err) diff --git a/internal/kldtx/txncontext.go b/internal/tx/txncontext.go similarity index 89% rename from internal/kldtx/txncontext.go rename to internal/tx/txncontext.go index d749e236..64e3e013 100644 --- a/internal/kldtx/txncontext.go +++ b/internal/tx/txncontext.go @@ -12,12 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldtx +package tx import ( "context" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/messages" ) // TxnContext is passed for each message that arrives at the bridge @@ -25,7 +25,7 @@ type TxnContext interface { // Return the Go context Context() context.Context // Get the headers of the message - Headers() *kldmessages.CommonHeaders + Headers() *messages.CommonHeaders // Unmarshal the supplied message into a give type Unmarshal(msg interface{}) error // Send an error reply @@ -36,7 +36,7 @@ type TxnContext interface { SendErrorReplyWithGapFill(status int, err error, gapFillTxHash string, gapFillSucceeded bool) // Send a reply that can be marshaled into bytes. // Sets all the common headers on behalf of the caller, based on the request context - Reply(replyMsg kldmessages.ReplyWithHeaders) + Reply(replyMsg messages.ReplyWithHeaders) // Get a string summary String() string } diff --git a/internal/kldtx/txndelaytracker.go b/internal/tx/txndelaytracker.go similarity index 99% rename from internal/kldtx/txndelaytracker.go rename to internal/tx/txndelaytracker.go index 1187a0b2..82d24e23 100644 --- a/internal/kldtx/txndelaytracker.go +++ b/internal/tx/txndelaytracker.go @@ -15,7 +15,7 @@ // Moving average logic builds upon // https://github.com/RobinUS2/golang-moving-average/blob/master/d.go -package kldtx +package tx import ( "time" diff --git a/internal/kldtx/txndelaytracker_test.go b/internal/tx/txndelaytracker_test.go similarity index 99% rename from internal/kldtx/txndelaytracker_test.go rename to internal/tx/txndelaytracker_test.go index 5afe97c8..85623f1f 100644 --- a/internal/kldtx/txndelaytracker_test.go +++ b/internal/tx/txndelaytracker_test.go @@ -14,7 +14,7 @@ // Moving average logic builds upon // https://github.com/RobinUS2/golang-moving-average/blob/master/ma.go -package kldtx +package tx import ( "fmt" diff --git a/internal/kldtx/txnprocessor.go b/internal/tx/txnprocessor.go similarity index 87% rename from internal/kldtx/txnprocessor.go rename to internal/tx/txnprocessor.go index 5ce63b49..caf4a466 100644 --- a/internal/kldtx/txnprocessor.go +++ b/internal/tx/txnprocessor.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldtx +package tx import ( "encoding/json" @@ -25,10 +25,10 @@ import ( "github.com/spf13/cobra" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/eth" + "github.com/kaleido-io/ethconnect/internal/messages" + "github.com/kaleido-io/ethconnect/internal/utils" log "github.com/sirupsen/logrus" ) @@ -40,7 +40,7 @@ const ( // for tracking all in-flight messages type TxnProcessor interface { OnMessage(TxnContext) - Init(kldeth.RPCClient) + Init(eth.RPCClient) ResolveAddress(from string) (resolvedFrom string, err error) } @@ -54,11 +54,11 @@ type inflightTxn struct { privacyGroupID string initialWaitDelay time.Duration txnContext TxnContext - tx *kldeth.Txn + tx *eth.Txn wg sync.WaitGroup registerAs string // passed from request to reply - rpc kldeth.RPCClient - signer kldeth.TXSigner + rpc eth.RPCClient + signer eth.TXSigner gapFillSucceeded bool gapFillTxHash string } @@ -97,16 +97,16 @@ type txnProcessor struct { inflightTxnsLock *sync.Mutex inflightTxns map[string]*inflightTxnState inflightTxnDelayer TxnDelayTracker - rpc kldeth.RPCClient + rpc eth.RPCClient addressBook AddressBook hdwallet HDWallet conf *TxnProcessorConf - rpcConf *kldeth.RPCConf + rpcConf *eth.RPCConf concurrencySlots chan bool } // NewTxnProcessor constructor for message procss -func NewTxnProcessor(conf *TxnProcessorConf, rpcConf *kldeth.RPCConf) TxnProcessor { +func NewTxnProcessor(conf *TxnProcessorConf, rpcConf *eth.RPCConf) TxnProcessor { if conf.SendConcurrency == 0 { conf.SendConcurrency = defaultSendConcurrency } @@ -121,7 +121,7 @@ func NewTxnProcessor(conf *TxnProcessorConf, rpcConf *kldeth.RPCConf) TxnProcess return p } -func (p *txnProcessor) Init(rpc kldeth.RPCClient) { +func (p *txnProcessor) Init(rpc eth.RPCClient) { p.rpc = rpc p.maxTXWaitTime = time.Duration(p.conf.MaxTXWaitTime) * time.Second if p.conf.AddressBookConf.AddressbookURLPrefix != "" { @@ -134,7 +134,7 @@ func (p *txnProcessor) Init(rpc kldeth.RPCClient) { // CobraInitTxnProcessor sets the standard command-line parameters for the txnprocessor func CobraInitTxnProcessor(cmd *cobra.Command, txconf *TxnProcessorConf) { - cmd.Flags().IntVarP(&txconf.MaxTXWaitTime, "tx-timeout", "x", kldutils.DefInt("ETH_TX_TIMEOUT", 0), "Maximum wait time for an individual transaction (seconds)") + cmd.Flags().IntVarP(&txconf.MaxTXWaitTime, "tx-timeout", "x", utils.DefInt("ETH_TX_TIMEOUT", 0), "Maximum wait time for an individual transaction (seconds)") cmd.Flags().BoolVarP(&txconf.HexValuesInReceipt, "hex-values", "H", false, "Include hex values for large numbers in receipts (as well as numeric strings)") cmd.Flags().BoolVarP(&txconf.AlwaysManageNonce, "predict-nonces", "P", false, "Predict the next nonce before sending (default=false for node-signed txns)") cmd.Flags().BoolVarP(&txconf.OrionPrivateAPIS, "orion-privapi", "G", false, "Use Orion JSON/RPC API semantics for private transactions") @@ -151,22 +151,22 @@ func (p *txnProcessor) OnMessage(txnContext TxnContext) { headers := txnContext.Headers() log.Debugf("Processing %+v", headers) switch headers.MsgType { - case kldmessages.MsgTypeDeployContract: - var deployContractMsg kldmessages.DeployContract + case messages.MsgTypeDeployContract: + var deployContractMsg messages.DeployContract if unmarshalErr = txnContext.Unmarshal(&deployContractMsg); unmarshalErr != nil { break } p.OnDeployContractMessage(txnContext, &deployContractMsg) break - case kldmessages.MsgTypeSendTransaction: - var sendTransactionMsg kldmessages.SendTransaction + case messages.MsgTypeSendTransaction: + var sendTransactionMsg messages.SendTransaction if unmarshalErr = txnContext.Unmarshal(&sendTransactionMsg); unmarshalErr != nil { break } p.OnSendTransactionMessage(txnContext, &sendTransactionMsg) break default: - unmarshalErr = klderrors.Errorf(klderrors.TransactionSendMsgTypeUnknown, headers.MsgType) + unmarshalErr = errors.Errorf(errors.TransactionSendMsgTypeUnknown, headers.MsgType) } // We must always send a reply if unmarshalErr != nil { @@ -185,10 +185,10 @@ func (p *txnProcessor) ResolveAddress(from string) (resolvedFrom string, err err return } -func (p *txnProcessor) resolveSigner(from string) (signer kldeth.TXSigner, err error) { +func (p *txnProcessor) resolveSigner(from string) (signer eth.TXSigner, err error) { if hdWalletRequest := IsHDWalletRequest(from); hdWalletRequest != nil { if p.hdwallet == nil { - err = klderrors.Errorf(klderrors.HDWalletSigningNoConfig) + err = errors.Errorf(errors.HDWalletSigningNoConfig) return } if signer, err = p.hdwallet.SignerFor(hdWalletRequest); err != nil { @@ -203,7 +203,7 @@ func (p *txnProcessor) resolveSigner(from string) (signer kldeth.TXSigner, err e // nonce for the transaction. // Builds a new wrapper containing this information, that can be added to // the inflight list if the transaction is submitted -func (p *txnProcessor) addInflightWrapper(txnContext TxnContext, msg *kldmessages.TransactionCommon) (inflight *inflightTxn, err error) { +func (p *txnProcessor) addInflightWrapper(txnContext TxnContext, msg *messages.TransactionCommon) (inflight *inflightTxn, err error) { inflight = &inflightTxn{ txnContext: txnContext, @@ -222,7 +222,7 @@ func (p *txnProcessor) addInflightWrapper(txnContext TxnContext, msg *kldmessage } // Validate the from address, and normalize to lower case with 0x prefix - from, err := kldutils.StrToAddress("from", msg.From) + from, err := utils.StrToAddress("from", msg.From) if err != nil { return } @@ -231,12 +231,12 @@ func (p *txnProcessor) addInflightWrapper(txnContext TxnContext, msg *kldmessage // Need to resolve privateFrom/privateFor to a privacyGroupID for Orion if p.conf.OrionPrivateAPIS { if msg.PrivacyGroupID != "" && len(msg.PrivateFor) > 0 { - err = klderrors.Errorf(klderrors.TransactionSendPrivateForAndPrivacyGroup) + err = errors.Errorf(errors.TransactionSendPrivateForAndPrivacyGroup) return } else if msg.PrivacyGroupID != "" { inflight.privacyGroupID = msg.PrivacyGroupID } else if len(msg.PrivateFor) > 0 { - if inflight.privacyGroupID, err = kldeth.GetOrionPrivacyGroup(txnContext.Context(), p.rpc, &from, msg.PrivateFrom, msg.PrivateFor); err != nil { + if inflight.privacyGroupID, err = eth.GetOrionPrivacyGroup(txnContext.Context(), p.rpc, &from, msg.PrivateFrom, msg.PrivateFor); err != nil { return } } @@ -277,7 +277,7 @@ func (p *txnProcessor) addInflightWrapper(txnContext TxnContext, msg *kldmessage fromNode := false if suppliedNonce != "" { if inflight.nonce, err = suppliedNonce.Int64(); err != nil { - err = klderrors.Errorf(klderrors.TransactionSendBadNonce, err) + err = errors.Errorf(errors.TransactionSendBadNonce, err) return } } else if p.conf.OrionPrivateAPIS && (len(msg.PrivateFor) > 0 || msg.PrivacyGroupID != "") { @@ -285,7 +285,7 @@ func (p *txnProcessor) addInflightWrapper(txnContext TxnContext, msg *kldmessage // group ID and nonce (the public transaction will be submitted by the pantheon node) // Note: We do not have highestNonce calculation for in-flight private transactions, // so attempting to submit more than one per block currently will FAIL - if inflight.nonce, err = kldeth.GetOrionTXCount(txnContext.Context(), p.rpc, &from, inflight.privacyGroupID); err != nil { + if inflight.nonce, err = eth.GetOrionTXCount(txnContext.Context(), p.rpc, &from, inflight.privacyGroupID); err != nil { p.inflightTxnsLock.Unlock() return } @@ -304,7 +304,7 @@ func (p *txnProcessor) addInflightWrapper(txnContext TxnContext, msg *kldmessage // we need to accept the possibility of 'replacement transaction underpriced' // (or if gas price is being varied by the submitter the potential of // overwriting a transaction) - if inflight.nonce, err = kldeth.GetTransactionCount(txnContext.Context(), p.rpc, &from, "pending"); err != nil { + if inflight.nonce, err = eth.GetTransactionCount(txnContext.Context(), p.rpc, &from, "pending"); err != nil { p.inflightTxnsLock.Unlock() return } @@ -374,7 +374,7 @@ func (p *txnProcessor) cancelInFlight(inflight *inflightTxn, submitted bool) { // to complete. Only func (p *txnProcessor) submitGapFillTX(inflight *inflightTxn) { if p.conf.AttemptGapFill { - tx, err := kldeth.NewNilTX(inflight.from, inflight.nonce, inflight.signer) + tx, err := eth.NewNilTX(inflight.from, inflight.nonce, inflight.signer) if err == nil { inflight.gapFillTxHash = tx.EthTX.Hash().String() err = tx.Send(inflight.txnContext.Context(), inflight.rpc) @@ -429,9 +429,9 @@ func (p *txnProcessor) waitForCompletion(inflight *inflightTxn, initialWaitDelay if timedOut { if err != nil { - inflight.txnContext.SendErrorReplyWithTX(500, klderrors.Errorf(klderrors.TransactionSendReceiptCheckError, retries, err), inflight.tx.Hash) + inflight.txnContext.SendErrorReplyWithTX(500, errors.Errorf(errors.TransactionSendReceiptCheckError, retries, err), inflight.tx.Hash) } else { - inflight.txnContext.SendErrorReplyWithTX(408, klderrors.Errorf(klderrors.TransactionSendReceiptCheckTimeout), inflight.tx.Hash) + inflight.txnContext.SendErrorReplyWithTX(408, errors.Errorf(errors.TransactionSendReceiptCheckTimeout), inflight.tx.Hash) } } else { // Update the stats @@ -444,11 +444,11 @@ func (p *txnProcessor) waitForCompletion(inflight *inflightTxn, initialWaitDelay log.Infof("Receipt for %s obtained after %.2fs Success=%t", inflight.tx.Hash, elapsed.Seconds(), isSuccess) // Build our reply - var reply kldmessages.TransactionReceipt + var reply messages.TransactionReceipt if isSuccess { - reply.Headers.MsgType = kldmessages.MsgTypeTransactionSuccess + reply.Headers.MsgType = messages.MsgTypeTransactionSuccess } else { - reply.Headers.MsgType = kldmessages.MsgTypeTransactionFailure + reply.Headers.MsgType = messages.MsgTypeTransactionFailure } reply.BlockHash = receipt.BlockHash if p.conf.HexValuesInReceipt { @@ -502,7 +502,7 @@ func (p *txnProcessor) waitForCompletion(inflight *inflightTxn, initialWaitDelay // addInflight adds a transaction to the inflight list, and kick off // a goroutine to check for its completion and send the result -func (p *txnProcessor) trackMining(inflight *inflightTxn, tx *kldeth.Txn) { +func (p *txnProcessor) trackMining(inflight *inflightTxn, tx *eth.Txn) { // Kick off the goroutine to track it to completion inflight.tx = tx @@ -511,7 +511,7 @@ func (p *txnProcessor) trackMining(inflight *inflightTxn, tx *kldeth.Txn) { } -func (p *txnProcessor) OnDeployContractMessage(txnContext TxnContext, msg *kldmessages.DeployContract) { +func (p *txnProcessor) OnDeployContractMessage(txnContext TxnContext, msg *messages.DeployContract) { inflight, err := p.addInflightWrapper(txnContext, &msg.TransactionCommon) if err != nil { @@ -521,7 +521,7 @@ func (p *txnProcessor) OnDeployContractMessage(txnContext TxnContext, msg *kldme inflight.registerAs = msg.RegisterAs msg.Nonce = inflight.nonceNumber() - tx, err := kldeth.NewContractDeployTxn(msg, inflight.signer) + tx, err := eth.NewContractDeployTxn(msg, inflight.signer) if err != nil { p.cancelInFlight(inflight, false /* not yet submitted */) txnContext.SendErrorReply(400, err) @@ -531,7 +531,7 @@ func (p *txnProcessor) OnDeployContractMessage(txnContext TxnContext, msg *kldme p.sendTransactionCommon(txnContext, inflight, tx) } -func (p *txnProcessor) OnSendTransactionMessage(txnContext TxnContext, msg *kldmessages.SendTransaction) { +func (p *txnProcessor) OnSendTransactionMessage(txnContext TxnContext, msg *messages.SendTransaction) { inflight, err := p.addInflightWrapper(txnContext, &msg.TransactionCommon) if err != nil { @@ -540,7 +540,7 @@ func (p *txnProcessor) OnSendTransactionMessage(txnContext TxnContext, msg *kldm } msg.Nonce = inflight.nonceNumber() - tx, err := kldeth.NewSendTxn(msg, inflight.signer) + tx, err := eth.NewSendTxn(msg, inflight.signer) if err != nil { p.cancelInFlight(inflight, false /* not yet submitted */) txnContext.SendErrorReply(400, err) @@ -550,7 +550,7 @@ func (p *txnProcessor) OnSendTransactionMessage(txnContext TxnContext, msg *kldm p.sendTransactionCommon(txnContext, inflight, tx) } -func (p *txnProcessor) sendTransactionCommon(txnContext TxnContext, inflight *inflightTxn, tx *kldeth.Txn) { +func (p *txnProcessor) sendTransactionCommon(txnContext TxnContext, inflight *inflightTxn, tx *eth.Txn) { tx.OrionPrivateAPIS = p.conf.OrionPrivateAPIS tx.PrivacyGroupID = inflight.privacyGroupID tx.NodeAssignNonce = inflight.nodeAssignNonce @@ -566,7 +566,7 @@ func (p *txnProcessor) sendTransactionCommon(txnContext TxnContext, inflight *in } } -func (p *txnProcessor) sendAndTrackMining(txnContext TxnContext, inflight *inflightTxn, tx *kldeth.Txn) { +func (p *txnProcessor) sendAndTrackMining(txnContext TxnContext, inflight *inflightTxn, tx *eth.Txn) { err := tx.Send(txnContext.Context(), inflight.rpc) if p.conf.SendConcurrency > 1 { <-p.concurrencySlots // return our slot as soon as send is complete, to let an awaiting send go diff --git a/internal/kldtx/txnprocessor_test.go b/internal/tx/txnprocessor_test.go similarity index 93% rename from internal/kldtx/txnprocessor_test.go rename to internal/tx/txnprocessor_test.go index e87582c5..04c726c8 100644 --- a/internal/kldtx/txnprocessor_test.go +++ b/internal/tx/txnprocessor_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldtx +package tx import ( "context" @@ -33,8 +33,8 @@ import ( ethbinding "github.com/kaleido-io/ethbinding/pkg" "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/kldeth" - "github.com/kaleido-io/ethconnect/internal/kldmessages" + "github.com/kaleido-io/ethconnect/internal/ethbind" + "github.com/kaleido-io/ethconnect/internal/messages" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -50,7 +50,7 @@ type errorReply struct { type testTxnContext struct { jsonMsg string badMsgType string - replies []kldmessages.ReplyWithHeaders + replies []messages.ReplyWithHeaders errorReplies []*errorReply } @@ -64,9 +64,9 @@ type testRPC struct { ethSendTransactionFirstReady bool ethGetTransactionCountResult ethbinding.HexUint64 ethGetTransactionCountErr error - ethGetTransactionReceiptResult kldeth.TxnReceipt + ethGetTransactionReceiptResult eth.TxnReceipt ethGetTransactionReceiptErr error - privFindPrivacyGroupResult []kldeth.OrionPrivacyGroup + privFindPrivacyGroupResult []eth.OrionPrivacyGroup privFindPrivacyGroupErr error ethEstimateGasResult ethbinding.HexUint64 ethEstimateGasErr error @@ -121,7 +121,7 @@ func (r *testRPC) CallContext(ctx context.Context, result interface{}, method st r.params = append(r.params, args) if method == "eth_sendTransaction" || method == "eea_sendTransaction" { r.condLock.Lock() - sendTX := args[0].(*kldeth.SendTXArgs) + sendTX := args[0].(*eth.SendTXArgs) isFirst := (sendTX.Nonce != nil && uint64(*sendTX.Nonce) == 0 && len(*sendTX.Data) > 0) reflect.ValueOf(result).Elem().Set(reflect.ValueOf(r.ethSendTransactionResult)) if isFirst && r.ethSendTransactionFirstCond != nil { @@ -167,8 +167,8 @@ func (c *testTxnContext) String() string { return "" } -func (c *testTxnContext) Headers() *kldmessages.CommonHeaders { - commonMsg := kldmessages.RequestCommon{} +func (c *testTxnContext) Headers() *messages.CommonHeaders { + commonMsg := messages.RequestCommon{} if c.badMsgType != "" { commonMsg.Headers.MsgType = c.badMsgType } else if err := c.Unmarshal(&commonMsg); err != nil { @@ -206,7 +206,7 @@ func (c *testTxnContext) SendErrorReplyWithTX(status int, err error, txHash stri }) } -func (c *testTxnContext) Reply(replyMsg kldmessages.ReplyWithHeaders) { +func (c *testTxnContext) Reply(replyMsg messages.ReplyWithHeaders) { log.Infof("Sending success reply: %s", replyMsg.ReplyHeaders().MsgType) c.replies = append(c.replies, replyMsg) } @@ -214,7 +214,7 @@ func (c *testTxnContext) Reply(replyMsg kldmessages.ReplyWithHeaders) { func TestOnMessageBadMessage(t *testing.T) { assert := assert.New(t) - txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, &kldeth.RPCConf{}).(*txnProcessor) + txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + " \"headers\":{\"type\": \"badness\"}" + @@ -230,7 +230,7 @@ func TestOnMessageBadMessage(t *testing.T) { func TestOnDeployContractMessageBadMsg(t *testing.T) { assert := assert.New(t) - txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, &kldeth.RPCConf{}).(*txnProcessor) + txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + " \"headers\":{\"type\": \"DeployContract\"}," + @@ -247,10 +247,10 @@ func TestOnDeployContractMessageBadMsg(t *testing.T) { func TestOnDeployContractMessageBadJSON(t *testing.T) { assert := assert.New(t) - txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, &kldeth.RPCConf{}).(*txnProcessor) + txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "badness" - testTxnContext.badMsgType = kldmessages.MsgTypeDeployContract + testTxnContext.badMsgType = messages.MsgTypeDeployContract txnProcessor.OnMessage(testTxnContext) assert.NotEmpty(testTxnContext.errorReplies) @@ -263,7 +263,7 @@ func TestOnDeployContractMessageGoodTxnErrOnReceipt(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodDeployTxnJSON testRPC := &testRPC{ @@ -290,19 +290,19 @@ func TestOnDeployContractMessageGoodTxnErrOnReceipt(t *testing.T) { } func goodMessageRPC() *testRPC { - blockHash := eth.API.HexToHash("0x6e710868fd2d0ac1f141ba3f0cd569e38ce1999d8f39518ee7633d2b9a7122af") + blockHash := ethbind.API.HexToHash("0x6e710868fd2d0ac1f141ba3f0cd569e38ce1999d8f39518ee7633d2b9a7122af") blockNumber := ethbinding.HexBigInt(*big.NewInt(12345)) - contractAddr := eth.API.HexToAddress("0x28a62Cb478a3c3d4DAAD84F1148ea16cd1A66F37") + contractAddr := ethbind.API.HexToAddress("0x28a62Cb478a3c3d4DAAD84F1148ea16cd1A66F37") cumulativeGasUsed := ethbinding.HexBigInt(*big.NewInt(23456)) - fromAddr := eth.API.HexToAddress("0xBa25be62a5C55d4ad1d5520268806A8730A4DE5E") + fromAddr := ethbind.API.HexToAddress("0xBa25be62a5C55d4ad1d5520268806A8730A4DE5E") gasUsed := ethbinding.HexBigInt(*big.NewInt(345678)) status := ethbinding.HexBigInt(*big.NewInt(1)) - toAddr := eth.API.HexToAddress("0xD7FAC2bCe408Ed7C6ded07a32038b1F79C2b27d3") - transactionHash := eth.API.HexToHash("0xe2215336b09f9b5b82e36e1144ed64f40a42e61b68fdaca82549fd98b8531a89") + toAddr := ethbind.API.HexToAddress("0xD7FAC2bCe408Ed7C6ded07a32038b1F79C2b27d3") + transactionHash := ethbind.API.HexToHash("0xe2215336b09f9b5b82e36e1144ed64f40a42e61b68fdaca82549fd98b8531a89") transactionIndex := ethbinding.HexUint(456789) testRPC := &testRPC{ ethSendTransactionResult: transactionHash.String(), - ethGetTransactionReceiptResult: kldeth.TxnReceipt{ + ethGetTransactionReceiptResult: eth.TxnReceipt{ BlockHash: &blockHash, BlockNumber: &blockNumber, ContractAddress: &contractAddr, @@ -323,7 +323,7 @@ func TestOnDeployContractMessageGoodTxnMined(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodDeployTxnJSON @@ -369,14 +369,14 @@ func TestOnDeployContractMessageGoodTxnMined(t *testing.T) { func TestOnDeployContractMessageGoodTxnMinedHDWallet(t *testing.T) { assert := assert.New(t) - key, _ := eth.API.GenerateKey() - addr := eth.API.PubkeyToAddress(key.PublicKey) + key, _ := ethbind.API.GenerateKey() + addr := ethbind.API.PubkeyToAddress(key.PublicKey) svr := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(200) res.Write([]byte(` { "address": "` + addr.String() + `", - "privateKey": "` + hex.EncodeToString(eth.API.FromECDSA(key)) + `" + "privateKey": "` + hex.EncodeToString(ethbind.API.FromECDSA(key)) + `" }`)) })) defer svr.Close() @@ -386,7 +386,7 @@ func TestOnDeployContractMessageGoodTxnMinedHDWallet(t *testing.T) { HDWalletConf: HDWalletConf{ URLTemplate: svr.URL, }, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodHDWalletDeployTxnJSON @@ -430,7 +430,7 @@ func TestOnDeployContractPrivateMessageGoodTxnMined(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodDeployTxnPrivateJSON @@ -479,7 +479,7 @@ func TestOnDeployContractMessageGoodTxnMinedWithHex(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, HexValuesInReceipt: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodDeployTxnJSON @@ -528,7 +528,7 @@ func TestOnDeployContractMessageFailedTxnMined(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodDeployTxnJSON @@ -554,7 +554,7 @@ func TestOnDeployContractMessageFailedTxn(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 5000, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodDeployTxnJSON testRPC := &testRPC{ @@ -576,7 +576,7 @@ func TestOnDeployContractMessageFailedToGetNonce(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) txnProcessor.conf.AlwaysManageNonce = true testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + @@ -600,7 +600,7 @@ func TestOnDeployContractMessageFailedToGetNonce(t *testing.T) { func TestOnSendTransactionMessageMissingFrom(t *testing.T) { assert := assert.New(t) - txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, &kldeth.RPCConf{}).(*txnProcessor) + txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + " \"headers\":{\"type\": \"SendTransaction\"}," + @@ -620,7 +620,7 @@ func TestOnSendTransactionMessageMissingFrom(t *testing.T) { func TestOnSendTransactionMessageBadNonce(t *testing.T) { assert := assert.New(t) - txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, &kldeth.RPCConf{}).(*txnProcessor) + txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + " \"headers\":{\"type\": \"SendTransaction\"}," + @@ -641,7 +641,7 @@ func TestOnSendTransactionMessageBadNonce(t *testing.T) { func TestOnSendTransactionMessageBadMsg(t *testing.T) { assert := assert.New(t) - txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, &kldeth.RPCConf{}).(*txnProcessor) + txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + " \"headers\":{\"type\": \"SendTransaction\"}," + @@ -664,10 +664,10 @@ func TestOnSendTransactionMessageBadMsg(t *testing.T) { func TestOnSendTransactionMessageBadJSON(t *testing.T) { assert := assert.New(t) - txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, &kldeth.RPCConf{}).(*txnProcessor) + txnProcessor := NewTxnProcessor(&TxnProcessorConf{}, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "badness" - testTxnContext.badMsgType = kldmessages.MsgTypeSendTransaction + testTxnContext.badMsgType = messages.MsgTypeSendTransaction txnProcessor.OnMessage(testTxnContext) for len(testTxnContext.errorReplies) == 0 { time.Sleep(1 * time.Millisecond) @@ -685,7 +685,7 @@ func TestOnSendTransactionMessageTxnTimeout(t *testing.T) { txHash := "0xac18e98664e160305cdb77e75e5eae32e55447e94ad8ceb0123729589ed09f8b" txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodSendTxnJSON testRPC := &testRPC{ @@ -715,7 +715,7 @@ func TestOnSendTransactionMessageFailedTxn(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodSendTxnJSON testRPC := &testRPC{ @@ -740,7 +740,7 @@ func TestOnSendTransactionMessageFailedWithGapFillOK(t *testing.T) { SendConcurrency: 10, AlwaysManageNonce: true, AttemptGapFill: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testRPC := goodMessageRPC() testRPC.ethSendTransactionErr = fmt.Errorf("pop") testRPC.ethSendTransactionErrOnce = true @@ -800,7 +800,7 @@ func TestOnSendTransactionMessageFailedWithGapFillFail(t *testing.T) { SendConcurrency: 10, AlwaysManageNonce: true, AttemptGapFill: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testRPC := goodMessageRPC() testRPC.ethSendTransactionErr = fmt.Errorf("pop") testRPC.ethSendTransactionErrOnce = false @@ -857,7 +857,7 @@ func TestOnSendTransactionMessageFailedToGetNonce(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) txnProcessor.conf.AlwaysManageNonce = true testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + @@ -884,7 +884,7 @@ func TestOnSendTransactionMessageInflightNonce(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, AlwaysManageNonce: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"] = &inflightTxnState{} txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"].txnsInFlight = []*inflightTxn{{nonce: 100}, {nonce: 101}} txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"].highestNonce = 101 @@ -915,7 +915,7 @@ func TestOnSendTransactionMessageFailedToEstimateGas(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) txnProcessor.conf.AlwaysManageNonce = true testRPC := goodMessageRPC() testRPC.ethSendTransactionFirstCond = sync.NewCond(&testRPC.condLock) @@ -959,7 +959,7 @@ func TestOnSendTransactionMessageOrionNoPrivacyGroup(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ OrionPrivateAPIS: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + " \"headers\":{\"type\": \"SendTransaction\"}," + @@ -989,7 +989,7 @@ func TestOnSendTransactionMessageOrionCannotUsePrivacyGroupIdAndPrivateFor(t *te txnProcessor := NewTxnProcessor(&TxnProcessorConf{ OrionPrivateAPIS: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = "{" + " \"headers\":{\"type\": \"SendTransaction\"}," + @@ -1016,7 +1016,7 @@ func TestOnSendTransactionMessageOrionFailNonce(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, OrionPrivateAPIS: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"] = &inflightTxnState{} txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"].txnsInFlight = []*inflightTxn{{nonce: 100}, {nonce: 101}} testTxnContext := &testTxnContext{} @@ -1030,7 +1030,7 @@ func TestOnSendTransactionMessageOrionFailNonce(t *testing.T) { "}" testRPC := &testRPC{ ethGetTransactionCountErr: fmt.Errorf("pop"), - privFindPrivacyGroupResult: []kldeth.OrionPrivacyGroup{ + privFindPrivacyGroupResult: []eth.OrionPrivacyGroup{ { PrivacyGroupID: "P8SxRUussJKqZu4+nUkMJpscQeWOR3HqbAXLakatsk8=", }, @@ -1054,7 +1054,7 @@ func TestOnSendTransactionMessageOrion(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, OrionPrivateAPIS: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"] = &inflightTxnState{} txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"].txnsInFlight = []*inflightTxn{{nonce: 100}, {nonce: 101}} testTxnContext := &testTxnContext{} @@ -1068,7 +1068,7 @@ func TestOnSendTransactionMessageOrion(t *testing.T) { "}" testRPC := &testRPC{ ethSendTransactionResult: "0xac18e98664e160305cdb77e75e5eae32e55447e94ad8ceb0123729589ed09f8b", - privFindPrivacyGroupResult: []kldeth.OrionPrivacyGroup{ + privFindPrivacyGroupResult: []eth.OrionPrivacyGroup{ { PrivacyGroupID: "P8SxRUussJKqZu4+nUkMJpscQeWOR3HqbAXLakatsk8=", }, @@ -1091,7 +1091,7 @@ func TestOnSendTransactionMessageOrionPrivacyGroupId(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, OrionPrivateAPIS: true, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"] = &inflightTxnState{} txnProcessor.inflightTxns["0x83dbc8e329b38cba0fc4ed99b1ce9c2a390abdc1"].txnsInFlight = []*inflightTxn{{nonce: 100}, {nonce: 101}} testTxnContext := &testTxnContext{} @@ -1149,8 +1149,8 @@ func TestOnSendTransactionAddressBook(t *testing.T) { AddressBookConf: AddressBookConf{ AddressbookURLPrefix: server.URL, }, - }, &kldeth.RPCConf{ - RPC: kldeth.RPCConnOpts{ + }, ð.RPCConf{ + RPC: eth.RPCConnOpts{ URL: server.URL, }, }).(*txnProcessor) @@ -1185,7 +1185,7 @@ func TestOnDeployContractMessageFailAddressLookup(t *testing.T) { AddressBookConf: AddressBookConf{ AddressbookURLPrefix: " ", }, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodDeployTxnJSON @@ -1207,7 +1207,7 @@ func TestOnDeployContractMessageFailHDWalletMissing(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodHDWalletDeployTxnJSON @@ -1230,7 +1230,7 @@ func TestOnDeployContractMessageFailHDWalletFail(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, HDWalletConf: HDWalletConf{URLTemplate: " "}, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testTxnContext := &testTxnContext{} testTxnContext.jsonMsg = goodHDWalletDeployTxnJSON @@ -1252,7 +1252,7 @@ func TestResolveAddressNonHDWallet(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testRPC := goodMessageRPC() txnProcessor.Init(testRPC) @@ -1264,14 +1264,14 @@ func TestResolveAddressNonHDWallet(t *testing.T) { func TestResolveAddressHDWalletSuccess(t *testing.T) { assert := assert.New(t) - key, _ := eth.API.GenerateKey() - addr := eth.API.PubkeyToAddress(key.PublicKey) + key, _ := ethbind.API.GenerateKey() + addr := ethbind.API.PubkeyToAddress(key.PublicKey) svr := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(200) res.Write([]byte(` { "address": "` + addr.String() + `", - "privateKey": "` + hex.EncodeToString(eth.API.FromECDSA(key)) + `" + "privateKey": "` + hex.EncodeToString(ethbind.API.FromECDSA(key)) + `" }`)) })) defer svr.Close() @@ -1281,7 +1281,7 @@ func TestResolveAddressHDWalletSuccess(t *testing.T) { HDWalletConf: HDWalletConf{ URLTemplate: svr.URL, }, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) testRPC := goodMessageRPC() txnProcessor.Init(testRPC) @@ -1295,7 +1295,7 @@ func TestResolveAddressHDWalletFail(t *testing.T) { txnProcessor := NewTxnProcessor(&TxnProcessorConf{ MaxTXWaitTime: 1, - }, &kldeth.RPCConf{}).(*txnProcessor) + }, ð.RPCConf{}).(*txnProcessor) _, err := txnProcessor.ResolveAddress("hd-testinst-testwallet-1234") assert.EqualError(err, "No HD Wallet Configuration") diff --git a/internal/kldutils/cmdutils.go b/internal/utils/cmdutils.go similarity index 99% rename from internal/kldutils/cmdutils.go rename to internal/utils/cmdutils.go index 1f07c9d2..f2f0c5e6 100644 --- a/internal/kldutils/cmdutils.go +++ b/internal/utils/cmdutils.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "encoding/json" diff --git a/internal/kldutils/cmdutils_test.go b/internal/utils/cmdutils_test.go similarity index 99% rename from internal/kldutils/cmdutils_test.go rename to internal/utils/cmdutils_test.go index cc91dfaf..695af7aa 100644 --- a/internal/kldutils/cmdutils_test.go +++ b/internal/utils/cmdutils_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "os" diff --git a/internal/kldutils/ethutils.go b/internal/utils/ethutils.go similarity index 73% rename from internal/kldutils/ethutils.go rename to internal/utils/ethutils.go index d40d8777..a4152d5a 100644 --- a/internal/kldutils/ethutils.go +++ b/internal/utils/ethutils.go @@ -12,29 +12,29 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "strings" ethbinding "github.com/kaleido-io/ethbinding/pkg" - "github.com/kaleido-io/ethconnect/internal/eth" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/ethbind" ) // StrToAddress is a helper to parse eth addresses with useful errors func StrToAddress(desc string, strAddr string) (addr ethbinding.Address, err error) { if strAddr == "" { - err = klderrors.Errorf(klderrors.HelperStrToAddressRequiredField, desc) + err = errors.Errorf(errors.HelperStrToAddressRequiredField, desc) return } if !strings.HasPrefix(strAddr, "0x") { strAddr = "0x" + strAddr } - if !eth.API.IsHexAddress(strAddr) { - err = klderrors.Errorf(klderrors.HelperStrToAddressBadAddress, desc) + if !ethbind.API.IsHexAddress(strAddr) { + err = errors.Errorf(errors.HelperStrToAddressBadAddress, desc) return } - addr = eth.API.HexToAddress(strAddr) + addr = ethbind.API.HexToAddress(strAddr) return } diff --git a/internal/kldutils/ethutils_test.go b/internal/utils/ethutils_test.go similarity index 98% rename from internal/kldutils/ethutils_test.go rename to internal/utils/ethutils_test.go index 8ebf120f..59d9cdb4 100644 --- a/internal/kldutils/ethutils_test.go +++ b/internal/utils/ethutils_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "testing" diff --git a/internal/kldutils/hostsfile.go b/internal/utils/hostsfile.go similarity index 98% rename from internal/kldutils/hostsfile.go rename to internal/utils/hostsfile.go index c97156b6..696706ae 100644 --- a/internal/kldutils/hostsfile.go +++ b/internal/utils/hostsfile.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "io/ioutil" diff --git a/internal/kldutils/hostsfile_test.go b/internal/utils/hostsfile_test.go similarity index 98% rename from internal/kldutils/hostsfile_test.go rename to internal/utils/hostsfile_test.go index ed239c91..0b5024aa 100644 --- a/internal/kldutils/hostsfile_test.go +++ b/internal/utils/hostsfile_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "path" diff --git a/internal/kldutils/httprequester.go b/internal/utils/httprequester.go similarity index 79% rename from internal/kldutils/httprequester.go rename to internal/utils/httprequester.go index cf8132af..2487f793 100644 --- a/internal/kldutils/httprequester.go +++ b/internal/utils/httprequester.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "bytes" @@ -21,7 +21,7 @@ import ( "io/ioutil" "net/http" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" log "github.com/sirupsen/logrus" ) @@ -57,7 +57,7 @@ func (hr *HTTPRequester) DoRequest(method, url string, bodyMap map[string]interf if bodyMap != nil { bodyBytes, ehr := json.Marshal(bodyMap) if ehr != nil { - return nil, klderrors.Errorf(klderrors.HTTPRequesterSerializeFailed, ehr) + return nil, errors.Errorf(errors.HTTPRequesterSerializeFailed, ehr) } body = bytes.NewReader(bodyBytes) } @@ -70,7 +70,7 @@ func (hr *HTTPRequester) DoRequest(method, url string, bodyMap map[string]interf res, ehr := hr.client.Do(req) if ehr != nil { log.Errorf("%s %s <-- !Failed: %s", method, url, ehr) - return nil, klderrors.Errorf(klderrors.HTTPRequesterNonStatusError, hr.name) + return nil, errors.Errorf(errors.HTTPRequesterNonStatusError, hr.name) } log.Infof("%s %s <-- [%d]", method, url, res.StatusCode) if res.StatusCode == 404 { @@ -83,14 +83,14 @@ func (hr *HTTPRequester) DoRequest(method, url string, bodyMap map[string]interf resBody, _ := ioutil.ReadAll(res.Body) if err := json.Unmarshal(resBody, &jsonBody); err != nil { log.Errorf("%s %s <-- [%d] !Failed to read body: %s", method, url, res.StatusCode, ehr) - return nil, klderrors.Errorf(klderrors.HTTPRequesterStatusErrorNoData, hr.name, res.StatusCode) + return nil, errors.Errorf(errors.HTTPRequesterStatusErrorNoData, hr.name, res.StatusCode) } if res.StatusCode < 200 || res.StatusCode >= 300 { log.Errorf("%s %s <-- [%d]: %+v", method, url, res.StatusCode, jsonBody) if ehrMsg, ok := jsonBody["errorMessage"]; ok { - return nil, klderrors.Errorf(klderrors.HTTPRequesterStatusErrorWithData, hr.name, res.StatusCode, ehrMsg) + return nil, errors.Errorf(errors.HTTPRequesterStatusErrorWithData, hr.name, res.StatusCode, ehrMsg) } - return nil, klderrors.Errorf(klderrors.HTTPRequesterStatusError, hr.name) + return nil, errors.Errorf(errors.HTTPRequesterStatusError, hr.name) } } return jsonBody, nil @@ -100,7 +100,7 @@ func (hr *HTTPRequester) DoRequest(method, url string, bodyMap map[string]interf func (hr *HTTPRequester) GetResponseString(m map[string]interface{}, p string, emptyOK bool) (string, error) { genericVal, exists := m[p] if !exists { - return "", klderrors.Errorf(klderrors.HTTPRequesterResponseMissingField, p, hr.name) + return "", errors.Errorf(errors.HTTPRequesterResponseMissingField, p, hr.name) } var stringVal string switch genericVal.(type) { @@ -109,10 +109,10 @@ func (hr *HTTPRequester) GetResponseString(m map[string]interface{}, p string, e case nil: stringVal = "" default: - return "", klderrors.Errorf(klderrors.HTTPRequesterResponseNonStringField, p, hr.name) + return "", errors.Errorf(errors.HTTPRequesterResponseNonStringField, p, hr.name) } if !emptyOK && stringVal == "" { - return "", klderrors.Errorf(klderrors.HTTPRequesterResponseNullField, p, hr.name) + return "", errors.Errorf(errors.HTTPRequesterResponseNullField, p, hr.name) } return stringVal, nil } diff --git a/internal/kldutils/httprequester_test.go b/internal/utils/httprequester_test.go similarity index 99% rename from internal/kldutils/httprequester_test.go rename to internal/utils/httprequester_test.go index 4ff16431..20d1a1c7 100644 --- a/internal/kldutils/httprequester_test.go +++ b/internal/utils/httprequester_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "encoding/json" diff --git a/internal/kldutils/maputils.go b/internal/utils/maputils.go similarity index 98% rename from internal/kldutils/maputils.go rename to internal/utils/maputils.go index 4719033c..d4afb400 100644 --- a/internal/kldutils/maputils.go +++ b/internal/utils/maputils.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import "reflect" diff --git a/internal/kldutils/maputils_test.go b/internal/utils/maputils_test.go similarity index 98% rename from internal/kldutils/maputils_test.go rename to internal/utils/maputils_test.go index c491ac88..07c1ccd4 100644 --- a/internal/kldutils/maputils_test.go +++ b/internal/utils/maputils_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "testing" diff --git a/internal/kldutils/payloadutils.go b/internal/utils/payloadutils.go similarity index 87% rename from internal/kldutils/payloadutils.go rename to internal/utils/payloadutils.go index eecb8d9b..20fa6bb2 100644 --- a/internal/kldutils/payloadutils.go +++ b/internal/utils/payloadutils.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "encoding/json" @@ -21,7 +21,7 @@ import ( "strings" "github.com/icza/dyno" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" log "github.com/sirupsen/logrus" yaml "gopkg.in/yaml.v2" ) @@ -35,11 +35,11 @@ const ( func YAMLorJSONPayload(req *http.Request) (map[string]interface{}, error) { if req.ContentLength > MaxPayloadSize { - return nil, klderrors.Errorf(klderrors.HelperYAMLorJSONPayloadTooLarge) + return nil, errors.Errorf(errors.HelperYAMLorJSONPayloadTooLarge) } originalPayload, err := ioutil.ReadAll(req.Body) if err != nil { - return nil, klderrors.Errorf(klderrors.HelperYAMLorJSONPayloadReadFailed, err) + return nil, errors.Errorf(errors.HelperYAMLorJSONPayloadReadFailed, err) } // We support both YAML and JSON input. @@ -68,7 +68,7 @@ func YAMLorJSONPayload(req *http.Request) (map[string]interface{}, error) { yamlGenericPayload := make(map[interface{}]interface{}) err := yaml.Unmarshal(originalPayload, &yamlGenericPayload) if err != nil { - return nil, klderrors.Errorf(klderrors.HelperYAMLorJSONPayloadParseFailed, err) + return nil, errors.Errorf(errors.HelperYAMLorJSONPayloadParseFailed, err) } msg = dyno.ConvertMapI2MapS(yamlGenericPayload).(map[string]interface{}) } diff --git a/internal/kldutils/payloadutils_test.go b/internal/utils/payloadutils_test.go similarity index 99% rename from internal/kldutils/payloadutils_test.go rename to internal/utils/payloadutils_test.go index 36299453..c08e4e6b 100644 --- a/internal/kldutils/payloadutils_test.go +++ b/internal/utils/payloadutils_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "bytes" diff --git a/internal/kldutils/tlsutils.go b/internal/utils/tlsutils.go similarity index 95% rename from internal/kldutils/tlsutils.go rename to internal/utils/tlsutils.go index 09997ebc..c5bfa06a 100644 --- a/internal/kldutils/tlsutils.go +++ b/internal/utils/tlsutils.go @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "crypto/tls" "crypto/x509" "io/ioutil" - "github.com/kaleido-io/ethconnect/internal/klderrors" + "github.com/kaleido-io/ethconnect/internal/errors" log "github.com/sirupsen/logrus" ) @@ -36,7 +36,7 @@ type TLSConfig struct { func CreateTLSConfiguration(tlsConfig *TLSConfig) (t *tls.Config, err error) { if !AllOrNoneReqd(tlsConfig.ClientCertsFile, tlsConfig.ClientKeyFile) { - err = klderrors.Errorf(klderrors.ConfigTLSCertOrKey) + err = errors.Errorf(errors.ConfigTLSCertOrKey) return } diff --git a/internal/kldutils/tlsutils_test.go b/internal/utils/tlsutils_test.go similarity index 99% rename from internal/kldutils/tlsutils_test.go rename to internal/utils/tlsutils_test.go index 0cf502ac..778b7339 100644 --- a/internal/kldutils/tlsutils_test.go +++ b/internal/utils/tlsutils_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "io/ioutil" diff --git a/internal/kldutils/uuidutils.go b/internal/utils/uuidutils.go similarity index 97% rename from internal/kldutils/uuidutils.go rename to internal/utils/uuidutils.go index 4ecefb59..ee446229 100644 --- a/internal/kldutils/uuidutils.go +++ b/internal/utils/uuidutils.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( uuid "github.com/nu7hatch/gouuid" diff --git a/internal/kldutils/uuidutils_test.go b/internal/utils/uuidutils_test.go similarity index 97% rename from internal/kldutils/uuidutils_test.go rename to internal/utils/uuidutils_test.go index c1b0033a..fedf339e 100644 --- a/internal/kldutils/uuidutils_test.go +++ b/internal/utils/uuidutils_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldutils +package utils import ( "testing" diff --git a/internal/kldws/wsconn.go b/internal/ws/wsconn.go similarity index 94% rename from internal/kldws/wsconn.go rename to internal/ws/wsconn.go index 20633b24..27d630a7 100644 --- a/internal/kldws/wsconn.go +++ b/internal/ws/wsconn.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldws +package ws import ( "reflect" @@ -23,8 +23,8 @@ import ( ws "github.com/gorilla/websocket" log "github.com/sirupsen/logrus" - "github.com/kaleido-io/ethconnect/internal/klderrors" - "github.com/kaleido-io/ethconnect/internal/kldutils" + "github.com/kaleido-io/ethconnect/internal/errors" + "github.com/kaleido-io/ethconnect/internal/utils" ) type webSocketConnection struct { @@ -48,7 +48,7 @@ type webSocketCommandMessage struct { func newConnection(server *webSocketServer, conn *ws.Conn) *webSocketConnection { wsc := &webSocketConnection{ - id: kldutils.UUIDv4(), + id: utils.UUIDv4(), server: server, conn: conn, newTopic: make(chan bool), @@ -150,7 +150,7 @@ func (c *webSocketConnection) listen() { case "ack": c.handleAckOrError(t, nil) case "error": - c.handleAckOrError(t, klderrors.Errorf(klderrors.EventStreamsWebSocketErrorFromClient, msg.Message)) + c.handleAckOrError(t, errors.Errorf(errors.EventStreamsWebSocketErrorFromClient, msg.Message)) default: log.Errorf("WS/%s: Unexpected message type: %+v", c.id, msg) } diff --git a/internal/kldws/wsserver.go b/internal/ws/wsserver.go similarity index 99% rename from internal/kldws/wsserver.go rename to internal/ws/wsserver.go index a1a48d40..0f22c317 100644 --- a/internal/kldws/wsserver.go +++ b/internal/ws/wsserver.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldws +package ws import ( "net/http" diff --git a/internal/kldws/wsserver_test.go b/internal/ws/wsserver_test.go similarity index 99% rename from internal/kldws/wsserver_test.go rename to internal/ws/wsserver_test.go index 6ca1895d..512bf7d2 100644 --- a/internal/kldws/wsserver_test.go +++ b/internal/ws/wsserver_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldws +package ws import ( "net/http" diff --git a/pkg/kldplugins/securitymodule.go b/pkg/plugins/securitymodule.go similarity index 99% rename from pkg/kldplugins/securitymodule.go rename to pkg/plugins/securitymodule.go index ab51b504..82ac3aa1 100644 --- a/pkg/kldplugins/securitymodule.go +++ b/pkg/plugins/securitymodule.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package kldplugins +package plugins // EventOperation enumerates operation types on events type EventOperation int diff --git a/test/abicoderv2_example.swagger.json b/test/abicoderv2_example.swagger.json index 7b3296e9..5fa8969b 100644 --- a/test/abicoderv2_example.swagger.json +++ b/test/abicoderv2_example.swagger.json @@ -150,73 +150,73 @@ "parameters": { "blocknumberParam": { "type": "string", - "description": "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-kaleido-blocknumber)", - "name": "kld-blocknumber", + "description": "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-firefly-blocknumber)", + "name": "fly-blocknumber", "in": "query" }, "callParam": { "type": "boolean", - "description": "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-kaleido-call)", - "name": "kld-call", + "description": "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-firefly-call)", + "name": "fly-call", "in": "query", "allowEmptyValue": true }, "fromParam": { "type": "string", - "description": "The 'from' address (header: x-kaleido-from)", - "name": "kld-from", + "description": "The 'from' address (header: x-firefly-from)", + "name": "fly-from", "in": "query" }, "gasParam": { "type": "integer", - "description": "Gas to send with the transaction (auto-calculated if not set) (header: x-kaleido-gas)", - "name": "kld-gas", + "description": "Gas to send with the transaction (auto-calculated if not set) (header: x-firefly-gas)", + "name": "fly-gas", "in": "query", "allowEmptyValue": true }, "gaspriceParam": { "type": "integer", - "description": "Gas Price offered (header: x-kaleido-gasprice)", - "name": "kld-gasprice", + "description": "Gas Price offered (header: x-firefly-gasprice)", + "name": "fly-gasprice", "in": "query", "allowEmptyValue": true }, "privacyGroupIdParam": { "type": "string", - "description": "Private transaction group ID (header: x-kaleido-privacyGroupId)", - "name": "kld-privacygroupid", + "description": "Private transaction group ID (header: x-firefly-privacyGroupId)", + "name": "fly-privacygroupid", "in": "query" }, "privateForParam": { "type": "string", - "description": "Private transaction recipients (comma separated or multiple params) (header: x-kaleido-privatefor)", - "name": "kld-privatefor", + "description": "Private transaction recipients (comma separated or multiple params) (header: x-firefly-privatefor)", + "name": "fly-privatefor", "in": "query" }, "privateFromParam": { "type": "string", - "description": "Private transaction sender (header: x-kaleido-privatefrom)", - "name": "kld-privatefrom", + "description": "Private transaction sender (header: x-firefly-privatefrom)", + "name": "fly-privatefrom", "in": "query" }, "registerParam": { "type": "string", - "description": "Register the installed contract on a friendly path (overwrites existing) (header: x-kaleido-register)", - "name": "kld-register", + "description": "Register the installed contract on a friendly path (overwrites existing) (header: x-firefly-register)", + "name": "fly-register", "in": "query" }, "syncParam": { "type": "boolean", "default": true, - "description": "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-kaleido-sync)", - "name": "kld-sync", + "description": "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-firefly-sync)", + "name": "fly-sync", "in": "query", "allowEmptyValue": true }, "valueParam": { "type": "integer", - "description": "Ether value to send with the transaction (header: x-kaleido-ethvalue)", - "name": "kld-ethvalue", + "description": "Ether value to send with the transaction (header: x-firefly-ethvalue)", + "name": "fly-ethvalue", "in": "query", "allowEmptyValue": true } diff --git a/test/erc20.swagger.json b/test/erc20.swagger.json index 3e40fffe..766412a8 100644 --- a/test/erc20.swagger.json +++ b/test/erc20.swagger.json @@ -15,7 +15,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "consumes": [ @@ -336,7 +336,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Function to check the amount of tokens that an owner allowed to a spender.", @@ -398,7 +398,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Function to check the amount of tokens that an owner allowed to a spender.", @@ -478,7 +478,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729", @@ -540,7 +540,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729", @@ -620,7 +620,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Gets the balance of the specified address.", @@ -675,7 +675,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Gets the balance of the specified address.", @@ -755,7 +755,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Decrease the amount of tokens that an owner allowed to a spender. approve should be called when _allowed[msg.sender][spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol Emits an Approval event.", @@ -817,7 +817,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Decrease the amount of tokens that an owner allowed to a spender. approve should be called when _allowed[msg.sender][spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol Emits an Approval event.", @@ -897,7 +897,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Increase the amount of tokens that an owner allowed to a spender. approve should be called when _allowed[msg.sender][spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol Emits an Approval event.", @@ -959,7 +959,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Increase the amount of tokens that an owner allowed to a spender. approve should be called when _allowed[msg.sender][spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol Emits an Approval event.", @@ -1039,7 +1039,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Total number of tokens in existence.", @@ -1087,7 +1087,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Total number of tokens in existence.", @@ -1167,7 +1167,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Transfer token to a specified address.", @@ -1229,7 +1229,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Transfer token to a specified address.", @@ -1309,7 +1309,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Transfer tokens from one address to another. Note that while this function emits an Approval event, this is not required as per the specification, and other compliant implementations may not emit the event.", @@ -1378,7 +1378,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Transfer tokens from one address to another. Note that while this function emits an Approval event, this is not required as per the specification, and other compliant implementations may not emit the event.", @@ -1697,79 +1697,79 @@ "parameters": { "blocknumberParam": { "type": "string", - "description": "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-kaleido-blocknumber)", - "name": "kld-blocknumber", + "description": "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-firefly-blocknumber)", + "name": "fly-blocknumber", "in": "query" }, "callParam": { "type": "boolean", - "description": "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-kaleido-call)", - "name": "kld-call", + "description": "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-firefly-call)", + "name": "fly-call", "in": "query", "allowEmptyValue": true }, "fromParam": { "type": "string", - "description": "The 'from' address (header: x-kaleido-from)", - "name": "kld-from", + "description": "The 'from' address (header: x-firefly-from)", + "name": "fly-from", "in": "query" }, "gasParam": { "type": "integer", - "description": "Gas to send with the transaction (auto-calculated if not set) (header: x-kaleido-gas)", - "name": "kld-gas", + "description": "Gas to send with the transaction (auto-calculated if not set) (header: x-firefly-gas)", + "name": "fly-gas", "in": "query", "allowEmptyValue": true }, "gaspriceParam": { "type": "integer", - "description": "Gas Price offered (header: x-kaleido-gasprice)", - "name": "kld-gasprice", + "description": "Gas Price offered (header: x-firefly-gasprice)", + "name": "fly-gasprice", "in": "query", "allowEmptyValue": true }, "privacyGroupIdParam": { "type": "string", - "description": "Private transaction group ID (header: x-kaleido-privacyGroupId)", - "name": "kld-privacygroupid", + "description": "Private transaction group ID (header: x-firefly-privacyGroupId)", + "name": "fly-privacygroupid", "in": "query" }, "privateForParam": { "type": "string", - "description": "Private transaction recipients (comma separated or multiple params) (header: x-kaleido-privatefor)", - "name": "kld-privatefor", + "description": "Private transaction recipients (comma separated or multiple params) (header: x-firefly-privatefor)", + "name": "fly-privatefor", "in": "query" }, "privateFromParam": { "type": "string", - "description": "Private transaction sender (header: x-kaleido-privatefrom)", - "name": "kld-privatefrom", + "description": "Private transaction sender (header: x-firefly-privatefrom)", + "name": "fly-privatefrom", "in": "query" }, "registerParam": { "type": "string", - "description": "Register the installed contract on a friendly path (overwrites existing) (header: x-kaleido-register)", - "name": "kld-register", + "description": "Register the installed contract on a friendly path (overwrites existing) (header: x-firefly-register)", + "name": "fly-register", "in": "query" }, "syncParam": { "type": "boolean", "default": true, - "description": "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-kaleido-sync)", - "name": "kld-sync", + "description": "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-firefly-sync)", + "name": "fly-sync", "in": "query", "allowEmptyValue": true }, "valueParam": { "type": "integer", - "description": "Ether value to send with the transaction (header: x-kaleido-ethvalue)", - "name": "kld-ethvalue", + "description": "Ether value to send with the transaction (header: x-firefly-ethvalue)", + "name": "fly-ethvalue", "in": "query", "allowEmptyValue": true } }, "securityDefinitions": { - "KaleidoAppCredential": { + "FireflyAppCredential": { "type": "basic" } } diff --git a/test/lotsoftypes.swagger.json b/test/lotsoftypes.swagger.json index fe0378a0..547d153b 100644 --- a/test/lotsoftypes.swagger.json +++ b/test/lotsoftypes.swagger.json @@ -16,7 +16,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Echo back some types", @@ -106,7 +106,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Echo back some types", @@ -179,7 +179,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Echo back some more types", @@ -269,7 +269,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "description": "Echo back some more types", @@ -342,7 +342,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "produces": [ @@ -424,7 +424,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "consumes": [ @@ -758,79 +758,79 @@ "parameters": { "blocknumberParam": { "type": "string", - "description": "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-kaleido-blocknumber)", - "name": "kld-blocknumber", + "description": "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-firefly-blocknumber)", + "name": "fly-blocknumber", "in": "query" }, "callParam": { "type": "boolean", - "description": "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-kaleido-call)", - "name": "kld-call", + "description": "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-firefly-call)", + "name": "fly-call", "in": "query", "allowEmptyValue": true }, "fromParam": { "type": "string", - "description": "The 'from' address (header: x-kaleido-from)", - "name": "kld-from", + "description": "The 'from' address (header: x-firefly-from)", + "name": "fly-from", "in": "query" }, "gasParam": { "type": "integer", - "description": "Gas to send with the transaction (auto-calculated if not set) (header: x-kaleido-gas)", - "name": "kld-gas", + "description": "Gas to send with the transaction (auto-calculated if not set) (header: x-firefly-gas)", + "name": "fly-gas", "in": "query", "allowEmptyValue": true }, "gaspriceParam": { "type": "integer", - "description": "Gas Price offered (header: x-kaleido-gasprice)", - "name": "kld-gasprice", + "description": "Gas Price offered (header: x-firefly-gasprice)", + "name": "fly-gasprice", "in": "query", "allowEmptyValue": true }, "privacyGroupIdParam": { "type": "string", - "description": "Private transaction group ID (header: x-kaleido-privacyGroupId)", - "name": "kld-privacygroupid", + "description": "Private transaction group ID (header: x-firefly-privacyGroupId)", + "name": "fly-privacygroupid", "in": "query" }, "privateForParam": { "type": "string", - "description": "Private transaction recipients (comma separated or multiple params) (header: x-kaleido-privatefor)", - "name": "kld-privatefor", + "description": "Private transaction recipients (comma separated or multiple params) (header: x-firefly-privatefor)", + "name": "fly-privatefor", "in": "query" }, "privateFromParam": { "type": "string", - "description": "Private transaction sender (header: x-kaleido-privatefrom)", - "name": "kld-privatefrom", + "description": "Private transaction sender (header: x-firefly-privatefrom)", + "name": "fly-privatefrom", "in": "query" }, "registerParam": { "type": "string", - "description": "Register the installed contract on a friendly path (overwrites existing) (header: x-kaleido-register)", - "name": "kld-register", + "description": "Register the installed contract on a friendly path (overwrites existing) (header: x-firefly-register)", + "name": "fly-register", "in": "query" }, "syncParam": { "type": "boolean", "default": true, - "description": "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-kaleido-sync)", - "name": "kld-sync", + "description": "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-firefly-sync)", + "name": "fly-sync", "in": "query", "allowEmptyValue": true }, "valueParam": { "type": "integer", - "description": "Ether value to send with the transaction (header: x-kaleido-ethvalue)", - "name": "kld-ethvalue", + "description": "Ether value to send with the transaction (header: x-firefly-ethvalue)", + "name": "fly-ethvalue", "in": "query", "allowEmptyValue": true } }, "securityDefinitions": { - "KaleidoAppCredential": { + "FireflyAppCredential": { "type": "basic" } } diff --git a/test/unnamedinput.swagger.json b/test/unnamedinput.swagger.json index 304ecf67..71264382 100644 --- a/test/unnamedinput.swagger.json +++ b/test/unnamedinput.swagger.json @@ -14,7 +14,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "consumes": [ @@ -129,7 +129,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "produces": [ @@ -190,7 +190,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "consumes": [ @@ -269,7 +269,7 @@ "get": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "produces": [ @@ -323,7 +323,7 @@ "post": { "security": [ { - "KaleidoAppCredential": [] + "FireflyAppCredential": [] } ], "consumes": [ @@ -456,79 +456,79 @@ "parameters": { "blocknumberParam": { "type": "string", - "description": "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-kaleido-blocknumber)", - "name": "kld-blocknumber", + "description": "The target block number for eth_call requests. One of 'earliest/latest/pending', a number or a hex string (header: x-firefly-blocknumber)", + "name": "fly-blocknumber", "in": "query" }, "callParam": { "type": "boolean", - "description": "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-kaleido-call)", - "name": "kld-call", + "description": "Perform a read-only call with the same parameters that would be used to invoke, and return result (header: x-firefly-call)", + "name": "fly-call", "in": "query", "allowEmptyValue": true }, "fromParam": { "type": "string", - "description": "The 'from' address (header: x-kaleido-from)", - "name": "kld-from", + "description": "The 'from' address (header: x-firefly-from)", + "name": "fly-from", "in": "query" }, "gasParam": { "type": "integer", - "description": "Gas to send with the transaction (auto-calculated if not set) (header: x-kaleido-gas)", - "name": "kld-gas", + "description": "Gas to send with the transaction (auto-calculated if not set) (header: x-firefly-gas)", + "name": "fly-gas", "in": "query", "allowEmptyValue": true }, "gaspriceParam": { "type": "integer", - "description": "Gas Price offered (header: x-kaleido-gasprice)", - "name": "kld-gasprice", + "description": "Gas Price offered (header: x-firefly-gasprice)", + "name": "fly-gasprice", "in": "query", "allowEmptyValue": true }, "privacyGroupIdParam": { "type": "string", - "description": "Private transaction group ID (header: x-kaleido-privacyGroupId)", - "name": "kld-privacygroupid", + "description": "Private transaction group ID (header: x-firefly-privacyGroupId)", + "name": "fly-privacygroupid", "in": "query" }, "privateForParam": { "type": "string", - "description": "Private transaction recipients (comma separated or multiple params) (header: x-kaleido-privatefor)", - "name": "kld-privatefor", + "description": "Private transaction recipients (comma separated or multiple params) (header: x-firefly-privatefor)", + "name": "fly-privatefor", "in": "query" }, "privateFromParam": { "type": "string", - "description": "Private transaction sender (header: x-kaleido-privatefrom)", - "name": "kld-privatefrom", + "description": "Private transaction sender (header: x-firefly-privatefrom)", + "name": "fly-privatefrom", "in": "query" }, "registerParam": { "type": "string", - "description": "Register the installed contract on a friendly path (overwrites existing) (header: x-kaleido-register)", - "name": "kld-register", + "description": "Register the installed contract on a friendly path (overwrites existing) (header: x-firefly-register)", + "name": "fly-register", "in": "query" }, "syncParam": { "type": "boolean", "default": true, - "description": "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-kaleido-sync)", - "name": "kld-sync", + "description": "Block the HTTP request until the tx is mined (does not store the receipt) (header: x-firefly-sync)", + "name": "fly-sync", "in": "query", "allowEmptyValue": true }, "valueParam": { "type": "integer", - "description": "Ether value to send with the transaction (header: x-kaleido-ethvalue)", - "name": "kld-ethvalue", + "description": "Ether value to send with the transaction (header: x-firefly-ethvalue)", + "name": "fly-ethvalue", "in": "query", "allowEmptyValue": true } }, "securityDefinitions": { - "KaleidoAppCredential": { + "FireflyAppCredential": { "type": "basic" } }