diff --git a/Makefile b/Makefile index 07211762b..d45a0fde6 100644 --- a/Makefile +++ b/Makefile @@ -218,22 +218,24 @@ protogen_clean: .PHONY: protogen_local ## Generate go structures for all of the protobufs protogen_local: go_protoc-go-inject-tag - $(eval proto_dir = "./shared/types/proto/") - protoc --go_opt=paths=source_relative -I=${proto_dir} -I=./shared/types/proto --go_out=./shared/types ./shared/types/proto/*.proto --experimental_allow_proto3_optional - protoc --go_opt=paths=source_relative -I=${proto_dir} -I=./utility/proto --go_out=./utility/types ./utility/proto/*.proto --experimental_allow_proto3_optional - protoc --go_opt=paths=source_relative -I=${proto_dir} -I=./shared/types/genesis/proto --go_out=./shared/types/genesis ./shared/types/genesis/proto/*.proto --experimental_allow_proto3_optional - protoc-go-inject-tag -input="./shared/types/genesis/*.pb.go" - protoc --go_opt=paths=source_relative -I=${proto_dir} -I=./consensus/types/proto --go_out=./consensus/types ./consensus/types/proto/*.proto --experimental_allow_proto3_optional - protoc --go_opt=paths=source_relative -I=${proto_dir} -I=./p2p/raintree/types/proto --go_out=./p2p/types ./p2p/raintree/types/proto/*.proto --experimental_allow_proto3_optional + $(eval proto_dir = ".") + protoc --go_opt=paths=source_relative -I=./shared/debug/proto --go_out=./shared/debug ./shared/debug/proto/*.proto --experimental_allow_proto3_optional + protoc --go_opt=paths=source_relative -I=./persistence/proto --go_out=./persistence/types ./persistence/proto/*.proto --experimental_allow_proto3_optional + protoc-go-inject-tag -input="./persistence/types/*.pb.go" + protoc --go_opt=paths=source_relative -I=./utility/types/proto --go_out=./utility/types ./utility/types/proto/*.proto --experimental_allow_proto3_optional + protoc --go_opt=paths=source_relative -I=./consensus/types/proto --go_out=./consensus/types ./consensus/types/proto/*.proto --experimental_allow_proto3_optional + protoc --go_opt=paths=source_relative -I=./p2p/raintree/types/proto --go_out=./p2p/types ./p2p/raintree/types/proto/*.proto --experimental_allow_proto3_optional + protoc --go_opt=paths=source_relative -I=./p2p/types/proto --go_out=./p2p/types ./p2p/types/proto/*.proto --experimental_allow_proto3_optional + protoc --go_opt=paths=source_relative -I=./telemetry/proto --go_out=./telemetry ./telemetry/proto/*.proto --experimental_allow_proto3_optional echo "View generated proto files by running: make protogen_show" .PHONY: protogen_docker_m1 -## TODO(derrandz): Test, validate & update. +## TECHDEBT: Test, validate & update. protogen_docker_m1: docker_check docker build -t pocket/proto-generator -f ./build/Dockerfile.m1.proto . && docker run --platform=linux/amd64 -it -v $(CWD)/shared:/usr/src/app/shared pocket/proto-generator .PHONY: protogen_docker -## TODO(derrandz): Test, validate & update. +## TECHDEBT: Test, validate & update. protogen_docker: docker_check docker build -t pocket/proto-generator -f ./build/Dockerfile.proto . && docker run -it -v $(CWD)/:/usr/src/app/ pocket/proto-generator @@ -343,6 +345,17 @@ benchmark_p2p_addrbook: # TODO_IN_THIS_COMMIT - SHOULD NEVER BE COMMITTED TO MASTER. It is a way to start the review process while non-critical changes are still in progress TODO_KEYWORDS = -e "TODO" -e "TECHDEBT" -e "IMPROVE" -e "DISCUSS" -e "INCOMPLETE" -e "INVESTIGATE" -e "CLEANUP" -e "HACK" -e "REFACTOR" -e "CONSIDERATION" -e "TODO_IN_THIS_COMMIT" -e "DISCUSS_IN_THIS_COMMIT" +# How do I use TODOs? +# 1. : ; +# e.g. HACK: This is a hack, we need to fix it later +# 2. If there's a specific issue, or specific person, add that in paranthesiss +# e.g. TODO(@Olshansk): Automatically link to the Github user https://github.com/olshansk +# e.g. INVESTIGATE(#420): Automatically link this to github issue https://github.com/pokt-network/pocket/issues/420 +# e.g. DISCUSS(@Olshansk, #420): Specific individual should tend to the action item in the specific ticket +# e.g. CLEANUP(core): This is not tied to an issue, or a person, but should only be done by the core team. +# e.g. CLEANUP: This is not tied to an issue, or a person, and can be done by the core team or external contributors. +# 3. Feel free to add additional keywords to the list above + .PHONY: todo_list ## List all the TODOs in the project (excludes vendor and prototype directories) todo_list: diff --git a/README.md b/README.md index eff269589..febb82574 100644 --- a/README.md +++ b/README.md @@ -32,13 +32,13 @@ All the links you'll need are listed below. If you'd like to contribute to the P - [Contribution Guide](docs/contributing/README.md) - [Release Guide](docs/build/README.md) - [Dependencies Guide](docs/deps/README.md) -- [Telemetry Guide](shared/telemetry/README.md) +- [Telemetry Guide](telemetry/README.md) ### Architectures - [Shared Architecture](shared/README.md) - [Utility Architecture](utility/doc/README.md) -- _Coming Soon: Consensus Architecture_ +- _Coming Soon: Consensus Architecture_ // TODO(olshansky): needs a README file with proper code structure - [Persistence Architecture](persistence/README.md) - [P2P Architecture](p2p/README.md) diff --git a/app/client/main.go b/app/client/main.go index e32ad26ec..0fbf20a8e 100644 --- a/app/client/main.go +++ b/app/client/main.go @@ -6,18 +6,20 @@ import ( "log" "os" + "github.com/pokt-network/pocket/shared/debug" + "github.com/pokt-network/pocket/telemetry" + "github.com/manifoldco/promptui" "github.com/pokt-network/pocket/consensus" "github.com/pokt-network/pocket/p2p" "github.com/pokt-network/pocket/shared" pocketCrypto "github.com/pokt-network/pocket/shared/crypto" "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/telemetry" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" "google.golang.org/protobuf/types/known/anypb" ) +// TODO(olshansky): Lowercase variables / constants that do not need to be exported. + const ( PromptResetToGenesis string = "ResetToGenesis" PromptPrintNodeState string = "PrintNodeState" @@ -25,8 +27,8 @@ const ( PromptTogglePacemakerMode string = "TogglePacemakerMode" PromptShowLatestBlockInStore string = "ShowLatestBlockInStore" - configPath string = "build/config/config1.json" - genesisPath string = "build/config/genesis.json" + defaultConfigPath = "build/config/config1.json" + defaultGenesisPath = "build/config/genesis.json" ) var items = []string{ @@ -44,39 +46,27 @@ var p2pMod modules.P2PModule var consensusMod modules.ConsensusModule func main() { - // HACK: rain tree will detect if trying to send to addr=self and not send it var err error - clientPrivateKey, err := pocketCrypto.GeneratePrivateKey() - if err != nil { - log.Fatalf(err.Error()) - } - - config, genesis := test_artifacts.ReadConfigAndGenesisFiles(configPath, genesisPath) - config.Base.PrivateKey = clientPrivateKey.String() - - consensusMod, err = consensus.Create(config, genesis) + consensusMod, err = consensus.Create(defaultConfigPath, defaultGenesisPath, true) // TECHDEBT: extra param required for injecting private key hack for debug client if err != nil { log.Fatalf("[ERROR] Failed to create consensus module: %v", err.Error()) } - - p2pMod, err = p2p.Create(config, genesis) + p2pMod, err = p2p.Create(defaultConfigPath, defaultGenesisPath, true) // TECHDEBT: extra param required for injecting private key hack for debug client if err != nil { log.Fatalf("[ERROR] Failed to create p2p module: %v", err.Error()) } - // This telemetry module instance is a NOOP because the 'enable_telemetry' flag in the `cfg` above is set to false. // Since this client mimics partial - networking only - functionality of a full node, some of the telemetry-related // code paths are executed. To avoid those messages interfering with the telemetry data collected, a non-nil telemetry // module that NOOPs (per the configs above) is injected. - telemetryMod, err := telemetry.Create(config, genesis) + telemetryMod, err := telemetry.Create(defaultConfigPath, defaultGenesisPath) if err != nil { log.Fatalf("[ERROR] Failed to create NOOP telemetry module: " + err.Error()) } - _ = shared.CreateBusWithOptionalModules(nil, p2pMod, nil, consensusMod, telemetryMod, config, genesis) + _ = shared.CreateBusWithOptionalModules(nil, p2pMod, nil, consensusMod, telemetryMod) p2pMod.Start() - // We are explicitly not calling `Start` on the consensus module for { selection, err := promptGetInput() @@ -110,32 +100,32 @@ func promptGetInput() (string, error) { func handleSelect(selection string) { switch selection { case PromptResetToGenesis: - m := &types.DebugMessage{ - Action: types.DebugMessageAction_DEBUG_CONSENSUS_RESET_TO_GENESIS, + m := &debug.DebugMessage{ + Action: debug.DebugMessageAction_DEBUG_CONSENSUS_RESET_TO_GENESIS, Message: nil, } broadcastDebugMessage(m) case PromptPrintNodeState: - m := &types.DebugMessage{ - Action: types.DebugMessageAction_DEBUG_CONSENSUS_PRINT_NODE_STATE, + m := &debug.DebugMessage{ + Action: debug.DebugMessageAction_DEBUG_CONSENSUS_PRINT_NODE_STATE, Message: nil, } broadcastDebugMessage(m) case PromptTriggerNextView: - m := &types.DebugMessage{ - Action: types.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW, + m := &debug.DebugMessage{ + Action: debug.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW, Message: nil, } broadcastDebugMessage(m) case PromptTogglePacemakerMode: - m := &types.DebugMessage{ - Action: types.DebugMessageAction_DEBUG_CONSENSUS_TOGGLE_PACE_MAKER_MODE, + m := &debug.DebugMessage{ + Action: debug.DebugMessageAction_DEBUG_CONSENSUS_TOGGLE_PACE_MAKER_MODE, Message: nil, } broadcastDebugMessage(m) case PromptShowLatestBlockInStore: - m := &types.DebugMessage{ - Action: types.DebugMessageAction_DEBUG_SHOW_LATEST_BLOCK_IN_STORE, + m := &debug.DebugMessage{ + Action: debug.DebugMessageAction_DEBUG_SHOW_LATEST_BLOCK_IN_STORE, Message: nil, } sendDebugMessage(m) @@ -145,7 +135,7 @@ func handleSelect(selection string) { } // Broadcast to the entire validator set -func broadcastDebugMessage(debugMsg *types.DebugMessage) { +func broadcastDebugMessage(debugMsg *debug.DebugMessage) { anyProto, err := anypb.New(debugMsg) if err != nil { log.Fatalf("[ERROR] Failed to create Any proto: %v", err) @@ -157,16 +147,16 @@ func broadcastDebugMessage(debugMsg *types.DebugMessage) { // p2pMod.Broadcast(anyProto, types.PocketTopic_DEBUG_TOPIC) for _, val := range consensusMod.ValidatorMap() { - addr, err := pocketCrypto.NewAddress(val.Address) + addr, err := pocketCrypto.NewAddress(val.GetAddress()) if err != nil { log.Fatalf("[ERROR] Failed to convert validator address into pocketCrypto.Address: %v", err) } - p2pMod.Send(addr, anyProto, types.PocketTopic_DEBUG_TOPIC) + p2pMod.Send(addr, anyProto, debug.PocketTopic_DEBUG_TOPIC) } } // Send to just a single (i.e. first) validator in the set -func sendDebugMessage(debugMsg *types.DebugMessage) { +func sendDebugMessage(debugMsg *debug.DebugMessage) { anyProto, err := anypb.New(debugMsg) if err != nil { log.Fatalf("[ERROR] Failed to create Any proto: %v", err) @@ -174,12 +164,12 @@ func sendDebugMessage(debugMsg *types.DebugMessage) { var validatorAddress []byte for _, val := range consensusMod.ValidatorMap() { - validatorAddress, err = pocketCrypto.NewAddress(val.Address) + validatorAddress, err = pocketCrypto.NewAddress(val.GetAddress()) if err != nil { log.Fatalf("[ERROR] Failed to convert validator address into pocketCrypto.Address: %v", err) } break } - p2pMod.Send(validatorAddress, anyProto, types.PocketTopic_DEBUG_TOPIC) + p2pMod.Send(validatorAddress, anyProto, debug.PocketTopic_DEBUG_TOPIC) } diff --git a/app/pocket/main.go b/app/pocket/main.go index 50bd5df45..ed3ac7e1a 100644 --- a/app/pocket/main.go +++ b/app/pocket/main.go @@ -5,7 +5,6 @@ import ( "log" "github.com/pokt-network/pocket/shared" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" ) // See `docs/build/README.md` for details on how this is injected via mage. @@ -22,10 +21,7 @@ func main() { log.Printf("Version flag currently unused %s\n", version) return } - - cfg, genesis := test_artifacts.ReadConfigAndGenesisFiles(*configFilename, *genesisFilename) - - pocketNode, err := shared.Create(cfg, genesis) + pocketNode, err := shared.Create(*configFilename, *genesisFilename) if err != nil { log.Fatalf("Failed to create pocket node: %s", err) } diff --git a/build/config/config1.json b/build/config/config1.json index c0281786e..d095ad4fd 100755 --- a/build/config/config1.json +++ b/build/config/config1.json @@ -1,7 +1,7 @@ { "base": { "root_directory": "/go/src/github.com/pocket-network", - "private_key": "ccec19df8fe866280e41da68d52d0ecdb07b01e85eeef45f400fd3a89b71c26a79254a4bc46bf1182826145b0b01b48bab4240cd30e23ba90e4e5e6b56961c6d" + "private_key": "f4f6d5a0001170bc61e3638dc68b5d1f54530e0923a0a1c70e0d39423a53104e030206dd1a85db222a5c641cba61921dfbb1fa6252b728bdcdedfc720f97e10c" }, "consensus": { "max_mempool_bytes": 500000000, @@ -9,7 +9,8 @@ "timeout_msec": 5000, "manual": true, "debug_time_between_steps_msec": 1000 - } + }, + "private_key": "f4f6d5a0001170bc61e3638dc68b5d1f54530e0923a0a1c70e0d39423a53104e030206dd1a85db222a5c641cba61921dfbb1fa6252b728bdcdedfc720f97e10c" }, "utility": {}, "persistence": { @@ -20,11 +21,12 @@ "p2p": { "consensus_port": 8080, "use_rain_tree": true, - "connection_type": 1 + "is_empty_connection_type": false, + "private_key": "f4f6d5a0001170bc61e3638dc68b5d1f54530e0923a0a1c70e0d39423a53104e030206dd1a85db222a5c641cba61921dfbb1fa6252b728bdcdedfc720f97e10c" }, "telemetry": { "enabled": true, "address": "0.0.0.0:9000", "endpoint": "/metrics" } -} +} \ No newline at end of file diff --git a/build/config/config2.json b/build/config/config2.json index 7d186a89c..7ca449cd4 100755 --- a/build/config/config2.json +++ b/build/config/config2.json @@ -1,7 +1,7 @@ { "base": { "root_directory": "/go/src/github.com/pocket-network", - "private_key": "8a76f99e3bf132f1d61bb4a123f495e00c169ac7c55fa1a2aa1b34196020edb191dd4fd53e8e27020d62796fe68b469fad5fa5a7abc61d3eb2bd98ba16af1e29" + "private_key": "fdc3f9c7439aa09fbe757abf217c64eb649b4ddfe11a98e15879e77bdbc5f1ccf81c19830cb42fa65d216946f230b5ffdc939717db7eb9503bbff97df91aa6a2" }, "consensus": { "max_mempool_bytes": 500000000, @@ -9,7 +9,8 @@ "timeout_msec": 5000, "manual": true, "debug_time_between_steps_msec": 1000 - } + }, + "private_key": "fdc3f9c7439aa09fbe757abf217c64eb649b4ddfe11a98e15879e77bdbc5f1ccf81c19830cb42fa65d216946f230b5ffdc939717db7eb9503bbff97df91aa6a2" }, "utility": {}, "persistence": { @@ -20,11 +21,12 @@ "p2p": { "consensus_port": 8080, "use_rain_tree": true, - "connection_type": 1 + "is_empty_connection_type": false, + "private_key": "fdc3f9c7439aa09fbe757abf217c64eb649b4ddfe11a98e15879e77bdbc5f1ccf81c19830cb42fa65d216946f230b5ffdc939717db7eb9503bbff97df91aa6a2" }, "telemetry": { "enabled": true, "address": "0.0.0.0:9000", "endpoint": "/metrics" } -} +} \ No newline at end of file diff --git a/build/config/config3.json b/build/config/config3.json index bf6bd4593..5b3b18f52 100755 --- a/build/config/config3.json +++ b/build/config/config3.json @@ -1,7 +1,7 @@ { "base": { "root_directory": "/go/src/github.com/pocket-network", - "private_key": "c7bd1bd027e76b31534c3f5226c8e3c3f2a034ba9fa11017b65191f7f9ef0d253e5e4bbed5f98721163bb84445072a9202d213f1e348c5e9e0e2ea83bbb7e3aa" + "private_key": "10c7ab1eca545fbc43a45385b189f363d303a592b4e6d8333d08c8b4b9c5cbcf93f17a5b4afc924fdda6070701c455b4ee7eae43e29324ac9de0b957f031c9c0" }, "consensus": { "max_mempool_bytes": 500000000, @@ -9,7 +9,8 @@ "timeout_msec": 5000, "manual": true, "debug_time_between_steps_msec": 1000 - } + }, + "private_key": "10c7ab1eca545fbc43a45385b189f363d303a592b4e6d8333d08c8b4b9c5cbcf93f17a5b4afc924fdda6070701c455b4ee7eae43e29324ac9de0b957f031c9c0" }, "utility": {}, "persistence": { @@ -20,11 +21,12 @@ "p2p": { "consensus_port": 8080, "use_rain_tree": true, - "connection_type": 1 + "is_empty_connection_type": false, + "private_key": "10c7ab1eca545fbc43a45385b189f363d303a592b4e6d8333d08c8b4b9c5cbcf93f17a5b4afc924fdda6070701c455b4ee7eae43e29324ac9de0b957f031c9c0" }, "telemetry": { "enabled": true, "address": "0.0.0.0:9000", "endpoint": "/metrics" } -} +} \ No newline at end of file diff --git a/build/config/config4.json b/build/config/config4.json index 251241162..1d21b7748 100755 --- a/build/config/config4.json +++ b/build/config/config4.json @@ -1,7 +1,7 @@ { "base": { "root_directory": "/go/src/github.com/pocket-network", - "private_key": "ddff03df6c525e551c5e9cd0e31ac4ec99dd6aa5d62185ba969bbf2e62db7e2c6c207cea1b1bf45dad8f8973d57291d3da31855254d7f1ed83ec3e06cabfe6b7" + "private_key": "458e94c056e0163c72752ebbd6df92a35fb6b30958d824be54af694f8ede4c7e06cc58d8c3ee9e463b4cfe680696a0b3eeed786bc3de1fa0268dfb4e4e1e9c68" }, "consensus": { "max_mempool_bytes": 500000000, @@ -9,7 +9,8 @@ "timeout_msec": 5000, "manual": true, "debug_time_between_steps_msec": 1000 - } + }, + "private_key": "458e94c056e0163c72752ebbd6df92a35fb6b30958d824be54af694f8ede4c7e06cc58d8c3ee9e463b4cfe680696a0b3eeed786bc3de1fa0268dfb4e4e1e9c68" }, "utility": {}, "persistence": { @@ -20,11 +21,12 @@ "p2p": { "consensus_port": 8080, "use_rain_tree": true, - "connection_type": 1 + "is_empty_connection_type": false, + "private_key": "458e94c056e0163c72752ebbd6df92a35fb6b30958d824be54af694f8ede4c7e06cc58d8c3ee9e463b4cfe680696a0b3eeed786bc3de1fa0268dfb4e4e1e9c68" }, "telemetry": { "enabled": true, "address": "0.0.0.0:9000", "endpoint": "/metrics" } -} +} \ No newline at end of file diff --git a/build/config/genesis.json b/build/config/genesis.json index 3ecc4991b..1a36da3b4 100755 --- a/build/config/genesis.json +++ b/build/config/genesis.json @@ -1,146 +1,149 @@ { - "consensus": { - "genesis_time": { - "seconds": 1660514050, - "nanos": 296019000 - }, - "chain_id": "testnet", - "max_block_bytes": 4000000 - }, - "utility": { - "pools": [ + "persistence_genesis_state": { + "accounts": [ { - "address": "ValidatorStakePool", + "address": "0f37b7f1558280dd9655f0e3dcb93328694bdd4c", "amount": "100000000000000" }, { - "address": "ServiceNodeStakePool", + "address": "1693f7b09263f46f1b7e9c63687f952c1b0e5dd2", "amount": "100000000000000" }, { - "address": "FishermanStakePool", + "address": "cdf887d902a5a95ef8c366fd8cf753aaee8f1821", "amount": "100000000000000" }, { - "address": "DAO", + "address": "60abc5fcb79b27c69d08f703fe2e48315ad6c604", "amount": "100000000000000" }, { - "address": "FeeCollector", - "amount": "0" - }, - { - "address": "AppStakePool", + "address": "8a442953a3c362d1ef235673fed7f6cd7e3af24e", "amount": "100000000000000" - } - ], - "accounts": [ + }, { - "address": "22b44cdddc6c3ca5e561cda2cae385a06e609671", + "address": "7fec1a29d776cad94e274cd2ff70a146a7a60a68", "amount": "100000000000000" }, { - "address": "fe8cd7ca148ff08bcffb84b42d92f6c868980afa", + "address": "17b999f3220e63a62a8d3926d9857324ac305035", "amount": "100000000000000" + } + ], + "pools": [ + { + "address": "FeeCollector", + "amount": "0" }, { - "address": "386a3b207085a9b44c4e5aaedf101990bea96eed", + "address": "AppStakePool", "amount": "100000000000000" }, { - "address": "d6990c242da15dddf43fbeb9169de110d5785b18", + "address": "ValidatorStakePool", "amount": "100000000000000" }, { - "address": "4a1226601a0f3cbba852a8086f14f9a00e5a6e82", + "address": "ServiceNodeStakePool", "amount": "100000000000000" }, { - "address": "efaf951a927b323251da5ab92c8927781395ce03", + "address": "FishermanStakePool", "amount": "100000000000000" }, { - "address": "3b67d1a6d63c295c312a2f013150f01f15f6d785", + "address": "DAO", "amount": "100000000000000" } ], - "applications": [ - { - "address": "3b67d1a6d63c295c312a2f013150f01f15f6d785", - "public_key": "d1e0ed14f7e5e98560f90cfaecc883e918558c5f458fc6aa37c799096a5045e6", - "chains": ["0001"], - "generic_param": "1000000", - "staked_amount": "1000000000000", - "paused_height": -1, - "unstaking_height": -1, - "output": "3b67d1a6d63c295c312a2f013150f01f15f6d785" - } - ], "validators": [ { - "address": "22b44cdddc6c3ca5e561cda2cae385a06e609671", - "public_key": "79254a4bc46bf1182826145b0b01b48bab4240cd30e23ba90e4e5e6b56961c6d", + "address": "0f37b7f1558280dd9655f0e3dcb93328694bdd4c", + "public_key": "030206dd1a85db222a5c641cba61921dfbb1fa6252b728bdcdedfc720f97e10c", + "chains": null, "generic_param": "node1.consensus:8080", "staked_amount": "1000000000000", "paused_height": -1, "unstaking_height": -1, - "output": "22b44cdddc6c3ca5e561cda2cae385a06e609671", + "output": "0f37b7f1558280dd9655f0e3dcb93328694bdd4c", "actor_type": 3 }, { - "address": "fe8cd7ca148ff08bcffb84b42d92f6c868980afa", - "public_key": "91dd4fd53e8e27020d62796fe68b469fad5fa5a7abc61d3eb2bd98ba16af1e29", + "address": "1693f7b09263f46f1b7e9c63687f952c1b0e5dd2", + "public_key": "f81c19830cb42fa65d216946f230b5ffdc939717db7eb9503bbff97df91aa6a2", + "chains": null, "generic_param": "node2.consensus:8080", "staked_amount": "1000000000000", "paused_height": -1, "unstaking_height": -1, - "output": "fe8cd7ca148ff08bcffb84b42d92f6c868980afa", + "output": "1693f7b09263f46f1b7e9c63687f952c1b0e5dd2", "actor_type": 3 }, { - "address": "386a3b207085a9b44c4e5aaedf101990bea96eed", - "public_key": "3e5e4bbed5f98721163bb84445072a9202d213f1e348c5e9e0e2ea83bbb7e3aa", + "address": "cdf887d902a5a95ef8c366fd8cf753aaee8f1821", + "public_key": "93f17a5b4afc924fdda6070701c455b4ee7eae43e29324ac9de0b957f031c9c0", + "chains": null, "generic_param": "node3.consensus:8080", "staked_amount": "1000000000000", "paused_height": -1, "unstaking_height": -1, - "output": "386a3b207085a9b44c4e5aaedf101990bea96eed", + "output": "cdf887d902a5a95ef8c366fd8cf753aaee8f1821", "actor_type": 3 }, { - "address": "d6990c242da15dddf43fbeb9169de110d5785b18", - "public_key": "6c207cea1b1bf45dad8f8973d57291d3da31855254d7f1ed83ec3e06cabfe6b7", + "address": "60abc5fcb79b27c69d08f703fe2e48315ad6c604", + "public_key": "06cc58d8c3ee9e463b4cfe680696a0b3eeed786bc3de1fa0268dfb4e4e1e9c68", + "chains": null, "generic_param": "node4.consensus:8080", "staked_amount": "1000000000000", "paused_height": -1, "unstaking_height": -1, - "output": "d6990c242da15dddf43fbeb9169de110d5785b18", + "output": "60abc5fcb79b27c69d08f703fe2e48315ad6c604", "actor_type": 3 } ], + "applications": [ + { + "address": "17b999f3220e63a62a8d3926d9857324ac305035", + "public_key": "f674286864d7f87175faf0a6c74f506c63c62dbcda58c0001c84e9e028b86ee4", + "chains": [ + "0001" + ], + "generic_param": "1000000", + "staked_amount": "1000000000000", + "paused_height": -1, + "unstaking_height": -1, + "output": "17b999f3220e63a62a8d3926d9857324ac305035", + "actor_type": 0 + } + ], "service_nodes": [ { - "address": "4a1226601a0f3cbba852a8086f14f9a00e5a6e82", - "public_key": "cf05669b65132a6bd1069bcddcf47c349dd84986a03782a55081b438e15aa1bb", - "chains": ["0001"], + "address": "8a442953a3c362d1ef235673fed7f6cd7e3af24e", + "public_key": "936460bb2c51b79a8aa1e42d1f1d983554fa21a598c20e1fddeb9d4fae8acf1c", + "chains": [ + "0001" + ], "generic_param": "node1.consensus:8080", "staked_amount": "1000000000000", "paused_height": -1, "unstaking_height": -1, - "output": "4a1226601a0f3cbba852a8086f14f9a00e5a6e82", + "output": "8a442953a3c362d1ef235673fed7f6cd7e3af24e", "actor_type": 1 } ], "fishermen": [ { - "address": "efaf951a927b323251da5ab92c8927781395ce03", - "public_key": "2beb3626a95b347057d8df86e5a4fc8b917775bd2f6594f99f0df7f25b6bae0d", - "chains": ["0001"], + "address": "7fec1a29d776cad94e274cd2ff70a146a7a60a68", + "public_key": "7f971fb0dcc5699fa41149682c03b17939eef53b7d7cae0ab839ac3cbb4ab96c", + "chains": [ + "0001" + ], "generic_param": "node1.consensus:8080", "staked_amount": "1000000000000", "paused_height": -1, "unstaking_height": -1, - "output": "efaf951a927b323251da5ab92c8927781395ce03", + "output": "7fec1a29d776cad94e274cd2ff70a146a7a60a68", "actor_type": 2 } ], @@ -254,5 +257,59 @@ "message_unpause_service_node_fee_owner": "da034209758b78eaea06dd99c07909ab54c99b45", "message_change_parameter_fee_owner": "da034209758b78eaea06dd99c07909ab54c99b45" } + }, + "consensus_genesis_state": { + "genesis_time": { + "seconds": 1662740528, + "nanos": 935916000 + }, + "chain_id": "testnet", + "max_block_bytes": 4000000, + "validators": [ + { + "address": "0f37b7f1558280dd9655f0e3dcb93328694bdd4c", + "public_key": "030206dd1a85db222a5c641cba61921dfbb1fa6252b728bdcdedfc720f97e10c", + "chains": null, + "generic_param": "node1.consensus:8080", + "staked_amount": "1000000000000", + "paused_height": -1, + "unstaking_height": -1, + "output": "0f37b7f1558280dd9655f0e3dcb93328694bdd4c", + "actor_type": 3 + }, + { + "address": "1693f7b09263f46f1b7e9c63687f952c1b0e5dd2", + "public_key": "f81c19830cb42fa65d216946f230b5ffdc939717db7eb9503bbff97df91aa6a2", + "chains": null, + "generic_param": "node2.consensus:8080", + "staked_amount": "1000000000000", + "paused_height": -1, + "unstaking_height": -1, + "output": "1693f7b09263f46f1b7e9c63687f952c1b0e5dd2", + "actor_type": 3 + }, + { + "address": "cdf887d902a5a95ef8c366fd8cf753aaee8f1821", + "public_key": "93f17a5b4afc924fdda6070701c455b4ee7eae43e29324ac9de0b957f031c9c0", + "chains": null, + "generic_param": "node3.consensus:8080", + "staked_amount": "1000000000000", + "paused_height": -1, + "unstaking_height": -1, + "output": "cdf887d902a5a95ef8c366fd8cf753aaee8f1821", + "actor_type": 3 + }, + { + "address": "60abc5fcb79b27c69d08f703fe2e48315ad6c604", + "public_key": "06cc58d8c3ee9e463b4cfe680696a0b3eeed786bc3de1fa0268dfb4e4e1e9c68", + "chains": null, + "generic_param": "node4.consensus:8080", + "staked_amount": "1000000000000", + "paused_height": -1, + "unstaking_height": -1, + "output": "60abc5fcb79b27c69d08f703fe2e48315ad6c604", + "actor_type": 3 + } + ] } -} +} \ No newline at end of file diff --git a/build/config/main.go b/build/config/main.go index 043ea2557..bee91117a 100644 --- a/build/config/main.go +++ b/build/config/main.go @@ -5,17 +5,19 @@ import ( "fmt" "io/ioutil" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" + "github.com/pokt-network/pocket/shared/test_artifacts" ) +// Utility to generate config and genesis files +// TODO(pocket/issues/182): Add a make target to help trigger this from cmdline + const ( - filePermissions = 0777 - genesisPath = "build/config/genesis.json" - configPathTemplate = "build/config/config%d.json" + defaultGenesisFilePath = "build/config/genesis.json" + defaultConfigFilePath = "build/config/config" + jsonSubfix = ".json" + rwoPerm = 0777 ) -// Utility to generate config and genesis files -// TODO(andrew): Add a make target to help trigger this from cmdline func main() { genesis, validatorPrivateKeys := test_artifacts.NewGenesisState(4, 1, 1, 1) configs := test_artifacts.NewDefaultConfigs(validatorPrivateKeys) @@ -23,7 +25,7 @@ func main() { if err != nil { panic(err) } - if err := ioutil.WriteFile(genesisPath, genesisJson, filePermissions); err != nil { + if err := ioutil.WriteFile(defaultGenesisFilePath, genesisJson, rwoPerm); err != nil { panic(err) } for i, config := range configs { @@ -31,7 +33,8 @@ func main() { if err != nil { panic(err) } - if err := ioutil.WriteFile(fmt.Sprintf(configPathTemplate, i+1), configJson, filePermissions); err != nil { + filePath := fmt.Sprintf("%s%d%s", defaultConfigFilePath, i+1, jsonSubfix) + if err := ioutil.WriteFile(filePath, configJson, rwoPerm); err != nil { panic(err) } } diff --git a/consensus/CHANGELOG.md b/consensus/CHANGELOG.md index d1074e99e..64d55cba0 100644 --- a/consensus/CHANGELOG.md +++ b/consensus/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.0.0.2] - 2022-08-25 +**Encapsulate structures previously in shared [#163](github.com/pokt-network/pocket/issues/163)** +- Ensured proto structures implement shared interfaces +- `ConsensusConfig` uses shared interfaces in order to accept `MockConsensusConfig` in test_artifacts +- `ConsensusGenesisState` uses shared interfaces in order to accept `MockConsensusGenesisState` in test_artifacts +- Implemented shared validator interface for `validator_map` functionality + ## [0.0.0.1] - 2021-03-31 HotPocket 1st Iteration (https://github.com/pokt-network/pocket/pull/48) diff --git a/consensus/block.go b/consensus/block.go index c66e2420f..ae531bcb8 100644 --- a/consensus/block.go +++ b/consensus/block.go @@ -2,15 +2,14 @@ package consensus import ( "encoding/hex" + "github.com/pokt-network/pocket/shared/codec" "unsafe" - "github.com/pokt-network/pocket/shared/types" - typesCons "github.com/pokt-network/pocket/consensus/types" ) // TODO(olshansky): Sync with Andrew on the type of validation we need here. -func (m *consensusModule) validateBlock(block *types.Block) error { +func (m *ConsensusModule) validateBlock(block *typesCons.Block) error { if block == nil { return typesCons.ErrNilBlock } @@ -18,7 +17,7 @@ func (m *consensusModule) validateBlock(block *types.Block) error { } // This is a helper function intended to be called by a leader/validator during a view change -func (m *consensusModule) prepareBlockAsLeader() (*types.Block, error) { +func (m *ConsensusModule) prepareBlockAsLeader() (*typesCons.Block, error) { if m.isReplica() { return nil, typesCons.ErrReplicaPrepareBlock } @@ -37,7 +36,7 @@ func (m *consensusModule) prepareBlockAsLeader() (*types.Block, error) { return nil, err } - blockHeader := &types.BlockHeader{ + blockHeader := &typesCons.BlockHeader{ Height: int64(m.Height), Hash: hex.EncodeToString(appHash), NumTxs: uint32(len(txs)), @@ -46,7 +45,7 @@ func (m *consensusModule) prepareBlockAsLeader() (*types.Block, error) { QuorumCertificate: []byte("HACK: Temporary placeholder"), } - block := &types.Block{ + block := &typesCons.Block{ BlockHeader: blockHeader, Transactions: txs, } @@ -55,7 +54,7 @@ func (m *consensusModule) prepareBlockAsLeader() (*types.Block, error) { } // This is a helper function intended to be called by a replica/voter during a view change -func (m *consensusModule) applyBlockAsReplica(block *types.Block) error { +func (m *ConsensusModule) applyBlockAsReplica(block *typesCons.Block) error { if m.isLeader() { return typesCons.ErrLeaderApplyBLock } @@ -83,7 +82,7 @@ func (m *consensusModule) applyBlockAsReplica(block *types.Block) error { } // Creates a new Utility context and clears/nullifies any previous contexts if they exist -func (m *consensusModule) refreshUtilityContext() error { +func (m *ConsensusModule) refreshUtilityContext() error { // This is a catch-all to release the previous utility context if it wasn't cleaned up // in the proper lifecycle (e.g. catch up, error, network partition, etc...). Ideally, this // should not be called. @@ -102,11 +101,11 @@ func (m *consensusModule) refreshUtilityContext() error { return nil } -func (m *consensusModule) commitBlock(block *types.Block) error { +func (m *ConsensusModule) commitBlock(block *typesCons.Block) error { m.nodeLog(typesCons.CommittingBlock(m.Height, len(block.Transactions))) // Store the block in the KV store - codec := types.GetCodec() + codec := codec.GetCodec() blockProtoBytes, err := codec.Marshal(block) if err != nil { return err diff --git a/consensus/consensus_tests/pacemaker_test.go b/consensus/consensus_tests/pacemaker_test.go index e8dd7cb4c..25553aa01 100644 --- a/consensus/consensus_tests/pacemaker_test.go +++ b/consensus/consensus_tests/pacemaker_test.go @@ -7,8 +7,6 @@ import ( "testing" "time" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/consensus" typesCons "github.com/pokt-network/pocket/consensus/types" "github.com/pokt-network/pocket/shared/modules" @@ -33,7 +31,7 @@ func TestTinyPacemakerTimeouts(t *testing.T) { paceMakerTimeout := 50 * time.Millisecond configs, genesisStates := GenerateNodeConfigs(t, numNodes) for _, config := range configs { - config.Consensus.PacemakerConfig.TimeoutMsec = paceMakerTimeoutMsec + config.Consensus.GetPaceMakerConfig().SetTimeoutMsec(paceMakerTimeoutMsec) } // Create & start test pocket nodes @@ -130,7 +128,7 @@ func TestPacemakerCatchupSameStepDifferentRounds(t *testing.T) { leaderRound := uint64(6) // Placeholder block - blockHeader := &types.BlockHeader{ + blockHeader := &typesCons.BlockHeader{ Height: int64(testHeight), Hash: hex.EncodeToString(appHash), NumTxs: 0, @@ -138,7 +136,7 @@ func TestPacemakerCatchupSameStepDifferentRounds(t *testing.T) { ProposerAddress: leader.Address.Bytes(), QuorumCertificate: nil, } - block := &types.Block{ + block := &typesCons.Block{ BlockHeader: blockHeader, Transactions: emptyTxs, } diff --git a/consensus/consensus_tests/utils_test.go b/consensus/consensus_tests/utils_test.go index b67c8ba58..2ab4ff850 100644 --- a/consensus/consensus_tests/utils_test.go +++ b/consensus/consensus_tests/utils_test.go @@ -3,15 +3,20 @@ package consensus_tests import ( "context" "encoding/hex" + "encoding/json" "flag" "fmt" + "io/ioutil" "log" - "math/big" + "os" "reflect" "sort" "testing" "time" + "github.com/pokt-network/pocket/shared/debug" + "github.com/pokt-network/pocket/shared/test_artifacts" + "github.com/golang/mock/gomock" "github.com/pokt-network/pocket/consensus" typesCons "github.com/pokt-network/pocket/consensus/types" @@ -19,14 +24,17 @@ import ( cryptoPocket "github.com/pokt-network/pocket/shared/crypto" "github.com/pokt-network/pocket/shared/modules" modulesMock "github.com/pokt-network/pocket/shared/modules/mocks" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" ) +func TestMain(m *testing.M) { + m.Run() + os.Remove(testingConfigFilePath) + os.Remove(testingGenesisFilePath) +} + // If this is set to true, consensus unit tests will fail if additional unexpected messages are received. // This slows down the tests because we always fail until the timeout specified by the test before continuing // but guarantees more correctness. @@ -54,33 +62,29 @@ type IdToNodeMapping map[typesCons.NodeId]*shared.Node /*** Node Generation Helpers ***/ -var ( - DefaultServiceURL = "https://foo.bar" // TODO (team) cleanup consensus testing module with centralization of utilities - DefaultChainID = "unittest_net" - DefaultStakeAmount = types.BigIntToString(big.NewInt(1000000000)) - DefaultAccountAmount = types.BigIntToString(big.NewInt(1000000000)) -) - -func GenerateNodeConfigs(_ *testing.T, numValidators int) (configs []*genesis.Config, genesisState *genesis.GenesisState) { - genesisState, keys := test_artifacts.NewGenesisState(numValidators, 1, 1, 1) +func GenerateNodeConfigs(_ *testing.T, validatorCount int) (configs []modules.Config, genesisState modules.GenesisState) { + var keys []string + genesisState, keys = test_artifacts.NewGenesisState(validatorCount, 1, 1, 1) configs = test_artifacts.NewDefaultConfigs(keys) - for _, config := range configs { - config.Consensus = &genesis.ConsensusConfig{ + for i, config := range configs { + config.Consensus = &typesCons.ConsensusConfig{ + PrivateKey: config.Base.PrivateKey, MaxMempoolBytes: 500000000, - PacemakerConfig: &genesis.PacemakerConfig{ + PacemakerConfig: &typesCons.PacemakerConfig{ TimeoutMsec: 5000, Manual: false, DebugTimeBetweenStepsMsec: 0, }, } + configs[i] = config } return } func CreateTestConsensusPocketNodes( t *testing.T, - configs []*genesis.Config, - genesisState *genesis.GenesisState, + configs []modules.Config, + genesisState modules.GenesisState, testChannel modules.EventsChannel, ) (pocketNodes IdToNodeMapping) { pocketNodes = make(IdToNodeMapping, len(configs)) @@ -101,16 +105,21 @@ func CreateTestConsensusPocketNodes( return } +const ( + testingGenesisFilePath = "genesis.json" + testingConfigFilePath = "config.json" +) + // Creates a pocket node where all the primary modules, exception for consensus, are mocked func CreateTestConsensusPocketNode( t *testing.T, - cfg *genesis.Config, - genesisState *genesis.GenesisState, + cfg modules.Config, + genesisState modules.GenesisState, testChannel modules.EventsChannel, ) *shared.Node { - consensusMod, err := consensus.Create(cfg, genesisState) + createTestingGenesisAndConfigFiles(t, cfg, genesisState) + consensusMod, err := consensus.Create(testingConfigFilePath, testingGenesisFilePath, false) require.NoError(t, err) - // TODO(olshansky): At the moment we are using the same base mocks for all the tests, // but note that they will need to be customized on a per test basis. persistenceMock := basePersistenceMock(t, testChannel) @@ -118,10 +127,12 @@ func CreateTestConsensusPocketNode( utilityMock := baseUtilityMock(t, testChannel) telemetryMock := baseTelemetryMock(t, testChannel) - bus, err := shared.CreateBus(persistenceMock, p2pMock, utilityMock, consensusMod, telemetryMock, cfg, genesisState) + bus, err := shared.CreateBus(persistenceMock, p2pMock, utilityMock, consensusMod, telemetryMock) require.NoError(t, err) + pk, err := cryptoPocket.NewPrivateKey(cfg.Base.PrivateKey) require.NoError(t, err) + pocketNode := &shared.Node{ Address: pk.Address(), } @@ -130,11 +141,33 @@ func CreateTestConsensusPocketNode( return pocketNode } +func createTestingGenesisAndConfigFiles(t *testing.T, cfg modules.Config, genesisState modules.GenesisState) { + config, err := json.Marshal(cfg.Consensus) + require.NoError(t, err) + + genesis, err := json.Marshal(genesisState.ConsensusGenesisState) + require.NoError(t, err) + + genesisFile := make(map[string]json.RawMessage) + configFile := make(map[string]json.RawMessage) + consensusModName := new(consensus.ConsensusModule).GetModuleName() + genesisFile[test_artifacts.GetGenesisFileName(consensusModName)] = genesis + configFile[consensusModName] = config + + genesisFileBz, err := json.MarshalIndent(genesisFile, "", " ") + require.NoError(t, err) + + consensusFileBz, err := json.MarshalIndent(configFile, "", " ") + require.NoError(t, err) + require.NoError(t, ioutil.WriteFile(testingGenesisFilePath, genesisFileBz, 0777)) + require.NoError(t, ioutil.WriteFile(testingConfigFilePath, consensusFileBz, 0777)) +} + func StartAllTestPocketNodes(t *testing.T, pocketNodes IdToNodeMapping) { for _, pocketNode := range pocketNodes { go pocketNode.Start() startEvent := pocketNode.GetBus().GetBusEvent() - require.Equal(t, startEvent.Topic, types.PocketTopic_POCKET_NODE_TOPIC) + require.Equal(t, startEvent.Topic, debug.PocketTopic_POCKET_NODE_TOPIC) } } @@ -154,32 +187,32 @@ func GetConsensusModImplementation(node *shared.Node) reflect.Value { /*** Debug/Development Message Helpers ***/ func TriggerNextView(t *testing.T, node *shared.Node) { - triggerDebugMessage(t, node, types.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW) + triggerDebugMessage(t, node, debug.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW) } -func triggerDebugMessage(t *testing.T, node *shared.Node, action types.DebugMessageAction) { - debugMessage := &types.DebugMessage{ - Action: types.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW, +func triggerDebugMessage(t *testing.T, node *shared.Node, action debug.DebugMessageAction) { + debugMessage := &debug.DebugMessage{ + Action: debug.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW, Message: nil, } anyProto, err := anypb.New(debugMessage) require.NoError(t, err) - e := &types.PocketEvent{Topic: types.PocketTopic_DEBUG_TOPIC, Data: anyProto} + e := &debug.PocketEvent{Topic: debug.PocketTopic_DEBUG_TOPIC, Data: anyProto} node.GetBus().PublishEventToBus(e) } /*** P2P Helpers ***/ func P2PBroadcast(_ *testing.T, nodes IdToNodeMapping, any *anypb.Any) { - e := &types.PocketEvent{Topic: types.PocketTopic_CONSENSUS_MESSAGE_TOPIC, Data: any} + e := &debug.PocketEvent{Topic: debug.PocketTopic_CONSENSUS_MESSAGE_TOPIC, Data: any} for _, node := range nodes { node.GetBus().PublishEventToBus(e) } } func P2PSend(_ *testing.T, node *shared.Node, any *anypb.Any) { - e := &types.PocketEvent{Topic: types.PocketTopic_CONSENSUS_MESSAGE_TOPIC, Data: any} + e := &debug.PocketEvent{Topic: debug.PocketTopic_CONSENSUS_MESSAGE_TOPIC, Data: any} node.GetBus().PublishEventToBus(e) } @@ -201,14 +234,14 @@ func WaitForNetworkConsensusMessages( } errorMessage := fmt.Sprintf("HotStuff step: %s, type: %s", typesCons.HotstuffStep_name[int32(step)], typesCons.HotstuffMessageType_name[int32(hotstuffMsgType)]) - return waitForNetworkConsensusMessagesInternal(t, testChannel, types.PocketTopic_CONSENSUS_MESSAGE_TOPIC, numMessages, millis, includeFilter, errorMessage) + return waitForNetworkConsensusMessagesInternal(t, testChannel, debug.PocketTopic_CONSENSUS_MESSAGE_TOPIC, numMessages, millis, includeFilter, errorMessage) } // IMPROVE(olshansky): Translate this to use generics. func waitForNetworkConsensusMessagesInternal( _ *testing.T, testChannel modules.EventsChannel, - topic types.PocketTopic, + topic debug.PocketTopic, numMessages int, millis time.Duration, includeFilter func(m *anypb.Any) bool, @@ -216,7 +249,7 @@ func waitForNetworkConsensusMessagesInternal( ) (messages []*anypb.Any, err error) { messages = make([]*anypb.Any, 0) ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*millis) - unused := make([]*types.PocketEvent, 0) // TODO: Move this into a pool rather than resending back to the eventbus. + unused := make([]*debug.PocketEvent, 0) // TODO: Move this into a pool rather than resending back to the eventbus. loop: for { select { @@ -290,15 +323,15 @@ func baseP2PMock(t *testing.T, testChannel modules.EventsChannel) *modulesMock.M p2pMock.EXPECT().SetBus(gomock.Any()).Do(func(modules.Bus) {}).AnyTimes() p2pMock.EXPECT(). Broadcast(gomock.Any(), gomock.Any()). - Do(func(msg *anypb.Any, topic types.PocketTopic) { - e := &types.PocketEvent{Topic: topic, Data: msg} + Do(func(msg *anypb.Any, topic debug.PocketTopic) { + e := &debug.PocketEvent{Topic: topic, Data: msg} testChannel <- *e }). AnyTimes() p2pMock.EXPECT(). Send(gomock.Any(), gomock.Any(), gomock.Any()). - Do(func(addr cryptoPocket.Address, msg *anypb.Any, topic types.PocketTopic) { - e := &types.PocketEvent{Topic: topic, Data: msg} + Do(func(addr cryptoPocket.Address, msg *anypb.Any, topic debug.PocketTopic) { + e := &debug.PocketEvent{Topic: topic, Data: msg} testChannel <- *e }). AnyTimes() diff --git a/consensus/debugging.go b/consensus/debugging.go index 2c4fc7aab..5e111095e 100644 --- a/consensus/debugging.go +++ b/consensus/debugging.go @@ -1,22 +1,22 @@ package consensus import ( + "github.com/pokt-network/pocket/shared/debug" "log" "time" typesCons "github.com/pokt-network/pocket/consensus/types" - "github.com/pokt-network/pocket/shared/types" ) -func (m *consensusModule) HandleDebugMessage(debugMessage *types.DebugMessage) error { +func (m *ConsensusModule) HandleDebugMessage(debugMessage *debug.DebugMessage) error { switch debugMessage.Action { - case types.DebugMessageAction_DEBUG_CONSENSUS_RESET_TO_GENESIS: + case debug.DebugMessageAction_DEBUG_CONSENSUS_RESET_TO_GENESIS: m.resetToGenesis(debugMessage) - case types.DebugMessageAction_DEBUG_CONSENSUS_PRINT_NODE_STATE: + case debug.DebugMessageAction_DEBUG_CONSENSUS_PRINT_NODE_STATE: m.printNodeState(debugMessage) - case types.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW: + case debug.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW: m.triggerNextView(debugMessage) - case types.DebugMessageAction_DEBUG_CONSENSUS_TOGGLE_PACE_MAKER_MODE: + case debug.DebugMessageAction_DEBUG_CONSENSUS_TOGGLE_PACE_MAKER_MODE: m.togglePacemakerManualMode(debugMessage) default: log.Printf("Debug message: %s \n", debugMessage.Message) @@ -24,7 +24,7 @@ func (m *consensusModule) HandleDebugMessage(debugMessage *types.DebugMessage) e return nil } -func (m *consensusModule) GetNodeState() typesCons.ConsensusNodeState { +func (m *ConsensusModule) GetNodeState() typesCons.ConsensusNodeState { leaderId := typesCons.NodeId(0) if m.LeaderId != nil { leaderId = *m.LeaderId @@ -39,7 +39,7 @@ func (m *consensusModule) GetNodeState() typesCons.ConsensusNodeState { } } -func (m *consensusModule) resetToGenesis(_ *types.DebugMessage) { +func (m *ConsensusModule) resetToGenesis(_ *debug.DebugMessage) { m.nodeLog(typesCons.DebugResetToGenesis) m.Height = 0 @@ -52,19 +52,19 @@ func (m *consensusModule) resetToGenesis(_ *types.DebugMessage) { m.clearLeader() m.clearMessagesPool() - m.GetBus().GetPersistenceModule().HandleDebugMessage(&types.DebugMessage{ - Action: types.DebugMessageAction_DEBUG_CLEAR_STATE, + m.GetBus().GetPersistenceModule().HandleDebugMessage(&debug.DebugMessage{ + Action: debug.DebugMessageAction_DEBUG_CLEAR_STATE, Message: nil, }) m.GetBus().GetPersistenceModule().Start() // reload genesis state } -func (m *consensusModule) printNodeState(_ *types.DebugMessage) { +func (m *ConsensusModule) printNodeState(_ *debug.DebugMessage) { state := m.GetNodeState() m.nodeLog(typesCons.DebugNodeState(state)) } -func (m *consensusModule) triggerNextView(_ *types.DebugMessage) { +func (m *ConsensusModule) triggerNextView(_ *debug.DebugMessage) { m.nodeLog(typesCons.DebugTriggerNextView) if m.Height == 0 || (m.Step == Decide && m.paceMaker.IsManualMode()) { @@ -78,7 +78,7 @@ func (m *consensusModule) triggerNextView(_ *types.DebugMessage) { } } -func (m *consensusModule) togglePacemakerManualMode(_ *types.DebugMessage) { +func (m *ConsensusModule) togglePacemakerManualMode(_ *debug.DebugMessage) { newMode := !m.paceMaker.IsManualMode() if newMode { m.nodeLog(typesCons.DebugTogglePacemakerManualMode("MANUAL")) diff --git a/consensus/helpers.go b/consensus/helpers.go index 5b265ba04..24a84612c 100644 --- a/consensus/helpers.go +++ b/consensus/helpers.go @@ -2,13 +2,13 @@ package consensus import ( "encoding/base64" + "github.com/pokt-network/pocket/shared/debug" "log" "google.golang.org/protobuf/proto" typesCons "github.com/pokt-network/pocket/consensus/types" cryptoPocket "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" "google.golang.org/protobuf/types/known/anypb" ) @@ -38,7 +38,7 @@ var ( // ** Hotstuff Helpers ** // -func (m *consensusModule) getQuorumCertificate(height uint64, step typesCons.HotstuffStep, round uint64) (*typesCons.QuorumCertificate, error) { +func (m *ConsensusModule) getQuorumCertificate(height uint64, step typesCons.HotstuffStep, round uint64) (*typesCons.QuorumCertificate, error) { var pss []*typesCons.PartialSignature for _, msg := range m.MessagePool[step] { // TODO(olshansky): Add tests for this @@ -78,7 +78,7 @@ func (m *consensusModule) getQuorumCertificate(height uint64, step typesCons.Hot }, nil } -func (m *consensusModule) findHighQC(step typesCons.HotstuffStep) (qc *typesCons.QuorumCertificate) { +func (m *ConsensusModule) findHighQC(step typesCons.HotstuffStep) (qc *typesCons.QuorumCertificate) { for _, m := range m.MessagePool[step] { if m.GetQuorumCertificate() == nil { continue @@ -98,8 +98,8 @@ func getThresholdSignature( return thresholdSig, nil } -func isSignatureValid(m *typesCons.HotstuffMessage, pubKeyStr string, signature []byte) bool { - pubKey, err := cryptoPocket.NewPublicKey(pubKeyStr) +func isSignatureValid(m *typesCons.HotstuffMessage, pubKeyString string, signature []byte) bool { + pubKey, err := cryptoPocket.NewPublicKey(pubKeyString) if err != nil { log.Println("[WARN] Error getting PublicKey from bytes:", err) return false @@ -112,11 +112,11 @@ func isSignatureValid(m *typesCons.HotstuffMessage, pubKeyStr string, signature return pubKey.Verify(bytesToVerify, signature) } -func (m *consensusModule) didReceiveEnoughMessageForStep(step typesCons.HotstuffStep) error { +func (m *ConsensusModule) didReceiveEnoughMessageForStep(step typesCons.HotstuffStep) error { return m.isOptimisticThresholdMet(len(m.MessagePool[step])) } -func (m *consensusModule) isOptimisticThresholdMet(n int) error { +func (m *ConsensusModule) isOptimisticThresholdMet(n int) error { numValidators := len(m.validatorMap) if !(float64(n) > ByzantineThreshold*float64(numValidators)) { return typesCons.ErrByzantineThresholdCheck(n, ByzantineThreshold*float64(numValidators)) @@ -134,7 +134,7 @@ func protoHash(m proto.Message) string { /*** P2P Helpers ***/ -func (m *consensusModule) sendToNode(msg *typesCons.HotstuffMessage) { +func (m *ConsensusModule) sendToNode(msg *typesCons.HotstuffMessage) { // TODO(olshansky): This can happen due to a race condition with the pacemaker. if m.LeaderId == nil { m.nodeLogError(typesCons.ErrNilLeaderId.Error(), nil) @@ -148,13 +148,13 @@ func (m *consensusModule) sendToNode(msg *typesCons.HotstuffMessage) { return } - if err := m.GetBus().GetP2PModule().Send(cryptoPocket.AddressFromString(m.IdToValAddrMap[*m.LeaderId]), anyConsensusMessage, types.PocketTopic_CONSENSUS_MESSAGE_TOPIC); err != nil { + if err := m.GetBus().GetP2PModule().Send(cryptoPocket.AddressFromString(m.IdToValAddrMap[*m.LeaderId]), anyConsensusMessage, debug.PocketTopic_CONSENSUS_MESSAGE_TOPIC); err != nil { m.nodeLogError(typesCons.ErrSendMessage.Error(), err) return } } -func (m *consensusModule) broadcastToNodes(msg *typesCons.HotstuffMessage) { +func (m *ConsensusModule) broadcastToNodes(msg *typesCons.HotstuffMessage) { m.nodeLog(typesCons.BroadcastingMessage(msg)) anyConsensusMessage, err := anypb.New(msg) if err != nil { @@ -162,7 +162,7 @@ func (m *consensusModule) broadcastToNodes(msg *typesCons.HotstuffMessage) { return } - if err := m.GetBus().GetP2PModule().Broadcast(anyConsensusMessage, types.PocketTopic_CONSENSUS_MESSAGE_TOPIC); err != nil { + if err := m.GetBus().GetP2PModule().Broadcast(anyConsensusMessage, debug.PocketTopic_CONSENSUS_MESSAGE_TOPIC); err != nil { m.nodeLogError(typesCons.ErrBroadcastMessage.Error(), err) return } @@ -170,7 +170,7 @@ func (m *consensusModule) broadcastToNodes(msg *typesCons.HotstuffMessage) { /*** Persistence Helpers ***/ -func (m *consensusModule) clearMessagesPool() { +func (m *ConsensusModule) clearMessagesPool() { for _, step := range HotstuffSteps { m.MessagePool[step] = make([]*typesCons.HotstuffMessage, 0) } @@ -178,20 +178,20 @@ func (m *consensusModule) clearMessagesPool() { /*** Leader Election Helpers ***/ -func (m *consensusModule) isLeader() bool { +func (m *ConsensusModule) isLeader() bool { return m.LeaderId != nil && *m.LeaderId == m.NodeId } -func (m *consensusModule) isReplica() bool { +func (m *ConsensusModule) isReplica() bool { return !m.isLeader() } -func (m *consensusModule) clearLeader() { +func (m *ConsensusModule) clearLeader() { m.logPrefix = DefaultLogPrefix m.LeaderId = nil } -func (m *consensusModule) electNextLeader(message *typesCons.HotstuffMessage) { +func (m *ConsensusModule) electNextLeader(message *typesCons.HotstuffMessage) { leaderId, err := m.leaderElectionMod.ElectNextLeader(message) if err != nil || leaderId == 0 { m.nodeLogError(typesCons.ErrLeaderElection(message).Error(), err) @@ -212,10 +212,10 @@ func (m *consensusModule) electNextLeader(message *typesCons.HotstuffMessage) { /*** General Infrastructure Helpers ***/ -func (m *consensusModule) nodeLog(s string) { +func (m *ConsensusModule) nodeLog(s string) { log.Printf("[%s][%d] %s\n", m.logPrefix, m.NodeId, s) } -func (m *consensusModule) nodeLogError(s string, err error) { +func (m *ConsensusModule) nodeLogError(s string, err error) { log.Printf("[ERROR][%s][%d] %s: %v\n", m.logPrefix, m.NodeId, s, err) } diff --git a/consensus/hotstuff_leader.go b/consensus/hotstuff_leader.go index 33fca4d50..d691ebc0c 100644 --- a/consensus/hotstuff_leader.go +++ b/consensus/hotstuff_leader.go @@ -9,7 +9,7 @@ import ( var ( LeaderMessageHandler HotstuffMessageHandler = &HotstuffLeaderMessageHandler{} - leaderHandlers = map[typesCons.HotstuffStep]func(*consensusModule, *typesCons.HotstuffMessage){ + leaderHandlers = map[typesCons.HotstuffStep]func(*ConsensusModule, *typesCons.HotstuffMessage){ NewRound: LeaderMessageHandler.HandleNewRoundMessage, Prepare: LeaderMessageHandler.HandlePrepareMessage, PreCommit: LeaderMessageHandler.HandlePrecommitMessage, @@ -22,7 +22,7 @@ type HotstuffLeaderMessageHandler struct{} /*** Prepare Step ***/ -func (handler *HotstuffLeaderMessageHandler) HandleNewRoundMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffLeaderMessageHandler) HandleNewRoundMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -78,7 +78,7 @@ func (handler *HotstuffLeaderMessageHandler) HandleNewRoundMessage(m *consensusM /*** PreCommit Step ***/ -func (handler *HotstuffLeaderMessageHandler) HandlePrepareMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffLeaderMessageHandler) HandlePrepareMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -122,7 +122,7 @@ func (handler *HotstuffLeaderMessageHandler) HandlePrepareMessage(m *consensusMo /*** Commit Step ***/ -func (handler *HotstuffLeaderMessageHandler) HandlePrecommitMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffLeaderMessageHandler) HandlePrecommitMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -166,7 +166,7 @@ func (handler *HotstuffLeaderMessageHandler) HandlePrecommitMessage(m *consensus /*** Decide Step ***/ -func (handler *HotstuffLeaderMessageHandler) HandleCommitMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffLeaderMessageHandler) HandleCommitMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -215,7 +215,7 @@ func (handler *HotstuffLeaderMessageHandler) HandleCommitMessage(m *consensusMod ) } -func (handler *HotstuffLeaderMessageHandler) HandleDecideMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffLeaderMessageHandler) HandleDecideMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -225,7 +225,7 @@ func (handler *HotstuffLeaderMessageHandler) HandleDecideMessage(m *consensusMod } // anteHandle is the general handler called for every before every specific HotstuffLeaderMessageHandler handler -func (handler *HotstuffLeaderMessageHandler) anteHandle(m *consensusModule, msg *typesCons.HotstuffMessage) error { +func (handler *HotstuffLeaderMessageHandler) anteHandle(m *ConsensusModule, msg *typesCons.HotstuffMessage) error { if err := handler.validateBasic(m, msg); err != nil { return err } @@ -233,7 +233,7 @@ func (handler *HotstuffLeaderMessageHandler) anteHandle(m *consensusModule, msg return nil } -func (handler *HotstuffLeaderMessageHandler) emitTelemetryEvent(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffLeaderMessageHandler) emitTelemetryEvent(m *ConsensusModule, msg *typesCons.HotstuffMessage) { m.GetBus(). GetTelemetryModule(). GetEventMetricsAgent(). @@ -247,7 +247,7 @@ func (handler *HotstuffLeaderMessageHandler) emitTelemetryEvent(m *consensusModu } // ValidateBasic general validation checks that apply to every HotstuffLeaderMessage -func (handler *HotstuffLeaderMessageHandler) validateBasic(m *consensusModule, msg *typesCons.HotstuffMessage) error { +func (handler *HotstuffLeaderMessageHandler) validateBasic(m *ConsensusModule, msg *typesCons.HotstuffMessage) error { // Discard messages with invalid partial signatures before storing it in the leader's consensus mempool if err := m.validatePartialSignature(msg); err != nil { return err @@ -255,7 +255,7 @@ func (handler *HotstuffLeaderMessageHandler) validateBasic(m *consensusModule, m return nil } -func (m *consensusModule) validatePartialSignature(msg *typesCons.HotstuffMessage) error { +func (m *ConsensusModule) validatePartialSignature(msg *typesCons.HotstuffMessage) error { if msg.Step == NewRound { m.nodeLog(typesCons.ErrUnnecessaryPartialSigForNewRound.Error()) return nil @@ -279,7 +279,7 @@ func (m *consensusModule) validatePartialSignature(msg *typesCons.HotstuffMessag if !ok { return typesCons.ErrMissingValidator(address, m.ValAddrToIdMap[address]) } - pubKey := validator.PublicKey + pubKey := validator.GetPublicKey() if isSignatureValid(msg, pubKey, msg.GetPartialSignature().Signature) { return nil } @@ -288,11 +288,11 @@ func (m *consensusModule) validatePartialSignature(msg *typesCons.HotstuffMessag address, m.ValAddrToIdMap[address], msg, pubKey) } -func (m *consensusModule) aggregateMessage(msg *typesCons.HotstuffMessage) { +func (m *ConsensusModule) aggregateMessage(msg *typesCons.HotstuffMessage) { // TODO(olshansky): Add proper tests for this when we figure out where the mempool should live. // NOTE: This is just a placeholder at the moment. It doesn't actually work because SizeOf returns // the size of the map pointer, and does not recursively determine the size of all the underlying elements. - if m.consCfg.MaxMempoolBytes < uint64(unsafe.Sizeof(m.MessagePool)) { + if m.consCfg.GetMaxMempoolBytes() < uint64(unsafe.Sizeof(m.MessagePool)) { m.nodeLogError(typesCons.DisregardHotstuffMessage, typesCons.ErrConsensusMempoolFull) return } diff --git a/consensus/hotstuff_replica.go b/consensus/hotstuff_replica.go index 70a8d9618..25041c766 100644 --- a/consensus/hotstuff_replica.go +++ b/consensus/hotstuff_replica.go @@ -12,7 +12,7 @@ type HotstuffReplicaMessageHandler struct{} var ( ReplicaMessageHandler HotstuffMessageHandler = &HotstuffReplicaMessageHandler{} - replicaHandlers = map[typesCons.HotstuffStep]func(*consensusModule, *typesCons.HotstuffMessage){ + replicaHandlers = map[typesCons.HotstuffStep]func(*ConsensusModule, *typesCons.HotstuffMessage){ NewRound: ReplicaMessageHandler.HandleNewRoundMessage, Prepare: ReplicaMessageHandler.HandlePrepareMessage, PreCommit: ReplicaMessageHandler.HandlePrecommitMessage, @@ -23,7 +23,7 @@ var ( /*** NewRound Step ***/ -func (handler *HotstuffReplicaMessageHandler) HandleNewRoundMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffReplicaMessageHandler) HandleNewRoundMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -37,7 +37,7 @@ func (handler *HotstuffReplicaMessageHandler) HandleNewRoundMessage(m *consensus /*** Prepare Step ***/ -func (handler *HotstuffReplicaMessageHandler) HandlePrepareMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffReplicaMessageHandler) HandlePrepareMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -70,7 +70,7 @@ func (handler *HotstuffReplicaMessageHandler) HandlePrepareMessage(m *consensusM /*** PreCommit Step ***/ -func (handler *HotstuffReplicaMessageHandler) HandlePrecommitMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffReplicaMessageHandler) HandlePrecommitMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -98,7 +98,7 @@ func (handler *HotstuffReplicaMessageHandler) HandlePrecommitMessage(m *consensu /*** Commit Step ***/ -func (handler *HotstuffReplicaMessageHandler) HandleCommitMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffReplicaMessageHandler) HandleCommitMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -126,7 +126,7 @@ func (handler *HotstuffReplicaMessageHandler) HandleCommitMessage(m *consensusMo /*** Decide Step ***/ -func (handler *HotstuffReplicaMessageHandler) HandleDecideMessage(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffReplicaMessageHandler) HandleDecideMessage(m *ConsensusModule, msg *typesCons.HotstuffMessage) { handler.emitTelemetryEvent(m, msg) if err := handler.anteHandle(m, msg); err != nil { @@ -150,12 +150,12 @@ func (handler *HotstuffReplicaMessageHandler) HandleDecideMessage(m *consensusMo } // anteHandle is the handler called on every replica message before specific handler -func (handler *HotstuffReplicaMessageHandler) anteHandle(m *consensusModule, msg *typesCons.HotstuffMessage) error { +func (handler *HotstuffReplicaMessageHandler) anteHandle(m *ConsensusModule, msg *typesCons.HotstuffMessage) error { log.Println("TODO: Hotstuff replica ante handle not implemented yet") return nil } -func (handler *HotstuffReplicaMessageHandler) emitTelemetryEvent(m *consensusModule, msg *typesCons.HotstuffMessage) { +func (handler *HotstuffReplicaMessageHandler) emitTelemetryEvent(m *ConsensusModule, msg *typesCons.HotstuffMessage) { m.GetBus(). GetTelemetryModule(). GetEventMetricsAgent(). @@ -168,7 +168,7 @@ func (handler *HotstuffReplicaMessageHandler) emitTelemetryEvent(m *consensusMod ) } -func (m *consensusModule) validateProposal(msg *typesCons.HotstuffMessage) error { +func (m *ConsensusModule) validateProposal(msg *typesCons.HotstuffMessage) error { if !(msg.Type == Propose && msg.Step == Prepare) { return typesCons.ErrProposalNotValidInPrepare } @@ -209,7 +209,7 @@ func (m *consensusModule) validateProposal(msg *typesCons.HotstuffMessage) error return typesCons.ErrUnhandledProposalCase } -func (m *consensusModule) validateQuorumCertificate(qc *typesCons.QuorumCertificate) error { +func (m *ConsensusModule) validateQuorumCertificate(qc *typesCons.QuorumCertificate) error { if qc == nil { return typesCons.ErrNilQC } @@ -232,7 +232,7 @@ func (m *consensusModule) validateQuorumCertificate(qc *typesCons.QuorumCertific } // TODO(olshansky): Every call to `IsSignatureValid` does a serialization and should be optimized. We can // just serialize `Message` once and verify each signature without re-serializing every time. - if !isSignatureValid(msgToJustify, validator.PublicKey, partialSig.Signature) { + if !isSignatureValid(msgToJustify, validator.GetPublicKey(), partialSig.Signature) { m.nodeLog(typesCons.WarnInvalidPartialSigInQC(partialSig.Address, m.ValAddrToIdMap[partialSig.Address])) continue } diff --git a/consensus/leader_election/module.go b/consensus/leader_election/module.go index 1f7aa26ec..a5e24dcf3 100644 --- a/consensus/leader_election/module.go +++ b/consensus/leader_election/module.go @@ -5,7 +5,10 @@ import ( typesCons "github.com/pokt-network/pocket/consensus/types" "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types/genesis" +) + +const ( + LeaderElectionModuleName = "leader_election" ) type LeaderElectionModule interface { @@ -19,7 +22,7 @@ type leaderElectionModule struct { bus modules.Bus } -func Create(_ *genesis.Config, _ *genesis.GenesisState) (LeaderElectionModule, error) { +func Create(_ *typesCons.ConsensusConfig, _ *typesCons.ConsensusGenesisState) (LeaderElectionModule, error) { return &leaderElectionModule{}, nil } @@ -32,6 +35,18 @@ func (m *leaderElectionModule) Stop() error { return nil } +func (m *leaderElectionModule) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + return // No-op +} + +func (m *leaderElectionModule) InitGenesis(pathToGenesisJSON string) (genesis modules.IGenesis, err error) { + return // No-op +} + +func (m *leaderElectionModule) GetModuleName() string { + return LeaderElectionModuleName +} + func (m *leaderElectionModule) SetBus(pocketBus modules.Bus) { m.bus = pocketBus } diff --git a/consensus/messages.go b/consensus/messages.go index 0dc8f5e72..4fd09cea5 100644 --- a/consensus/messages.go +++ b/consensus/messages.go @@ -3,15 +3,13 @@ package consensus import ( "log" - "github.com/pokt-network/pocket/shared/types" - typesCons "github.com/pokt-network/pocket/consensus/types" "github.com/pokt-network/pocket/shared/crypto" "google.golang.org/protobuf/proto" ) func CreateProposeMessage( - m *consensusModule, + m *ConsensusModule, step typesCons.HotstuffStep, // step can be taken from `m` but is specified explicitly via interface to avoid ambiguity qc *typesCons.QuorumCertificate, ) (*typesCons.HotstuffMessage, error) { @@ -44,9 +42,9 @@ func CreateProposeMessage( } func CreateVoteMessage( - m *consensusModule, + m *ConsensusModule, step typesCons.HotstuffStep, // step can be taken from `m` but is specified explicitly via interface to avoid ambiguity - block *types.Block, + block *typesCons.Block, ) (*typesCons.HotstuffMessage, error) { if block == nil { return nil, typesCons.ErrNilBlockVote diff --git a/consensus/module.go b/consensus/module.go index 6999f4488..d2e3e1481 100644 --- a/consensus/module.go +++ b/consensus/module.go @@ -1,37 +1,44 @@ package consensus import ( + "encoding/json" "fmt" + "io/ioutil" "log" "github.com/pokt-network/pocket/consensus/leader_election" - consensusTelemetry "github.com/pokt-network/pocket/consensus/telemetry" typesCons "github.com/pokt-network/pocket/consensus/types" cryptoPocket "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" + "github.com/pokt-network/pocket/shared/test_artifacts" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" + + consensusTelemetry "github.com/pokt-network/pocket/consensus/telemetry" + "github.com/pokt-network/pocket/shared/modules" ) const ( - DefaultLogPrefix string = "NODE" // Just a default that'll be replaced during consensus operations. + DefaultLogPrefix = "NODE" // Just a default that'll be replaced during consensus operations. + ConsensusModuleName = "consensus" ) -var _ modules.ConsensusModule = &consensusModule{} +var _ modules.ConsensusGenesisState = &typesCons.ConsensusGenesisState{} +var _ modules.PacemakerConfig = &typesCons.PacemakerConfig{} +var _ modules.ConsensusConfig = &typesCons.ConsensusConfig{} +var _ modules.ConsensusModule = &ConsensusModule{} // TODO(olshansky): Any reason to make all of these attributes local only (i.e. not exposed outside the struct)? -type consensusModule struct { +// TODO(olshansky): Look for a way to not externalize the `ConsensusModule` struct +type ConsensusModule struct { bus modules.Bus privateKey cryptoPocket.Ed25519PrivateKey - consCfg *genesis.ConsensusConfig + consCfg modules.ConsensusConfig // Hotstuff Height uint64 Round uint64 Step typesCons.HotstuffStep - Block *types.Block // The current block being voted on prior to committing to finality + Block *typesCons.Block // The current block being voted on prior to committing to finality HighPrepareQC *typesCons.QuorumCertificate // Highest QC for which replica voted PRECOMMIT LockedQC *typesCons.QuorumCertificate // Highest QC for which replica voted COMMIT @@ -44,7 +51,7 @@ type consensusModule struct { // Consensus State appHash string - validatorMap map[string]*genesis.Actor + validatorMap typesCons.ValidatorMap // Module Dependencies utilityContext modules.UtilityContext @@ -58,7 +65,18 @@ type consensusModule struct { MaxBlockBytes uint64 } -func Create(cfg *genesis.Config, genesis *genesis.GenesisState) (modules.ConsensusModule, error) { +func Create(configPath, genesisPath string, useRandomPK bool) (modules.ConsensusModule, error) { + cm := new(ConsensusModule) + c, err := cm.InitConfig(configPath) + if err != nil { + return nil, err + } + g, err := cm.InitGenesis(genesisPath) + if err != nil { + return nil, err + } + cfg := c.(*typesCons.ConsensusConfig) + genesis := g.(*typesCons.ConsensusGenesisState) leaderElectionMod, err := leader_election.Create(cfg, genesis) if err != nil { return nil, err @@ -70,20 +88,24 @@ func Create(cfg *genesis.Config, genesis *genesis.GenesisState) (modules.Consens return nil, err } - privateKey, err := cryptoPocket.NewPrivateKey(cfg.Base.PrivateKey) + valMap := typesCons.ValidatorListToMap(genesis.Validators) + var privateKey cryptoPocket.PrivateKey + if useRandomPK { + privateKey, err = cryptoPocket.GeneratePrivateKey() + } else { + privateKey, err = cryptoPocket.NewPrivateKey(cfg.PrivateKey) + } if err != nil { return nil, err } address := privateKey.Address().String() - - valMap := validatorListToMap(genesis.Utility.Validators) valIdMap, idValMap := typesCons.GetValAddrToIdMap(valMap) - m := &consensusModule{ + m := &ConsensusModule{ bus: nil, privateKey: privateKey.(cryptoPocket.Ed25519PrivateKey), - consCfg: cfg.Consensus, + consCfg: cfg, Height: 0, Round: 0, @@ -107,7 +129,7 @@ func Create(cfg *genesis.Config, genesis *genesis.GenesisState) (modules.Consens logPrefix: DefaultLogPrefix, MessagePool: make(map[typesCons.HotstuffStep][]*typesCons.HotstuffMessage), - MaxBlockBytes: genesis.Consensus.MaxBlockBytes, + MaxBlockBytes: genesis.GetMaxBlockBytes(), } // TODO(olshansky): Look for a way to avoid doing this. @@ -116,7 +138,40 @@ func Create(cfg *genesis.Config, genesis *genesis.GenesisState) (modules.Consens return m, nil } -func (m *consensusModule) Start() error { +func (m *ConsensusModule) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + data, err := ioutil.ReadFile(pathToConfigJSON) + if err != nil { + return + } + // over arching configuration file + rawJSON := make(map[string]json.RawMessage) + if err = json.Unmarshal(data, &rawJSON); err != nil { + log.Fatalf("[ERROR] an error occurred unmarshalling the %s file: %v", pathToConfigJSON, err.Error()) + } + // consensus specific configuration file + config = new(typesCons.ConsensusConfig) + err = json.Unmarshal(rawJSON[m.GetModuleName()], config) + return +} + +func (m *ConsensusModule) InitGenesis(pathToGenesisJSON string) (genesis modules.IGenesis, err error) { + data, err := ioutil.ReadFile(pathToGenesisJSON) + if err != nil { + return + } + // over arching configuration file + rawJSON := make(map[string]json.RawMessage) + if err = json.Unmarshal(data, &rawJSON); err != nil { + log.Fatalf("[ERROR] an error occurred unmarshalling the %s file: %v", pathToGenesisJSON, err.Error()) + } + // consensus specific configuration file + genesis = new(typesCons.ConsensusGenesisState) + + err = json.Unmarshal(rawJSON[test_artifacts.GetGenesisFileName(m.GetModuleName())], genesis) + return +} + +func (m *ConsensusModule) Start() error { m.GetBus(). GetTelemetryModule(). GetTimeSeriesAgent(). @@ -140,24 +195,28 @@ func (m *consensusModule) Start() error { return nil } -func (m *consensusModule) Stop() error { +func (m *ConsensusModule) Stop() error { return nil } -func (m *consensusModule) GetBus() modules.Bus { +func (m *ConsensusModule) GetModuleName() string { + return ConsensusModuleName +} + +func (m *ConsensusModule) GetBus() modules.Bus { if m.bus == nil { log.Fatalf("PocketBus is not initialized") } return m.bus } -func (m *consensusModule) SetBus(pocketBus modules.Bus) { +func (m *ConsensusModule) SetBus(pocketBus modules.Bus) { m.bus = pocketBus m.paceMaker.SetBus(pocketBus) m.leaderElectionMod.SetBus(pocketBus) } -func (m *consensusModule) loadPersistedState() error { +func (m *ConsensusModule) loadPersistedState() error { persistenceContext, err := m.GetBus().GetPersistenceModule().NewReadContext(-1) // Unknown height if err != nil { return nil @@ -184,7 +243,7 @@ func (m *consensusModule) loadPersistedState() error { } // TODO(discuss): Low priority design: think of a way to make `hotstuff_*` files be a sub-package under consensus. -// This is currently not possible because functions tied to the `consensusModule` +// This is currently not possible because functions tied to the `ConsensusModule` // struct (implementing the ConsensusModule module), which spans multiple files. /* TODO(discuss): The reason we do not assign both the leader and the replica handlers @@ -201,16 +260,16 @@ handler which has both pros and cons: * Code is less "generalizable" and therefore potentially more error prone */ -// TODO(olshansky): Should we just make these singletons or embed them directly in the consensusModule? +// TODO(olshansky): Should we just make these singletons or embed them directly in the ConsensusModule? type HotstuffMessageHandler interface { - HandleNewRoundMessage(*consensusModule, *typesCons.HotstuffMessage) - HandlePrepareMessage(*consensusModule, *typesCons.HotstuffMessage) - HandlePrecommitMessage(*consensusModule, *typesCons.HotstuffMessage) - HandleCommitMessage(*consensusModule, *typesCons.HotstuffMessage) - HandleDecideMessage(*consensusModule, *typesCons.HotstuffMessage) + HandleNewRoundMessage(*ConsensusModule, *typesCons.HotstuffMessage) + HandlePrepareMessage(*ConsensusModule, *typesCons.HotstuffMessage) + HandlePrecommitMessage(*ConsensusModule, *typesCons.HotstuffMessage) + HandleCommitMessage(*ConsensusModule, *typesCons.HotstuffMessage) + HandleDecideMessage(*ConsensusModule, *typesCons.HotstuffMessage) } -func (m *consensusModule) HandleMessage(message *anypb.Any) error { +func (m *ConsensusModule) HandleMessage(message *anypb.Any) error { switch message.MessageName() { case HotstuffMessage: var hotstuffMessage typesCons.HotstuffMessage @@ -228,7 +287,7 @@ func (m *consensusModule) HandleMessage(message *anypb.Any) error { return nil } -func (m *consensusModule) handleHotstuffMessage(msg *typesCons.HotstuffMessage) { +func (m *ConsensusModule) handleHotstuffMessage(msg *typesCons.HotstuffMessage) { m.nodeLog(typesCons.DebugHandlingHotstuffMessage(msg)) // Liveness & safety checks @@ -256,22 +315,14 @@ func (m *consensusModule) handleHotstuffMessage(msg *typesCons.HotstuffMessage) leaderHandlers[msg.Step](m, msg) } -func (m *consensusModule) AppHash() string { +func (m *ConsensusModule) AppHash() string { return m.appHash } -func (m *consensusModule) CurrentHeight() uint64 { +func (m *ConsensusModule) CurrentHeight() uint64 { return m.Height } -func (m *consensusModule) ValidatorMap() modules.ValidatorMap { - return m.validatorMap -} - -func validatorListToMap(validators []*genesis.Actor) (m modules.ValidatorMap) { - m = make(modules.ValidatorMap, len(validators)) - for _, v := range validators { - m[v.Address] = v - } - return +func (m *ConsensusModule) ValidatorMap() modules.ValidatorMap { + return typesCons.ValidatorMapToModulesValidatorMap(m.validatorMap) } diff --git a/consensus/pacemaker.go b/consensus/pacemaker.go index 606657731..c2655e315 100644 --- a/consensus/pacemaker.go +++ b/consensus/pacemaker.go @@ -7,18 +7,22 @@ import ( consensusTelemetry "github.com/pokt-network/pocket/consensus/telemetry" typesCons "github.com/pokt-network/pocket/consensus/types" + "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types/genesis" +) + +const ( + PacemakerModuleName = "pacemaker" ) type Pacemaker interface { modules.Module PacemakerDebug - // TODO(olshansky): Rather than exposing the underlying `consensusModule` struct, + // TODO(olshansky): Rather than exposing the underlying `ConsensusModule` struct, // we could create a `ConsensusModuleDebug` interface that'll expose setters/getters // for the height/round/step/etc, and interface with the module that way. - SetConsensusModule(module *consensusModule) + SetConsensusModule(module *ConsensusModule) ValidateMessage(message *typesCons.HotstuffMessage) error RestartTimer() @@ -33,12 +37,12 @@ type paceMaker struct { bus modules.Bus // TODO(olshansky): The reason `pacemaker_*` files are not a sub-package under consensus - // due to it's dependency on the underlying implementation of `consensusModule`. Think + // due to it's dependency on the underlying implementation of `ConsensusModule`. Think // through a way to decouple these. This could be fixed with reflection but that's not // a great idea in production code. - consensusMod *consensusModule + consensusMod *ConsensusModule - pacemakerConfigs *genesis.PacemakerConfig + pacemakerConfigs modules.PacemakerConfig stepCancelFunc context.CancelFunc @@ -46,19 +50,26 @@ type paceMaker struct { paceMakerDebug } -// TODO(drewskey): Pass in `genesis` and `config` here for consistency. -func CreatePacemaker(cfg *genesis.Config) (m *paceMaker, err error) { +func (p *paceMaker) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + return // No-op +} + +func (p *paceMaker) InitGenesis(pathToGenesisJSON string) (genesis modules.IGenesis, err error) { + return // No-op +} + +func CreatePacemaker(cfg *typesCons.ConsensusConfig) (m *paceMaker, err error) { return &paceMaker{ bus: nil, consensusMod: nil, - pacemakerConfigs: cfg.Consensus.PacemakerConfig, + pacemakerConfigs: cfg.GetPaceMakerConfig(), stepCancelFunc: nil, // Only set on restarts paceMakerDebug: paceMakerDebug{ - manualMode: cfg.Consensus.PacemakerConfig.Manual, - debugTimeBetweenStepsMsec: cfg.Consensus.PacemakerConfig.DebugTimeBetweenStepsMsec, + manualMode: cfg.GetPaceMakerConfig().GetManual(), + debugTimeBetweenStepsMsec: cfg.GetPaceMakerConfig().GetDebugTimeBetweenStepsMsec(), quorumCertificate: nil, }, }, nil @@ -72,6 +83,10 @@ func (p *paceMaker) Stop() error { return nil } +func (p *paceMaker) GetModuleName() string { + return PacemakerModuleName +} + func (m *paceMaker) SetBus(pocketBus modules.Bus) { m.bus = pocketBus } @@ -83,7 +98,7 @@ func (m *paceMaker) GetBus() modules.Bus { return m.bus } -func (m *paceMaker) SetConsensusModule(c *consensusModule) { +func (m *paceMaker) SetConsensusModule(c *ConsensusModule) { m.consensusMod = c } @@ -218,7 +233,7 @@ func (p *paceMaker) startNextView(qc *typesCons.QuorumCertificate, forceNextView } // TODO(olshansky): Increase timeout using exponential backoff. -func (p *paceMaker) getStepTimeout(round uint64) time.Duration { - baseTimeout := time.Duration(int64(time.Millisecond) * int64(p.pacemakerConfigs.TimeoutMsec)) +func (p *paceMaker) getStepTimeout(_ uint64) time.Duration { + baseTimeout := time.Duration(int64(time.Millisecond) * int64(p.pacemakerConfigs.GetTimeoutMsec())) return baseTimeout } diff --git a/shared/types/proto/block.proto b/consensus/types/proto/block.proto similarity index 87% rename from shared/types/proto/block.proto rename to consensus/types/proto/block.proto index bd02dfec8..6024bcea4 100644 --- a/shared/types/proto/block.proto +++ b/consensus/types/proto/block.proto @@ -1,7 +1,7 @@ syntax = "proto3"; -package shared; +package consensus; -option go_package = "github.com/pokt-network/pocket/shared/types"; +option go_package = "github.com/pokt-network/pocket/consensus/types"; import "google/protobuf/timestamp.proto"; diff --git a/consensus/types/proto/consensus_config.proto b/consensus/types/proto/consensus_config.proto new file mode 100644 index 000000000..c7662cd80 --- /dev/null +++ b/consensus/types/proto/consensus_config.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; +package consensus; + +option go_package = "github.com/pokt-network/pocket/consensus/types"; + +message ConsensusConfig { + string private_key = 1; + uint64 max_mempool_bytes = 2; // TODO(olshansky): add unit tests for this + PacemakerConfig pacemaker_config = 3; +} + +message PacemakerConfig { + uint64 timeout_msec = 1; + bool manual = 2; + uint64 debug_time_between_steps_msec = 3; +} diff --git a/consensus/types/proto/consensus_genesis.proto b/consensus/types/proto/consensus_genesis.proto new file mode 100644 index 000000000..0d6ac61c4 --- /dev/null +++ b/consensus/types/proto/consensus_genesis.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; +package consensus; + +import "google/protobuf/timestamp.proto"; + +option go_package = "github.com/pokt-network/pocket/consensus/types"; + +message ConsensusGenesisState { + google.protobuf.Timestamp genesis_time = 1; + string chain_id = 2; // TODO/DISCUSS re-evaluate naming covention + uint64 max_block_bytes = 3; + repeated Validator validators = 4; +} + +message Validator { + string address = 1; + string public_key = 2; + string staked_amount = 3; + string generic_param = 4; // TODO/DISCUSS re-evaluate naming covention +} \ No newline at end of file diff --git a/consensus/types/proto/hotstuff_types.proto b/consensus/types/proto/hotstuff_types.proto index d3f0ef0f0..b1f7c9b4d 100644 --- a/consensus/types/proto/hotstuff_types.proto +++ b/consensus/types/proto/hotstuff_types.proto @@ -39,7 +39,7 @@ message QuorumCertificate { uint64 height = 1; uint64 round = 2; HotstuffStep step = 3; - shared.Block block = 4; + consensus.Block block = 4; ThresholdSignature threshold_signature = 5; } @@ -48,7 +48,7 @@ message HotstuffMessage { uint64 height = 2; HotstuffStep step = 3; uint64 round = 4; - shared.Block block = 5; + consensus.Block block = 5; oneof justification { QuorumCertificate quorum_certificate = 6; // From NODE -> NODE when new rounds start; one of {HighQC, TimeoutQC, CommitQC} diff --git a/consensus/types/types.go b/consensus/types/types.go index 72d006508..36896cfaf 100644 --- a/consensus/types/types.go +++ b/consensus/types/types.go @@ -1,15 +1,15 @@ package types import ( + "github.com/pokt-network/pocket/shared/modules" "sort" - - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" ) type NodeId uint64 type ValAddrToIdMap map[string]NodeId // Mapping from hex encoded address to an integer node id. type IdToValAddrMap map[NodeId]string // Mapping from node id to a hex encoded string address. +type ValidatorMap map[string]modules.Actor type ConsensusNodeState struct { NodeId NodeId @@ -21,7 +21,7 @@ type ConsensusNodeState struct { IsLeader bool } -func GetValAddrToIdMap(validatorMap map[string]*typesGenesis.Actor) (ValAddrToIdMap, IdToValAddrMap) { +func GetValAddrToIdMap(validatorMap ValidatorMap) (ValAddrToIdMap, IdToValAddrMap) { valAddresses := make([]string, 0, len(validatorMap)) for addr := range validatorMap { valAddresses = append(valAddresses, addr) @@ -38,3 +38,35 @@ func GetValAddrToIdMap(validatorMap map[string]*typesGenesis.Actor) (ValAddrToId return valToIdMap, idToValMap } + +func (x *ConsensusConfig) GetPaceMakerConfig() modules.PacemakerConfig { + return x.GetPacemakerConfig() +} + +func (x *PacemakerConfig) SetTimeoutMsec(u uint64) { + x.TimeoutMsec = u +} + +func ValidatorMapToModulesValidatorMap(validatorMap ValidatorMap) (vm modules.ValidatorMap) { + vm = make(modules.ValidatorMap) + for _, v := range validatorMap { + vm[v.GetAddress()] = v + } + return +} + +func ValidatorListToMap(validators []*Validator) (m ValidatorMap) { + m = make(ValidatorMap, len(validators)) + for _, v := range validators { + m[v.GetAddress()] = v + } + return +} + +var _ modules.Actor = &Validator{} + +func (x *Validator) GetPausedHeight() int64 { panic("not implemented on consensus validator") } +func (x *Validator) GetUnstakingHeight() int64 { panic("not implemented on consensus validator") } +func (x *Validator) GetOutput() string { panic("not implemented on consensus validator") } +func (x *Validator) GetActorTyp() modules.ActorType { panic("not implemented on consensus validator") } +func (x *Validator) GetChains() []string { panic("not implemented on consensus validator") } diff --git a/p2p/CHANGELOG.md b/p2p/CHANGELOG.md index cc2b7ddb5..98a388960 100644 --- a/p2p/CHANGELOG.md +++ b/p2p/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.0.0.2] - 2022-08-25 +**Encapsulate structures previously in shared [#163](github.com/pokt-network/pocket/issues/163)** +- Ensured proto structures implement shared interfaces +- `P2PConfig` uses shared interfaces in order to accept `MockP2PConfig` in `test_artifacts` +- Moved connection_type to bool for simplicity (need to figure out how to do Enums without sharing the structure) + ## [0.0.0.1] - 2022-07-26 - Deprecated old p2p for pre2p raintree diff --git a/p2p/README.md b/p2p/README.md index f41d7496c..8633a1fd7 100644 --- a/p2p/README.md +++ b/p2p/README.md @@ -46,22 +46,26 @@ The `Network Module` is where RainTree (or the simpler basic approach) is implem ```bash p2p -├── README.md # Self link to this README -├── transport.go # Varying implementations of the `Transport` (e.g. TCP, Passthrough) for network communication -├── module.go # The implementation of the P2P Interface +├── README.md # Self link to this README +├── transport.go # Varying implementations of the `Transport` (e.g. TCP, Passthrough) for network communication +├── module.go # The implementation of the P2P Interface ├── raintree -│   ├── addrbook_utils.go # AddrBook utilities -│   ├── addrbook_utils_test.go # AddrBook utilities unit tests -│   ├── network.go # Implementation of the Network interface using RainTree's specification +│   ├── addrbook_utils.go # AddrBook utilities +│   ├── addrbook_utils_test.go # AddrBook utilities unit tests +│   ├── network.go # Implementation of the Network interface using RainTree's specification +│   ├── utils.go │   └── types │   └── proto │   └── raintree.proto ├── raintree_integration_test.go # RainTree unit tests ├── raintree_integration_utils_test.go # Test suite for RainTree -├── stdnetwork # This can eventually be deprecated once raintree is verified. -│   └── network.go # Implementation of the Network interface using Golang's std networking lib +├── stdnetwork # This can eventually be deprecated once raintree is verified. +│   └── network.go # Implementation of the Network interface using Golang's std networking lib +├── telemetry +│   ├── metrics.go ├── types -│   ├── network.go # Network Interface definition +│   ├── proto # Proto3 messages for generated types +│   ├── network.go # Network Interface definition └── utils.go ``` diff --git a/p2p/module.go b/p2p/module.go index c07c1ffda..eeac684ce 100644 --- a/p2p/module.go +++ b/p2p/module.go @@ -5,25 +5,31 @@ package p2p // to be a "real" replacement for now. import ( + "encoding/json" + "io/ioutil" "log" + "github.com/pokt-network/pocket/shared/debug" + "github.com/pokt-network/pocket/p2p/raintree" "github.com/pokt-network/pocket/p2p/stdnetwork" p2pTelemetry "github.com/pokt-network/pocket/p2p/telemetry" typesP2P "github.com/pokt-network/pocket/p2p/types" cryptoPocket "github.com/pokt-network/pocket/shared/crypto" "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" ) var _ modules.P2PModule = &p2pModule{} +const ( + P2PModuleName = "p2p" +) + type p2pModule struct { bus modules.Bus - p2pConfig *genesis.P2PConfig // TODO (Olshansk) to remove this since it'll be available via the bus + p2pConfig modules.P2PConfig // TODO (olshansky): to remove this since it'll be available via the bus listener typesP2P.Transport address cryptoPocket.Address @@ -31,27 +37,58 @@ type p2pModule struct { network typesP2P.Network } -func Create(cfg *genesis.Config, _ *genesis.GenesisState) (m modules.P2PModule, err error) { - log.Println("Creating network module") +// TECHDEBT(drewsky): Discuss how to best expose/access `Address` throughout the codebase. +func (m *p2pModule) GetAddress() (cryptoPocket.Address, error) { + return m.address, nil +} - l, err := CreateListener(cfg.P2P) +func Create(configPath, genesisPath string, useRandomPK bool) (m modules.P2PModule, err error) { + log.Println("Creating network module") + c, err := new(p2pModule).InitConfig(configPath) if err != nil { return nil, err } - privateKey, err := cryptoPocket.NewPrivateKey(cfg.Base.PrivateKey) + cfg := c.(*typesP2P.P2PConfig) + l, err := CreateListener(cfg) + if err != nil { + return nil, err + } + var privateKey cryptoPocket.PrivateKey + if useRandomPK { + privateKey, err = cryptoPocket.GeneratePrivateKey() + } else { + privateKey, err = cryptoPocket.NewPrivateKey(cfg.PrivateKey) + } if err != nil { return nil, err } m = &p2pModule{ - p2pConfig: cfg.P2P, + p2pConfig: cfg, listener: l, address: privateKey.Address(), + } + return m, nil +} - network: nil, +func (m *p2pModule) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + data, err := ioutil.ReadFile(pathToConfigJSON) + if err != nil { + return + } + // over arching configuration file + rawJSON := make(map[string]json.RawMessage) + if err = json.Unmarshal(data, &rawJSON); err != nil { + log.Fatalf("[ERROR] an error occurred unmarshalling the %s file: %v", pathToConfigJSON, err.Error()) } + // p2p specific configuration file + config = new(typesP2P.P2PConfig) + err = json.Unmarshal(rawJSON[m.GetModuleName()], config) + return +} - return m, nil +func (m *p2pModule) InitGenesis(pathToGenesisJSON string) (genesis modules.IGenesis, err error) { + return // No-op } func (m *p2pModule) SetBus(bus modules.Bus) { @@ -68,6 +105,10 @@ func (m *p2pModule) GetBus() modules.Bus { return m.bus } +func (m *p2pModule) GetModuleName() string { + return P2PModuleName +} + func (m *p2pModule) Start() error { log.Println("Starting network module") @@ -84,15 +125,12 @@ func (m *p2pModule) Start() error { return err } - if m.p2pConfig.UseRainTree { + if m.p2pConfig.GetUseRainTree() { m.network = raintree.NewRainTreeNetwork(m.address, addrBook) } else { m.network = stdnetwork.NewNetwork(addrBook) } m.network.SetBus(m.GetBus()) - - m.network.SetBus(m.GetBus()) - go func() { for { data, err := m.listener.Read() @@ -120,8 +158,8 @@ func (m *p2pModule) Stop() error { return nil } -func (m *p2pModule) Broadcast(msg *anypb.Any, topic types.PocketTopic) error { - c := &types.PocketEvent{ +func (m *p2pModule) Broadcast(msg *anypb.Any, topic debug.PocketTopic) error { + c := &debug.PocketEvent{ Topic: topic, Data: msg, } @@ -134,8 +172,8 @@ func (m *p2pModule) Broadcast(msg *anypb.Any, topic types.PocketTopic) error { return m.network.NetworkBroadcast(data) } -func (m *p2pModule) Send(addr cryptoPocket.Address, msg *anypb.Any, topic types.PocketTopic) error { - c := &types.PocketEvent{ +func (m *p2pModule) Send(addr cryptoPocket.Address, msg *anypb.Any, topic debug.PocketTopic) error { + c := &debug.PocketEvent{ Topic: topic, Data: msg, } @@ -161,13 +199,13 @@ func (m *p2pModule) handleNetworkMessage(networkMsgData []byte) { return } - networkMessage := types.PocketEvent{} + networkMessage := debug.PocketEvent{} if err := proto.Unmarshal(appMsgData, &networkMessage); err != nil { log.Println("Error decoding network message: ", err) return } - event := types.PocketEvent{ + event := debug.PocketEvent{ Topic: networkMessage.Topic, Data: networkMessage.Data, } diff --git a/p2p/module_raintree_test.go b/p2p/module_raintree_test.go index e27176803..e7ed4be8e 100644 --- a/p2p/module_raintree_test.go +++ b/p2p/module_raintree_test.go @@ -3,13 +3,19 @@ package p2p import ( "crypto/ed25519" "encoding/binary" + "encoding/json" "fmt" + "io/ioutil" + "os" + "path/filepath" "sort" + "strconv" "sync" "testing" "time" - "github.com/pokt-network/pocket/shared/types/genesis" + "github.com/pokt-network/pocket/shared/debug" + "github.com/pokt-network/pocket/shared/test_artifacts" "github.com/golang/mock/gomock" typesP2P "github.com/pokt-network/pocket/p2p/types" @@ -17,7 +23,6 @@ import ( cryptoPocket "github.com/pokt-network/pocket/shared/crypto" "github.com/pokt-network/pocket/shared/modules" modulesMock "github.com/pokt-network/pocket/shared/modules/mocks" - "github.com/pokt-network/pocket/shared/types" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/anypb" ) @@ -213,7 +218,7 @@ func testRainTreeCalls(t *testing.T, origNode string, testCommConfig TestRainTre // Trigger originator message p := &anypb.Any{} p2pMod := p2pModules[origNode] - p2pMod.Broadcast(p, types.PocketTopic_DEBUG_TOPIC) + p2pMod.Broadcast(p, debug.PocketTopic_DEBUG_TOPIC) // Wait for completion done := make(chan struct{}) @@ -238,6 +243,9 @@ const ( maxNumKeys = 42 // The number of keys generated for all the unit tests. Optimization to avoid regenerating every time. serviceUrlFormat = "val_%d" testChannelSize = 10000 + testingGenesisFilePath = "genesis" + testingConfigFilePath = "config" + jsonPosfix = ".json" ) // TODO(olshansky): Add configurations tests for dead and partially visible nodes @@ -278,7 +286,7 @@ func prepareBusMock(t *testing.T, wg *sync.WaitGroup, consensusMock *modulesMock ctrl := gomock.NewController(t) busMock := modulesMock.NewMockBus(ctrl) - busMock.EXPECT().PublishEventToBus(gomock.Any()).Do(func(e *types.PocketEvent) { + busMock.EXPECT().PublishEventToBus(gomock.Any()).Do(func(e *debug.PocketEvent) { wg.Done() fmt.Println("App specific bus mock publishing event to bus") }).MaxTimes(1) // Using `MaxTimes` rather than `Times` because originator node implicitly handles the message @@ -289,14 +297,14 @@ func prepareBusMock(t *testing.T, wg *sync.WaitGroup, consensusMock *modulesMock return busMock } -func prepareConsensusMock(t *testing.T, genesisState *genesis.GenesisState) *modulesMock.MockConsensusModule { +func prepareConsensusMock(t *testing.T, genesisState modules.GenesisState) *modulesMock.MockConsensusModule { ctrl := gomock.NewController(t) consensusMock := modulesMock.NewMockConsensusModule(ctrl) - validators := genesisState.Utility.Validators + validators := genesisState.PersistenceGenesisState.GetVals() m := make(modules.ValidatorMap, len(validators)) for _, v := range validators { - m[v.Address] = v + m[v.GetAddress()] = v } consensusMock.EXPECT().ValidatorMap().Return(m).AnyTimes() @@ -362,37 +370,56 @@ func prepareConnMock(t *testing.T, expectedNumNetworkReads, expectedNumNetworkWr return connMock } -func prepareP2PModules(t *testing.T, configs []*genesis.Config) (p2pModules map[string]*p2pModule) { +func prepareP2PModules(t *testing.T, configs []modules.Config) (p2pModules map[string]*p2pModule) { p2pModules = make(map[string]*p2pModule, len(configs)) for i, config := range configs { - p2pMod, err := Create(config, nil) + createTestingGenesisAndConfigFiles(t, config, modules.GenesisState{}, i) + p2pMod, err := Create(testingConfigFilePath+strconv.Itoa(i)+jsonPosfix, testingGenesisFilePath+jsonPosfix, false) require.NoError(t, err) p2pModules[validatorId(t, i+1)] = p2pMod.(*p2pModule) } return } -func createConfigs(t *testing.T, numValidators int) (configs []*genesis.Config, genesisState *genesis.GenesisState) { - configs = make([]*genesis.Config, numValidators) +func createTestingGenesisAndConfigFiles(t *testing.T, cfg modules.Config, genesisState modules.GenesisState, n int) { + config, err := json.Marshal(cfg.P2P) + require.NoError(t, err) + + genesis, err := json.Marshal(genesisState.ConsensusGenesisState) + require.NoError(t, err) + + genesisFile := make(map[string]json.RawMessage) + configFile := make(map[string]json.RawMessage) + moduleName := new(p2pModule).GetModuleName() + + genesisFile[test_artifacts.GetGenesisFileName(moduleName)] = genesis + configFile[moduleName] = config + genesisFileBz, err := json.MarshalIndent(genesisFile, "", " ") + require.NoError(t, err) + + p2pFileBz, err := json.MarshalIndent(configFile, "", " ") + require.NoError(t, err) + require.NoError(t, ioutil.WriteFile(testingGenesisFilePath+jsonPosfix, genesisFileBz, 0777)) + require.NoError(t, ioutil.WriteFile(testingConfigFilePath+strconv.Itoa(n)+jsonPosfix, p2pFileBz, 0777)) +} + +func createConfigs(t *testing.T, numValidators int) (configs []modules.Config, genesisState modules.GenesisState) { + configs = make([]modules.Config, numValidators) valKeys := make([]cryptoPocket.PrivateKey, numValidators) copy(valKeys[:], keys[:numValidators]) genesisState = createGenesisState(t, valKeys) - for i := range configs { - configs[i] = &genesis.Config{ - Base: &genesis.BaseConfig{ + configs[i] = modules.Config{ + Base: &modules.BaseConfig{ RootDirectory: "", PrivateKey: valKeys[i].String(), }, - Consensus: &genesis.ConsensusConfig{}, - Utility: &genesis.UtilityConfig{}, - Persistence: &genesis.PersistenceConfig{}, - P2P: &genesis.P2PConfig{ - ConsensusPort: 8080, - UseRainTree: true, - ConnectionType: genesis.ConnectionType_EmptyConnection, + P2P: &typesP2P.P2PConfig{ + PrivateKey: valKeys[i].String(), + ConsensusPort: 8080, + UseRainTree: true, + IsEmptyConnectionType: true, }, - Telemetry: nil, } } return @@ -402,11 +429,11 @@ func validatorId(_ *testing.T, i int) string { return fmt.Sprintf(serviceUrlFormat, i) } -func createGenesisState(t *testing.T, valKeys []cryptoPocket.PrivateKey) *genesis.GenesisState { - validators := make([]*genesis.Actor, len(valKeys)) +func createGenesisState(t *testing.T, valKeys []cryptoPocket.PrivateKey) modules.GenesisState { + validators := make([]modules.Actor, len(valKeys)) for i, valKey := range valKeys { addr := valKey.Address().String() - val := &genesis.Actor{ + val := &test_artifacts.MockActor{ Address: addr, PublicKey: valKey.PublicKey().String(), GenericParam: validatorId(t, i+1), @@ -417,9 +444,17 @@ func createGenesisState(t *testing.T, valKeys []cryptoPocket.PrivateKey) *genesi } validators[i] = val } - return &genesis.GenesisState{ - Utility: &genesis.UtilityGenesisState{ + return modules.GenesisState{ + PersistenceGenesisState: &test_artifacts.MockPersistenceGenesisState{ Validators: validators, }, } } + +func TestMain(m *testing.M) { + m.Run() + files, _ := filepath.Glob("*.json") + for _, f := range files { + os.Remove(f) + } +} diff --git a/p2p/pre2p/types/mocks/network_mock.go b/p2p/pre2p/types/mocks/network_mock.go deleted file mode 100644 index 6d4fceb8c..000000000 --- a/p2p/pre2p/types/mocks/network_mock.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: p2p/pre2p/types/network.go - -// Package mock_types is a generated GoMock package. -package mock_types - -import ( - "github.com/pokt-network/pocket/p2p/types" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - crypto "github.com/pokt-network/pocket/shared/crypto" -) - -// MockNetwork is a mock of Network interface. -type MockNetwork struct { - ctrl *gomock.Controller - recorder *MockNetworkMockRecorder -} - -// MockNetworkMockRecorder is the mock recorder for MockNetwork. -type MockNetworkMockRecorder struct { - mock *MockNetwork -} - -// NewMockNetwork creates a new mock instance. -func NewMockNetwork(ctrl *gomock.Controller) *MockNetwork { - mock := &MockNetwork{ctrl: ctrl} - mock.recorder = &MockNetworkMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockNetwork) EXPECT() *MockNetworkMockRecorder { - return m.recorder -} - -// AddPeerToAddrBook mocks base method. -func (m *MockNetwork) AddPeerToAddrBook(peer *types.NetworkPeer) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddPeerToAddrBook", peer) - ret0, _ := ret[0].(error) - return ret0 -} - -// AddPeerToAddrBook indicates an expected call of AddPeerToAddrBook. -func (mr *MockNetworkMockRecorder) AddPeerToAddrBook(peer interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddPeerToAddrBook", reflect.TypeOf((*MockNetwork)(nil).AddPeerToAddrBook), peer) -} - -// GetAddrBook mocks base method. -func (m *MockNetwork) GetAddrBook() types.AddrBook { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAddrBook") - ret0, _ := ret[0].(types.AddrBook) - return ret0 -} - -// GetAddrBook indicates an expected call of GetAddrBook. -func (mr *MockNetworkMockRecorder) GetAddrBook() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAddrBook", reflect.TypeOf((*MockNetwork)(nil).GetAddrBook)) -} - -// HandleNetworkData mocks base method. -func (m *MockNetwork) HandleNetworkData(data []byte) ([]byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HandleNetworkData", data) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HandleNetworkData indicates an expected call of HandleNetworkData. -func (mr *MockNetworkMockRecorder) HandleNetworkData(data interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleNetworkData", reflect.TypeOf((*MockNetwork)(nil).HandleNetworkData), data) -} - -// NetworkBroadcast mocks base method. -func (m *MockNetwork) NetworkBroadcast(data []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NetworkBroadcast", data) - ret0, _ := ret[0].(error) - return ret0 -} - -// NetworkBroadcast indicates an expected call of NetworkBroadcast. -func (mr *MockNetworkMockRecorder) NetworkBroadcast(data interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NetworkBroadcast", reflect.TypeOf((*MockNetwork)(nil).NetworkBroadcast), data) -} - -// NetworkSend mocks base method. -func (m *MockNetwork) NetworkSend(data []byte, address crypto.Address) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NetworkSend", data, address) - ret0, _ := ret[0].(error) - return ret0 -} - -// NetworkSend indicates an expected call of NetworkSend. -func (mr *MockNetworkMockRecorder) NetworkSend(data, address interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NetworkSend", reflect.TypeOf((*MockNetwork)(nil).NetworkSend), data, address) -} - -// RemovePeerToAddrBook mocks base method. -func (m *MockNetwork) RemovePeerToAddrBook(peer *types.NetworkPeer) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RemovePeerToAddrBook", peer) - ret0, _ := ret[0].(error) - return ret0 -} - -// RemovePeerToAddrBook indicates an expected call of RemovePeerToAddrBook. -func (mr *MockNetworkMockRecorder) RemovePeerToAddrBook(peer interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemovePeerToAddrBook", reflect.TypeOf((*MockNetwork)(nil).RemovePeerToAddrBook), peer) -} - -// MockTransport is a mock of Transport interface. -type MockTransport struct { - ctrl *gomock.Controller - recorder *MockTransportMockRecorder -} - -// MockTransportMockRecorder is the mock recorder for MockTransport. -type MockTransportMockRecorder struct { - mock *MockTransport -} - -// NewMockTransport creates a new mock instance. -func NewMockTransport(ctrl *gomock.Controller) *MockTransport { - mock := &MockTransport{ctrl: ctrl} - mock.recorder = &MockTransportMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTransport) EXPECT() *MockTransportMockRecorder { - return m.recorder -} - -// Close mocks base method. -func (m *MockTransport) Close() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close. -func (mr *MockTransportMockRecorder) Close() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockTransport)(nil).Close)) -} - -// IsListener mocks base method. -func (m *MockTransport) IsListener() bool { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "IsListener") - ret0, _ := ret[0].(bool) - return ret0 -} - -// IsListener indicates an expected call of IsListener. -func (mr *MockTransportMockRecorder) IsListener() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsListener", reflect.TypeOf((*MockTransport)(nil).IsListener)) -} - -// Read mocks base method. -func (m *MockTransport) Read() ([]byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Read") - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Read indicates an expected call of Read. -func (mr *MockTransportMockRecorder) Read() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockTransport)(nil).Read)) -} - -// Write mocks base method. -func (m *MockTransport) Write(arg0 []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Write", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// Write indicates an expected call of Write. -func (mr *MockTransportMockRecorder) Write(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockTransport)(nil).Write), arg0) -} diff --git a/p2p/raintree/network.go b/p2p/raintree/network.go index b956c56ec..a3f7000de 100644 --- a/p2p/raintree/network.go +++ b/p2p/raintree/network.go @@ -1,17 +1,17 @@ package raintree import ( - "encoding/binary" "fmt" "log" "math/rand" "time" + "github.com/pokt-network/pocket/shared/debug" + p2pTelemetry "github.com/pokt-network/pocket/p2p/telemetry" typesP2P "github.com/pokt-network/pocket/p2p/types" cryptoPocket "github.com/pokt-network/pocket/shared/crypto" "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types" "google.golang.org/protobuf/proto" ) @@ -33,7 +33,7 @@ type rainTreeNetwork struct { maxNumLevels uint32 // TECHDEBT(drewsky): What should we use for de-duping messages within P2P? - mempool types.Mempool + mempool map[uint64]struct{} // TODO (drewsky) replace map implementation (can grow unbounded) } func NewRainTreeNetwork(addr cryptoPocket.Address, addrBook typesP2P.AddrBook) typesP2P.Network { @@ -44,8 +44,7 @@ func NewRainTreeNetwork(addr cryptoPocket.Address, addrBook typesP2P.AddrBook) t addrBookMap: make(typesP2P.AddrBookMap), addrList: make([]string, 0), maxNumLevels: 0, - // TODO: Mempool size should be configurable - mempool: types.NewMempool(1000000, 1000), + mempool: make(map[uint64]struct{}), } if err := n.processAddrBookUpdates(); err != nil { @@ -66,7 +65,6 @@ func (n *rainTreeNetwork) networkBroadcastAtLevel(data []byte, level uint32, non if level == 0 { return nil } - msg := &typesP2P.RainTreeMessage{ Level: level, Data: data, @@ -157,7 +155,7 @@ func (n *rainTreeNetwork) HandleNetworkData(data []byte) ([]byte, error) { return nil, err } - networkMessage := types.PocketEvent{} + networkMessage := debug.PocketEvent{} if err := proto.Unmarshal(rainTreeMsg.Data, &networkMessage); err != nil { log.Println("Error decoding network message: ", err) return nil, err @@ -170,33 +168,24 @@ func (n *rainTreeNetwork) HandleNetworkData(data []byte) ([]byte, error) { } } - // DISCUSSION(team): What do you think about turning GetHashStringFromBytes to GetHashString using generics? - // I am in favor of that to hide away the logic of converting T to binary. - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(rainTreeMsg.Nonce)) - hashString := GetHashStringFromBytes(b) - // Avoids this node from processing a messages / transactions is has already processed at the // application layer. The logic above makes sure it is only propagated and returns. // TODO(team): Add more tests to verify this is sufficient for deduping purposes. - if n.mempool.Contains(hashString) { + if _, contains := n.mempool[rainTreeMsg.Nonce]; contains { n.GetBus(). GetTelemetryModule(). GetEventMetricsAgent(). EmitEvent( p2pTelemetry.P2P_EVENT_METRICS_NAMESPACE, p2pTelemetry.BROADCAST_MESSAGE_REDUNDANCY_PER_BLOCK_EVENT_METRIC_NAME, - p2pTelemetry.RAINTREE_MESSAGE_EVENT_METRIC_HASH_LABEL, hashString, + p2pTelemetry.RAINTREE_MESSAGE_EVENT_METRIC_NONCE_LABEL, rainTreeMsg.Nonce, p2pTelemetry.RAINTREE_MESSAGE_EVENT_METRIC_HEIGHT_LABEL, blockHeight, ) return nil, nil } - // Error handling the addition transaction to the local mempool - if err := n.mempool.AddTransaction(b); err != nil { - return nil, fmt.Errorf("error adding transaction to RainTree mempool: %s", err.Error()) - } + n.mempool[rainTreeMsg.Nonce] = struct{}{} // Return the data back to the caller so it can be handeled by the app specific bus return rainTreeMsg.Data, nil diff --git a/p2p/telemetry/metrics.go b/p2p/telemetry/metrics.go index dac6d01d2..726d34c44 100644 --- a/p2p/telemetry/metrics.go +++ b/p2p/telemetry/metrics.go @@ -15,5 +15,5 @@ const ( // Attributes RAINTREE_MESSAGE_EVENT_METRIC_HEIGHT_LABEL = "height" - RAINTREE_MESSAGE_EVENT_METRIC_HASH_LABEL = "hash" + RAINTREE_MESSAGE_EVENT_METRIC_NONCE_LABEL = "nonce" ) diff --git a/p2p/transport.go b/p2p/transport.go index a9a2bd183..44ac1e238 100644 --- a/p2p/transport.go +++ b/p2p/transport.go @@ -6,32 +6,32 @@ import ( "net" typesP2P "github.com/pokt-network/pocket/p2p/types" - "github.com/pokt-network/pocket/shared/types/genesis" + "github.com/pokt-network/pocket/shared/modules" ) const ( TCPNetworkLayerProtocol = "tcp4" ) -func CreateListener(cfg *genesis.P2PConfig) (typesP2P.Transport, error) { - switch cfg.ConnectionType { - case genesis.ConnectionType_TCPConnection: - return createTCPListener(cfg) - case genesis.ConnectionType_EmptyConnection: +func CreateListener(cfg modules.P2PConfig) (typesP2P.Transport, error) { + switch cfg.IsEmptyConnType() { // TECHDEBT kept in switch format because this should be an enum not a bool + case true: return createEmptyListener(cfg) + case false: + return createTCPListener(cfg) default: - return nil, fmt.Errorf("unsupported connection type for listener: %s", cfg.ConnectionType) + return nil, fmt.Errorf("unsupported connection type for listener: %v", cfg.IsEmptyConnType()) } } -func CreateDialer(cfg *genesis.P2PConfig, url string) (typesP2P.Transport, error) { - switch cfg.ConnectionType { - case genesis.ConnectionType_TCPConnection: - return createTCPDialer(cfg, url) - case genesis.ConnectionType_EmptyConnection: +func CreateDialer(cfg modules.P2PConfig, url string) (typesP2P.Transport, error) { + switch cfg.IsEmptyConnType() { + case true: return createEmptyDialer(cfg, url) + case false: + return createTCPDialer(cfg, url) default: - return nil, fmt.Errorf("unsupported connection type for dialer: %s", cfg.ConnectionType) + return nil, fmt.Errorf("unsupported connection type for dialer: %v", cfg.IsEmptyConnType()) } } @@ -42,8 +42,8 @@ type tcpConn struct { listener *net.TCPListener } -func createTCPListener(cfg *genesis.P2PConfig) (*tcpConn, error) { - addr, err := net.ResolveTCPAddr(TCPNetworkLayerProtocol, fmt.Sprintf(":%d", cfg.ConsensusPort)) +func createTCPListener(cfg modules.P2PConfig) (*tcpConn, error) { + addr, err := net.ResolveTCPAddr(TCPNetworkLayerProtocol, fmt.Sprintf(":%d", cfg.GetConsensusPort())) if err != nil { return nil, err } @@ -57,7 +57,7 @@ func createTCPListener(cfg *genesis.P2PConfig) (*tcpConn, error) { }, nil } -func createTCPDialer(cfg *genesis.P2PConfig, url string) (*tcpConn, error) { +func createTCPDialer(_ modules.P2PConfig, url string) (*tcpConn, error) { addr, err := net.ResolveTCPAddr(TCPNetworkLayerProtocol, url) if err != nil { return nil, err @@ -119,11 +119,11 @@ var _ typesP2P.Transport = &emptyConn{} type emptyConn struct { } -func createEmptyListener(_ *genesis.P2PConfig) (typesP2P.Transport, error) { +func createEmptyListener(_ modules.P2PConfig) (typesP2P.Transport, error) { return &emptyConn{}, nil } -func createEmptyDialer(_ *genesis.P2PConfig, _ string) (typesP2P.Transport, error) { +func createEmptyDialer(_ modules.P2PConfig, _ string) (typesP2P.Transport, error) { return &emptyConn{}, nil } diff --git a/p2p/types/p2p_config.go b/p2p/types/p2p_config.go new file mode 100644 index 000000000..c6fa251c0 --- /dev/null +++ b/p2p/types/p2p_config.go @@ -0,0 +1,12 @@ +package types + +import "github.com/pokt-network/pocket/shared/modules" + +var _ modules.P2PConfig = &P2PConfig{} + +func (x *P2PConfig) IsEmptyConnType() bool { + if x.GetIsEmptyConnectionType() { + return true + } + return false +} diff --git a/p2p/types/proto/p2p_config.proto b/p2p/types/proto/p2p_config.proto new file mode 100644 index 000000000..5bb7d29be --- /dev/null +++ b/p2p/types/proto/p2p_config.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; +package p2p; + +option go_package = "github.com/pokt-network/pocket/p2p/types"; + +message P2PConfig { + string private_key = 1; + uint32 consensus_port = 2; + bool use_rain_tree = 3; + bool is_empty_connection_type = 4; // TODO (Drewsky) switch back to enum +} + +enum ConnectionType { + EmptyConnection = 0; + TCPConnection = 1; +} \ No newline at end of file diff --git a/p2p/utils.go b/p2p/utils.go index efaed84cd..d6be5dfba 100644 --- a/p2p/utils.go +++ b/p2p/utils.go @@ -2,16 +2,15 @@ package p2p import ( "fmt" - "log" - typesP2P "github.com/pokt-network/pocket/p2p/types" cryptoPocket "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types/genesis" + "github.com/pokt-network/pocket/shared/modules" + "log" ) // CLEANUP(drewsky): These functions will turn into more of a "ActorToAddrBook" when we have a closer // integration with utility. -func ValidatorMapToAddrBook(cfg *genesis.P2PConfig, validators map[string]*genesis.Actor) (typesP2P.AddrBook, error) { +func ValidatorMapToAddrBook(cfg modules.P2PConfig, validators map[string]modules.Actor) (typesP2P.AddrBook, error) { book := make(typesP2P.AddrBook, 0) for _, v := range validators { networkPeer, err := ValidatorToNetworkPeer(cfg, v) @@ -26,13 +25,13 @@ func ValidatorMapToAddrBook(cfg *genesis.P2PConfig, validators map[string]*genes // CLEANUP(drewsky): These functions will turn into more of a "ActorToAddrBook" when we have a closer // integration with utility. -func ValidatorToNetworkPeer(cfg *genesis.P2PConfig, v *genesis.Actor) (*typesP2P.NetworkPeer, error) { - conn, err := CreateDialer(cfg, v.GenericParam) // service url +func ValidatorToNetworkPeer(cfg modules.P2PConfig, v modules.Actor) (*typesP2P.NetworkPeer, error) { + conn, err := CreateDialer(cfg, v.GetGenericParam()) // service url if err != nil { return nil, fmt.Errorf("error resolving addr: %v", err) } - pubKey, err := cryptoPocket.NewPublicKey(v.PublicKey) + pubKey, err := cryptoPocket.NewPublicKey(v.GetPublicKey()) if err != nil { return nil, err } @@ -41,7 +40,7 @@ func ValidatorToNetworkPeer(cfg *genesis.P2PConfig, v *genesis.Actor) (*typesP2P Dialer: conn, PublicKey: pubKey, Address: pubKey.Address(), - ServiceUrl: v.GenericParam, // service url + ServiceUrl: v.GetGenericParam(), // service url } return peer, nil diff --git a/persistence/CHANGELOG.md b/persistence/CHANGELOG.md index d33f8c4b4..ac3e52e83 100644 --- a/persistence/CHANGELOG.md +++ b/persistence/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.0.0.4] - 2022-08-25 +**Encapsulate structures previously in shared [#163](github.com/pokt-network/pocket/issues/163)** +- Renamed schema -> types +- Added genesis, config, and unstaking proto files from shared +- Ensured proto structures implement shared interfaces +- Populate `PersistenceGenesisState` uses shared interfaces in order to accept `MockPersistenceGenesisState` +- ^ Same applies for `PersistenceConfig` +- Bumped cleanup TODOs to #149 due to scope size of #163 + ## [0.0.0.3] - 2022-08-16 **Main persistence module changes:** diff --git a/persistence/README.md b/persistence/README.md index 5c16a3982..b909250fa 100644 --- a/persistence/README.md +++ b/persistence/README.md @@ -49,25 +49,33 @@ persistence # Directly contains the persistence module interface for eac ├── account.go ├── application.go ├── block.go +├── context.go # Postgres context logic +├── debug.go # For temporary localnet ├── db.go # Helpers to connect and initialize the Postgres database ├── fisherman.go +├── genesis.go # Populate genesis logic ├── gov.go ├── module.go # Implementation of the persistence module interface ├── service_node.go ├── shared_sql.go # Database implementation helpers shared across all protocol actors └── validator.go ├── docs -├── schema # Directly contains the SQL schema and SQL query builders used by the files above +├── kvstore # Key value store for database +├── proto # Proto3 message files for generated structures +├── types # Directly contains the SQL schema and SQL query builders used by the files above +│   ├── migrations │   ├── account.go │   ├── application.go -│   ├── base_actor.go # Implementation of the `protocol_actor.go` interface shared across all actors +│   ├── base_actor.go # Implementation of the `protocol_actor.go` interface shared across all actors │   ├── block.go │   ├── fisherman.go │   ├── gov.go -│   ├── migrations -│   ├── protocol_actor.go # Interface definition for the schema shared across all actors +│   ├── persistence_genesis.go # Implements shared genesis interface +│   ├── protocol_actor.go # Interface definition for the schema shared across all actors │   ├── service_node.go -│   ├── shared_sql.go # Query building implementation helpers shared across all protocol actors +│   ├── shared_sql.go # Query building implementation helpers shared across all protocol actors +│   └── unstaking.go # Implements shared unstaking interface +│   └── util.go │   └── validator.go └── test # Unit & fuzzing tests ``` diff --git a/persistence/account.go b/persistence/account.go index 844208da5..aa8790002 100644 --- a/persistence/account.go +++ b/persistence/account.go @@ -4,9 +4,9 @@ import ( "encoding/hex" "math/big" + "github.com/pokt-network/pocket/persistence/types" + "github.com/jackc/pgx/v4" - "github.com/pokt-network/pocket/persistence/schema" - shared "github.com/pokt-network/pocket/shared/types" ) // TODO(https://github.com/pokt-network/pocket/issues/102): Generalize Pool and Account operations. @@ -29,7 +29,7 @@ func (p PostgresContext) getAccountAmountStr(address string, height int64) (amou } amount = defaultAccountAmountStr - if err = txn.QueryRow(ctx, schema.GetAccountAmountQuery(address, height)).Scan(&amount); err != pgx.ErrNoRows { + if err = txn.QueryRow(ctx, types.GetAccountAmountQuery(address, height)).Scan(&amount); err != pgx.ErrNoRows { return } @@ -62,14 +62,14 @@ func (p PostgresContext) SetAccountAmount(address []byte, amount string) error { return err } // DISCUSS(team): Do we want to panic if `amount < 0` here? - if _, err = txn.Exec(ctx, schema.InsertAccountAmountQuery(hex.EncodeToString(address), amount, height)); err != nil { + if _, err = txn.Exec(ctx, types.InsertAccountAmountQuery(hex.EncodeToString(address), amount, height)); err != nil { return err } return nil } func (p *PostgresContext) operationAccountAmount(address []byte, deltaAmount string, op func(*big.Int, *big.Int) error) error { - return p.operationPoolOrAccAmount(hex.EncodeToString(address), deltaAmount, op, p.getAccountAmountStr, schema.InsertAccountAmountQuery) + return p.operationPoolOrAccAmount(hex.EncodeToString(address), deltaAmount, op, p.getAccountAmountStr, types.InsertAccountAmountQuery) } // --- Pool Functions --- @@ -84,7 +84,7 @@ func (p PostgresContext) InsertPool(name string, address []byte, amount string) if err != nil { return err } - if _, err = txn.Exec(ctx, schema.InsertPoolAmountQuery(name, amount, height)); err != nil { + if _, err = txn.Exec(ctx, types.InsertPoolAmountQuery(name, amount, height)); err != nil { return err } return nil @@ -97,7 +97,7 @@ func (p PostgresContext) GetPoolAmount(name string, height int64) (amount string } amount = defaultAccountAmountStr - if err = txn.QueryRow(ctx, schema.GetPoolAmountQuery(name, height)).Scan(&amount); err != pgx.ErrNoRows { + if err = txn.QueryRow(ctx, types.GetPoolAmountQuery(name, height)).Scan(&amount); err != pgx.ErrNoRows { return } @@ -130,14 +130,14 @@ func (p PostgresContext) SetPoolAmount(name string, amount string) error { if err != nil { return err } - if _, err = txn.Exec(ctx, schema.InsertPoolAmountQuery(name, amount, height)); err != nil { + if _, err = txn.Exec(ctx, types.InsertPoolAmountQuery(name, amount, height)); err != nil { return err } return nil } func (p *PostgresContext) operationPoolAmount(name string, amount string, op func(*big.Int, *big.Int) error) error { - return p.operationPoolOrAccAmount(name, amount, op, p.GetPoolAmount, schema.InsertPoolAmountQuery) + return p.operationPoolOrAccAmount(name, amount, op, p.GetPoolAmount, types.InsertPoolAmountQuery) } func (p *PostgresContext) operationPoolOrAccAmount(name, amount string, @@ -156,18 +156,18 @@ func (p *PostgresContext) operationPoolOrAccAmount(name, amount string, if err != nil { return err } - originalAmountBig, err := shared.StringToBigInt(originalAmount) + originalAmountBig, err := types.StringToBigInt(originalAmount) if err != nil { return err } - amountBig, err := shared.StringToBigInt(amount) + amountBig, err := types.StringToBigInt(amount) if err != nil { return err } if err := op(originalAmountBig, amountBig); err != nil { return err } - if _, err = txn.Exec(ctx, insert(name, shared.BigIntToString(originalAmountBig), height)); err != nil { + if _, err = txn.Exec(ctx, insert(name, types.BigIntToString(originalAmountBig), height)); err != nil { return err } return nil diff --git a/persistence/application.go b/persistence/application.go index c93660f7e..0f2b88512 100644 --- a/persistence/application.go +++ b/persistence/application.go @@ -4,16 +4,16 @@ import ( "encoding/hex" "log" - "github.com/pokt-network/pocket/persistence/schema" - "github.com/pokt-network/pocket/shared/types" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" ) func (p PostgresContext) GetAppExists(address []byte, height int64) (exists bool, err error) { - return p.GetExists(schema.ApplicationActor, address, height) + return p.GetExists(types.ApplicationActor, address, height) } func (p PostgresContext) GetApp(address []byte, height int64) (operator, publicKey, stakedTokens, maxRelays, outputAddress string, pauseHeight, unstakingHeight int64, chains []string, err error) { - actor, err := p.GetActor(schema.ApplicationActor, address, height) + actor, err := p.GetActor(types.ApplicationActor, address, height) operator = actor.Address publicKey = actor.PublicKey stakedTokens = actor.StakedTokens @@ -26,7 +26,7 @@ func (p PostgresContext) GetApp(address []byte, height int64) (operator, publicK } func (p PostgresContext) InsertApp(address []byte, publicKey []byte, output []byte, _ bool, _ int, maxRelays string, stakedAmount string, chains []string, pausedHeight int64, unstakingHeight int64) error { - return p.InsertActor(schema.ApplicationActor, schema.BaseActor{ + return p.InsertActor(types.ApplicationActor, types.BaseActor{ Address: hex.EncodeToString(address), PublicKey: hex.EncodeToString(publicKey), StakedTokens: stakedAmount, @@ -39,7 +39,7 @@ func (p PostgresContext) InsertApp(address []byte, publicKey []byte, output []by } func (p PostgresContext) UpdateApp(address []byte, maxRelays string, stakedAmount string, chains []string) error { - return p.UpdateActor(schema.ApplicationActor, schema.BaseActor{ + return p.UpdateActor(types.ApplicationActor, types.BaseActor{ Address: hex.EncodeToString(address), StakedTokens: stakedAmount, ActorSpecificParam: maxRelays, @@ -48,11 +48,11 @@ func (p PostgresContext) UpdateApp(address []byte, maxRelays string, stakedAmoun } func (p PostgresContext) GetAppStakeAmount(height int64, address []byte) (string, error) { - return p.GetActorStakeAmount(schema.ApplicationActor, address, height) + return p.GetActorStakeAmount(types.ApplicationActor, address, height) } func (p PostgresContext) SetAppStakeAmount(address []byte, stakeAmount string) error { - return p.SetActorStakeAmount(schema.ApplicationActor, address, stakeAmount) + return p.SetActorStakeAmount(types.ApplicationActor, address, stakeAmount) } func (p PostgresContext) DeleteApp(_ []byte) error { @@ -60,30 +60,30 @@ func (p PostgresContext) DeleteApp(_ []byte) error { return nil } -func (p PostgresContext) GetAppsReadyToUnstake(height int64, _ int) ([]*types.UnstakingActor, error) { - return p.GetActorsReadyToUnstake(schema.ApplicationActor, height) +func (p PostgresContext) GetAppsReadyToUnstake(height int64, _ int) ([]modules.IUnstakingActor, error) { + return p.GetActorsReadyToUnstake(types.ApplicationActor, height) } func (p PostgresContext) GetAppStatus(address []byte, height int64) (int, error) { - return p.GetActorStatus(schema.ApplicationActor, address, height) + return p.GetActorStatus(types.ApplicationActor, address, height) } func (p PostgresContext) SetAppUnstakingHeightAndStatus(address []byte, unstakingHeight int64, _ int) error { - return p.SetActorUnstakingHeightAndStatus(schema.ApplicationActor, address, unstakingHeight) + return p.SetActorUnstakingHeightAndStatus(types.ApplicationActor, address, unstakingHeight) } func (p PostgresContext) GetAppPauseHeightIfExists(address []byte, height int64) (int64, error) { - return p.GetActorPauseHeightIfExists(schema.ApplicationActor, address, height) + return p.GetActorPauseHeightIfExists(types.ApplicationActor, address, height) } func (p PostgresContext) SetAppStatusAndUnstakingHeightIfPausedBefore(pausedBeforeHeight, unstakingHeight int64, _ int) error { - return p.SetActorStatusAndUnstakingHeightIfPausedBefore(schema.ApplicationActor, pausedBeforeHeight, unstakingHeight) + return p.SetActorStatusAndUnstakingHeightIfPausedBefore(types.ApplicationActor, pausedBeforeHeight, unstakingHeight) } func (p PostgresContext) SetAppPauseHeight(address []byte, height int64) error { - return p.SetActorPauseHeight(schema.ApplicationActor, address, height) + return p.SetActorPauseHeight(types.ApplicationActor, address, height) } func (p PostgresContext) GetAppOutputAddress(operator []byte, height int64) ([]byte, error) { - return p.GetActorOutputAddress(schema.ApplicationActor, operator, height) + return p.GetActorOutputAddress(types.ApplicationActor, operator, height) } diff --git a/persistence/block.go b/persistence/block.go index 39789512b..170f81984 100644 --- a/persistence/block.go +++ b/persistence/block.go @@ -3,9 +3,8 @@ package persistence import ( "encoding/binary" "encoding/hex" + "github.com/pokt-network/pocket/persistence/types" "log" - - "github.com/pokt-network/pocket/persistence/schema" ) // OPTIMIZE(team): get from blockstore or keep in memory @@ -15,7 +14,7 @@ func (p PostgresContext) GetLatestBlockHeight() (latestHeight uint64, err error) return 0, err } - err = txn.QueryRow(ctx, schema.GetLatestBlockHeightQuery()).Scan(&latestHeight) + err = txn.QueryRow(ctx, types.GetLatestBlockHeightQuery()).Scan(&latestHeight) return } @@ -27,7 +26,7 @@ func (p PostgresContext) GetBlockHash(height int64) ([]byte, error) { } var hexHash string - err = txn.QueryRow(ctx, schema.GetBlockHashQuery(height)).Scan(&hexHash) + err = txn.QueryRow(ctx, types.GetBlockHashQuery(height)).Scan(&hexHash) if err != nil { return nil, err } @@ -62,7 +61,7 @@ func (p PostgresContext) InsertBlock(height uint64, hash string, proposerAddr [] return err } - _, err = tx.Exec(ctx, schema.InsertBlockQuery(height, hash, proposerAddr, quorumCert)) + _, err = tx.Exec(ctx, types.InsertBlockQuery(height, hash, proposerAddr, quorumCert)) return err } diff --git a/persistence/db.go b/persistence/db.go index f6da21772..519e17670 100644 --- a/persistence/db.go +++ b/persistence/db.go @@ -4,11 +4,11 @@ import ( "context" "errors" "fmt" + "github.com/pokt-network/pocket/persistence/types" "github.com/jackc/pgconn" "github.com/jackc/pgx/v4" "github.com/pokt-network/pocket/persistence/kvstore" - "github.com/pokt-network/pocket/persistence/schema" "github.com/pokt-network/pocket/shared/modules" ) @@ -25,11 +25,11 @@ const ( DuplicateObjectErrorCode = "42710" ) -var protocolActorSchemas = []schema.ProtocolActorSchema{ - schema.ApplicationActor, - schema.FishermanActor, - schema.ServiceNodeActor, - schema.ValidatorActor, +var protocolActorSchemas = []types.ProtocolActorSchema{ + types.ApplicationActor, + types.FishermanActor, + types.ServiceNodeActor, + types.ValidatorActor, } var _ modules.PersistenceRWContext = &PostgresContext{} @@ -121,7 +121,7 @@ func initializeAllTables(ctx context.Context, db *pgx.Conn) error { return nil } -func initializeProtocolActorTables(ctx context.Context, db *pgx.Conn, actor schema.ProtocolActorSchema) error { +func initializeProtocolActorTables(ctx context.Context, db *pgx.Conn, actor types.ProtocolActorSchema) error { if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, actor.GetTableName(), actor.GetTableSchema())); err != nil { return err } @@ -134,28 +134,28 @@ func initializeProtocolActorTables(ctx context.Context, db *pgx.Conn, actor sche } func initializeAccountTables(ctx context.Context, db *pgx.Conn) error { - if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, schema.AccountTableName, schema.AccountTableSchema)); err != nil { + if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, types.AccountTableName, types.AccountTableSchema)); err != nil { return err } - if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, schema.PoolTableName, schema.PoolTableSchema)); err != nil { + if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, types.PoolTableName, types.PoolTableSchema)); err != nil { return err } return nil } func initializeGovTables(ctx context.Context, db *pgx.Conn) error { - if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s`, fmt.Sprintf(CreateEnumType, schema.ValTypeName), schema.ValTypeEnumTypes)); err != nil { + if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s`, fmt.Sprintf(CreateEnumType, types.ValTypeName), types.ValTypeEnumTypes)); err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) && pgErr.Code != DuplicateObjectErrorCode { return err } } - if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, schema.ParamsTableName, schema.ParamsTableSchema)); err != nil { + if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, types.ParamsTableName, types.ParamsTableSchema)); err != nil { return err } - if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, schema.FlagsTableName, schema.FlagsTableSchema)); err != nil { + if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, types.FlagsTableName, types.FlagsTableSchema)); err != nil { return err } @@ -163,7 +163,7 @@ func initializeGovTables(ctx context.Context, db *pgx.Conn) error { } func initializeBlockTables(ctx context.Context, db *pgx.Conn) error { - if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, schema.BlockTableName, schema.BlockTableSchema)); err != nil { + if _, err := db.Exec(ctx, fmt.Sprintf(`%s %s %s %s`, CreateTable, IfNotExists, types.BlockTableName, types.BlockTableSchema)); err != nil { return err } return nil @@ -192,15 +192,15 @@ func (p PostgresContext) DebugClearAll() error { } } - if _, err = tx.Exec(ctx, schema.ClearAllGovParamsQuery()); err != nil { + if _, err = tx.Exec(ctx, types.ClearAllGovParamsQuery()); err != nil { return err } - if _, err = tx.Exec(ctx, schema.ClearAllGovFlagsQuery()); err != nil { + if _, err = tx.Exec(ctx, types.ClearAllGovFlagsQuery()); err != nil { return err } - if _, err = tx.Exec(ctx, schema.ClearAllBlocksQuery()); err != nil { + if _, err = tx.Exec(ctx, types.ClearAllBlocksQuery()); err != nil { return err } diff --git a/persistence/debugging.go b/persistence/debug.go similarity index 58% rename from persistence/debugging.go rename to persistence/debug.go index 7f6cbceee..3fdc583a4 100644 --- a/persistence/debugging.go +++ b/persistence/debug.go @@ -3,23 +3,31 @@ package persistence import ( "log" - "github.com/pokt-network/pocket/shared/types" + typesCons "github.com/pokt-network/pocket/consensus/types" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/codec" + "github.com/pokt-network/pocket/shared/debug" ) -func (m *persistenceModule) HandleDebugMessage(debugMessage *types.DebugMessage) error { +func (m *PersistenceModule) HandleDebugMessage(debugMessage *debug.DebugMessage) error { switch debugMessage.Action { - case types.DebugMessageAction_DEBUG_SHOW_LATEST_BLOCK_IN_STORE: + case debug.DebugMessageAction_DEBUG_SHOW_LATEST_BLOCK_IN_STORE: m.showLatestBlockInStore(debugMessage) - case types.DebugMessageAction_DEBUG_CLEAR_STATE: + case debug.DebugMessageAction_DEBUG_CLEAR_STATE: m.clearState(debugMessage) - m.populateGenesisState(m.GetBus().GetGenesis()) + g, err := m.InitGenesis(m.genesisPath) + if err != nil { + return err + } + m.populateGenesisState(g.(*types.PersistenceGenesisState)) default: log.Printf("Debug message not handled by persistence module: %s \n", debugMessage.Message) } return nil } -func (m *persistenceModule) showLatestBlockInStore(_ *types.DebugMessage) { +// TODO(olshansky): Create a shared interface `Block` to avoid the use of typesCons here. +func (m *PersistenceModule) showLatestBlockInStore(_ *debug.DebugMessage) { // TODO: Add an iterator to the `kvstore` and use that instead height := m.GetBus().GetConsensusModule().CurrentHeight() - 1 // -1 because we want the latest committed height blockBytes, err := m.GetBlockStore().Get(heightToBytes(int64(height))) @@ -27,14 +35,14 @@ func (m *persistenceModule) showLatestBlockInStore(_ *types.DebugMessage) { log.Printf("Error getting block %d from block store: %s \n", height, err) return } - codec := types.GetCodec() - block := &types.Block{} + codec := codec.GetCodec() + block := &typesCons.Block{} codec.Unmarshal(blockBytes, block) log.Printf("Block at height %d with %d transactions: %+v \n", height, len(block.Transactions), block) } -func (m *persistenceModule) clearState(_ *types.DebugMessage) { +func (m *PersistenceModule) clearState(_ *debug.DebugMessage) { context, err := m.NewRWContext(-1) defer context.Commit() if err != nil { diff --git a/shared/types/genesis/doc/CHANGELOG.md b/persistence/doc/CHANGELOG.md similarity index 100% rename from shared/types/genesis/doc/CHANGELOG.md rename to persistence/doc/CHANGELOG.md diff --git a/shared/types/genesis/doc/README.md b/persistence/doc/README.md similarity index 100% rename from shared/types/genesis/doc/README.md rename to persistence/doc/README.md diff --git a/persistence/fisherman.go b/persistence/fisherman.go index e0bd2f90d..6426957c0 100644 --- a/persistence/fisherman.go +++ b/persistence/fisherman.go @@ -4,16 +4,16 @@ import ( "encoding/hex" "log" - "github.com/pokt-network/pocket/persistence/schema" - "github.com/pokt-network/pocket/shared/types" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" ) func (p PostgresContext) GetFishermanExists(address []byte, height int64) (exists bool, err error) { - return p.GetExists(schema.FishermanActor, address, height) + return p.GetExists(types.FishermanActor, address, height) } func (p PostgresContext) GetFisherman(address []byte, height int64) (operator, publicKey, stakedTokens, serviceURL, outputAddress string, pausedHeight, unstakingHeight int64, chains []string, err error) { - actor, err := p.GetActor(schema.FishermanActor, address, height) + actor, err := p.GetActor(types.FishermanActor, address, height) operator = actor.Address publicKey = actor.PublicKey stakedTokens = actor.StakedTokens @@ -26,7 +26,7 @@ func (p PostgresContext) GetFisherman(address []byte, height int64) (operator, p } func (p PostgresContext) InsertFisherman(address []byte, publicKey []byte, output []byte, _ bool, _ int, serviceURL string, stakedAmount string, chains []string, pausedHeight int64, unstakingHeight int64) error { - return p.InsertActor(schema.FishermanActor, schema.BaseActor{ + return p.InsertActor(types.FishermanActor, types.BaseActor{ Address: hex.EncodeToString(address), PublicKey: hex.EncodeToString(publicKey), StakedTokens: stakedAmount, @@ -39,7 +39,7 @@ func (p PostgresContext) InsertFisherman(address []byte, publicKey []byte, outpu } func (p PostgresContext) UpdateFisherman(address []byte, serviceURL string, stakedAmount string, chains []string) error { - return p.UpdateActor(schema.FishermanActor, schema.BaseActor{ + return p.UpdateActor(types.FishermanActor, types.BaseActor{ Address: hex.EncodeToString(address), StakedTokens: stakedAmount, ActorSpecificParam: serviceURL, @@ -53,37 +53,37 @@ func (p PostgresContext) DeleteFisherman(_ []byte) error { } func (p PostgresContext) GetFishermanStakeAmount(height int64, address []byte) (string, error) { - return p.GetActorStakeAmount(schema.FishermanActor, address, height) + return p.GetActorStakeAmount(types.FishermanActor, address, height) } func (p PostgresContext) SetFishermanStakeAmount(address []byte, stakeAmount string) error { - return p.SetActorStakeAmount(schema.FishermanActor, address, stakeAmount) + return p.SetActorStakeAmount(types.FishermanActor, address, stakeAmount) } -func (p PostgresContext) GetFishermenReadyToUnstake(height int64, _ int) ([]*types.UnstakingActor, error) { - return p.GetActorsReadyToUnstake(schema.FishermanActor, height) +func (p PostgresContext) GetFishermenReadyToUnstake(height int64, _ int) ([]modules.IUnstakingActor, error) { + return p.GetActorsReadyToUnstake(types.FishermanActor, height) } func (p PostgresContext) GetFishermanStatus(address []byte, height int64) (status int, err error) { - return p.GetActorStatus(schema.FishermanActor, address, height) + return p.GetActorStatus(types.FishermanActor, address, height) } func (p PostgresContext) SetFishermanUnstakingHeightAndStatus(address []byte, unstakingHeight int64, _ int) error { - return p.SetActorUnstakingHeightAndStatus(schema.FishermanActor, address, unstakingHeight) + return p.SetActorUnstakingHeightAndStatus(types.FishermanActor, address, unstakingHeight) } func (p PostgresContext) GetFishermanPauseHeightIfExists(address []byte, height int64) (int64, error) { - return p.GetActorPauseHeightIfExists(schema.FishermanActor, address, height) + return p.GetActorPauseHeightIfExists(types.FishermanActor, address, height) } func (p PostgresContext) SetFishermanStatusAndUnstakingHeightIfPausedBefore(pausedBeforeHeight, unstakingHeight int64, _ int) error { - return p.SetActorStatusAndUnstakingHeightIfPausedBefore(schema.FishermanActor, pausedBeforeHeight, unstakingHeight) + return p.SetActorStatusAndUnstakingHeightIfPausedBefore(types.FishermanActor, pausedBeforeHeight, unstakingHeight) } func (p PostgresContext) SetFishermanPauseHeight(address []byte, height int64) error { - return p.SetActorPauseHeight(schema.FishermanActor, address, height) + return p.SetActorPauseHeight(types.FishermanActor, address, height) } func (p PostgresContext) GetFishermanOutputAddress(operator []byte, height int64) (output []byte, err error) { - return p.GetActorOutputAddress(schema.FishermanActor, operator, height) + return p.GetActorOutputAddress(types.FishermanActor, operator, height) } diff --git a/persistence/genesis.go b/persistence/genesis.go index 3989534fc..543e9a539 100644 --- a/persistence/genesis.go +++ b/persistence/genesis.go @@ -6,16 +6,15 @@ import ( "log" "math/big" - "github.com/pokt-network/pocket/persistence/schema" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" ) // TODO(andrew): Use `log.Fatalf` instead of `log.Fatal(fmt.Sprintf())`. // TODO(andrew): generalize with the `actors interface` // WARNING: This function crashes the process if there is an error populating the genesis state. -func (m *persistenceModule) populateGenesisState(state *genesis.GenesisState) { +func (m *PersistenceModule) populateGenesisState(state *types.PersistenceGenesisState) { log.Println("Populating genesis state...") // REFACTOR: This business logic should probably live in `types/genesis.go` @@ -38,108 +37,109 @@ func (m *persistenceModule) populateGenesisState(state *genesis.GenesisState) { if err != nil { log.Fatalf("an error occurred creating the rwContext for the genesis state: %s", err.Error()) } - // We commit the context at the end - for _, acc := range state.Utility.Accounts { - addrBz, err := hex.DecodeString(acc.Address) + if err != nil { + log.Fatal(fmt.Sprintf("an error occurred creating the rwContext for the genesis state: %s", err.Error())) + } + for _, acc := range state.GetAccs() { + addrBz, err := hex.DecodeString(acc.GetAddress()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", acc.Address)) + log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", acc.GetAddress())) } - err = rwContext.SetAccountAmount(addrBz, acc.Amount) + err = rwContext.SetAccountAmount(addrBz, acc.GetAmount()) if err != nil { log.Fatal(fmt.Sprintf("an error occurred inserting an acc in the genesis state: %s", err.Error())) } } - for _, pool := range state.Utility.Pools { - poolNameBytes := []byte(pool.Address) - err = rwContext.InsertPool(pool.Address, poolNameBytes, pool.Amount) + for _, pool := range state.GetAccPools() { + poolNameBytes := []byte(pool.GetAddress()) + err = rwContext.InsertPool(pool.GetAddress(), poolNameBytes, pool.GetAmount()) if err != nil { log.Fatal(fmt.Sprintf("an error occurred inserting an pool in the genesis state: %s", err.Error())) } } - // TODO(andrew): genericize the genesis population logic for actors; pocket/issues/163 - for _, act := range state.Utility.Applications { - addrBz, err := hex.DecodeString(act.Address) + for _, act := range state.GetApps() { // TODO (Andrew) genericize the genesis population logic for actors #149 + addrBz, err := hex.DecodeString(act.GetAddress()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", act.Address)) + log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", act.GetAddress())) } - pubKeyBz, err := hex.DecodeString(act.PublicKey) + pubKeyBz, err := hex.DecodeString(act.GetPublicKey()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting pubKey to bytes %s", act.PublicKey)) + log.Fatal(fmt.Sprintf("an error occurred converting pubKey to bytes %s", act.GetPublicKey())) } - outputBz, err := hex.DecodeString(act.Output) + outputBz, err := hex.DecodeString(act.GetOutput()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting output to bytes %s", act.Output)) + log.Fatal(fmt.Sprintf("an error occurred converting output to bytes %s", act.GetOutput())) } - err = rwContext.InsertApp(addrBz, pubKeyBz, outputBz, false, StakedStatus, act.GenericParam, act.StakedAmount, act.Chains, act.PausedHeight, act.UnstakingHeight) + err = rwContext.InsertApp(addrBz, pubKeyBz, outputBz, false, StakedStatus, act.GetGenericParam(), act.GetStakedAmount(), act.GetChains(), act.GetPausedHeight(), act.GetUnstakingHeight()) if err != nil { log.Fatal(fmt.Sprintf("an error occurred inserting an app in the genesis state: %s", err.Error())) } - if err = addValueToPool(genesis.Pool_Names_AppStakePool.String(), act.StakedAmount); err != nil { - log.Fatal(fmt.Sprintf("an error occurred inserting staked tokens into %s pool", genesis.Pool_Names_AppStakePool)) + if err = addValueToPool(types.Pool_Names_AppStakePool.String(), act.GetStakedAmount()); err != nil { + log.Fatal(fmt.Sprintf("an error occurred inserting staked tokens into %s pool: %s", types.Pool_Names_AppStakePool, err.Error())) } } - for _, act := range state.Utility.ServiceNodes { - addrBz, err := hex.DecodeString(act.Address) + for _, act := range state.GetNodes() { + addrBz, err := hex.DecodeString(act.GetAddress()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", act.Address)) + log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", act.GetAddress())) } - pubKeyBz, err := hex.DecodeString(act.PublicKey) + pubKeyBz, err := hex.DecodeString(act.GetPublicKey()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting pubKey to bytes %s", act.PublicKey)) + log.Fatal(fmt.Sprintf("an error occurred converting pubKey to bytes %s", act.GetPublicKey())) } - outputBz, err := hex.DecodeString(act.Output) + outputBz, err := hex.DecodeString(act.GetOutput()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting output to bytes %s", act.Output)) + log.Fatal(fmt.Sprintf("an error occurred converting output to bytes %s", act.GetOutput())) } - err = rwContext.InsertServiceNode(addrBz, pubKeyBz, outputBz, false, StakedStatus, act.GenericParam, act.StakedAmount, act.Chains, act.PausedHeight, act.UnstakingHeight) + err = rwContext.InsertServiceNode(addrBz, pubKeyBz, outputBz, false, StakedStatus, act.GetGenericParam(), act.GetStakedAmount(), act.GetChains(), act.GetPausedHeight(), act.GetUnstakingHeight()) if err != nil { log.Fatal(fmt.Sprintf("an error occurred inserting a service node in the genesis state: %s", err.Error())) } - if err = addValueToPool(genesis.Pool_Names_ServiceNodeStakePool.String(), act.StakedAmount); err != nil { - log.Fatal(fmt.Sprintf("an error occurred inserting staked tokens into %s pool", genesis.Pool_Names_ServiceNodeStakePool.String())) + if err = addValueToPool(types.Pool_Names_ServiceNodeStakePool.String(), act.GetStakedAmount()); err != nil { + log.Fatal(fmt.Sprintf("an error occurred inserting staked tokens into %s pool: %s", types.Pool_Names_ServiceNodeStakePool.String(), err.Error())) } } - for _, act := range state.Utility.Fishermen { - addrBz, err := hex.DecodeString(act.Address) + for _, act := range state.GetFish() { + addrBz, err := hex.DecodeString(act.GetAddress()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", act.Address)) + log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", act.GetAddress())) } - pubKeyBz, err := hex.DecodeString(act.PublicKey) + pubKeyBz, err := hex.DecodeString(act.GetPublicKey()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting pubKey to bytes %s", act.PublicKey)) + log.Fatal(fmt.Sprintf("an error occurred converting pubKey to bytes %s", act.GetPublicKey())) } - outputBz, err := hex.DecodeString(act.Output) + outputBz, err := hex.DecodeString(act.GetOutput()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting output to bytes %s", act.Output)) + log.Fatal(fmt.Sprintf("an error occurred converting output to bytes %s", act.GetOutput())) } - err = rwContext.InsertFisherman(addrBz, pubKeyBz, outputBz, false, StakedStatus, act.GenericParam, act.StakedAmount, act.Chains, act.PausedHeight, act.UnstakingHeight) + err = rwContext.InsertFisherman(addrBz, pubKeyBz, outputBz, false, StakedStatus, act.GetGenericParam(), act.GetStakedAmount(), act.GetChains(), act.GetPausedHeight(), act.GetUnstakingHeight()) if err != nil { log.Fatal(fmt.Sprintf("an error occurred inserting a fisherman in the genesis state: %s", err.Error())) } - if err = addValueToPool(genesis.Pool_Names_FishermanStakePool.String(), act.StakedAmount); err != nil { - log.Fatal(fmt.Sprintf("an error occurred inserting staked tokens into %s pool", genesis.Pool_Names_FishermanStakePool.String())) + if err = addValueToPool(types.Pool_Names_FishermanStakePool.String(), act.GetStakedAmount()); err != nil { + log.Fatal(fmt.Sprintf("an error occurred inserting staked tokens into %s pool: %s", types.Pool_Names_FishermanStakePool.String(), err.Error())) } } - for _, act := range state.Utility.Validators { - addrBz, err := hex.DecodeString(act.Address) + for _, act := range state.GetVals() { + addrBz, err := hex.DecodeString(act.GetAddress()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", act.Address)) + log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", act.GetAddress())) } - pubKeyBz, err := hex.DecodeString(act.PublicKey) + pubKeyBz, err := hex.DecodeString(act.GetPublicKey()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting pubKey to bytes %s", act.PublicKey)) + log.Fatal(fmt.Sprintf("an error occurred converting pubKey to bytes %s", act.GetPublicKey())) } - outputBz, err := hex.DecodeString(act.Output) + outputBz, err := hex.DecodeString(act.GetOutput()) if err != nil { - log.Fatal(fmt.Sprintf("an error occurred converting output to bytes %s", act.Output)) + log.Fatal(fmt.Sprintf("an error occurred converting output to bytes %s", act.GetOutput())) } - err = rwContext.InsertValidator(addrBz, pubKeyBz, outputBz, false, StakedStatus, act.GenericParam, act.StakedAmount, act.PausedHeight, act.UnstakingHeight) + err = rwContext.InsertValidator(addrBz, pubKeyBz, outputBz, false, StakedStatus, act.GetGenericParam(), act.GetStakedAmount(), act.GetPausedHeight(), act.GetUnstakingHeight()) if err != nil { log.Fatal(fmt.Sprintf("an error occurred inserting a validator in the genesis state: %s", err.Error())) } - if err = addValueToPool(genesis.Pool_Names_ValidatorStakePool.String(), act.StakedAmount); err != nil { - log.Fatal(fmt.Sprintf("an error occurred inserting staked tokens into %s pool", genesis.Pool_Names_ValidatorStakePool.String())) + if err = addValueToPool(types.Pool_Names_ValidatorStakePool.String(), act.GetStakedAmount()); err != nil { + log.Fatal(fmt.Sprintf("an error occurred inserting staked tokens into %s pool: %s", types.Pool_Names_ValidatorStakePool.String(), err.Error())) } } // TODO(team): use params from genesis file - not the hardcoded @@ -159,20 +159,21 @@ func (m *persistenceModule) populateGenesisState(state *genesis.GenesisState) { // TODO(pocket/issues/149): All of the functions below following a structure similar to `GetAll` // can easily be refactored and condensed into a single function using a generic type or a common // interface. -func (p PostgresContext) GetAllAccounts(height int64) (accs []*genesis.Account, err error) { +func (p PostgresContext) GetAllAccounts(height int64) (accs []modules.Account, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return nil, err } - rows, err := txn.Query(ctx, schema.SelectAccounts(height, schema.AccountTableName)) + rows, err := txn.Query(ctx, types.SelectAccounts(height, types.AccountTableName)) if err != nil { return nil, err } for rows.Next() { - acc := new(genesis.Account) + acc := new(types.Account) if err = rows.Scan(&acc.Address, &acc.Amount, &height); err != nil { return nil, err } + // acc.Address, err = address if err != nil { return nil, err } @@ -181,18 +182,18 @@ func (p PostgresContext) GetAllAccounts(height int64) (accs []*genesis.Account, return } -// TODO(andrew): Consolidate with `GetAllAccounts` -func (p PostgresContext) GetAllPools(height int64) (accs []*genesis.Account, err error) { +// CLEANUP: Consolidate with GetAllAccounts. +func (p PostgresContext) GetAllPools(height int64) (accs []modules.Account, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return nil, err } - rows, err := txn.Query(ctx, schema.SelectPools(height, schema.PoolTableName)) + rows, err := txn.Query(ctx, types.SelectPools(height, types.PoolTableName)) if err != nil { return nil, err } for rows.Next() { - pool := new(genesis.Account) + pool := new(types.Account) if err = rows.Scan(&pool.Address, &pool.Amount, &height); err != nil { return nil, err } @@ -201,18 +202,18 @@ func (p PostgresContext) GetAllPools(height int64) (accs []*genesis.Account, err return } -func (p PostgresContext) GetAllApps(height int64) (apps []*genesis.Actor, err error) { +func (p PostgresContext) GetAllApps(height int64) (apps []modules.Actor, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return nil, err } - rows, err := txn.Query(ctx, schema.ApplicationActor.GetAllQuery(height)) + rows, err := txn.Query(ctx, types.ApplicationActor.GetAllQuery(height)) if err != nil { return nil, err } - var actors []schema.BaseActor + var actors []types.BaseActor for rows.Next() { - var actor schema.BaseActor + var actor types.BaseActor actor, height, err = p.GetActorFromRow(rows) if err != nil { return @@ -221,27 +222,27 @@ func (p PostgresContext) GetAllApps(height int64) (apps []*genesis.Actor, err er } rows.Close() for _, actor := range actors { - actor, err = p.GetChainsForActor(ctx, txn, schema.ApplicationActor, actor, height) + actor, err = p.GetChainsForActor(ctx, txn, types.ApplicationActor, actor, height) if err != nil { return } - apps = append(apps, p.BaseActorToActor(actor, genesis.ActorType_App)) + apps = append(apps, p.BaseActorToActor(actor, types.ActorType_App)) } return } -func (p PostgresContext) GetAllValidators(height int64) (vals []*genesis.Actor, err error) { +func (p PostgresContext) GetAllValidators(height int64) (vals []modules.Actor, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return nil, err } - rows, err := txn.Query(ctx, schema.ValidatorActor.GetAllQuery(height)) + rows, err := txn.Query(ctx, types.ValidatorActor.GetAllQuery(height)) if err != nil { return nil, err } - var actors []schema.BaseActor + var actors []types.BaseActor for rows.Next() { - var actor schema.BaseActor + var actor types.BaseActor actor, height, err = p.GetActorFromRow(rows) if err != nil { return @@ -250,27 +251,27 @@ func (p PostgresContext) GetAllValidators(height int64) (vals []*genesis.Actor, } rows.Close() for _, actor := range actors { - actor, err = p.GetChainsForActor(ctx, txn, schema.ApplicationActor, actor, height) + actor, err = p.GetChainsForActor(ctx, txn, types.ApplicationActor, actor, height) if err != nil { return } - vals = append(vals, p.BaseActorToActor(actor, genesis.ActorType_Val)) + vals = append(vals, p.BaseActorToActor(actor, types.ActorType_Val)) } return } -func (p PostgresContext) GetAllServiceNodes(height int64) (sn []*genesis.Actor, err error) { +func (p PostgresContext) GetAllServiceNodes(height int64) (sn []modules.Actor, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return nil, err } - rows, err := txn.Query(ctx, schema.ServiceNodeActor.GetAllQuery(height)) + rows, err := txn.Query(ctx, types.ServiceNodeActor.GetAllQuery(height)) if err != nil { return nil, err } - var actors []schema.BaseActor + var actors []types.BaseActor for rows.Next() { - var actor schema.BaseActor + var actor types.BaseActor actor, height, err = p.GetActorFromRow(rows) if err != nil { return @@ -279,27 +280,27 @@ func (p PostgresContext) GetAllServiceNodes(height int64) (sn []*genesis.Actor, } rows.Close() for _, actor := range actors { - actor, err = p.GetChainsForActor(ctx, txn, schema.ServiceNodeActor, actor, height) + actor, err = p.GetChainsForActor(ctx, txn, types.ServiceNodeActor, actor, height) if err != nil { return } - sn = append(sn, p.BaseActorToActor(actor, genesis.ActorType_Node)) + sn = append(sn, p.BaseActorToActor(actor, types.ActorType_Node)) } return } -func (p PostgresContext) GetAllFishermen(height int64) (f []*genesis.Actor, err error) { +func (p PostgresContext) GetAllFishermen(height int64) (f []modules.Actor, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return nil, err } - rows, err := txn.Query(ctx, schema.FishermanActor.GetAllQuery(height)) + rows, err := txn.Query(ctx, types.FishermanActor.GetAllQuery(height)) if err != nil { return nil, err } - var actors []schema.BaseActor + var actors []types.BaseActor for rows.Next() { - var actor schema.BaseActor + var actor types.BaseActor actor, height, err = p.GetActorFromRow(rows) if err != nil { return @@ -308,17 +309,18 @@ func (p PostgresContext) GetAllFishermen(height int64) (f []*genesis.Actor, err } rows.Close() for _, actor := range actors { - actor, err = p.GetChainsForActor(ctx, txn, schema.FishermanActor, actor, height) + actor, err = p.GetChainsForActor(ctx, txn, types.FishermanActor, actor, height) if err != nil { return } - f = append(f, p.BaseActorToActor(actor, genesis.ActorType_Fish)) + f = append(f, p.BaseActorToActor(actor, types.ActorType_Fish)) } return } -func (p PostgresContext) BaseActorToActor(ba schema.BaseActor, actorType genesis.ActorType) *genesis.Actor { // TODO (Team) deprecate with interface #163 - actor := new(genesis.Actor) +// TODO (Team) deprecate with interface #163 as #163 is getting large +func (p PostgresContext) BaseActorToActor(ba types.BaseActor, actorType types.ActorType) *types.Actor { + actor := new(types.Actor) actor.ActorType = actorType actor.Address = ba.Address actor.PublicKey = ba.PublicKey diff --git a/persistence/gov.go b/persistence/gov.go index b19f82a91..ffca99aef 100644 --- a/persistence/gov.go +++ b/persistence/gov.go @@ -3,23 +3,21 @@ package persistence import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" "log" "strconv" - - "github.com/pokt-network/pocket/persistence/schema" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" ) // TODO (Team) BUG setting parameters twice on the same height causes issues. We need to move the schema away from 'end_height' and // more towards the height_constraint architecture func (p PostgresContext) GetBlocksPerSession(height int64) (int, error) { - return p.GetIntParam(types.BlocksPerSessionParamName, height) + return p.GetIntParam(modules.BlocksPerSessionParamName, height) } func (p PostgresContext) GetServiceNodesPerSessionAt(height int64) (int, error) { - return p.GetIntParam(types.ServiceNodesPerSessionParamName, height) + return p.GetIntParam(modules.ServiceNodesPerSessionParamName, height) } func (p PostgresContext) InitParams() error { @@ -27,22 +25,22 @@ func (p PostgresContext) InitParams() error { if err != nil { return err } - _, err = txn.Exec(ctx, schema.InsertParams(test_artifacts.DefaultParams(), p.Height)) + _, err = txn.Exec(ctx, types.InsertParams(types.DefaultParams(), p.Height)) return err } func (p PostgresContext) GetIntParam(paramName string, height int64) (int, error) { - v, _, err := getParamOrFlag[int](p, schema.ParamsTableName, paramName, height) + v, _, err := getParamOrFlag[int](p, types.ParamsTableName, paramName, height) return v, err } func (p PostgresContext) GetStringParam(paramName string, height int64) (string, error) { - v, _, err := getParamOrFlag[string](p, schema.ParamsTableName, paramName, height) + v, _, err := getParamOrFlag[string](p, types.ParamsTableName, paramName, height) return v, err } func (p PostgresContext) GetBytesParam(paramName string, height int64) (param []byte, err error) { - v, _, err := getParamOrFlag[[]byte](p, schema.ParamsTableName, paramName, height) + v, _, err := getParamOrFlag[[]byte](p, types.ParamsTableName, paramName, height) return v, err } @@ -56,15 +54,15 @@ func (p PostgresContext) InitFlags() error { } func (p PostgresContext) GetIntFlag(flagName string, height int64) (value int, enabled bool, err error) { - return getParamOrFlag[int](p, schema.FlagsTableName, flagName, height) + return getParamOrFlag[int](p, types.FlagsTableName, flagName, height) } func (p PostgresContext) GetStringFlag(flagName string, height int64) (value string, enabled bool, err error) { - return getParamOrFlag[string](p, schema.FlagsTableName, flagName, height) + return getParamOrFlag[string](p, types.FlagsTableName, flagName, height) } func (p PostgresContext) GetBytesFlag(flagName string, height int64) (value []byte, enabled bool, err error) { - return getParamOrFlag[[]byte](p, schema.FlagsTableName, flagName, height) + return getParamOrFlag[[]byte](p, types.FlagsTableName, flagName, height) } func (p PostgresContext) SetFlag(flagName string, value any, enabled bool) error { @@ -92,7 +90,7 @@ func (p PostgresContext) setParamOrFlag(name string, value any, enabled *bool) e // setParamOrFlag sets a param or a flag. // If `enabled` is nil, we are dealing with a param, otherwise it's a flag -func setParamOrFlag[T schema.SupportedParamTypes](p PostgresContext, paramName string, paramValue T, enabled *bool) error { +func setParamOrFlag[T types.SupportedParamTypes](p PostgresContext, paramName string, paramValue T, enabled *bool) error { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return err @@ -101,11 +99,11 @@ func setParamOrFlag[T schema.SupportedParamTypes](p PostgresContext, paramName s if err != nil { return err } - tableName := schema.ParamsTableName + tableName := types.ParamsTableName if enabled != nil { - tableName = schema.FlagsTableName + tableName = types.FlagsTableName } - if _, err = txn.Exec(ctx, schema.InsertParamOrFlag(tableName, paramName, height, paramValue, enabled)); err != nil { + if _, err = txn.Exec(ctx, types.InsertParamOrFlag(tableName, paramName, height, paramValue, enabled)); err != nil { return err } return nil @@ -118,8 +116,8 @@ func getParamOrFlag[T int | string | []byte](p PostgresContext, tableName, param } var stringVal string - row := txn.QueryRow(ctx, schema.GetParamOrFlagQuery(tableName, paramName, height)) - if tableName == schema.ParamsTableName { + row := txn.QueryRow(ctx, types.GetParamOrFlagQuery(tableName, paramName, height)) + if tableName == types.ParamsTableName { err = row.Scan(&stringVal) } else { err = row.Scan(&stringVal, &enabled) diff --git a/persistence/module.go b/persistence/module.go index beafae844..a7e434735 100644 --- a/persistence/module.go +++ b/persistence/module.go @@ -2,31 +2,53 @@ package persistence import ( "context" + "encoding/json" "fmt" + "io/ioutil" "log" + "github.com/pokt-network/pocket/persistence/types" + "github.com/jackc/pgx/v4" "github.com/pokt-network/pocket/persistence/kvstore" "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types/genesis" + "github.com/pokt-network/pocket/shared/test_artifacts" ) -var _ modules.PersistenceModule = &persistenceModule{} +var _ modules.PersistenceModule = &PersistenceModule{} var _ modules.PersistenceRWContext = &PostgresContext{} +var _ modules.PersistenceGenesisState = &types.PersistenceGenesisState{} +var _ modules.PersistenceConfig = &types.PersistenceConfig{} -type persistenceModule struct { +type PersistenceModule struct { bus modules.Bus postgresURL string nodeSchema string + genesisPath string blockStore kvstore.KVStore // INVESTIGATE: We may need to create a custom `BlockStore` package in the future // TECHDEBT: Need to implement context pooling (for writes), timeouts (for read & writes), etc... writeContext *PostgresContext // only one write context is allowed at a time } -func Create(cfg *genesis.Config, genesis *genesis.GenesisState) (modules.PersistenceModule, error) { - conn, err := connectToDatabase(cfg.Persistence.PostgresUrl, cfg.Persistence.NodeSchema) +const ( + PersistenceModuleName = "persistence" +) + +func Create(configPath, genesisPath string) (modules.PersistenceModule, error) { + m := new(PersistenceModule) + c, err := m.InitConfig(configPath) + if err != nil { + return nil, err + } + cfg := c.(*types.PersistenceConfig) + g, err := m.InitGenesis(genesisPath) + if err != nil { + return nil, err + } + genesis := g.(*types.PersistenceGenesisState) + conn, err := connectToDatabase(cfg.GetPostgresUrl(), cfg.GetNodeSchema()) if err != nil { return nil, err } @@ -35,15 +57,16 @@ func Create(cfg *genesis.Config, genesis *genesis.GenesisState) (modules.Persist } conn.Close(context.TODO()) - blockStore, err := initializeBlockStore(cfg.Persistence.BlockStorePath) + blockStore, err := initializeBlockStore(cfg.GetBlockStorePath()) if err != nil { return nil, err } - persistenceMod := &persistenceModule{ + persistenceMod := &PersistenceModule{ bus: nil, - postgresURL: cfg.Persistence.PostgresUrl, - nodeSchema: cfg.Persistence.NodeSchema, + postgresURL: cfg.GetPostgresUrl(), + nodeSchema: cfg.GetNodeSchema(), + genesisPath: genesisPath, blockStore: blockStore, writeContext: nil, } @@ -64,28 +87,64 @@ func Create(cfg *genesis.Config, genesis *genesis.GenesisState) (modules.Persist return persistenceMod, nil } -func (m *persistenceModule) Start() error { +func (m *PersistenceModule) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + data, err := ioutil.ReadFile(pathToConfigJSON) + if err != nil { + return + } + // over arching configuration file + rawJSON := make(map[string]json.RawMessage) + if err = json.Unmarshal(data, &rawJSON); err != nil { + log.Fatalf("[ERROR] an error occurred unmarshalling the %s file: %v", pathToConfigJSON, err.Error()) + } + // persistence specific configuration file + config = new(types.PersistenceConfig) + err = json.Unmarshal(rawJSON[m.GetModuleName()], config) + return +} + +func (m *PersistenceModule) InitGenesis(pathToGenesisJSON string) (genesis modules.IGenesis, err error) { + data, err := ioutil.ReadFile(pathToGenesisJSON) + if err != nil { + return + } + // over arching configuration file + rawJSON := make(map[string]json.RawMessage) + if err = json.Unmarshal(data, &rawJSON); err != nil { + log.Fatalf("[ERROR] an error occurred unmarshalling the %s file: %v", pathToGenesisJSON, err.Error()) + } + // persistence specific configuration file + genesis = new(types.PersistenceGenesisState) + err = json.Unmarshal(rawJSON[test_artifacts.GetGenesisFileName(m.GetModuleName())], genesis) + return +} + +func (m *PersistenceModule) Start() error { log.Println("Starting persistence module...") return nil } -func (m *persistenceModule) Stop() error { +func (m *PersistenceModule) Stop() error { m.blockStore.Stop() return nil } -func (m *persistenceModule) SetBus(bus modules.Bus) { +func (m *PersistenceModule) GetModuleName() string { + return PersistenceModuleName +} + +func (m *PersistenceModule) SetBus(bus modules.Bus) { m.bus = bus } -func (m *persistenceModule) GetBus() modules.Bus { +func (m *PersistenceModule) GetBus() modules.Bus { if m.bus == nil { log.Fatalf("PocketBus is not initialized") } return m.bus } -func (m *persistenceModule) NewRWContext(height int64) (modules.PersistenceRWContext, error) { +func (m *PersistenceModule) NewRWContext(height int64) (modules.PersistenceRWContext, error) { if m.writeContext != nil && !m.writeContext.DB.conn.IsClosed() { return nil, fmt.Errorf("write context already exists") } @@ -115,7 +174,7 @@ func (m *persistenceModule) NewRWContext(height int64) (modules.PersistenceRWCon } -func (m *persistenceModule) NewReadContext(height int64) (modules.PersistenceReadContext, error) { +func (m *PersistenceModule) NewReadContext(height int64) (modules.PersistenceReadContext, error) { conn, err := connectToDatabase(m.postgresURL, m.nodeSchema) if err != nil { return nil, err @@ -139,7 +198,7 @@ func (m *persistenceModule) NewReadContext(height int64) (modules.PersistenceRea }, nil } -func (m *persistenceModule) ResetContext() error { +func (m *PersistenceModule) ResetContext() error { if m.writeContext != nil { if !m.writeContext.DB.Tx.Conn().IsClosed() { if err := m.writeContext.Release(); err != nil { @@ -151,7 +210,7 @@ func (m *persistenceModule) ResetContext() error { return nil } -func (m *persistenceModule) GetBlockStore() kvstore.KVStore { +func (m *PersistenceModule) GetBlockStore() kvstore.KVStore { return m.blockStore } @@ -164,7 +223,7 @@ func initializeBlockStore(blockStorePath string) (kvstore.KVStore, error) { // TODO(drewsky): Simplify and externalize the logic for whether genesis should be populated and // move the if logic out of this file. -func (m *persistenceModule) shouldHydrateGenesisDb() (bool, error) { +func (m *PersistenceModule) shouldHydrateGenesisDb() (bool, error) { checkContext, err := m.NewReadContext(-1) if err != nil { return false, err diff --git a/persistence/proto/persistence_config.proto b/persistence/proto/persistence_config.proto new file mode 100644 index 000000000..6d5858afe --- /dev/null +++ b/persistence/proto/persistence_config.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; +package persistence; + +option go_package = "github.com/pokt-network/pocket/persistence/types"; + +message PersistenceConfig { + string postgres_url = 1; + string node_schema = 2; + string block_store_path = 3; +} \ No newline at end of file diff --git a/shared/types/genesis/proto/gov.proto b/persistence/proto/persistence_genesis.proto similarity index 91% rename from shared/types/genesis/proto/gov.proto rename to persistence/proto/persistence_genesis.proto index dc7e8ce5b..066898814 100644 --- a/shared/types/genesis/proto/gov.proto +++ b/persistence/proto/persistence_genesis.proto @@ -1,10 +1,50 @@ syntax = "proto3"; +package persistence; -package genesis; +option go_package = "github.com/pokt-network/pocket/persistence/types"; -// TODO (team) move to utility module #163 +message PersistenceGenesisState { + repeated Account pools = 1; + repeated Account accounts = 2; + repeated Actor applications = 3; + repeated Actor validators = 4; + repeated Actor service_nodes = 5; + repeated Actor fishermen = 6; + Params params = 7; +} -option go_package = "github.com/pokt-network/pocket/shared/types/genesis"; +message Account { + string address = 1; + string amount = 2; +} + +enum Pool_Names { + DAO = 0; + FeeCollector = 1; + AppStakePool = 2; + ValidatorStakePool = 3; + ServiceNodeStakePool = 4; + FishermanStakePool = 5; +} + +enum ActorType { + App = 0; + Node = 1; + Fish = 2; + Val = 3; +} + +message Actor { + ActorType actor_type = 1; + string address = 2; + string public_key = 3; + repeated string chains = 4; + string generic_param = 5; + string staked_amount = 6; + int64 paused_height = 7; + int64 unstaking_height = 8; + string output = 9; +} // DISCUSS(drewskey): Explore a more general purpose "feature flag" like approach for this. message Params { @@ -231,4 +271,4 @@ message Params { string message_unpause_service_node_fee_owner = 108; //@gotags: pokt:"val_type=STRING" string message_change_parameter_fee_owner = 109; -} +} \ No newline at end of file diff --git a/persistence/proto/unstaking.proto b/persistence/proto/unstaking.proto new file mode 100644 index 000000000..42848b3d8 --- /dev/null +++ b/persistence/proto/unstaking.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; +package persistence; + +option go_package = "github.com/pokt-network/pocket/persistence/types"; + +message UnstakingActor { + bytes address = 1; + string stake_amount = 2; + bytes output_address = 3; +} \ No newline at end of file diff --git a/persistence/service_node.go b/persistence/service_node.go index 746a6d69a..ba770f29e 100644 --- a/persistence/service_node.go +++ b/persistence/service_node.go @@ -4,16 +4,16 @@ import ( "encoding/hex" "log" - "github.com/pokt-network/pocket/persistence/schema" - "github.com/pokt-network/pocket/shared/types" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" ) func (p PostgresContext) GetServiceNodeExists(address []byte, height int64) (exists bool, err error) { - return p.GetExists(schema.ServiceNodeActor, address, height) + return p.GetExists(types.ServiceNodeActor, address, height) } func (p PostgresContext) GetServiceNode(address []byte, height int64) (operator, publicKey, stakedTokens, serviceURL, outputAddress string, pausedHeight, unstakingHeight int64, chains []string, err error) { - actor, err := p.GetActor(schema.ServiceNodeActor, address, height) + actor, err := p.GetActor(types.ServiceNodeActor, address, height) operator = actor.Address publicKey = actor.PublicKey stakedTokens = actor.StakedTokens @@ -26,7 +26,7 @@ func (p PostgresContext) GetServiceNode(address []byte, height int64) (operator, } func (p PostgresContext) InsertServiceNode(address []byte, publicKey []byte, output []byte, _ bool, _ int, serviceURL string, stakedAmount string, chains []string, pausedHeight int64, unstakingHeight int64) error { - return p.InsertActor(schema.ServiceNodeActor, schema.BaseActor{ + return p.InsertActor(types.ServiceNodeActor, types.BaseActor{ Address: hex.EncodeToString(address), PublicKey: hex.EncodeToString(publicKey), StakedTokens: stakedAmount, @@ -39,7 +39,7 @@ func (p PostgresContext) InsertServiceNode(address []byte, publicKey []byte, out } func (p PostgresContext) UpdateServiceNode(address []byte, serviceURL string, stakedAmount string, chains []string) error { - return p.UpdateActor(schema.ServiceNodeActor, schema.BaseActor{ + return p.UpdateActor(types.ServiceNodeActor, types.BaseActor{ Address: hex.EncodeToString(address), StakedTokens: stakedAmount, ActorSpecificParam: serviceURL, @@ -53,41 +53,41 @@ func (p PostgresContext) DeleteServiceNode(address []byte) error { } func (p PostgresContext) GetServiceNodeStakeAmount(height int64, address []byte) (string, error) { - return p.GetActorStakeAmount(schema.ServiceNodeActor, address, height) + return p.GetActorStakeAmount(types.ServiceNodeActor, address, height) } func (p PostgresContext) SetServiceNodeStakeAmount(address []byte, stakeAmount string) error { - return p.SetActorStakeAmount(schema.ServiceNodeActor, address, stakeAmount) + return p.SetActorStakeAmount(types.ServiceNodeActor, address, stakeAmount) } func (p PostgresContext) GetServiceNodeCount(chain string, height int64) (int, error) { panic("GetServiceNodeCount not implemented") } -func (p PostgresContext) GetServiceNodesReadyToUnstake(height int64, _ int) ([]*types.UnstakingActor, error) { - return p.GetActorsReadyToUnstake(schema.ServiceNodeActor, height) +func (p PostgresContext) GetServiceNodesReadyToUnstake(height int64, _ int) ([]modules.IUnstakingActor, error) { + return p.GetActorsReadyToUnstake(types.ServiceNodeActor, height) } func (p PostgresContext) GetServiceNodeStatus(address []byte, height int64) (int, error) { - return p.GetActorStatus(schema.ServiceNodeActor, address, height) + return p.GetActorStatus(types.ServiceNodeActor, address, height) } func (p PostgresContext) SetServiceNodeUnstakingHeightAndStatus(address []byte, unstakingHeight int64, _ int) error { - return p.SetActorUnstakingHeightAndStatus(schema.ServiceNodeActor, address, unstakingHeight) + return p.SetActorUnstakingHeightAndStatus(types.ServiceNodeActor, address, unstakingHeight) } func (p PostgresContext) GetServiceNodePauseHeightIfExists(address []byte, height int64) (int64, error) { - return p.GetActorPauseHeightIfExists(schema.ServiceNodeActor, address, height) + return p.GetActorPauseHeightIfExists(types.ServiceNodeActor, address, height) } func (p PostgresContext) SetServiceNodeStatusAndUnstakingHeightIfPausedBefore(pausedBeforeHeight, unstakingHeight int64, _ int) error { - return p.SetActorStatusAndUnstakingHeightIfPausedBefore(schema.ServiceNodeActor, pausedBeforeHeight, unstakingHeight) + return p.SetActorStatusAndUnstakingHeightIfPausedBefore(types.ServiceNodeActor, pausedBeforeHeight, unstakingHeight) } func (p PostgresContext) SetServiceNodePauseHeight(address []byte, height int64) error { - return p.SetActorPauseHeight(schema.ServiceNodeActor, address, height) + return p.SetActorPauseHeight(types.ServiceNodeActor, address, height) } func (p PostgresContext) GetServiceNodeOutputAddress(operator []byte, height int64) (output []byte, err error) { - return p.GetActorOutputAddress(schema.ServiceNodeActor, operator, height) + return p.GetActorOutputAddress(types.ServiceNodeActor, operator, height) } diff --git a/persistence/shared_sql.go b/persistence/shared_sql.go index 83225f69a..21c35ce2a 100644 --- a/persistence/shared_sql.go +++ b/persistence/shared_sql.go @@ -4,14 +4,15 @@ import ( "context" "encoding/hex" "fmt" - "github.com/jackc/pgx/v4" - "github.com/pokt-network/pocket/persistence/schema" - "github.com/pokt-network/pocket/shared/types" + "github.com/jackc/pgx/v4" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" ) // IMPROVE(team): Move this into a proto enum. We are not using `iota` for the time being // for the purpose of being explicit: https://github.com/pokt-network/pocket/pull/140#discussion_r939731342 +// TODO Cleanup with #149 const ( UndefinedStakingStatus = 0 UnstakingStatus = 1 @@ -30,7 +31,7 @@ func UnstakingHeightToStatus(unstakingHeight int64) int32 { } } -func (p *PostgresContext) GetExists(actorSchema schema.ProtocolActorSchema, address []byte, height int64) (exists bool, err error) { +func (p *PostgresContext) GetExists(actorSchema types.ProtocolActorSchema, address []byte, height int64) (exists bool, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return @@ -43,7 +44,7 @@ func (p *PostgresContext) GetExists(actorSchema schema.ProtocolActorSchema, addr return } -func (p *PostgresContext) GetActor(actorSchema schema.ProtocolActorSchema, address []byte, height int64) (actor schema.BaseActor, err error) { +func (p *PostgresContext) GetActor(actorSchema types.ProtocolActorSchema, address []byte, height int64) (actor types.BaseActor, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return @@ -56,7 +57,7 @@ func (p *PostgresContext) GetActor(actorSchema schema.ProtocolActorSchema, addre return p.GetChainsForActor(ctx, txn, actorSchema, actor, height) } -func (p *PostgresContext) GetActorFromRow(row pgx.Row) (actor schema.BaseActor, height int64, err error) { +func (p *PostgresContext) GetActorFromRow(row pgx.Row) (actor types.BaseActor, height int64, err error) { err = row.Scan( &actor.Address, &actor.PublicKey, &actor.StakedTokens, &actor.ActorSpecificParam, &actor.OutputAddress, &actor.PausedHeight, &actor.UnstakingHeight, @@ -67,9 +68,9 @@ func (p *PostgresContext) GetActorFromRow(row pgx.Row) (actor schema.BaseActor, func (p *PostgresContext) GetChainsForActor( ctx context.Context, txn pgx.Tx, - actorSchema schema.ProtocolActorSchema, - actor schema.BaseActor, - height int64) (a schema.BaseActor, err error) { + actorSchema types.ProtocolActorSchema, + actor types.BaseActor, + height int64) (a types.BaseActor, err error) { if actorSchema.GetChainsTableName() == "" { return actor, nil } @@ -95,7 +96,7 @@ func (p *PostgresContext) GetChainsForActor( return actor, nil } -func (p *PostgresContext) InsertActor(actorSchema schema.ProtocolActorSchema, actor schema.BaseActor) error { +func (p *PostgresContext) InsertActor(actorSchema types.ProtocolActorSchema, actor types.BaseActor) error { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return err @@ -113,7 +114,7 @@ func (p *PostgresContext) InsertActor(actorSchema schema.ProtocolActorSchema, ac return err } -func (p *PostgresContext) UpdateActor(actorSchema schema.ProtocolActorSchema, actor schema.BaseActor) error { +func (p *PostgresContext) UpdateActor(actorSchema types.ProtocolActorSchema, actor types.BaseActor) error { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return err @@ -130,7 +131,7 @@ func (p *PostgresContext) UpdateActor(actorSchema schema.ProtocolActorSchema, ac chainsTableName := actorSchema.GetChainsTableName() if chainsTableName != "" && actor.Chains != nil { - if _, err = txn.Exec(ctx, schema.NullifyChains(actor.Address, height, chainsTableName)); err != nil { + if _, err = txn.Exec(ctx, types.NullifyChains(actor.Address, height, chainsTableName)); err != nil { return err } if _, err = txn.Exec(ctx, actorSchema.UpdateChainsQuery(actor.Address, actor.Chains, height)); err != nil { @@ -141,7 +142,7 @@ func (p *PostgresContext) UpdateActor(actorSchema schema.ProtocolActorSchema, ac return nil } -func (p *PostgresContext) GetActorsReadyToUnstake(actorSchema schema.ProtocolActorSchema, height int64) (actors []*types.UnstakingActor, err error) { +func (p *PostgresContext) GetActorsReadyToUnstake(actorSchema types.ProtocolActorSchema, height int64) (actors []modules.IUnstakingActor, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return nil, err @@ -154,24 +155,20 @@ func (p *PostgresContext) GetActorsReadyToUnstake(actorSchema schema.ProtocolAct defer rows.Close() for rows.Next() { - // IMPROVE(team): Can we refactor so we pass the unstaking actor fields directly? - unstakingActor := types.UnstakingActor{} - var addr, output string - if err = rows.Scan(&addr, &unstakingActor.StakeAmount, &output); err != nil { + unstakingActor := &types.UnstakingActor{} + var addr, output, stakeAmount string + if err = rows.Scan(&addr, &stakeAmount, &output); err != nil { return } - if unstakingActor.Address, err = hex.DecodeString(addr); err != nil { - return nil, err - } - if unstakingActor.OutputAddress, err = hex.DecodeString(output); err != nil { - return nil, err - } - actors = append(actors, &unstakingActor) + unstakingActor.SetAddress(addr) + unstakingActor.SetStakeAmount(stakeAmount) + unstakingActor.SetOutputAddress(output) + actors = append(actors, unstakingActor) } return } -func (p *PostgresContext) GetActorStatus(actorSchema schema.ProtocolActorSchema, address []byte, height int64) (int, error) { +func (p *PostgresContext) GetActorStatus(actorSchema types.ProtocolActorSchema, address []byte, height int64) (int, error) { var unstakingHeight int64 ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { @@ -192,7 +189,7 @@ func (p *PostgresContext) GetActorStatus(actorSchema schema.ProtocolActorSchema, } } -func (p *PostgresContext) SetActorUnstakingHeightAndStatus(actorSchema schema.ProtocolActorSchema, address []byte, unstakingHeight int64) error { +func (p *PostgresContext) SetActorUnstakingHeightAndStatus(actorSchema types.ProtocolActorSchema, address []byte, unstakingHeight int64) error { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return err @@ -207,20 +204,20 @@ func (p *PostgresContext) SetActorUnstakingHeightAndStatus(actorSchema schema.Pr return err } -func (p *PostgresContext) GetActorPauseHeightIfExists(actorSchema schema.ProtocolActorSchema, address []byte, height int64) (pausedHeight int64, err error) { +func (p *PostgresContext) GetActorPauseHeightIfExists(actorSchema types.ProtocolActorSchema, address []byte, height int64) (pausedHeight int64, err error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { - return schema.DefaultBigInt, err + return types.DefaultBigInt, err } if err := txn.QueryRow(ctx, actorSchema.GetPausedHeightQuery(hex.EncodeToString(address), height)).Scan(&pausedHeight); err != nil { - return schema.DefaultBigInt, err + return types.DefaultBigInt, err } return pausedHeight, nil } -func (p PostgresContext) SetActorStatusAndUnstakingHeightIfPausedBefore(actorSchema schema.ProtocolActorSchema, pausedBeforeHeight, unstakingHeight int64) error { +func (p PostgresContext) SetActorStatusAndUnstakingHeightIfPausedBefore(actorSchema types.ProtocolActorSchema, pausedBeforeHeight, unstakingHeight int64) error { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return err @@ -235,7 +232,7 @@ func (p PostgresContext) SetActorStatusAndUnstakingHeightIfPausedBefore(actorSch return err } -func (p PostgresContext) SetActorPauseHeight(actorSchema schema.ProtocolActorSchema, address []byte, pauseHeight int64) error { +func (p PostgresContext) SetActorPauseHeight(actorSchema types.ProtocolActorSchema, address []byte, pauseHeight int64) error { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return err @@ -250,7 +247,7 @@ func (p PostgresContext) SetActorPauseHeight(actorSchema schema.ProtocolActorSch return err } -func (p PostgresContext) SetActorStakeAmount(actorSchema schema.ProtocolActorSchema, address []byte, stakeAmount string) error { +func (p PostgresContext) SetActorStakeAmount(actorSchema types.ProtocolActorSchema, address []byte, stakeAmount string) error { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return err @@ -264,7 +261,7 @@ func (p PostgresContext) SetActorStakeAmount(actorSchema schema.ProtocolActorSch return err } -func (p PostgresContext) GetActorOutputAddress(actorSchema schema.ProtocolActorSchema, operatorAddr []byte, height int64) ([]byte, error) { +func (p PostgresContext) GetActorOutputAddress(actorSchema types.ProtocolActorSchema, operatorAddr []byte, height int64) ([]byte, error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { return nil, err @@ -278,15 +275,15 @@ func (p PostgresContext) GetActorOutputAddress(actorSchema schema.ProtocolActorS return hex.DecodeString(outputAddr) } -func (p PostgresContext) GetActorStakeAmount(actorSchema schema.ProtocolActorSchema, address []byte, height int64) (string, error) { +func (p PostgresContext) GetActorStakeAmount(actorSchema types.ProtocolActorSchema, address []byte, height int64) (string, error) { ctx, txn, err := p.DB.GetCtxAndTxn() if err != nil { - return types.EmptyString, err + return "", err } var stakeAmount string if err := txn.QueryRow(ctx, actorSchema.GetStakeAmountQuery(hex.EncodeToString(address), height)).Scan(&stakeAmount); err != nil { - return types.EmptyString, err + return "", err } return stakeAmount, nil } diff --git a/persistence/test/account_test.go b/persistence/test/account_test.go index 9fa67ae16..d6146581f 100644 --- a/persistence/test/account_test.go +++ b/persistence/test/account_test.go @@ -3,6 +3,8 @@ package test import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" "log" "math/big" "math/rand" @@ -10,14 +12,11 @@ import ( "github.com/pokt-network/pocket/persistence" "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" - - // TODO(andrew): Find all places where we import genesis twice (like below) and update the imports appropriately. - "github.com/pokt-network/pocket/shared/types/genesis" - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" "github.com/stretchr/testify/require" ) +// TODO(andrew): Find all places where we import twice and update the imports appropriately. + func FuzzAccountAmount(f *testing.F) { db := NewFuzzTestPostgresContext(f, 0) operations := []string{ @@ -294,9 +293,8 @@ func TestSubPoolAmount(t *testing.T) { func TestGetAllAccounts(t *testing.T) { db := NewTestPostgresContext(t, 0) - - updateAccount := func(db *persistence.PostgresContext, acc *genesis.Account) error { - if addr, err := hex.DecodeString(acc.Address); err == nil { + updateAccount := func(db *persistence.PostgresContext, acc modules.Account) error { + if addr, err := hex.DecodeString(acc.GetAddress()); err == nil { return nil } else { return db.AddAccountAmount(addr, "10") @@ -310,8 +308,8 @@ func TestGetAllAccounts(t *testing.T) { func TestGetAllPools(t *testing.T) { db := NewTestPostgresContext(t, 0) - updatePool := func(db *persistence.PostgresContext, pool *genesis.Account) error { - return db.AddPoolAmount(pool.Address, "10") + updatePool := func(db *persistence.PostgresContext, pool modules.Account) error { + return db.AddPoolAmount(pool.GetAddress(), "10") } getAllActorsTest(t, db, db.GetAllPools, createAndInsertNewPool, updatePool, 6) @@ -319,7 +317,7 @@ func TestGetAllPools(t *testing.T) { // --- Helpers --- -func createAndInsertNewAccount(db *persistence.PostgresContext) (*genesis.Account, error) { +func createAndInsertNewAccount(db *persistence.PostgresContext) (modules.Account, error) { account := newTestAccount(nil) addr, err := hex.DecodeString(account.Address) if err != nil { @@ -328,31 +326,31 @@ func createAndInsertNewAccount(db *persistence.PostgresContext) (*genesis.Accoun return &account, db.SetAccountAmount(addr, DefaultAccountAmount) } -func createAndInsertNewPool(db *persistence.PostgresContext) (*genesis.Account, error) { +func createAndInsertNewPool(db *persistence.PostgresContext) (modules.Account, error) { pool := newTestPool(nil) return &pool, db.SetPoolAmount(pool.Address, DefaultAccountAmount) } -// TODO(andrew): consolidate newTestAccount and newTestPool into one function +// TODO(olshansky): consolidate newTestAccount and newTestPool into one function // Note to the reader: lack of consistency between []byte and string in addresses will be consolidated. -func newTestAccount(t *testing.T) typesGenesis.Account { +func newTestAccount(t *testing.T) types.Account { addr, err := crypto.GenerateAddress() if t != nil { require.NoError(t, err) } - return typesGenesis.Account{ + return types.Account{ Address: hex.EncodeToString(addr), Amount: DefaultAccountAmount, } } -func newTestPool(t *testing.T) typesGenesis.Account { +func newTestPool(t *testing.T) types.Account { addr, err := crypto.GenerateAddress() if t != nil { require.NoError(t, err) } - return typesGenesis.Account{ + return types.Account{ Address: hex.EncodeToString(addr), Amount: DefaultAccountAmount, } diff --git a/persistence/test/application_test.go b/persistence/test/application_test.go index f3d0bb74e..51033f4b1 100644 --- a/persistence/test/application_test.go +++ b/persistence/test/application_test.go @@ -3,21 +3,20 @@ package test import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/persistence/types" "log" "testing" "github.com/pokt-network/pocket/persistence" - "github.com/pokt-network/pocket/persistence/schema" "github.com/pokt-network/pocket/shared/crypto" - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" "github.com/stretchr/testify/require" ) func FuzzApplication(f *testing.F) { fuzzSingleProtocolActor(f, - NewTestGenericActor(schema.ApplicationActor, newTestApp), - GetGenericActor(schema.ApplicationActor, getTestApp), - schema.ApplicationActor) + NewTestGenericActor(types.ApplicationActor, newTestApp), + GetGenericActor(types.ApplicationActor, getTestApp), + types.ApplicationActor) } func TestInsertAppAndExists(t *testing.T) { @@ -116,13 +115,13 @@ func TestGetAppsReadyToUnstake(t *testing.T) { unstakingApps, err := db.GetAppsReadyToUnstake(0, persistence.UnstakingStatus) require.NoError(t, err) require.Equal(t, 1, len(unstakingApps), "wrong number of actors ready to unstake at height 0") - require.Equal(t, app.Address, hex.EncodeToString(unstakingApps[0].Address), "unexpected application actor returned") + require.Equal(t, app.Address, hex.EncodeToString(unstakingApps[0].GetAddress()), "unexpected application actor returned") // Check unstaking apps at height 1 unstakingApps, err = db.GetAppsReadyToUnstake(1, persistence.UnstakingStatus) require.NoError(t, err) require.Equal(t, 2, len(unstakingApps), "wrong number of actors ready to unstake at height 1") - require.ElementsMatch(t, [][]byte{addrBz2, addrBz3}, [][]byte{unstakingApps[0].Address, unstakingApps[1].Address}) + require.ElementsMatch(t, [][]byte{addrBz2, addrBz3}, [][]byte{unstakingApps[0].GetAddress(), unstakingApps[1].GetAddress()}) } func TestGetAppStatus(t *testing.T) { @@ -201,7 +200,7 @@ func TestGetAppOutputAddress(t *testing.T) { require.Equal(t, hex.EncodeToString(output), app.Output, "unexpected output address") } -func newTestApp() (*typesGenesis.Actor, error) { +func newTestApp() (*types.Actor, error) { operatorKey, err := crypto.GeneratePublicKey() if err != nil { return nil, err @@ -212,7 +211,7 @@ func newTestApp() (*typesGenesis.Actor, error) { return nil, err } - return &typesGenesis.Actor{ + return &types.Actor{ Address: hex.EncodeToString(operatorKey.Address()), PublicKey: hex.EncodeToString(operatorKey.Bytes()), Chains: DefaultChains, @@ -247,7 +246,7 @@ func TestGetSetStakeAmount(t *testing.T) { require.Equal(t, newStakeAmount, stakeAmountAfter, "unexpected status") } -func createAndInsertDefaultTestApp(db *persistence.PostgresContext) (*typesGenesis.Actor, error) { +func createAndInsertDefaultTestApp(db *persistence.PostgresContext) (*types.Actor, error) { app, err := newTestApp() if err != nil { return nil, err @@ -279,13 +278,13 @@ func createAndInsertDefaultTestApp(db *persistence.PostgresContext) (*typesGenes DefaultUnstakingHeight) } -func getTestApp(db *persistence.PostgresContext, address []byte) (*typesGenesis.Actor, error) { +func getTestApp(db *persistence.PostgresContext, address []byte) (*types.Actor, error) { operator, publicKey, stakedTokens, maxRelays, outputAddress, pauseHeight, unstakingHeight, chains, err := db.GetApp(address, db.Height) if err != nil { return nil, err } - return &typesGenesis.Actor{ + return &types.Actor{ Address: operator, PublicKey: publicKey, Chains: chains, diff --git a/persistence/test/fisherman_test.go b/persistence/test/fisherman_test.go index 83e984004..6249f6e7a 100644 --- a/persistence/test/fisherman_test.go +++ b/persistence/test/fisherman_test.go @@ -3,21 +3,22 @@ package test import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/persistence/types" "log" "testing" "github.com/pokt-network/pocket/persistence" - "github.com/pokt-network/pocket/persistence/schema" "github.com/pokt-network/pocket/shared/crypto" - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" "github.com/stretchr/testify/require" ) +// TODO(andrew): Rename `addrBz` to `fishAddrBz` so tests are easier to read and understand. Ditto in all other locations. + func FuzzFisherman(f *testing.F) { fuzzSingleProtocolActor(f, - NewTestGenericActor(schema.FishermanActor, newTestFisherman), - GetGenericActor(schema.FishermanActor, getTestFisherman), - schema.FishermanActor) + NewTestGenericActor(types.FishermanActor, newTestFisherman), + GetGenericActor(types.FishermanActor, getTestFisherman), + types.FishermanActor) } func TestGetSetFishermanStakeAmount(t *testing.T) { @@ -36,7 +37,6 @@ func TestInsertFishermanAndExists(t *testing.T) { fisherman2, err := createAndInsertDefaultTestFisherman(db) require.NoError(t, err) - // TODO(andrew): Rename `addrBz` to `fishAddrBz` so tests are easier to read and understand. Ditto in all other locations. addrBz, err := hex.DecodeString(fisherman.Address) require.NoError(t, err) addrBz2, err := hex.DecodeString(fisherman2.Address) @@ -118,19 +118,17 @@ func TestGetFishermenReadyToUnstake(t *testing.T) { err = db.SetFishermanUnstakingHeightAndStatus(addrBz3, 1, persistence.UnstakingStatus) require.NoError(t, err) - // TODO(andrew): Replace `fisherman` with `fishermans` for grammatic correctness - // Check unstaking fishermans at height 0 unstakingFishermen, err := db.GetFishermenReadyToUnstake(0, persistence.UnstakingStatus) require.NoError(t, err) require.Equal(t, 1, len(unstakingFishermen), "wrong number of actors ready to unstake at height 0") - require.Equal(t, fisherman.Address, hex.EncodeToString(unstakingFishermen[0].Address), "unexpected fishermanlication actor returned") + require.Equal(t, fisherman.Address, hex.EncodeToString(unstakingFishermen[0].GetAddress()), "unexpected fishermanlication actor returned") // Check unstaking fishermans at height 1 unstakingFishermen, err = db.GetFishermenReadyToUnstake(1, persistence.UnstakingStatus) require.NoError(t, err) require.Equal(t, 2, len(unstakingFishermen), "wrong number of actors ready to unstake at height 1") - require.ElementsMatch(t, [][]byte{addrBz2, addrBz3}, [][]byte{unstakingFishermen[0].Address, unstakingFishermen[1].Address}) + require.ElementsMatch(t, [][]byte{addrBz2, addrBz3}, [][]byte{unstakingFishermen[0].GetAddress(), unstakingFishermen[1].GetAddress()}) } func TestGetFishermanStatus(t *testing.T) { @@ -214,7 +212,7 @@ func TestGetFishermanOutputAddress(t *testing.T) { require.Equal(t, hex.EncodeToString(output), fisherman.Output, "unexpected output address") } -func newTestFisherman() (*typesGenesis.Actor, error) { +func newTestFisherman() (*types.Actor, error) { operatorKey, err := crypto.GeneratePublicKey() if err != nil { return nil, err @@ -225,7 +223,7 @@ func newTestFisherman() (*typesGenesis.Actor, error) { return nil, err } - return &typesGenesis.Actor{ + return &types.Actor{ Address: hex.EncodeToString(operatorKey.Address()), PublicKey: hex.EncodeToString(operatorKey.Bytes()), Chains: DefaultChains, @@ -237,7 +235,7 @@ func newTestFisherman() (*typesGenesis.Actor, error) { }, nil } -func createAndInsertDefaultTestFisherman(db *persistence.PostgresContext) (*typesGenesis.Actor, error) { +func createAndInsertDefaultTestFisherman(db *persistence.PostgresContext) (*types.Actor, error) { fisherman, err := newTestFisherman() if err != nil { return nil, err @@ -267,7 +265,7 @@ func createAndInsertDefaultTestFisherman(db *persistence.PostgresContext) (*type DefaultUnstakingHeight) } -func getTestFisherman(db *persistence.PostgresContext, address []byte) (*typesGenesis.Actor, error) { +func getTestFisherman(db *persistence.PostgresContext, address []byte) (*types.Actor, error) { operator, publicKey, stakedTokens, serviceURL, outputAddress, pauseHeight, unstakingHeight, chains, err := db.GetFisherman(address, db.Height) if err != nil { return nil, err @@ -288,7 +286,7 @@ func getTestFisherman(db *persistence.PostgresContext, address []byte) (*typesGe return nil, err } - return &typesGenesis.Actor{ + return &types.Actor{ Address: hex.EncodeToString(operatorAddr), PublicKey: hex.EncodeToString(operatorPubKey), Chains: chains, diff --git a/persistence/test/generic_test.go b/persistence/test/generic_test.go index fa68f60eb..c29e0d528 100644 --- a/persistence/test/generic_test.go +++ b/persistence/test/generic_test.go @@ -2,19 +2,21 @@ package test import ( "encoding/hex" + "github.com/pokt-network/pocket/persistence/types" "reflect" "testing" "github.com/pokt-network/pocket/persistence" - "github.com/pokt-network/pocket/persistence/schema" "github.com/stretchr/testify/require" ) +// TODO(andrew): Be consistent with `GenericParam` and `ActorSpecificParam` throughout the codebase; preferably the latter. + func GetGenericActor[T any]( - protocolActorSchema schema.ProtocolActorSchema, + protocolActorSchema types.ProtocolActorSchema, getActor func(*persistence.PostgresContext, []byte) (T, error), -) func(*persistence.PostgresContext, string) (*schema.BaseActor, error) { - return func(db *persistence.PostgresContext, address string) (*schema.BaseActor, error) { +) func(*persistence.PostgresContext, string) (*types.BaseActor, error) { + return func(db *persistence.PostgresContext, address string) (*types.BaseActor, error) { addr, err := hex.DecodeString(address) if err != nil { return nil, err @@ -28,11 +30,11 @@ func GetGenericActor[T any]( } } -func NewTestGenericActor[T any](protocolActorSchema schema.ProtocolActorSchema, newActor func() (T, error)) func() (schema.BaseActor, error) { - return func() (schema.BaseActor, error) { +func NewTestGenericActor[T any](protocolActorSchema types.ProtocolActorSchema, newActor func() (T, error)) func() (types.BaseActor, error) { + return func() (types.BaseActor, error) { actor, err := newActor() if err != nil { - return schema.BaseActor{}, err + return types.BaseActor{}, err } return getActorValues(protocolActorSchema, reflect.Indirect(reflect.ValueOf(actor))), nil } @@ -41,9 +43,9 @@ func NewTestGenericActor[T any](protocolActorSchema schema.ProtocolActorSchema, func getAllActorsTest[T any]( t *testing.T, db *persistence.PostgresContext, - getAllActors func(height int64) ([]*T, error), - createTestActor func(*persistence.PostgresContext) (*T, error), - updateActor func(*persistence.PostgresContext, *T) error, + getAllActors func(height int64) ([]T, error), + createTestActor func(*persistence.PostgresContext) (T, error), + updateActor func(*persistence.PostgresContext, T) error, initialCount int, ) { // The default test state contains `initialCount` actors @@ -156,17 +158,16 @@ func getTestGetSetStakeAmountTest[T any]( require.Equal(t, newStakeAmount, stakeAmountAfter, "unexpected status") } -func getActorValues(_ schema.ProtocolActorSchema, actorValue reflect.Value) schema.BaseActor { +func getActorValues(_ types.ProtocolActorSchema, actorValue reflect.Value) types.BaseActor { chains := make([]string, 0) if actorValue.FieldByName("Chains").Kind() != 0 { chains = actorValue.FieldByName("Chains").Interface().([]string) } - return schema.BaseActor{ - Address: actorValue.FieldByName("Address").String(), - PublicKey: actorValue.FieldByName("PublicKey").String(), - StakedTokens: actorValue.FieldByName("StakedAmount").String(), - // TODO(andrew): Be consistent with `GenericParam` and `ActorSpecificParam` throughout the codebase; preferably the latter. + return types.BaseActor{ + Address: actorValue.FieldByName("Address").String(), + PublicKey: actorValue.FieldByName("PublicKey").String(), + StakedTokens: actorValue.FieldByName("StakedAmount").String(), ActorSpecificParam: actorValue.FieldByName("GenericParam").String(), OutputAddress: actorValue.FieldByName("Output").String(), PausedHeight: int64(actorValue.FieldByName("PausedHeight").Int()), diff --git a/persistence/test/gov_test.go b/persistence/test/gov_test.go index 28ea4e963..21815b279 100644 --- a/persistence/test/gov_test.go +++ b/persistence/test/gov_test.go @@ -2,9 +2,9 @@ package test import ( "encoding/hex" + "github.com/pokt-network/pocket/shared/modules" "testing" - "github.com/pokt-network/pocket/shared/types" "github.com/stretchr/testify/require" ) @@ -22,13 +22,13 @@ func TestGetSetIntParam(t *testing.T) { newMaxChains := 42 - err = db.SetParam(types.AppMaxChainsParamName, newMaxChains) + err = db.SetParam(modules.AppMaxChainsParamName, newMaxChains) require.NoError(t, err) height, err := db.GetHeight() require.NoError(t, err) - maxChains, err := db.GetIntParam(types.AppMaxChainsParamName, height) + maxChains, err := db.GetIntParam(modules.AppMaxChainsParamName, height) require.NoError(t, err) require.Equal(t, newMaxChains, maxChains) @@ -42,13 +42,13 @@ func TestGetSetStringParam(t *testing.T) { newServiceNodeMinimumStake := "99999999" - err = db.SetParam(types.ServiceNodeMinimumStakeParamName, newServiceNodeMinimumStake) + err = db.SetParam(modules.ServiceNodeMinimumStakeParamName, newServiceNodeMinimumStake) require.NoError(t, err) height, err := db.GetHeight() require.NoError(t, err) - serviceNodeMinimumStake, err := db.GetStringParam(types.ServiceNodeMinimumStakeParamName, height) + serviceNodeMinimumStake, err := db.GetStringParam(modules.ServiceNodeMinimumStakeParamName, height) require.NoError(t, err) require.Equal(t, newServiceNodeMinimumStake, serviceNodeMinimumStake) @@ -63,13 +63,13 @@ func TestGetSetByteArrayParam(t *testing.T) { newOwner, err := hex.DecodeString("63585955783252764a6e576a5631647542486168426c63774e4655345a57617468545532637a6330516e4d5978575977674553537857644e4a6b4c7734575335416a65616c6d57494a47535364555933686d565a706e57564a6d6143526c54594248626864465a72646c624f646c59704a45536a6c6c52794d32527849545733566c6557464763745a465377466a57324a316157314562554a6c564b6c325470394753696c58544846474e786331567a70554d534a6c5335566d4c356f305157684663726c6b4e4a4e305931496c624a4e58537035554d4a7058564a705561506c3259484a47614b6c585a") require.NoError(t, err) - err = db.SetParam(types.ServiceNodeUnstakingBlocksOwner, newOwner) + err = db.SetParam(modules.ServiceNodeUnstakingBlocksOwner, newOwner) require.NoError(t, err) height, err := db.GetHeight() require.NoError(t, err) - owner, err := db.GetBytesParam(types.ServiceNodeUnstakingBlocksOwner, height) + owner, err := db.GetBytesParam(modules.ServiceNodeUnstakingBlocksOwner, height) require.NoError(t, err) require.Equal(t, newOwner, owner) @@ -84,13 +84,13 @@ func TestGetSetToggleIntFlag(t *testing.T) { newMaxChains := 42 // insert with false - err = db.SetFlag(types.AppMaxChainsParamName, newMaxChains, false) + err = db.SetFlag(modules.AppMaxChainsParamName, newMaxChains, false) require.NoError(t, err) height, err := db.GetHeight() require.NoError(t, err) - maxChains, enabled, err := db.GetIntFlag(types.AppMaxChainsParamName, height) + maxChains, enabled, err := db.GetIntFlag(modules.AppMaxChainsParamName, height) require.NoError(t, err) require.Equal(t, newMaxChains, maxChains) @@ -98,13 +98,13 @@ func TestGetSetToggleIntFlag(t *testing.T) { require.Equal(t, false, enabled) // toggle to true - err = db.SetFlag(types.AppMaxChainsParamName, newMaxChains, true) + err = db.SetFlag(modules.AppMaxChainsParamName, newMaxChains, true) require.NoError(t, err) height, err = db.GetHeight() require.NoError(t, err) - maxChains, enabled, err = db.GetIntFlag(types.AppMaxChainsParamName, height) + maxChains, enabled, err = db.GetIntFlag(modules.AppMaxChainsParamName, height) require.NoError(t, err) require.Equal(t, newMaxChains, maxChains) @@ -121,26 +121,26 @@ func TestGetSetToggleStringFlag(t *testing.T) { newServiceNodeMinimumStake := "99999999" // insert with false - err = db.SetFlag(types.ServiceNodeMinimumStakeParamName, newServiceNodeMinimumStake, false) + err = db.SetFlag(modules.ServiceNodeMinimumStakeParamName, newServiceNodeMinimumStake, false) require.NoError(t, err) height, err := db.GetHeight() require.NoError(t, err) - serviceNodeMinimumStake, enabled, err := db.GetStringFlag(types.ServiceNodeMinimumStakeParamName, height) + serviceNodeMinimumStake, enabled, err := db.GetStringFlag(modules.ServiceNodeMinimumStakeParamName, height) require.NoError(t, err) require.Equal(t, newServiceNodeMinimumStake, serviceNodeMinimumStake) require.Equal(t, false, enabled) //toggle to true - err = db.SetFlag(types.ServiceNodeMinimumStakeParamName, newServiceNodeMinimumStake, true) + err = db.SetFlag(modules.ServiceNodeMinimumStakeParamName, newServiceNodeMinimumStake, true) require.NoError(t, err) height, err = db.GetHeight() require.NoError(t, err) - serviceNodeMinimumStake, enabled, err = db.GetStringFlag(types.ServiceNodeMinimumStakeParamName, height) + serviceNodeMinimumStake, enabled, err = db.GetStringFlag(modules.ServiceNodeMinimumStakeParamName, height) require.NoError(t, err) require.Equal(t, newServiceNodeMinimumStake, serviceNodeMinimumStake) @@ -158,26 +158,26 @@ func TestGetSetToggleByteArrayFlag(t *testing.T) { require.NoError(t, err) // insert with false - err = db.SetFlag(types.ServiceNodeUnstakingBlocksOwner, newOwner, false) + err = db.SetFlag(modules.ServiceNodeUnstakingBlocksOwner, newOwner, false) require.NoError(t, err) height, err := db.GetHeight() require.NoError(t, err) - owner, enabled, err := db.GetBytesFlag(types.ServiceNodeUnstakingBlocksOwner, height) + owner, enabled, err := db.GetBytesFlag(modules.ServiceNodeUnstakingBlocksOwner, height) require.NoError(t, err) require.Equal(t, newOwner, owner) require.Equal(t, false, enabled) //toggle to true - err = db.SetFlag(types.ServiceNodeUnstakingBlocksOwner, newOwner, true) + err = db.SetFlag(modules.ServiceNodeUnstakingBlocksOwner, newOwner, true) require.NoError(t, err) height, err = db.GetHeight() require.NoError(t, err) - owner, enabled, err = db.GetBytesFlag(types.ServiceNodeUnstakingBlocksOwner, height) + owner, enabled, err = db.GetBytesFlag(modules.ServiceNodeUnstakingBlocksOwner, height) require.NoError(t, err) require.Equal(t, newOwner, owner) diff --git a/persistence/test/service_node_test.go b/persistence/test/service_node_test.go index c170c636f..bc2093405 100644 --- a/persistence/test/service_node_test.go +++ b/persistence/test/service_node_test.go @@ -3,23 +3,20 @@ package test import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/persistence/types" "log" "testing" "github.com/pokt-network/pocket/persistence" - "github.com/pokt-network/pocket/persistence/schema" "github.com/pokt-network/pocket/shared/crypto" - - // TODO(andrew): Remove all `typesGenesis` imports and use `genesis` instead. - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" "github.com/stretchr/testify/require" ) func FuzzServiceNode(f *testing.F) { fuzzSingleProtocolActor(f, - NewTestGenericActor(schema.ServiceNodeActor, newTestServiceNode), - GetGenericActor(schema.ServiceNodeActor, getTestServiceNode), - schema.ServiceNodeActor) + NewTestGenericActor(types.ServiceNodeActor, newTestServiceNode), + GetGenericActor(types.ServiceNodeActor, getTestServiceNode), + types.ServiceNodeActor) } func TestGetSetServiceNodeStakeAmount(t *testing.T) { @@ -125,13 +122,13 @@ func TestGetServiceNodesReadyToUnstake(t *testing.T) { unstakingServiceNodes, err := db.GetServiceNodesReadyToUnstake(0, persistence.UnstakingStatus) require.NoError(t, err) require.Equal(t, 1, len(unstakingServiceNodes), "wrong number of actors ready to unstake at height 0") - require.Equal(t, serviceNode.Address, hex.EncodeToString(unstakingServiceNodes[0].Address), "unexpected serviceNodelication actor returned") + require.Equal(t, serviceNode.Address, hex.EncodeToString(unstakingServiceNodes[0].GetAddress()), "unexpected serviceNodelication actor returned") // Check unstaking serviceNodes at height 1 unstakingServiceNodes, err = db.GetServiceNodesReadyToUnstake(1, persistence.UnstakingStatus) require.NoError(t, err) require.Equal(t, 2, len(unstakingServiceNodes), "wrong number of actors ready to unstake at height 1") - require.ElementsMatch(t, [][]byte{addrBz2, addrBz3}, [][]byte{unstakingServiceNodes[0].Address, unstakingServiceNodes[1].Address}) + require.ElementsMatch(t, [][]byte{addrBz2, addrBz3}, [][]byte{unstakingServiceNodes[0].GetAddress(), unstakingServiceNodes[1].GetAddress()}) } func TestGetServiceNodeStatus(t *testing.T) { @@ -215,7 +212,7 @@ func TestGetServiceNodeOutputAddress(t *testing.T) { require.Equal(t, hex.EncodeToString(output), serviceNode.Output, "unexpected output address") } -func newTestServiceNode() (*typesGenesis.Actor, error) { +func newTestServiceNode() (*types.Actor, error) { operatorKey, err := crypto.GeneratePublicKey() if err != nil { return nil, err @@ -226,7 +223,7 @@ func newTestServiceNode() (*typesGenesis.Actor, error) { return nil, err } - return &typesGenesis.Actor{ + return &types.Actor{ Address: hex.EncodeToString(operatorKey.Address()), PublicKey: hex.EncodeToString(operatorKey.Bytes()), Chains: DefaultChains, @@ -238,12 +235,11 @@ func newTestServiceNode() (*typesGenesis.Actor, error) { }, nil } -func createAndInsertDefaultTestServiceNode(db *persistence.PostgresContext) (*typesGenesis.Actor, error) { +func createAndInsertDefaultTestServiceNode(db *persistence.PostgresContext) (*types.Actor, error) { serviceNode, err := newTestServiceNode() if err != nil { return nil, err } - // TODO(andrew): Use `require.NoError` addrBz, err := hex.DecodeString(serviceNode.Address) if err != nil { log.Fatal(fmt.Sprintf("an error occurred converting address to bytes %s", serviceNode.Address)) @@ -269,7 +265,7 @@ func createAndInsertDefaultTestServiceNode(db *persistence.PostgresContext) (*ty DefaultUnstakingHeight) } -func getTestServiceNode(db *persistence.PostgresContext, address []byte) (*typesGenesis.Actor, error) { +func getTestServiceNode(db *persistence.PostgresContext, address []byte) (*types.Actor, error) { operator, publicKey, stakedTokens, serviceURL, outputAddress, pauseHeight, unstakingHeight, chains, err := db.GetServiceNode(address, db.Height) if err != nil { return nil, err @@ -290,7 +286,7 @@ func getTestServiceNode(db *persistence.PostgresContext, address []byte) (*types return nil, err } - return &typesGenesis.Actor{ + return &types.Actor{ Address: hex.EncodeToString(operatorAddr), PublicKey: hex.EncodeToString(operatorPubKey), Chains: chains, diff --git a/persistence/test/setup_test.go b/persistence/test/setup_test.go index 865c31eb4..e3162a4d9 100644 --- a/persistence/test/setup_test.go +++ b/persistence/test/setup_test.go @@ -2,21 +2,23 @@ package test import ( "encoding/hex" + "encoding/json" "fmt" + "io/ioutil" "log" "math/big" "math/rand" + "os" "strings" "testing" "time" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/test_artifacts" + "github.com/pokt-network/pocket/persistence" - "github.com/pokt-network/pocket/persistence/schema" "github.com/pokt-network/pocket/shared/modules" - sharedTest "github.com/pokt-network/pocket/shared/tests" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" + sharedTest "github.com/pokt-network/pocket/shared/test_artifacts" "github.com/stretchr/testify/require" "golang.org/x/exp/slices" ) @@ -46,9 +48,7 @@ var ( testSchema = "test_schema" ) - -// TODO(olshansky): Find a way to avoid this global test variable -var testPersistenceMod modules.PersistenceModule +var testPersistenceMod modules.PersistenceModule // initialized in TestMain // See https://github.com/ory/dockertest as reference for the template of this code // Postgres example can be found here: https://github.com/ory/dockertest/blob/v3/examples/PostgreSQL.md @@ -56,6 +56,8 @@ func TestMain(m *testing.M) { pool, resource, dbUrl := sharedTest.SetupPostgresDocker() testPersistenceMod = newTestPersistenceModule(dbUrl) m.Run() + os.Remove(testingConfigFilePath) + os.Remove(testingGenesisFilePath) sharedTest.CleanupPostgresDocker(m, pool, resource) } @@ -96,20 +98,16 @@ func NewFuzzTestPostgresContext(f *testing.F, height int64) *persistence.Postgre // TODO(andrew): Take in `t testing.T` as a parameter and error if there's an issue func newTestPersistenceModule(databaseUrl string) modules.PersistenceModule { - cfg := &genesis.Config{ - Base: &genesis.BaseConfig{}, - Consensus: &genesis.ConsensusConfig{}, - Utility: &genesis.UtilityConfig{}, - Persistence: &genesis.PersistenceConfig{ + cfg := modules.Config{ + Persistence: &types.PersistenceConfig{ PostgresUrl: databaseUrl, NodeSchema: testSchema, BlockStorePath: "", }, - P2P: &genesis.P2PConfig{}, - Telemetry: &genesis.TelemetryConfig{}, } genesisState, _ := test_artifacts.NewGenesisState(5, 1, 1, 1) - persistenceMod, err := persistence.Create(cfg, genesisState) + createTestingGenesisAndConfigFiles(cfg, genesisState) + persistenceMod, err := persistence.Create(testingConfigFilePath, testingGenesisFilePath) if err != nil { log.Fatalf("Error creating persistence module: %s", err) } @@ -119,9 +117,9 @@ func newTestPersistenceModule(databaseUrl string) modules.PersistenceModule { // IMPROVE(team): Extend this to more complex and variable test cases challenging & randomizing the state of persistence. func fuzzSingleProtocolActor( f *testing.F, - newTestActor func() (schema.BaseActor, error), - getTestActor func(db *persistence.PostgresContext, address string) (*schema.BaseActor, error), - protocolActorSchema schema.ProtocolActorSchema) { + newTestActor func() (types.BaseActor, error), + getTestActor func(db *persistence.PostgresContext, address string) (*types.BaseActor, error), + protocolActorSchema types.ProtocolActorSchema) { db := NewFuzzTestPostgresContext(f, 0) @@ -176,9 +174,9 @@ func fuzzSingleProtocolActor( newStakedTokens = getRandomBigIntString() case 1: switch protocolActorSchema.GetActorSpecificColName() { - case schema.ServiceURLCol: + case types.ServiceURLCol: newActorSpecificParam = getRandomServiceURL() - case schema.MaxRelaysCol: + case types.MaxRelaysCol: newActorSpecificParam = getRandomBigIntString() default: t.Error("Unexpected actor specific column name") @@ -189,7 +187,7 @@ func fuzzSingleProtocolActor( } } } - updatedActor := schema.BaseActor{ + updatedActor := types.BaseActor{ Address: originalActor.Address, PublicKey: originalActor.PublicKey, StakedTokens: newStakedTokens, @@ -219,8 +217,8 @@ func fuzzSingleProtocolActor( if originalActor.UnstakingHeight != db.Height { // Not ready to unstake require.Nil(t, unstakingActors) } else { - idx := slices.IndexFunc(unstakingActors, func(a *types.UnstakingActor) bool { - return originalActor.Address == hex.EncodeToString(a.Address) + idx := slices.IndexFunc(unstakingActors, func(a modules.IUnstakingActor) bool { + return originalActor.Address == hex.EncodeToString(a.GetAddress()) }) require.NotEqual(t, idx, -1, fmt.Sprintf("actor that is unstaking was not found %+v", originalActor)) } @@ -285,6 +283,43 @@ func fuzzSingleProtocolActor( }) } +// TODO(olshansky): Make these functions & variables more functional to avoid having "unexpected" +// side effects and making it clearer to the reader. +const ( + testingGenesisFilePath = "genesis.json" + testingConfigFilePath = "config.json" +) + +func createTestingGenesisAndConfigFiles(cfg modules.Config, genesisState modules.GenesisState) { + config, err := json.Marshal(cfg.Persistence) + if err != nil { + log.Fatal(err) + } + genesis, err := json.Marshal(genesisState.PersistenceGenesisState) + if err != nil { + log.Fatal(err) + } + genesisFile := make(map[string]json.RawMessage) + configFile := make(map[string]json.RawMessage) + persistenceModuleName := new(persistence.PersistenceModule).GetModuleName() + genesisFile[test_artifacts.GetGenesisFileName(persistenceModuleName)] = genesis + configFile[persistenceModuleName] = config + genesisFileBz, err := json.MarshalIndent(genesisFile, "", " ") + if err != nil { + log.Fatal(err) + } + configFileBz, err := json.MarshalIndent(configFile, "", " ") + if err != nil { + log.Fatal(err) + } + if err := ioutil.WriteFile(testingGenesisFilePath, genesisFileBz, 0777); err != nil { + log.Fatal(err) + } + if err := ioutil.WriteFile(testingConfigFilePath, configFileBz, 0777); err != nil { + log.Fatal(err) + } +} + func getRandomChains() (chains []string) { setRandomSeed() diff --git a/persistence/test/validator_test.go b/persistence/test/validator_test.go index d34a1a08a..abf5217e0 100644 --- a/persistence/test/validator_test.go +++ b/persistence/test/validator_test.go @@ -3,21 +3,20 @@ package test import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/persistence/types" "log" "testing" "github.com/pokt-network/pocket/persistence" - "github.com/pokt-network/pocket/persistence/schema" "github.com/pokt-network/pocket/shared/crypto" - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" "github.com/stretchr/testify/require" ) func FuzzValidator(f *testing.F) { fuzzSingleProtocolActor(f, - NewTestGenericActor(schema.ValidatorActor, newTestValidator), - GetGenericActor(schema.ValidatorActor, getTestValidator), - schema.ValidatorActor) + NewTestGenericActor(types.ValidatorActor, newTestValidator), + GetGenericActor(types.ValidatorActor, getTestValidator), + types.ValidatorActor) } func TestGetSetValidatorStakeAmount(t *testing.T) { @@ -120,13 +119,13 @@ func TestGetValidatorsReadyToUnstake(t *testing.T) { unstakingValidators, err := db.GetValidatorsReadyToUnstake(0, persistence.UnstakingStatus) require.NoError(t, err) require.Equal(t, 1, len(unstakingValidators), "wrong number of actors ready to unstake at height 0") - require.Equal(t, validator.Address, hex.EncodeToString(unstakingValidators[0].Address), "unexpected validatorlication actor returned") + require.Equal(t, validator.Address, hex.EncodeToString(unstakingValidators[0].GetAddress()), "unexpected validatorlication actor returned") // Check unstaking validators at height 1 unstakingValidators, err = db.GetValidatorsReadyToUnstake(1, persistence.UnstakingStatus) require.NoError(t, err) require.Equal(t, 2, len(unstakingValidators), "wrong number of actors ready to unstake at height 1") - require.ElementsMatch(t, [][]byte{addrBz2, addrBz3}, [][]byte{unstakingValidators[0].Address, unstakingValidators[1].Address}) + require.ElementsMatch(t, [][]byte{addrBz2, addrBz3}, [][]byte{unstakingValidators[0].GetAddress(), unstakingValidators[1].GetAddress()}) } func TestGetValidatorStatus(t *testing.T) { @@ -211,7 +210,7 @@ func TestGetValidatorOutputAddress(t *testing.T) { require.Equal(t, hex.EncodeToString(output), validator.Output, "unexpected output address") } -func newTestValidator() (*typesGenesis.Actor, error) { +func newTestValidator() (*types.Actor, error) { operatorKey, err := crypto.GeneratePublicKey() if err != nil { return nil, err @@ -222,7 +221,7 @@ func newTestValidator() (*typesGenesis.Actor, error) { return nil, err } - return &typesGenesis.Actor{ + return &types.Actor{ Address: hex.EncodeToString(operatorKey.Address()), PublicKey: hex.EncodeToString(operatorKey.Bytes()), GenericParam: DefaultServiceUrl, @@ -233,7 +232,7 @@ func newTestValidator() (*typesGenesis.Actor, error) { }, nil } -func createAndInsertDefaultTestValidator(db *persistence.PostgresContext) (*typesGenesis.Actor, error) { +func createAndInsertDefaultTestValidator(db *persistence.PostgresContext) (*types.Actor, error) { validator, err := newTestValidator() if err != nil { return nil, err @@ -262,7 +261,7 @@ func createAndInsertDefaultTestValidator(db *persistence.PostgresContext) (*type DefaultUnstakingHeight) } -func getTestValidator(db *persistence.PostgresContext, address []byte) (*typesGenesis.Actor, error) { +func getTestValidator(db *persistence.PostgresContext, address []byte) (*types.Actor, error) { operator, publicKey, stakedTokens, serviceURL, outputAddress, pauseHeight, unstakingHeight, err := db.GetValidator(address, db.Height) if err != nil { return nil, err @@ -283,7 +282,7 @@ func getTestValidator(db *persistence.PostgresContext, address []byte) (*typesGe return nil, err } - return &typesGenesis.Actor{ + return &types.Actor{ Address: hex.EncodeToString(operatorAddr), PublicKey: hex.EncodeToString(operatorPubKey), GenericParam: serviceURL, diff --git a/persistence/schema/account.go b/persistence/types/account.go similarity index 99% rename from persistence/schema/account.go rename to persistence/types/account.go index 8658c558b..a726b3dce 100644 --- a/persistence/schema/account.go +++ b/persistence/types/account.go @@ -1,4 +1,4 @@ -package schema +package types import "fmt" diff --git a/persistence/schema/application.go b/persistence/types/application.go similarity index 97% rename from persistence/schema/application.go rename to persistence/types/application.go index de38a44d1..141dd46e4 100644 --- a/persistence/schema/application.go +++ b/persistence/types/application.go @@ -1,4 +1,4 @@ -package schema +package types var _ ProtocolActorSchema = &ApplicationSchema{} diff --git a/persistence/schema/base_actor.go b/persistence/types/base_actor.go similarity index 96% rename from persistence/schema/base_actor.go rename to persistence/types/base_actor.go index 72db76132..9514b15eb 100644 --- a/persistence/schema/base_actor.go +++ b/persistence/types/base_actor.go @@ -1,4 +1,6 @@ -package schema +package types + +import "github.com/pokt-network/pocket/shared/modules" // TECHDEBT: Consider moving this to a protobuf. This struct was created to make testing simple of protocol actors that // share most of the schema. We need to investigate if there's a better solution, or document this more appropriately @@ -141,3 +143,12 @@ func (actor *BaseProtocolActorSchema) ClearAllQuery() string { func (actor *BaseProtocolActorSchema) ClearAllChainsQuery() string { return ClearAll(actor.chainsTableName) } + +var _ modules.Actor = &Actor{} + +func (x *Actor) GetActorTyp() modules.ActorType { + if x != nil { + return x.GetActorType() + } + return ActorType_App +} diff --git a/persistence/schema/block.go b/persistence/types/block.go similarity index 98% rename from persistence/schema/block.go rename to persistence/types/block.go index 4055b16a7..802d608c4 100644 --- a/persistence/schema/block.go +++ b/persistence/types/block.go @@ -1,4 +1,4 @@ -package schema +package types import "fmt" diff --git a/persistence/schema/fisherman.go b/persistence/types/fisherman.go similarity index 97% rename from persistence/schema/fisherman.go rename to persistence/types/fisherman.go index 6482d08bf..da116a7fe 100644 --- a/persistence/schema/fisherman.go +++ b/persistence/types/fisherman.go @@ -1,4 +1,4 @@ -package schema +package types var _ ProtocolActorSchema = &FishermanSchema{} diff --git a/persistence/schema/gov.go b/persistence/types/gov.go similarity index 96% rename from persistence/schema/gov.go rename to persistence/types/gov.go index cd6c5fe32..c2b6bdb4b 100644 --- a/persistence/schema/gov.go +++ b/persistence/types/gov.go @@ -1,13 +1,12 @@ -package schema +package types import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/shared/modules" "log" "reflect" "strings" - - "github.com/pokt-network/pocket/shared/types/genesis" ) // init initializes a map that contains the metadata extracted from `gov.proto`. @@ -63,7 +62,7 @@ var ( // It leverages metadata in the form of struct tags (see `parseGovProto` for more information). // // WARNING: reflections in prod -func InsertParams(params *genesis.Params, height int64) string { +func InsertParams(params modules.Params, height int64) string { val := reflect.ValueOf(params) var sb strings.Builder @@ -175,7 +174,7 @@ type govParamMetadata struct { // WARNING: reflections in prod func parseGovProto() (govParamMetadataMap map[string]govParamMetadata) { govParamMetadataMap = make(map[string]govParamMetadata) - fields := reflect.VisibleFields(reflect.TypeOf(genesis.Params{})) + fields := reflect.VisibleFields(reflect.TypeOf(Params{})) for _, field := range fields { if !field.IsExported() { continue diff --git a/persistence/schema/test/gov_test.go b/persistence/types/gov_test.go similarity index 96% rename from persistence/schema/test/gov_test.go rename to persistence/types/gov_test.go index f32ccdbc1..b0222bb29 100644 --- a/persistence/schema/test/gov_test.go +++ b/persistence/types/gov_test.go @@ -1,16 +1,12 @@ -package test +package types import ( "testing" - - "github.com/pokt-network/pocket/persistence/schema" - "github.com/pokt-network/pocket/shared/types/genesis" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" ) func TestInsertParams(t *testing.T) { type args struct { - params *genesis.Params + params *Params height int64 } tests := []struct { @@ -21,8 +17,8 @@ func TestInsertParams(t *testing.T) { { name: "should insert genesis.DefaultParams() as expected", args: args{ - params: test_artifacts.DefaultParams(), - height: schema.DefaultBigInt, + params: DefaultParams(), + height: DefaultBigInt, }, want: "INSERT INTO params VALUES ('blocks_per_session', -1, 'BIGINT', 4)," + "('app_minimum_stake', -1, 'STRING', '15000000000')," + @@ -138,7 +134,7 @@ func TestInsertParams(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := schema.InsertParams(tt.args.params, tt.args.height); got != tt.want { + if got := InsertParams(tt.args.params, tt.args.height); got != tt.want { t.Errorf("InsertParams() = %v, want %v", got, tt.want) } }) diff --git a/persistence/schema/migrations/1_users_genesis.down.sql b/persistence/types/migrations/1_users_genesis.down.sql similarity index 100% rename from persistence/schema/migrations/1_users_genesis.down.sql rename to persistence/types/migrations/1_users_genesis.down.sql diff --git a/persistence/schema/migrations/1_users_genesis.up.sql b/persistence/types/migrations/1_users_genesis.up.sql similarity index 100% rename from persistence/schema/migrations/1_users_genesis.up.sql rename to persistence/types/migrations/1_users_genesis.up.sql diff --git a/persistence/types/persistence_genesis.go b/persistence/types/persistence_genesis.go new file mode 100644 index 000000000..a7250a5ae --- /dev/null +++ b/persistence/types/persistence_genesis.go @@ -0,0 +1,174 @@ +package types + +import ( + "math/big" + + "github.com/pokt-network/pocket/shared/crypto" + "github.com/pokt-network/pocket/shared/modules" + "github.com/pokt-network/pocket/utility/types" +) + +// TODO (Research) is there anyway to not have to name these protobuf files uniquely? +// not a fan of _config/genesis.go would rather just config/genesis.go + +func (x *PersistenceGenesisState) GetAccs() []modules.Account { + return AccToAccInterface(x.GetAccounts()) +} + +func (x *PersistenceGenesisState) GetAccPools() []modules.Account { + return AccToAccInterface(x.GetPools()) +} + +func (x *PersistenceGenesisState) GetApps() []modules.Actor { + return ActorsToActorsInterface(x.GetApplications()) +} + +func (x *PersistenceGenesisState) GetVals() []modules.Actor { + return ActorsToActorsInterface(x.GetValidators()) +} + +func (x *PersistenceGenesisState) GetFish() []modules.Actor { + return ActorsToActorsInterface(x.GetFishermen()) +} + +func (x *PersistenceGenesisState) GetNodes() []modules.Actor { + return ActorsToActorsInterface(x.GetServiceNodes()) +} + +func (x *PersistenceGenesisState) GetParameters() modules.Params { + return x.GetParams() +} + +// RESEARCH(olshansky): AFAIK this is the only way to convert slice of structs into interface - O(n) +// https://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces +func ActorsToActorsInterface(a []*Actor) (actorI []modules.Actor) { + for _, actor := range a { + actorI = append(actorI, actor) + } + return +} + +func AccToAccInterface(a []*Account) (accI []modules.Account) { + for _, acc := range a { + accI = append(accI, acc) + } + return +} + +var ( + DefaultParamsOwner, _ = crypto.NewPrivateKey("ff538589deb7f28bbce1ba68b37d2efc0eaa03204b36513cf88422a875559e38d6cbe0430ddd85a5e48e0c99ef3dea47bf0d1a83c6e6ad1640f72201dc8a0120") +) + +func DefaultParams() *Params { // TODO this is just a test / demo artifact and should be deprecated by genesis file + return &Params{ + BlocksPerSession: 4, + AppMinimumStake: types.BigIntToString(big.NewInt(15000000000)), + AppMaxChains: 15, + AppBaselineStakeRate: 100, + AppStakingAdjustment: 0, + AppUnstakingBlocks: 2016, + AppMinimumPauseBlocks: 4, + AppMaxPauseBlocks: 672, + ServiceNodeMinimumStake: types.BigIntToString(big.NewInt(15000000000)), + ServiceNodeMaxChains: 15, + ServiceNodeUnstakingBlocks: 2016, + ServiceNodeMinimumPauseBlocks: 4, + ServiceNodeMaxPauseBlocks: 672, + ServiceNodesPerSession: 24, + FishermanMinimumStake: types.BigIntToString(big.NewInt(15000000000)), + FishermanMaxChains: 15, + FishermanUnstakingBlocks: 2016, + FishermanMinimumPauseBlocks: 4, + FishermanMaxPauseBlocks: 672, + ValidatorMinimumStake: types.BigIntToString(big.NewInt(15000000000)), + ValidatorUnstakingBlocks: 2016, + ValidatorMinimumPauseBlocks: 4, + ValidatorMaxPauseBlocks: 672, + ValidatorMaximumMissedBlocks: 5, + ValidatorMaxEvidenceAgeInBlocks: 8, + ProposerPercentageOfFees: 10, + MissedBlocksBurnPercentage: 1, + DoubleSignBurnPercentage: 5, + MessageDoubleSignFee: types.BigIntToString(big.NewInt(10000)), + MessageSendFee: types.BigIntToString(big.NewInt(10000)), + MessageStakeFishermanFee: types.BigIntToString(big.NewInt(10000)), + MessageEditStakeFishermanFee: types.BigIntToString(big.NewInt(10000)), + MessageUnstakeFishermanFee: types.BigIntToString(big.NewInt(10000)), + MessagePauseFishermanFee: types.BigIntToString(big.NewInt(10000)), + MessageUnpauseFishermanFee: types.BigIntToString(big.NewInt(10000)), + MessageFishermanPauseServiceNodeFee: types.BigIntToString(big.NewInt(10000)), + MessageTestScoreFee: types.BigIntToString(big.NewInt(10000)), + MessageProveTestScoreFee: types.BigIntToString(big.NewInt(10000)), + MessageStakeAppFee: types.BigIntToString(big.NewInt(10000)), + MessageEditStakeAppFee: types.BigIntToString(big.NewInt(10000)), + MessageUnstakeAppFee: types.BigIntToString(big.NewInt(10000)), + MessagePauseAppFee: types.BigIntToString(big.NewInt(10000)), + MessageUnpauseAppFee: types.BigIntToString(big.NewInt(10000)), + MessageStakeValidatorFee: types.BigIntToString(big.NewInt(10000)), + MessageEditStakeValidatorFee: types.BigIntToString(big.NewInt(10000)), + MessageUnstakeValidatorFee: types.BigIntToString(big.NewInt(10000)), + MessagePauseValidatorFee: types.BigIntToString(big.NewInt(10000)), + MessageUnpauseValidatorFee: types.BigIntToString(big.NewInt(10000)), + MessageStakeServiceNodeFee: types.BigIntToString(big.NewInt(10000)), + MessageEditStakeServiceNodeFee: types.BigIntToString(big.NewInt(10000)), + MessageUnstakeServiceNodeFee: types.BigIntToString(big.NewInt(10000)), + MessagePauseServiceNodeFee: types.BigIntToString(big.NewInt(10000)), + MessageUnpauseServiceNodeFee: types.BigIntToString(big.NewInt(10000)), + MessageChangeParameterFee: types.BigIntToString(big.NewInt(10000)), + AclOwner: DefaultParamsOwner.Address().String(), + BlocksPerSessionOwner: DefaultParamsOwner.Address().String(), + AppMinimumStakeOwner: DefaultParamsOwner.Address().String(), + AppMaxChainsOwner: DefaultParamsOwner.Address().String(), + AppBaselineStakeRateOwner: DefaultParamsOwner.Address().String(), + AppStakingAdjustmentOwner: DefaultParamsOwner.Address().String(), + AppUnstakingBlocksOwner: DefaultParamsOwner.Address().String(), + AppMinimumPauseBlocksOwner: DefaultParamsOwner.Address().String(), + AppMaxPausedBlocksOwner: DefaultParamsOwner.Address().String(), + ServiceNodeMinimumStakeOwner: DefaultParamsOwner.Address().String(), + ServiceNodeMaxChainsOwner: DefaultParamsOwner.Address().String(), + ServiceNodeUnstakingBlocksOwner: DefaultParamsOwner.Address().String(), + ServiceNodeMinimumPauseBlocksOwner: DefaultParamsOwner.Address().String(), + ServiceNodeMaxPausedBlocksOwner: DefaultParamsOwner.Address().String(), + ServiceNodesPerSessionOwner: DefaultParamsOwner.Address().String(), + FishermanMinimumStakeOwner: DefaultParamsOwner.Address().String(), + FishermanMaxChainsOwner: DefaultParamsOwner.Address().String(), + FishermanUnstakingBlocksOwner: DefaultParamsOwner.Address().String(), + FishermanMinimumPauseBlocksOwner: DefaultParamsOwner.Address().String(), + FishermanMaxPausedBlocksOwner: DefaultParamsOwner.Address().String(), + ValidatorMinimumStakeOwner: DefaultParamsOwner.Address().String(), + ValidatorUnstakingBlocksOwner: DefaultParamsOwner.Address().String(), + ValidatorMinimumPauseBlocksOwner: DefaultParamsOwner.Address().String(), + ValidatorMaxPausedBlocksOwner: DefaultParamsOwner.Address().String(), + ValidatorMaximumMissedBlocksOwner: DefaultParamsOwner.Address().String(), + ValidatorMaxEvidenceAgeInBlocksOwner: DefaultParamsOwner.Address().String(), + ProposerPercentageOfFeesOwner: DefaultParamsOwner.Address().String(), + MissedBlocksBurnPercentageOwner: DefaultParamsOwner.Address().String(), + DoubleSignBurnPercentageOwner: DefaultParamsOwner.Address().String(), + MessageDoubleSignFeeOwner: DefaultParamsOwner.Address().String(), + MessageSendFeeOwner: DefaultParamsOwner.Address().String(), + MessageStakeFishermanFeeOwner: DefaultParamsOwner.Address().String(), + MessageEditStakeFishermanFeeOwner: DefaultParamsOwner.Address().String(), + MessageUnstakeFishermanFeeOwner: DefaultParamsOwner.Address().String(), + MessagePauseFishermanFeeOwner: DefaultParamsOwner.Address().String(), + MessageUnpauseFishermanFeeOwner: DefaultParamsOwner.Address().String(), + MessageFishermanPauseServiceNodeFeeOwner: DefaultParamsOwner.Address().String(), + MessageTestScoreFeeOwner: DefaultParamsOwner.Address().String(), + MessageProveTestScoreFeeOwner: DefaultParamsOwner.Address().String(), + MessageStakeAppFeeOwner: DefaultParamsOwner.Address().String(), + MessageEditStakeAppFeeOwner: DefaultParamsOwner.Address().String(), + MessageUnstakeAppFeeOwner: DefaultParamsOwner.Address().String(), + MessagePauseAppFeeOwner: DefaultParamsOwner.Address().String(), + MessageUnpauseAppFeeOwner: DefaultParamsOwner.Address().String(), + MessageStakeValidatorFeeOwner: DefaultParamsOwner.Address().String(), + MessageEditStakeValidatorFeeOwner: DefaultParamsOwner.Address().String(), + MessageUnstakeValidatorFeeOwner: DefaultParamsOwner.Address().String(), + MessagePauseValidatorFeeOwner: DefaultParamsOwner.Address().String(), + MessageUnpauseValidatorFeeOwner: DefaultParamsOwner.Address().String(), + MessageStakeServiceNodeFeeOwner: DefaultParamsOwner.Address().String(), + MessageEditStakeServiceNodeFeeOwner: DefaultParamsOwner.Address().String(), + MessageUnstakeServiceNodeFeeOwner: DefaultParamsOwner.Address().String(), + MessagePauseServiceNodeFeeOwner: DefaultParamsOwner.Address().String(), + MessageUnpauseServiceNodeFeeOwner: DefaultParamsOwner.Address().String(), + MessageChangeParameterFeeOwner: DefaultParamsOwner.Address().String(), + } +} diff --git a/persistence/schema/protocol_actor.go b/persistence/types/protocol_actor.go similarity index 99% rename from persistence/schema/protocol_actor.go rename to persistence/types/protocol_actor.go index 1fa41e548..4b57e8e40 100644 --- a/persistence/schema/protocol_actor.go +++ b/persistence/types/protocol_actor.go @@ -1,4 +1,4 @@ -package schema +package types // Interface common to all protocol actors at the persistence schema layer. This exposes SQL specific // attributes and queries. diff --git a/persistence/schema/service_node.go b/persistence/types/service_node.go similarity index 97% rename from persistence/schema/service_node.go rename to persistence/types/service_node.go index 3f0777efa..76857e0da 100644 --- a/persistence/schema/service_node.go +++ b/persistence/types/service_node.go @@ -1,4 +1,4 @@ -package schema +package types var _ ProtocolActorSchema = &ServiceNodeSchema{} diff --git a/persistence/schema/shared_sql.go b/persistence/types/shared_sql.go similarity index 99% rename from persistence/schema/shared_sql.go rename to persistence/types/shared_sql.go index 6cc03023a..5502c03d3 100644 --- a/persistence/schema/shared_sql.go +++ b/persistence/types/shared_sql.go @@ -1,4 +1,4 @@ -package schema +package types import ( "bytes" @@ -122,7 +122,6 @@ func Insert( height=EXCLUDED.height`, tableName, actorSpecificParam, actor.Address, actor.PublicKey, actor.StakedTokens, actorSpecificParamValue, - // actor.OutputAddress, DefaultBigInt, DefaultBigInt, height, actor.OutputAddress, actor.PausedHeight, actor.UnstakingHeight, height, constraintName, actorSpecificParam, actorSpecificParam) diff --git a/persistence/types/unstaking.go b/persistence/types/unstaking.go new file mode 100644 index 000000000..9ba09358e --- /dev/null +++ b/persistence/types/unstaking.go @@ -0,0 +1,30 @@ +package types + +import ( + "encoding/hex" + "log" + + shared "github.com/pokt-network/pocket/shared/modules" +) + +var _ shared.IUnstakingActor = &UnstakingActor{} + +func (x *UnstakingActor) SetAddress(address string) { // TODO (team) convert address to string #149 + s, err := hex.DecodeString(address) + if err != nil { + log.Fatal(err) + } + x.Address = s +} + +func (x *UnstakingActor) SetStakeAmount(stakeAmount string) { + x.StakeAmount = stakeAmount +} + +func (x *UnstakingActor) SetOutputAddress(address string) { + s, err := hex.DecodeString(address) + if err != nil { + log.Fatal(err) + } + x.OutputAddress = s +} diff --git a/persistence/types/util.go b/persistence/types/util.go new file mode 100644 index 000000000..eb673df62 --- /dev/null +++ b/persistence/types/util.go @@ -0,0 +1,23 @@ +package types + +import ( + "fmt" + "math/big" +) + +const ( + DefaultDenomination = 10 +) + +func StringToBigInt(s string) (*big.Int, error) { + b := big.Int{} + i, ok := b.SetString(s, DefaultDenomination) + if !ok { + return nil, fmt.Errorf("unable to SetString() with base 10") + } + return i, nil +} + +func BigIntToString(b *big.Int) string { + return b.Text(DefaultDenomination) +} diff --git a/persistence/schema/validator.go b/persistence/types/validator.go similarity index 99% rename from persistence/schema/validator.go rename to persistence/types/validator.go index 0474ad301..7d1219e8b 100644 --- a/persistence/schema/validator.go +++ b/persistence/types/validator.go @@ -1,4 +1,4 @@ -package schema +package types var _ ProtocolActorSchema = &ValidatorSchema{} diff --git a/persistence/validator.go b/persistence/validator.go index 8cac24da4..c14c28602 100644 --- a/persistence/validator.go +++ b/persistence/validator.go @@ -4,16 +4,16 @@ import ( "encoding/hex" "log" - "github.com/pokt-network/pocket/persistence/schema" - "github.com/pokt-network/pocket/shared/types" + "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" ) func (p PostgresContext) GetValidatorExists(address []byte, height int64) (exists bool, err error) { - return p.GetExists(schema.ValidatorActor, address, height) + return p.GetExists(types.ValidatorActor, address, height) } func (p PostgresContext) GetValidator(address []byte, height int64) (operator, publicKey, stakedTokens, serviceURL, outputAddress string, pausedHeight, unstakingHeight int64, err error) { - actor, err := p.GetActor(schema.ValidatorActor, address, height) + actor, err := p.GetActor(types.ValidatorActor, address, height) operator = actor.Address publicKey = actor.PublicKey stakedTokens = actor.StakedTokens @@ -25,7 +25,7 @@ func (p PostgresContext) GetValidator(address []byte, height int64) (operator, p } func (p PostgresContext) InsertValidator(address []byte, publicKey []byte, output []byte, _ bool, _ int, serviceURL string, stakedAmount string, pausedHeight int64, unstakingHeight int64) error { - return p.InsertActor(schema.ValidatorActor, schema.BaseActor{ + return p.InsertActor(types.ValidatorActor, types.BaseActor{ Address: hex.EncodeToString(address), PublicKey: hex.EncodeToString(publicKey), StakedTokens: stakedAmount, @@ -37,7 +37,7 @@ func (p PostgresContext) InsertValidator(address []byte, publicKey []byte, outpu } func (p PostgresContext) UpdateValidator(address []byte, serviceURL string, stakedAmount string) error { - return p.UpdateActor(schema.ValidatorActor, schema.BaseActor{ + return p.UpdateActor(types.ValidatorActor, types.BaseActor{ Address: hex.EncodeToString(address), StakedTokens: stakedAmount, ActorSpecificParam: serviceURL, @@ -50,35 +50,35 @@ func (p PostgresContext) DeleteValidator(address []byte) error { } func (p PostgresContext) GetValidatorStakeAmount(height int64, address []byte) (string, error) { - return p.GetActorStakeAmount(schema.ValidatorActor, address, height) + return p.GetActorStakeAmount(types.ValidatorActor, address, height) } func (p PostgresContext) SetValidatorStakeAmount(address []byte, stakeAmount string) error { - return p.SetActorStakeAmount(schema.ValidatorActor, address, stakeAmount) + return p.SetActorStakeAmount(types.ValidatorActor, address, stakeAmount) } -func (p PostgresContext) GetValidatorsReadyToUnstake(height int64, _ int) ([]*types.UnstakingActor, error) { - return p.GetActorsReadyToUnstake(schema.ValidatorActor, height) +func (p PostgresContext) GetValidatorsReadyToUnstake(height int64, _ int) ([]modules.IUnstakingActor, error) { + return p.GetActorsReadyToUnstake(types.ValidatorActor, height) } func (p PostgresContext) GetValidatorStatus(address []byte, height int64) (int, error) { - return p.GetActorStatus(schema.ValidatorActor, address, height) + return p.GetActorStatus(types.ValidatorActor, address, height) } func (p PostgresContext) SetValidatorUnstakingHeightAndStatus(address []byte, unstakingHeight int64, _ int) error { - return p.SetActorUnstakingHeightAndStatus(schema.ValidatorActor, address, unstakingHeight) + return p.SetActorUnstakingHeightAndStatus(types.ValidatorActor, address, unstakingHeight) } func (p PostgresContext) GetValidatorPauseHeightIfExists(address []byte, height int64) (int64, error) { - return p.GetActorPauseHeightIfExists(schema.ValidatorActor, address, height) + return p.GetActorPauseHeightIfExists(types.ValidatorActor, address, height) } func (p PostgresContext) SetValidatorsStatusAndUnstakingHeightIfPausedBefore(pausedBeforeHeight, unstakingHeight int64, _ int) error { - return p.SetActorStatusAndUnstakingHeightIfPausedBefore(schema.ValidatorActor, pausedBeforeHeight, unstakingHeight) + return p.SetActorStatusAndUnstakingHeightIfPausedBefore(types.ValidatorActor, pausedBeforeHeight, unstakingHeight) } func (p PostgresContext) SetValidatorPauseHeight(address []byte, height int64) error { - return p.SetActorPauseHeight(schema.ValidatorActor, address, height) + return p.SetActorPauseHeight(types.ValidatorActor, address, height) } // TODO(team): The Get & Update operations need to be made atomic @@ -105,7 +105,7 @@ func (p PostgresContext) GetValidatorStakedTokens(address []byte, height int64) } func (p PostgresContext) GetValidatorOutputAddress(operator []byte, height int64) (output []byte, err error) { - return p.GetActorOutputAddress(schema.ValidatorActor, operator, height) + return p.GetActorOutputAddress(types.ValidatorActor, operator, height) } // TODO(team): implement missed blocks diff --git a/shared/CHANGELOG.md b/shared/CHANGELOG.md new file mode 100644 index 000000000..c56752bf4 --- /dev/null +++ b/shared/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +All notable changes to this module will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.0.0] - 2022-08-25 + +### [#163](https://github.com/pokt-network/pocket/issues/163) Minimization +- Moved all shared structures out of the shared module +- Moved structure responsibility of config and genesis to the respective modules +- Shared interfaces and general 'base' configuration located here +- Moved make client code to 'debug' to clarify that the event distribution is for the temporary local net +- Left multiple `TODO` for remaining code in test_artifacts to think on removal of shared testing code diff --git a/shared/README.md b/shared/README.md index dea1b26a6..a7690d588 100644 --- a/shared/README.md +++ b/shared/README.md @@ -19,6 +19,7 @@ ```bash shared # [to-be-refactored] All of this is bound to change +├── codec # App wide encoding (currently protobuf) ├── config # Utilities to load and verify Node configurations ├── crypto # Shared crypto utilities specific to Pocket ├── modules # Interfaces to the core Pocket modules @@ -29,11 +30,8 @@ shared # [to-be-refactored] All of this is bound to change | ├── utility_module.go | ├── persistence_module.go | ├── telemetry_module.go -├── telemetry # Cross-module telemetry -├── tests # Cross-module and shared-utility tests -├── types # Types (structs & protos) shared across modules -| ├── # Please reach out to the team if you need a walk-through for these -├── utils # Various helper utilities used across the repo +| ├── types.go # Shared interfaces +├── tests # Cross-module and shared testing_artifacts (to be refactored to make testing more modular) ├── node.go # The main entrypoint to the Pocket Node ├── bus.go # Implementation of the Bus module ``` diff --git a/shared/bus.go b/shared/bus.go index 7f27b38e4..aead9647c 100644 --- a/shared/bus.go +++ b/shared/bus.go @@ -1,11 +1,10 @@ package shared import ( + "github.com/pokt-network/pocket/shared/debug" "log" "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" ) var _ modules.Bus = &bus{} @@ -22,13 +21,6 @@ type bus struct { utility modules.UtilityModule consensus modules.ConsensusModule telemetry modules.TelemetryModule - - // Configurations - config *genesis.Config - - // TECHDEBT(drewsky): We're only storing the `genesis` in the bus so we can access it for - // debug purposes. Ideally, we can restart the entire lifecycle. - genesis *genesis.GenesisState } const ( @@ -41,8 +33,6 @@ func CreateBus( utility modules.UtilityModule, consensus modules.ConsensusModule, telemetry modules.TelemetryModule, - config *genesis.Config, - genesis *genesis.GenesisState, ) (modules.Bus, error) { bus := &bus{ channel: make(modules.EventsChannel, DefaultPocketBusBufferSize), @@ -52,9 +42,6 @@ func CreateBus( utility: utility, consensus: consensus, telemetry: telemetry, - - config: config, - genesis: genesis, } modules := map[string]modules.Module{ @@ -94,8 +81,6 @@ func CreateBusWithOptionalModules( utility modules.UtilityModule, consensus modules.ConsensusModule, telemetry modules.TelemetryModule, - config *genesis.Config, - genesis *genesis.GenesisState, ) modules.Bus { bus := &bus{ channel: make(modules.EventsChannel, DefaultPocketBusBufferSize), @@ -104,9 +89,6 @@ func CreateBusWithOptionalModules( utility: utility, consensus: consensus, telemetry: telemetry, - - config: config, - genesis: genesis, } maybeSetModuleBus := func(mod modules.Module) { @@ -124,43 +106,35 @@ func CreateBusWithOptionalModules( return bus } -func (m *bus) PublishEventToBus(e *types.PocketEvent) { +func (m bus) PublishEventToBus(e *debug.PocketEvent) { m.channel <- *e } -func (m *bus) GetBusEvent() *types.PocketEvent { +func (m bus) GetBusEvent() *debug.PocketEvent { e := <-m.channel return &e } -func (m *bus) GetEventBus() modules.EventsChannel { +func (m bus) GetEventBus() modules.EventsChannel { return m.channel } -func (m *bus) GetPersistenceModule() modules.PersistenceModule { +func (m bus) GetPersistenceModule() modules.PersistenceModule { return m.persistence } -func (m *bus) GetP2PModule() modules.P2PModule { +func (m bus) GetP2PModule() modules.P2PModule { return m.p2p } -func (m *bus) GetUtilityModule() modules.UtilityModule { +func (m bus) GetUtilityModule() modules.UtilityModule { return m.utility } -func (m *bus) GetConsensusModule() modules.ConsensusModule { +func (m bus) GetConsensusModule() modules.ConsensusModule { return m.consensus } -func (m *bus) GetTelemetryModule() modules.TelemetryModule { +func (m bus) GetTelemetryModule() modules.TelemetryModule { return m.telemetry } - -func (m *bus) GetConfig() *genesis.Config { - return m.config -} - -func (m *bus) GetGenesis() *genesis.GenesisState { - return m.genesis -} diff --git a/shared/types/codec.go b/shared/codec/codec.go similarity index 56% rename from shared/types/codec.go rename to shared/codec/codec.go index 9438a6db0..6eeb393bb 100644 --- a/shared/types/codec.go +++ b/shared/codec/codec.go @@ -1,4 +1,4 @@ -package types +package codec import ( "google.golang.org/protobuf/proto" @@ -6,44 +6,44 @@ import ( ) type Codec interface { // TODO (Team) move to shared. Possibly rename - Marshal(proto.Message) ([]byte, Error) - Unmarshal([]byte, proto.Message) Error - ToAny(proto.Message) (*anypb.Any, Error) - FromAny(*anypb.Any) (proto.Message, Error) + Marshal(proto.Message) ([]byte, error) + Unmarshal([]byte, proto.Message) error + ToAny(proto.Message) (*anypb.Any, error) + FromAny(*anypb.Any) (proto.Message, error) } var _ Codec = &ProtoCodec{} type ProtoCodec struct{} -func (p *ProtoCodec) Marshal(message proto.Message) ([]byte, Error) { +func (p *ProtoCodec) Marshal(message proto.Message) ([]byte, error) { bz, err := proto.Marshal(message) if err != nil { - return nil, ErrProtoMarshal(err) + return nil, err } return bz, nil } -func (p *ProtoCodec) Unmarshal(bz []byte, message proto.Message) Error { +func (p *ProtoCodec) Unmarshal(bz []byte, message proto.Message) error { err := proto.Unmarshal(bz, message) if err != nil { - return ErrProtoUnmarshal(err) + return err } return nil } -func (p *ProtoCodec) ToAny(message proto.Message) (*anypb.Any, Error) { +func (p *ProtoCodec) ToAny(message proto.Message) (*anypb.Any, error) { any, err := anypb.New(message) if err != nil { - return nil, ErrProtoNewAny(err) + return nil, err } return any, nil } -func (p *ProtoCodec) FromAny(any *anypb.Any) (proto.Message, Error) { +func (p *ProtoCodec) FromAny(any *anypb.Any) (proto.Message, error) { msg, err := anypb.UnmarshalNew(any, proto.UnmarshalOptions{}) if err != nil { - return nil, ErrProtoUnmarshal(err) + return nil, err } return msg, nil } diff --git a/shared/codec/codec_test.go b/shared/codec/codec_test.go new file mode 100644 index 000000000..e8b081830 --- /dev/null +++ b/shared/codec/codec_test.go @@ -0,0 +1,9 @@ +package codec + +import ( + "testing" +) + +func TestUtilityCodec(t *testing.T) { + // TODO (Team) need proto structure to test - but don't want to import any +} diff --git a/shared/types/proto/debug_message.proto b/shared/debug/proto/debug_message.proto similarity index 89% rename from shared/types/proto/debug_message.proto rename to shared/debug/proto/debug_message.proto index 927b7ff9e..e38d42f93 100644 --- a/shared/types/proto/debug_message.proto +++ b/shared/debug/proto/debug_message.proto @@ -1,7 +1,7 @@ syntax = "proto3"; package shared; -option go_package = "github.com/pokt-network/pocket/shared/types"; +option go_package = "github.com/pokt-network/pocket/shared/debug"; import "google/protobuf/any.proto"; diff --git a/shared/types/proto/events.proto b/shared/debug/proto/events.proto similarity index 82% rename from shared/types/proto/events.proto rename to shared/debug/proto/events.proto index 729bf976d..5c3dbaf19 100644 --- a/shared/types/proto/events.proto +++ b/shared/debug/proto/events.proto @@ -3,7 +3,7 @@ import "google/protobuf/any.proto"; package pocket; -option go_package = "github.com/pokt-network/pocket/shared/types"; +option go_package = "github.com/pokt-network/pocket/shared/debug"; enum PocketTopic { UNKNOWN_POCKET_TOPIC = 0; diff --git a/shared/modules/bus_module.go b/shared/modules/bus_module.go index b635243ef..2c895ba26 100644 --- a/shared/modules/bus_module.go +++ b/shared/modules/bus_module.go @@ -1,19 +1,19 @@ package modules import ( - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" + "encoding/json" + "github.com/pokt-network/pocket/shared/debug" ) // TODO(design): Discuss if this channel should be of pointers to PocketEvents or not. Pointers // would avoid doing object copying, but might also be less thread safe if another goroutine changes // it, which could potentially be a feature rather than a bug. -type EventsChannel chan types.PocketEvent +type EventsChannel chan debug.PocketEvent type Bus interface { // Bus Events - PublishEventToBus(e *types.PocketEvent) - GetBusEvent() *types.PocketEvent + PublishEventToBus(e *debug.PocketEvent) + GetBusEvent() *debug.PocketEvent GetEventBus() EventsChannel // Pocket modules @@ -24,6 +24,6 @@ type Bus interface { GetTelemetryModule() TelemetryModule // Configuration - GetConfig() *genesis.Config - GetGenesis() *genesis.GenesisState + GetConfig() map[string]json.RawMessage + GetGenesis() map[string]json.RawMessage } diff --git a/shared/modules/consensus_module.go b/shared/modules/consensus_module.go index 3cd392920..f348a01a8 100644 --- a/shared/modules/consensus_module.go +++ b/shared/modules/consensus_module.go @@ -1,19 +1,18 @@ package modules import ( - "github.com/pokt-network/pocket/shared/types" - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" + "github.com/pokt-network/pocket/shared/debug" "google.golang.org/protobuf/types/known/anypb" ) -type ValidatorMap map[string]*typesGenesis.Actor +type ValidatorMap map[string]Actor // TODO (Drewsky) deprecate Validator map or populate from persistence module type ConsensusModule interface { Module // Consensus Engine HandleMessage(*anypb.Any) error - HandleDebugMessage(*types.DebugMessage) error + HandleDebugMessage(*debug.DebugMessage) error // Consensus State CurrentHeight() uint64 diff --git a/shared/modules/doc/CHANGELOG.md b/shared/modules/doc/CHANGELOG.md new file mode 100644 index 000000000..fd53e8c55 --- /dev/null +++ b/shared/modules/doc/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this module will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.0.0.1] - 2022-08-21 +- Minimized shared module with [#163](https://github.com/pokt-network/pocket/issues/163) +- Deprecated shared/types, moved remaining interfaces to shared/modules +- Most GenesisTypes moved to persistence + +## [0.0.0.0] - 2022-08-08 + +- Deprecated old placeholder genesis_state and genesis_config +- Added utility_genesis_state to genesis_state +- Added consensus_genesis_state to genesis_state +- Added genesis_time to consensus_genesis_state +- Added chainID to consensus_genesis_state +- Added max_block_bytes to consensus_genesis_state +- Added accounts and pools to utility_genesis_state +- Added validators to utility_genesis_state +- Added applications to utility_genesis_state +- Added service_nodes to utility_genesis_state +- Added fishermen to utility_genesis_state +- Deprecated shared/config/ +- Added new shared config proto3 structure +- Added base_config to config +- Added utility_config to config +- Added consensus_config to config +- Added persistence_config to config +- Added p2p_config to config +- Added telemetry_config to config +- Opened followup issue #163 +- Added config and genesis generator to build package +- Deprecated old build files +- Use new config and genesis files for make compose_and_watch +- Use new config and genesis files for make client_start && make client_connect diff --git a/shared/modules/doc/README.md b/shared/modules/doc/README.md new file mode 100644 index 000000000..ebb206afd --- /dev/null +++ b/shared/modules/doc/README.md @@ -0,0 +1,39 @@ +# Genesis Module + +This document is meant to be the development level documentation for the genesis state details related to the design of the codebase and information related to development. + +!!! IMPORTANT !!! + +This directory was created for the purposes of integration between the four core modules and is +not intended to store all the core shared types in the long-term. + +Speak to @andrewnguyen22 or @Olshansk for more details. + +!!! IMPORTANT !!! + +## Implementation + +In order to maintain code agnostic from the inception of the implementation, protobuf3 is utilized for all structures in this package. + +It is important to note, that while Pocket V1 strives to not share objects between modules, the genesis module will inevitably overlap between other modules. + +Another architecture worth considering and perhaps is more optimal as the project nears mainnet is allowing each module to create and maintain their own genesis object and config files + +### Code Organization + +```bash +genesis +├── docs +│   ├── CHANGELOG.md # Genesis module changelog +│   ├── README.md # Genesis module README +├── proto +│   ├── account.proto # account structure +│   ├── actor.proto # actor structure +│   ├── config.proto # configuration structure +│   ├── gov.proto # params structure +│   ├── state.proto # genesis state structure +├── test_artifacts # the central point of all testing code (WIP) +│   ├── generator.go # generate the genesis and config.json for tests and build +│   ├── gov.go # default testing parameters + +``` diff --git a/shared/modules/module.go b/shared/modules/module.go index 43cc4516a..1255d5cba 100644 --- a/shared/modules/module.go +++ b/shared/modules/module.go @@ -4,6 +4,7 @@ package modules // TODO(drewsky): Add `Create` function; pocket/issues/163 // TODO(drewsky): Do not embed this inside of modules but force it via an implicit cast at compile time type Module interface { + InitializableModule IntegratableModule InterruptableModule } @@ -17,3 +18,9 @@ type InterruptableModule interface { Start() error Stop() error } + +type InitializableModule interface { + GetModuleName() string + InitConfig(pathToConfigJSON string) (IConfig, error) + InitGenesis(pathToGenesisJSON string) (IGenesis, error) +} diff --git a/shared/modules/p2p_module.go b/shared/modules/p2p_module.go index 1e0a29468..d55b640d9 100644 --- a/shared/modules/p2p_module.go +++ b/shared/modules/p2p_module.go @@ -2,12 +2,13 @@ package modules import ( cryptoPocket "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" + "github.com/pokt-network/pocket/shared/debug" "google.golang.org/protobuf/types/known/anypb" ) type P2PModule interface { Module - Broadcast(msg *anypb.Any, topic types.PocketTopic) error // TODO(derrandz): get rid of topic - Send(addr cryptoPocket.Address, msg *anypb.Any, topic types.PocketTopic) error // TODO(derrandz): get rid of topic + Broadcast(msg *anypb.Any, topic debug.PocketTopic) error // TECHDEBT: get rid of topic + Send(addr cryptoPocket.Address, msg *anypb.Any, topic debug.PocketTopic) error // TECHDEBT: get rid of topic + GetAddress() (cryptoPocket.Address, error) } diff --git a/shared/modules/persistence_module.go b/shared/modules/persistence_module.go index 7bdadde4a..91577b377 100644 --- a/shared/modules/persistence_module.go +++ b/shared/modules/persistence_module.go @@ -2,7 +2,7 @@ package modules import ( "github.com/pokt-network/pocket/persistence/kvstore" - "github.com/pokt-network/pocket/shared/types" + "github.com/pokt-network/pocket/shared/debug" ) type PersistenceModule interface { @@ -19,7 +19,7 @@ type PersistenceModule interface { GetBlockStore() kvstore.KVStore // Debugging / development only - HandleDebugMessage(*types.DebugMessage) error + HandleDebugMessage(*debug.DebugMessage) error } // Interface defining the context within which the node can operate with the persistence layer. @@ -38,7 +38,7 @@ type PersistenceRWContext interface { // NOTE: There's not really a use case for a write only interface, // but it abstracts and contrasts nicely against the read only context -// TODO(andrew): convert address and public key to string not bytes; pocket/issues/163 +// TODO (andrew) convert address and public key to string not bytes #149 type PersistenceWriteContext interface { // TODO: Simplify the interface (reference - https://dave.cheney.net/practical-go/presentations/gophercon-israel.html#_prefer_single_method_interfaces) // - Add general purpose methods such as `ActorOperation(enum_actor_type, ...)` which can be use like so: `Insert(FISHERMAN, ...)` @@ -70,8 +70,7 @@ type PersistenceWriteContext interface { SubtractPoolAmount(name string, amount string) error SetPoolAmount(name string, amount string) error - // TODO(andrew): remove address from pool; pocket/issues/163 - InsertPool(name string, address []byte, amount string) error + InsertPool(name string, address []byte, amount string) error // TODO (Andrew) remove address from pool #149 // Account Operations AddAccountAmount(address []byte, amount string) error @@ -145,24 +144,28 @@ type PersistenceReadContext interface { // Returns "0" if the account does not exist GetPoolAmount(name string, height int64) (amount string, err error) + GetAllPools(height int64) ([]Account, error) // Account Queries // Returns "0" if the account does not exist GetAccountAmount(address []byte, height int64) (string, error) + GetAllAccounts(height int64) ([]Account, error) // App Queries + GetAllApps(height int64) ([]Actor, error) GetAppExists(address []byte, height int64) (exists bool, err error) GetAppStakeAmount(height int64, address []byte) (string, error) - GetAppsReadyToUnstake(height int64, status int) (apps []*types.UnstakingActor, err error) + GetAppsReadyToUnstake(height int64, status int) (apps []IUnstakingActor, err error) GetAppStatus(address []byte, height int64) (status int, err error) GetAppPauseHeightIfExists(address []byte, height int64) (int64, error) GetAppOutputAddress(operator []byte, height int64) (output []byte, err error) // ServiceNode Queries + GetAllServiceNodes(height int64) ([]Actor, error) GetServiceNodeExists(address []byte, height int64) (exists bool, err error) GetServiceNodeStakeAmount(height int64, address []byte) (string, error) - GetServiceNodesReadyToUnstake(height int64, status int) (serviceNodes []*types.UnstakingActor, err error) + GetServiceNodesReadyToUnstake(height int64, status int) (serviceNodes []IUnstakingActor, err error) GetServiceNodeStatus(address []byte, height int64) (status int, err error) GetServiceNodePauseHeightIfExists(address []byte, height int64) (int64, error) GetServiceNodeOutputAddress(operator []byte, height int64) (output []byte, err error) @@ -170,17 +173,19 @@ type PersistenceReadContext interface { GetServiceNodesPerSessionAt(height int64) (int, error) // Fisherman Queries + GetAllFishermen(height int64) ([]Actor, error) GetFishermanExists(address []byte, height int64) (exists bool, err error) GetFishermanStakeAmount(height int64, address []byte) (string, error) - GetFishermenReadyToUnstake(height int64, status int) (fishermen []*types.UnstakingActor, err error) + GetFishermenReadyToUnstake(height int64, status int) (fishermen []IUnstakingActor, err error) GetFishermanStatus(address []byte, height int64) (status int, err error) GetFishermanPauseHeightIfExists(address []byte, height int64) (int64, error) GetFishermanOutputAddress(operator []byte, height int64) (output []byte, err error) // Validator Queries + GetAllValidators(height int64) ([]Actor, error) GetValidatorExists(address []byte, height int64) (exists bool, err error) GetValidatorStakeAmount(height int64, address []byte) (string, error) - GetValidatorsReadyToUnstake(height int64, status int) (validators []*types.UnstakingActor, err error) + GetValidatorsReadyToUnstake(height int64, status int) (validators []IUnstakingActor, err error) GetValidatorStatus(address []byte, height int64) (status int, err error) GetValidatorPauseHeightIfExists(address []byte, height int64) (int64, error) GetValidatorOutputAddress(operator []byte, height int64) (output []byte, err error) diff --git a/shared/types/gov.go b/shared/modules/types.go similarity index 52% rename from shared/types/gov.go rename to shared/modules/types.go index 133346c9b..3c179f3a5 100644 --- a/shared/types/gov.go +++ b/shared/modules/types.go @@ -1,6 +1,241 @@ -package types +package modules -// TODO(pocket/issues/163): Move this into utility +import ( + "google.golang.org/protobuf/types/known/timestamppb" +) + +// This file contains the minimum shared structures (GenesisState) and the many shared interfaces the modules implement +// the main purpose of this structure is to ensure the ownership of the + +type GenesisState struct { + PersistenceGenesisState PersistenceGenesisState `json:"persistence_genesis_state"` + ConsensusGenesisState ConsensusGenesisState `json:"consensus_genesis_state"` +} + +type BaseConfig struct { + RootDirectory string `json:"root_directory"` + PrivateKey string `json:"private_key"` // TODO (pocket/issues/150) better architecture for key management (keybase, keyfiles, etc.) +} + +type Config struct { + Base *BaseConfig `json:"base"` + Consensus ConsensusConfig `json:"consensus"` + Utility UtilityConfig `json:"utility"` + Persistence PersistenceConfig `json:"persistence"` + P2P P2PConfig `json:"p2p"` + Telemetry TelemetryConfig `json:"telemetry"` +} + +type ConsensusConfig interface { + GetMaxMempoolBytes() uint64 + GetPaceMakerConfig() PacemakerConfig +} + +type PacemakerConfig interface { + SetTimeoutMsec(uint64) + GetTimeoutMsec() uint64 + GetManual() bool + GetDebugTimeBetweenStepsMsec() uint64 +} + +type PersistenceConfig interface { + GetPostgresUrl() string + GetNodeSchema() string + GetBlockStorePath() string +} + +type P2PConfig interface { + GetConsensusPort() uint32 + GetUseRainTree() bool + IsEmptyConnType() bool // TODO (team) make enum +} + +type TelemetryConfig interface { + GetEnabled() bool + GetAddress() string + GetEndpoint() string +} + +type UtilityConfig interface{} + +type PersistenceGenesisState interface { + GetAccs() []Account + GetAccPools() []Account + GetApps() []Actor + GetVals() []Actor + GetFish() []Actor + GetNodes() []Actor + GetParameters() Params +} + +type ConsensusGenesisState interface { + GetGenesisTime() *timestamppb.Timestamp + GetChainId() string + GetMaxBlockBytes() uint64 +} + +type Account interface { + GetAddress() string + GetAmount() string +} + +type Actor interface { + GetAddress() string + GetPublicKey() string + GetChains() []string + GetGenericParam() string + GetStakedAmount() string + GetPausedHeight() int64 + GetUnstakingHeight() int64 + GetOutput() string + GetActorTyp() ActorType // TODO (research) this method has to be implemented manually which is a pain +} + +type ActorType interface { + String() string +} + +type IUnstakingActor interface { + GetAddress() []byte + SetAddress(address string) + GetStakeAmount() string + SetStakeAmount(address string) + GetOutputAddress() []byte + SetOutputAddress(address string) +} + +type Params interface { + GetAppMinimumStake() string + GetAppMaxChains() int32 + GetAppBaselineStakeRate() int32 + GetAppStakingAdjustment() int32 + GetAppUnstakingBlocks() int32 + GetAppMinimumPauseBlocks() int32 + GetAppMaxPauseBlocks() int32 + GetBlocksPerSession() int32 + + GetServiceNodeMinimumStake() string + GetServiceNodeMaxChains() int32 + GetServiceNodeUnstakingBlocks() int32 + GetServiceNodeMinimumPauseBlocks() int32 + GetServiceNodeMaxPauseBlocks() int32 + GetServiceNodesPerSession() int32 + + GetFishermanMinimumStake() string + GetFishermanMaxChains() int32 + GetFishermanUnstakingBlocks() int32 + GetFishermanMinimumPauseBlocks() int32 + GetFishermanMaxPauseBlocks() int32 + + GetValidatorMinimumStake() string + GetValidatorUnstakingBlocks() int32 + GetValidatorMinimumPauseBlocks() int32 + GetValidatorMaxPauseBlocks() int32 + GetValidatorMaximumMissedBlocks() int32 + GetProposerPercentageOfFees() int32 + GetValidatorMaxEvidenceAgeInBlocks() int32 + GetMissedBlocksBurnPercentage() int32 + GetDoubleSignBurnPercentage() int32 + + GetMessageDoubleSignFee() string + GetMessageSendFee() string + GetMessageStakeFishermanFee() string + GetMessageEditStakeFishermanFee() string + GetMessageUnstakeFishermanFee() string + GetMessagePauseFishermanFee() string + GetMessageUnpauseFishermanFee() string + GetMessageFishermanPauseServiceNodeFee() string + GetMessageTestScoreFee() string + GetMessageProveTestScoreFee() string + GetMessageStakeAppFee() string + GetMessageEditStakeAppFee() string + GetMessageUnstakeAppFee() string + GetMessagePauseAppFee() string + GetMessageUnpauseAppFee() string + GetMessageStakeValidatorFee() string + GetMessageEditStakeValidatorFee() string + GetMessageUnstakeValidatorFee() string + GetMessagePauseValidatorFee() string + GetMessageUnpauseValidatorFee() string + GetMessageStakeServiceNodeFee() string + GetMessageEditStakeServiceNodeFee() string + GetMessageUnstakeServiceNodeFee() string + GetMessagePauseServiceNodeFee() string + GetMessageUnpauseServiceNodeFee() string + GetMessageChangeParameterFee() string + + // ACL Queries + GetAclOwner() string + GetBlocksPerSessionOwner() string + GetAppMaxChainsOwner() string + GetAppMinimumStakeOwner() string + GetAppBaselineStakeRateOwner() string + GetAppStakingAdjustmentOwner() string + GetAppUnstakingBlocksOwner() string + GetAppMinimumPauseBlocksOwner() string + GetAppMaxPausedBlocksOwner() string + GetServiceNodeMinimumStakeOwner() string + GetServiceNodeMaxChainsOwner() string + GetServiceNodeUnstakingBlocksOwner() string + GetServiceNodeMinimumPauseBlocksOwner() string + GetServiceNodeMaxPausedBlocksOwner() string + GetFishermanMinimumStakeOwner() string + GetFishermanMaxChainsOwner() string + GetFishermanUnstakingBlocksOwner() string + GetFishermanMinimumPauseBlocksOwner() string + GetFishermanMaxPausedBlocksOwner() string + GetValidatorMinimumStakeOwner() string + GetValidatorUnstakingBlocksOwner() string + GetValidatorMinimumPauseBlocksOwner() string + GetValidatorMaxPausedBlocksOwner() string + GetValidatorMaximumMissedBlocksOwner() string + GetProposerPercentageOfFeesOwner() string + GetValidatorMaxEvidenceAgeInBlocksOwner() string + GetMissedBlocksBurnPercentageOwner() string + GetDoubleSignBurnPercentageOwner() string + GetServiceNodesPerSessionOwner() string + GetMessageDoubleSignFeeOwner() string + GetMessageSendFeeOwner() string + GetMessageStakeFishermanFeeOwner() string + GetMessageEditStakeFishermanFeeOwner() string + GetMessageUnstakeFishermanFeeOwner() string + GetMessagePauseFishermanFeeOwner() string + GetMessageUnpauseFishermanFeeOwner() string + GetMessageFishermanPauseServiceNodeFeeOwner() string + GetMessageTestScoreFeeOwner() string + GetMessageProveTestScoreFeeOwner() string + GetMessageStakeAppFeeOwner() string + GetMessageEditStakeAppFeeOwner() string + GetMessageUnstakeAppFeeOwner() string + GetMessagePauseAppFeeOwner() string + GetMessageUnpauseAppFeeOwner() string + GetMessageStakeValidatorFeeOwner() string + GetMessageEditStakeValidatorFeeOwner() string + GetMessageUnstakeValidatorFeeOwner() string + GetMessagePauseValidatorFeeOwner() string + GetMessageUnpauseValidatorFeeOwner() string + GetMessageStakeServiceNodeFeeOwner() string + GetMessageEditStakeServiceNodeFeeOwner() string + GetMessageUnstakeServiceNodeFeeOwner() string + GetMessagePauseServiceNodeFeeOwner() string + GetMessageUnpauseServiceNodeFeeOwner() string + GetMessageChangeParameterFeeOwner() string +} + +var _ IConfig = PacemakerConfig(nil) +var _ IConfig = PersistenceConfig(nil) +var _ IConfig = P2PConfig(nil) +var _ IConfig = TelemetryConfig(nil) +var _ IConfig = UtilityConfig(nil) + +var _ IGenesis = PersistenceGenesisState(nil) +var _ IGenesis = ConsensusGenesisState(nil) + +// TODO think of a way to enforce these configuration interfaces as true configs/genesis, this is merely decorative at this point +type IConfig interface{} +type IGenesis interface{} + +// TODO (Team) move to use proto string() and deprecate #149 const ( BlocksPerSessionParamName = "blocks_per_session" diff --git a/shared/node.go b/shared/node.go index 9def93987..7d65b8dc2 100644 --- a/shared/node.go +++ b/shared/node.go @@ -3,14 +3,14 @@ package shared import ( "log" + "github.com/pokt-network/pocket/shared/debug" + "github.com/pokt-network/pocket/telemetry" + "github.com/pokt-network/pocket/consensus" "github.com/pokt-network/pocket/p2p" "github.com/pokt-network/pocket/persistence" cryptoPocket "github.com/pokt-network/pocket/shared/crypto" "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/telemetry" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" "github.com/pokt-network/pocket/utility" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" @@ -18,50 +18,52 @@ import ( var _ modules.Module = &Node{} +const ( + MainModuleName = "main" +) + type Node struct { bus modules.Bus Address cryptoPocket.Address } -func Create(cfg *genesis.Config, genesis *genesis.GenesisState) (n *Node, err error) { - persistenceMod, err := persistence.Create(cfg, genesis) +func Create(configPath, genesisPath string) (n *Node, err error) { + persistenceMod, err := persistence.Create(configPath, genesisPath) if err != nil { return nil, err } - p2pMod, err := p2p.Create(cfg, genesis) + p2pMod, err := p2p.Create(configPath, genesisPath, false) if err != nil { return nil, err } - utilityMod, err := utility.Create(cfg, genesis) + utilityMod, err := utility.Create(configPath, genesisPath) if err != nil { return nil, err } - consensusMod, err := consensus.Create(cfg, genesis) + consensusMod, err := consensus.Create(configPath, genesisPath, false) if err != nil { return nil, err } - telemetryMod, err := telemetry.Create(cfg, genesis) + telemetryMod, err := telemetry.Create(configPath, genesisPath) if err != nil { return nil, err } - bus, err := CreateBus(persistenceMod, p2pMod, utilityMod, consensusMod, telemetryMod, cfg, genesis) + bus, err := CreateBus(persistenceMod, p2pMod, utilityMod, consensusMod, telemetryMod) if err != nil { return nil, err } - - pk, err := cryptoPocket.NewPrivateKey(cfg.Base.PrivateKey) + addr, err := p2pMod.GetAddress() if err != nil { return nil, err } - return &Node{ bus: bus, - Address: pk.Address(), + Address: addr, }, nil } @@ -91,7 +93,7 @@ func (node *Node) Start() error { } // The first event signaling that the node has started - signalNodeStartedEvent := &types.PocketEvent{Topic: types.PocketTopic_POCKET_NODE_TOPIC, Data: nil} + signalNodeStartedEvent := &debug.PocketEvent{Topic: debug.PocketTopic_POCKET_NODE_TOPIC, Data: nil} node.GetBus().PublishEventToBus(signalNodeStartedEvent) log.Println("About to start pocket node main loop...") @@ -121,13 +123,13 @@ func (m *Node) GetBus() modules.Bus { return m.bus } -func (node *Node) handleEvent(event *types.PocketEvent) error { +func (node *Node) handleEvent(event *debug.PocketEvent) error { switch event.Topic { - case types.PocketTopic_CONSENSUS_MESSAGE_TOPIC: + case debug.PocketTopic_CONSENSUS_MESSAGE_TOPIC: return node.GetBus().GetConsensusModule().HandleMessage(event.Data) - case types.PocketTopic_DEBUG_TOPIC: + case debug.PocketTopic_DEBUG_TOPIC: return node.handleDebugEvent(event.Data) - case types.PocketTopic_POCKET_NODE_TOPIC: + case debug.PocketTopic_POCKET_NODE_TOPIC: log.Println("[NOOP] Received pocket node topic signal") default: log.Printf("[WARN] Unsupported PocketEvent topic: %s \n", event.Topic) @@ -136,21 +138,21 @@ func (node *Node) handleEvent(event *types.PocketEvent) error { } func (node *Node) handleDebugEvent(anyMessage *anypb.Any) error { - var debugMessage types.DebugMessage + var debugMessage debug.DebugMessage err := anypb.UnmarshalTo(anyMessage, &debugMessage, proto.UnmarshalOptions{}) if err != nil { return err } switch debugMessage.Action { - case types.DebugMessageAction_DEBUG_CONSENSUS_RESET_TO_GENESIS: + case debug.DebugMessageAction_DEBUG_CONSENSUS_RESET_TO_GENESIS: fallthrough - case types.DebugMessageAction_DEBUG_CONSENSUS_PRINT_NODE_STATE: + case debug.DebugMessageAction_DEBUG_CONSENSUS_PRINT_NODE_STATE: fallthrough - case types.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW: + case debug.DebugMessageAction_DEBUG_CONSENSUS_TRIGGER_NEXT_VIEW: fallthrough - case types.DebugMessageAction_DEBUG_CONSENSUS_TOGGLE_PACE_MAKER_MODE: + case debug.DebugMessageAction_DEBUG_CONSENSUS_TOGGLE_PACE_MAKER_MODE: return node.GetBus().GetConsensusModule().HandleDebugMessage(&debugMessage) - case types.DebugMessageAction_DEBUG_SHOW_LATEST_BLOCK_IN_STORE: + case debug.DebugMessageAction_DEBUG_SHOW_LATEST_BLOCK_IN_STORE: return node.GetBus().GetPersistenceModule().HandleDebugMessage(&debugMessage) default: log.Printf("Debug message: %s \n", debugMessage.Message) @@ -158,3 +160,15 @@ func (node *Node) handleDebugEvent(anyMessage *anypb.Any) error { return nil } + +func (node *Node) GetModuleName() string { + return MainModuleName +} + +func (node *Node) InitConfig(pathToConfigJSON string) (modules.IConfig, error) { + return nil, nil +} + +func (node *Node) InitGenesis(pathToGenesisJSON string) (modules.IGenesis, error) { + return nil, nil +} diff --git a/shared/telemetry/module.go b/shared/telemetry/module.go deleted file mode 100644 index bb79a9608..000000000 --- a/shared/telemetry/module.go +++ /dev/null @@ -1,15 +0,0 @@ -package telemetry - -import ( - "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types/genesis" -) - -// TODO(pocket/issues/99): Add a switch statement and configuration variable when support for other telemetry modules is added. -func Create(cfg *genesis.Config, _ *genesis.GenesisState) (modules.TelemetryModule, error) { - if cfg.Telemetry.Enabled { - return CreatePrometheusTelemetryModule(cfg) - } else { - return CreateNoopTelemetryModule(cfg) - } -} diff --git a/shared/types/genesis/test_artifacts/generator.go b/shared/test_artifacts/generator.go similarity index 50% rename from shared/types/genesis/test_artifacts/generator.go rename to shared/test_artifacts/generator.go index afa420759..912e9fe2b 100644 --- a/shared/types/genesis/test_artifacts/generator.go +++ b/shared/test_artifacts/generator.go @@ -1,19 +1,21 @@ package test_artifacts import ( - "encoding/json" "fmt" - "io/ioutil" - "log" + typesPersistence "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" + "github.com/pokt-network/pocket/utility/types" "math/big" "strconv" "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" "google.golang.org/protobuf/types/known/timestamppb" ) +// TODO (Team)/INVESTIGATE(olshansy) It seems improperly scoped that the modules have to have shared 'testing' code +// It might be an inevitability to have shared testing code, but would like more eyes on it. +// Look for opportunities to make testing completely modular + var ( DefaultChains = []string{"0001"} DefaultServiceURL = "" @@ -29,20 +31,21 @@ var ( DefaultMaxBlockBytes = uint64(4000000) ) -// TODO(drewsky): this is meant to be a **temporary** replacement for the recently deprecated -// 'genesis config' option. We need to implement a real suite soon! -func NewGenesisState(numValidators, numServiceNodes, numApplications, numFisherman int) (genesisState *genesis.GenesisState, validatorPrivateKeys []string) { - apps, appsPrivateKeys := NewActors(genesis.ActorType_App, numApplications) - vals, validatorPrivateKeys := NewActors(genesis.ActorType_Val, numValidators) - serviceNodes, snPrivateKeys := NewActors(genesis.ActorType_Node, numServiceNodes) - fish, fishPrivateKeys := NewActors(genesis.ActorType_Fish, numFisherman) - return &genesis.GenesisState{ - Consensus: &genesis.ConsensusGenesisState{ +// TODO (Team) this is meant to be a **temporary** replacement for the recently deprecated +// 'genesis config' option. We need to implement a real suite soon! +func NewGenesisState(numValidators, numServiceNodes, numApplications, numFisherman int) (genesisState modules.GenesisState, validatorPrivateKeys []string) { + apps, appsPrivateKeys := NewActors(MockActorType_App, numApplications) + vals, validatorPrivateKeys := NewActors(MockActorType_Val, numValidators) + serviceNodes, snPrivateKeys := NewActors(MockActorType_Node, numServiceNodes) + fish, fishPrivateKeys := NewActors(MockActorType_Fish, numFisherman) + return modules.GenesisState{ + ConsensusGenesisState: &MockConsensusGenesisState{ GenesisTime: timestamppb.Now(), ChainId: DefaultChainID, MaxBlockBytes: DefaultMaxBlockBytes, + Validators: vals, }, - Utility: &genesis.UtilityGenesisState{ + PersistenceGenesisState: &MockPersistenceGenesisState{ Pools: NewPools(), Accounts: NewAccounts(numValidators+numServiceNodes+numApplications+numFisherman, append(append(append(validatorPrivateKeys, snPrivateKeys...), fishPrivateKeys...), appsPrivateKeys...)...), // TODO(olshansky): clean this up Applications: apps, @@ -54,39 +57,41 @@ func NewGenesisState(numValidators, numServiceNodes, numApplications, numFisherm }, validatorPrivateKeys } -func NewDefaultConfigs(privateKeys []string) (configs []*genesis.Config) { +func NewDefaultConfigs(privateKeys []string) (configs []modules.Config) { for i, pk := range privateKeys { configs = append(configs, NewDefaultConfig(i, pk)) } return } -func NewDefaultConfig(nodeNum int, privateKey string) *genesis.Config { - return &genesis.Config{ - Base: &genesis.BaseConfig{ +func NewDefaultConfig(i int, pk string) modules.Config { + return modules.Config{ + Base: &modules.BaseConfig{ RootDirectory: "/go/src/github.com/pocket-network", - PrivateKey: privateKey, + PrivateKey: pk, }, - Consensus: &genesis.ConsensusConfig{ + Consensus: &MockConsensusConfig{ MaxMempoolBytes: 500000000, - PacemakerConfig: &genesis.PacemakerConfig{ + PacemakerConfig: &MockPacemakerConfig{ TimeoutMsec: 5000, Manual: true, DebugTimeBetweenStepsMsec: 1000, }, + PrivateKey: pk, }, - Utility: &genesis.UtilityConfig{}, - Persistence: &genesis.PersistenceConfig{ + Utility: &MockUtilityConfig{}, + Persistence: &typesPersistence.PersistenceConfig{ PostgresUrl: "postgres://postgres:postgres@pocket-db:5432/postgres", - NodeSchema: "node" + strconv.Itoa(nodeNum+1), + NodeSchema: "node" + strconv.Itoa(i+1), BlockStorePath: "/var/blockstore", }, - P2P: &genesis.P2PConfig{ - ConsensusPort: 8080, - UseRainTree: true, - ConnectionType: genesis.ConnectionType_TCPConnection, + P2P: &MockP2PConfig{ + ConsensusPort: 8080, + UseRainTree: true, + IsEmptyConnectionType: false, + PrivateKey: pk, }, - Telemetry: &genesis.TelemetryConfig{ + Telemetry: &MockTelemetryConfig{ Enabled: true, Address: "0.0.0.0:9000", Endpoint: "/metrics", @@ -94,17 +99,16 @@ func NewDefaultConfig(nodeNum int, privateKey string) *genesis.Config { } } -// TODO: in the real testing suite, we need to populate the pool amounts dependent on the actors -func NewPools() (pools []*genesis.Account) { - for _, name := range genesis.Pool_Names_name { - if name == genesis.Pool_Names_FeeCollector.String() { - pools = append(pools, &genesis.Account{ +func NewPools() (pools []modules.Account) { // TODO (Team) in the real testing suite, we need to populate the pool amounts dependent on the actors + for _, name := range typesPersistence.Pool_Names_name { + if name == typesPersistence.Pool_Names_FeeCollector.String() { + pools = append(pools, &MockAcc{ Address: name, Amount: "0", }) continue } - pools = append(pools, &genesis.Account{ + pools = append(pools, &MockAcc{ Address: name, Amount: DefaultAccountAmountString, }) @@ -112,14 +116,14 @@ func NewPools() (pools []*genesis.Account) { return } -func NewAccounts(n int, privateKeys ...string) (accounts []*genesis.Account) { +func NewAccounts(n int, privateKeys ...string) (accounts []modules.Account) { for i := 0; i < n; i++ { _, _, addr := GenerateNewKeysStrings() if privateKeys != nil { pk, _ := crypto.NewPrivateKey(privateKeys[i]) addr = pk.Address().String() } - accounts = append(accounts, &genesis.Account{ + accounts = append(accounts, &MockAcc{ Address: addr, Amount: DefaultAccountAmountString, }) @@ -127,28 +131,28 @@ func NewAccounts(n int, privateKeys ...string) (accounts []*genesis.Account) { return } -func NewActors(actorType genesis.ActorType, n int) (actors []*genesis.Actor, privateKeys []string) { +func NewActors(actorType MockActorType, n int) (actors []modules.Actor, privateKeys []string) { for i := 0; i < n; i++ { genericParam := fmt.Sprintf("node%d.consensus:8080", i+1) - if actorType == genesis.ActorType_App { + if int32(actorType) == int32(MockActorType_App) { genericParam = DefaultMaxRelaysString } - actor, pk := NewDefaultActor(actorType, genericParam) + actor, pk := NewDefaultActor(int32(actorType), genericParam) actors = append(actors, actor) privateKeys = append(privateKeys, pk) } return } -func NewDefaultActor(actorType genesis.ActorType, genericParam string) (actor *genesis.Actor, privateKey string) { +func NewDefaultActor(actorType int32, genericParam string) (actor modules.Actor, privateKey string) { privKey, pubKey, addr := GenerateNewKeysStrings() chains := DefaultChains - if actorType == genesis.ActorType_Val { + if actorType == int32(typesPersistence.ActorType_Val) { chains = nil - } else if actorType == genesis.ActorType_App { + } else if actorType == int32(MockActorType_App) { genericParam = DefaultMaxRelaysString } - return &genesis.Actor{ + return &MockActor{ Address: addr, PublicKey: pubKey, Chains: chains, @@ -157,7 +161,7 @@ func NewDefaultActor(actorType genesis.ActorType, genericParam string) (actor *g PausedHeight: DefaultPauseHeight, UnstakingHeight: DefaultUnstakingHeight, Output: addr, - ActorType: actorType, + ActorType: MockActorType(actorType), }, privKey } @@ -175,31 +179,3 @@ func GenerateNewKeysStrings() (privateKey, publicKey, address string) { address = addr.String() return } - -func ReadConfigAndGenesisFiles(configPath string, genesisPath string) (config *genesis.Config, genesisState *genesis.GenesisState) { - if configPath == "" { - log.Fatalf("config path cannot be empty") - } - if genesisPath == "" { - log.Fatalf("genesis path cannot be empty") - } - - config = new(genesis.Config) - configFile, err := ioutil.ReadFile(configPath) - if err != nil { - log.Fatalf("[ERROR] an error occurred reading config.json file: %v", err.Error()) - } - if err = json.Unmarshal(configFile, config); err != nil { - log.Fatalf("[ERROR] an error occurred unmarshalling the config.json file: %v", err.Error()) - } - - genesisState = new(genesis.GenesisState) - genesisFile, err := ioutil.ReadFile(genesisPath) - if err != nil { - log.Fatalf("[ERROR] an error occurred reading genesis.json file: %v", err.Error()) - } - if err = json.Unmarshal(genesisFile, genesisState); err != nil { - log.Fatalf("[ERROR] an error occurred unmarshalling the genesis.json file: %v", err.Error()) - } - return -} diff --git a/shared/test_artifacts/genesis.go b/shared/test_artifacts/genesis.go new file mode 100644 index 000000000..91594d001 --- /dev/null +++ b/shared/test_artifacts/genesis.go @@ -0,0 +1,11 @@ +package test_artifacts + +import "fmt" + +const ( + genesisStatePostfix = "_genesis_state" +) + +func GetGenesisFileName(moduleName string) string { + return fmt.Sprintf("%s%s", moduleName, genesisStatePostfix) +} diff --git a/shared/types/genesis/test_artifacts/gov.go b/shared/test_artifacts/gov.go similarity index 83% rename from shared/types/genesis/test_artifacts/gov.go rename to shared/test_artifacts/gov.go index bfab987aa..84deeb1c0 100644 --- a/shared/types/genesis/test_artifacts/gov.go +++ b/shared/test_artifacts/gov.go @@ -1,27 +1,21 @@ package test_artifacts import ( + "github.com/pokt-network/pocket/shared/modules" + "github.com/pokt-network/pocket/utility/types" "math/big" "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" ) +// TODO (Team) this entire file should be re-scoped. DefaultParameters are only a testing thing because prod defers to the genesis file + var ( - // NOTE: this is for fun illustration purposes... The addresses begin with DA0, DA0, and FEE :) - // Of course, in a production network the params / owners must be set in the genesis file - DefaultParamsOwner, _ = crypto.NewPrivateKey("ff538589deb7f28bbce1ba68b37d2efc0eaa03204b36513cf88422a875559e38d6cbe0430ddd85a5e48e0c99ef3dea47bf0d1a83c6e6ad1640f72201dc8a0120") - DefaultDAOPool, _ = crypto.NewPrivateKey("b1dfb25a67dadf9cdd39927b86166149727649af3a3143e66e558652f8031f3faacaa24a69bcf2819ed97ab5ed8d1e490041e5c7ef9e1eddba8b5678f997ae58") - DefaultFeeCollector, _ = crypto.NewPrivateKey("bdc02826b5da77b90a5d1550443b3f007725cc654c10002aa01e65a131f3464b826f8e7911fa89b4bd6659c3175114d714c60bac63acc63817c0d3a4ed2fdab8") - DefaultFishermanStakePool, _ = crypto.NewPrivateKey("f3dd5c8ccd9a7c8d0afd36424c6fbe8ead55315086ef3d0d03ce8c7357e5e306733a711adb6fc8fbef6a3e2ac2db7842433053a23c751d19573ab85b52316f67") - DefaultServiceNodeStakePool, _ = crypto.NewPrivateKey("b4e4426ed014d5ee89949e6f60c406c328e4fce466cd25f4697a41046b34313097a8cc38033822da010422851062ae6b21b8e29d4c34193b7d8fa0f37b6593b6") - DefaultValidatorStakePool, _ = crypto.NewPrivateKey("e0b8b7cdb33f11a8d70eb05070e53b02fe74f4499aed7b159bd2dd256e356d67664b5b682e40ee218e5feea05c2a1bb595ec15f3850c92b571cdf950b4d9ba23") - DefaultAppStakePool, _ = crypto.NewPrivateKey("429627bac8dc322f0aeeb2b8f25b329899b7ebb9605d603b5fb74557b13357e50834e9575c19d9d7d664ec460a98abb2435ece93440eb482c87d5b7259a8d271") + DefaultParamsOwner, _ = crypto.NewPrivateKey("ff538589deb7f28bbce1ba68b37d2efc0eaa03204b36513cf88422a875559e38d6cbe0430ddd85a5e48e0c99ef3dea47bf0d1a83c6e6ad1640f72201dc8a0120") ) -func DefaultParams() *genesis.Params { - return &genesis.Params{ +func DefaultParams() modules.Params { + return &MockParams{ BlocksPerSession: 4, AppMinimumStake: types.BigIntToString(big.NewInt(15000000000)), AppMaxChains: 15, diff --git a/shared/test_artifacts/mock.go b/shared/test_artifacts/mock.go new file mode 100644 index 000000000..99c61665d --- /dev/null +++ b/shared/test_artifacts/mock.go @@ -0,0 +1,909 @@ +package test_artifacts + +import ( + "fmt" + "github.com/pokt-network/pocket/shared/modules" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// This file contains *seemingly* necessary implementations of the shared interfaces in order to +// do things like: create a genesis file and perform testing where cross module implementations are needed +// (see call to action in generator.go to try to remove the cross module testing code) + +// TODO (Team) convert these to proper mocks +var _ modules.Actor = &MockActor{} +var _ modules.Account = &MockAcc{} + +type MockAcc struct { + Address string `json:"address"` + Amount string `json:"amount"` +} + +func (m *MockAcc) GetAddress() string { + return m.Address +} + +func (m *MockAcc) GetAmount() string { + return m.Amount +} + +type MockActor struct { + Address string `json:"address"` + PublicKey string `json:"public_key"` + Chains []string `json:"chains"` + GenericParam string `json:"generic_param"` + StakedAmount string `json:"staked_amount"` + PausedHeight int64 `json:"paused_height"` + UnstakingHeight int64 `json:"unstaking_height"` + Output string `json:"output"` + ActorType MockActorType `json:"actor_type"` +} + +const ( + MockActorType_App MockActorType = 0 + MockActorType_Node MockActorType = 1 + MockActorType_Fish MockActorType = 2 + MockActorType_Val MockActorType = 3 +) + +func (m *MockActor) GetAddress() string { + return m.Address +} + +func (m *MockActor) GetPublicKey() string { + return m.PublicKey +} + +func (m *MockActor) GetChains() []string { + return m.Chains +} + +func (m *MockActor) GetGenericParam() string { + return m.GenericParam +} + +func (m *MockActor) GetStakedAmount() string { + return m.StakedAmount +} + +func (m *MockActor) GetPausedHeight() int64 { + return m.PausedHeight +} + +func (m *MockActor) GetUnstakingHeight() int64 { + return m.UnstakingHeight +} + +func (m *MockActor) GetOutput() string { + return m.Output +} + +func (m *MockActor) GetActorTyp() modules.ActorType { + return m.ActorType +} + +type MockActorType int32 + +func (m MockActorType) String() string { + return fmt.Sprintf("%d", m) +} + +var _ modules.PersistenceGenesisState = &MockPersistenceGenesisState{} +var _ modules.ConsensusGenesisState = &MockConsensusGenesisState{} + +type MockConsensusGenesisState struct { + GenesisTime *timestamppb.Timestamp `json:"genesis_time"` + ChainId string `json:"chain_id"` + MaxBlockBytes uint64 `json:"max_block_bytes"` + Validators []modules.Actor `json:"validators"` +} + +func (m *MockConsensusGenesisState) GetGenesisTime() *timestamppb.Timestamp { + return m.GenesisTime +} + +func (m *MockConsensusGenesisState) GetChainId() string { + return m.ChainId +} + +func (m *MockConsensusGenesisState) GetMaxBlockBytes() uint64 { + return m.MaxBlockBytes +} + +type MockPersistenceGenesisState struct { + Accounts []modules.Account `json:"accounts"` + Pools []modules.Account `json:"pools"` + Validators []modules.Actor `json:"validators"` + Applications []modules.Actor `json:"applications"` + ServiceNodes []modules.Actor `json:"service_nodes"` + Fishermen []modules.Actor `json:"fishermen"` + Params modules.Params `json:"params"` +} + +func (m MockPersistenceGenesisState) GetAccs() []modules.Account { + return m.Accounts +} + +func (m MockPersistenceGenesisState) GetAccPools() []modules.Account { + return m.Pools +} + +func (m MockPersistenceGenesisState) GetApps() []modules.Actor { + return m.Applications +} + +func (m MockPersistenceGenesisState) GetVals() []modules.Actor { + return m.Validators +} + +func (m MockPersistenceGenesisState) GetFish() []modules.Actor { + return m.Fishermen +} + +func (m MockPersistenceGenesisState) GetNodes() []modules.Actor { + return m.ServiceNodes +} + +func (m MockPersistenceGenesisState) GetParameters() modules.Params { + return m.Params +} + +var _ modules.ConsensusConfig = &MockConsensusConfig{} +var _ modules.PacemakerConfig = &MockPacemakerConfig{} +var _ modules.PersistenceConfig = &MockPersistenceConfig{} + +type MockPersistenceConfig struct { + PostgresUrl string `json:"postgres_url"` + NodeSchema string `json:"node_schema"` + BlockStorePath string `json:"block_store_path"` +} + +func (m *MockPersistenceConfig) GetPostgresUrl() string { + return m.PostgresUrl +} + +func (m *MockPersistenceConfig) GetNodeSchema() string { + return m.NodeSchema +} + +func (m *MockPersistenceConfig) GetBlockStorePath() string { + return m.BlockStorePath +} + +type MockConsensusConfig struct { + MaxMempoolBytes uint64 `json:"max_mempool_bytes"` + PacemakerConfig *MockPacemakerConfig `json:"pacemaker_config"` + PrivateKey string `json:"private_key"` +} + +func (m *MockConsensusConfig) GetMaxMempoolBytes() uint64 { + return m.MaxMempoolBytes +} + +func (m *MockConsensusConfig) GetPaceMakerConfig() modules.PacemakerConfig { + return m.PacemakerConfig +} + +type MockPacemakerConfig struct { + TimeoutMsec uint64 `json:"timeout_msec"` + Manual bool `json:"manual"` + DebugTimeBetweenStepsMsec uint64 `json:"debug_time_between_steps_msec"` +} + +func (m *MockPacemakerConfig) SetTimeoutMsec(u uint64) { + m.TimeoutMsec = u +} + +func (m *MockPacemakerConfig) GetTimeoutMsec() uint64 { + return m.TimeoutMsec +} + +func (m *MockPacemakerConfig) GetManual() bool { + return m.Manual +} + +func (m *MockPacemakerConfig) GetDebugTimeBetweenStepsMsec() uint64 { + return m.DebugTimeBetweenStepsMsec +} + +var _ modules.P2PConfig = &MockP2PConfig{} + +type MockP2PConfig struct { + ConsensusPort uint32 `json:"consensus_port"` + UseRainTree bool `json:"use_rain_tree"` + IsEmptyConnectionType bool `json:"is_empty_connection_type"` + PrivateKey string `json:"private_key"` +} + +func (m *MockP2PConfig) GetConsensusPort() uint32 { + return m.ConsensusPort +} + +func (m *MockP2PConfig) GetUseRainTree() bool { + return m.UseRainTree +} + +func (m *MockP2PConfig) IsEmptyConnType() bool { + return m.IsEmptyConnectionType +} + +var _ modules.TelemetryConfig = &MockTelemetryConfig{} + +type MockTelemetryConfig struct { + Enabled bool `json:"enabled"` + Address string `json:"address"` + Endpoint string `json:"endpoint"` +} + +func (m *MockTelemetryConfig) GetEnabled() bool { + return m.Enabled +} + +func (m *MockTelemetryConfig) GetAddress() string { + return m.Address +} + +func (m *MockTelemetryConfig) GetEndpoint() string { + return m.Endpoint +} + +type MockUtilityConfig struct{} + +var _ modules.Params = &MockParams{} + +type MockParams struct { + //@gotags: pokt:"val_type=BIGINT" + BlocksPerSession int32 `protobuf:"varint,1,opt,name=blocks_per_session,json=blocksPerSession,proto3" json:"blocks_per_session,omitempty"` + //@gotags: pokt:"val_type=STRING" + AppMinimumStake string `protobuf:"bytes,2,opt,name=app_minimum_stake,json=appMinimumStake,proto3" json:"app_minimum_stake,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + AppMaxChains int32 `protobuf:"varint,3,opt,name=app_max_chains,json=appMaxChains,proto3" json:"app_max_chains,omitempty"` + //@gotags: pokt:"val_type=BIGINT" + AppBaselineStakeRate int32 `protobuf:"varint,4,opt,name=app_baseline_stake_rate,json=appBaselineStakeRate,proto3" json:"app_baseline_stake_rate,omitempty"` + //@gotags: pokt:"val_type=BIGINT" + AppStakingAdjustment int32 `protobuf:"varint,5,opt,name=app_staking_adjustment,json=appStakingAdjustment,proto3" json:"app_staking_adjustment,omitempty"` + //@gotags: pokt:"val_type=BIGINT" + AppUnstakingBlocks int32 `protobuf:"varint,6,opt,name=app_unstaking_blocks,json=appUnstakingBlocks,proto3" json:"app_unstaking_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + AppMinimumPauseBlocks int32 `protobuf:"varint,7,opt,name=app_minimum_pause_blocks,json=appMinimumPauseBlocks,proto3" json:"app_minimum_pause_blocks,omitempty"` + //@gotags: pokt:"val_type=BIGINT" + AppMaxPauseBlocks int32 `protobuf:"varint,8,opt,name=app_max_pause_blocks,json=appMaxPauseBlocks,proto3" json:"app_max_pause_blocks,omitempty"` + //@gotags: pokt:"val_type=STRING" + ServiceNodeMinimumStake string `protobuf:"bytes,9,opt,name=service_node_minimum_stake,json=serviceNodeMinimumStake,proto3" json:"service_node_minimum_stake,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + ServiceNodeMaxChains int32 `protobuf:"varint,10,opt,name=service_node_max_chains,json=serviceNodeMaxChains,proto3" json:"service_node_max_chains,omitempty"` + //@gotags: pokt:"val_type=BIGINT" + ServiceNodeUnstakingBlocks int32 `protobuf:"varint,11,opt,name=service_node_unstaking_blocks,json=serviceNodeUnstakingBlocks,proto3" json:"service_node_unstaking_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + ServiceNodeMinimumPauseBlocks int32 `protobuf:"varint,12,opt,name=service_node_minimum_pause_blocks,json=serviceNodeMinimumPauseBlocks,proto3" json:"service_node_minimum_pause_blocks,omitempty"` + //@gotags: pokt:"val_type=BIGINT" + ServiceNodeMaxPauseBlocks int32 `protobuf:"varint,13,opt,name=service_node_max_pause_blocks,json=serviceNodeMaxPauseBlocks,proto3" json:"service_node_max_pause_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + ServiceNodesPerSession int32 `protobuf:"varint,14,opt,name=service_nodes_per_session,json=serviceNodesPerSession,proto3" json:"service_nodes_per_session,omitempty"` + //@gotags: pokt:"val_type=STRING" + FishermanMinimumStake string `protobuf:"bytes,15,opt,name=fisherman_minimum_stake,json=fishermanMinimumStake,proto3" json:"fisherman_minimum_stake,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + FishermanMaxChains int32 `protobuf:"varint,16,opt,name=fisherman_max_chains,json=fishermanMaxChains,proto3" json:"fisherman_max_chains,omitempty"` + //@gotags: pokt:"val_type=BIGINT" + FishermanUnstakingBlocks int32 `protobuf:"varint,17,opt,name=fisherman_unstaking_blocks,json=fishermanUnstakingBlocks,proto3" json:"fisherman_unstaking_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + FishermanMinimumPauseBlocks int32 `protobuf:"varint,18,opt,name=fisherman_minimum_pause_blocks,json=fishermanMinimumPauseBlocks,proto3" json:"fisherman_minimum_pause_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + FishermanMaxPauseBlocks int32 `protobuf:"varint,19,opt,name=fisherman_max_pause_blocks,json=fishermanMaxPauseBlocks,proto3" json:"fisherman_max_pause_blocks,omitempty"` + //@gotags: pokt:"val_type=STRING" + ValidatorMinimumStake string `protobuf:"bytes,20,opt,name=validator_minimum_stake,json=validatorMinimumStake,proto3" json:"validator_minimum_stake,omitempty"` + //@gotags: pokt:"val_type=BIGINT" + ValidatorUnstakingBlocks int32 `protobuf:"varint,21,opt,name=validator_unstaking_blocks,json=validatorUnstakingBlocks,proto3" json:"validator_unstaking_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + ValidatorMinimumPauseBlocks int32 `protobuf:"varint,22,opt,name=validator_minimum_pause_blocks,json=validatorMinimumPauseBlocks,proto3" json:"validator_minimum_pause_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + ValidatorMaxPauseBlocks int32 `protobuf:"varint,23,opt,name=validator_max_pause_blocks,json=validatorMaxPauseBlocks,proto3" json:"validator_max_pause_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + ValidatorMaximumMissedBlocks int32 `protobuf:"varint,24,opt,name=validator_maximum_missed_blocks,json=validatorMaximumMissedBlocks,proto3" json:"validator_maximum_missed_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + ValidatorMaxEvidenceAgeInBlocks int32 `protobuf:"varint,25,opt,name=validator_max_evidence_age_in_blocks,json=validatorMaxEvidenceAgeInBlocks,proto3" json:"validator_max_evidence_age_in_blocks,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + ProposerPercentageOfFees int32 `protobuf:"varint,26,opt,name=proposer_percentage_of_fees,json=proposerPercentageOfFees,proto3" json:"proposer_percentage_of_fees,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + MissedBlocksBurnPercentage int32 `protobuf:"varint,27,opt,name=missed_blocks_burn_percentage,json=missedBlocksBurnPercentage,proto3" json:"missed_blocks_burn_percentage,omitempty"` + //@gotags: pokt:"val_type=SMALLINT" + DoubleSignBurnPercentage int32 `protobuf:"varint,28,opt,name=double_sign_burn_percentage,json=doubleSignBurnPercentage,proto3" json:"double_sign_burn_percentage,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageDoubleSignFee string `protobuf:"bytes,29,opt,name=message_double_sign_fee,json=messageDoubleSignFee,proto3" json:"message_double_sign_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageSendFee string `protobuf:"bytes,30,opt,name=message_send_fee,json=messageSendFee,proto3" json:"message_send_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageStakeFishermanFee string `protobuf:"bytes,31,opt,name=message_stake_fisherman_fee,json=messageStakeFishermanFee,proto3" json:"message_stake_fisherman_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageEditStakeFishermanFee string `protobuf:"bytes,32,opt,name=message_edit_stake_fisherman_fee,json=messageEditStakeFishermanFee,proto3" json:"message_edit_stake_fisherman_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnstakeFishermanFee string `protobuf:"bytes,33,opt,name=message_unstake_fisherman_fee,json=messageUnstakeFishermanFee,proto3" json:"message_unstake_fisherman_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessagePauseFishermanFee string `protobuf:"bytes,34,opt,name=message_pause_fisherman_fee,json=messagePauseFishermanFee,proto3" json:"message_pause_fisherman_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnpauseFishermanFee string `protobuf:"bytes,35,opt,name=message_unpause_fisherman_fee,json=messageUnpauseFishermanFee,proto3" json:"message_unpause_fisherman_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageFishermanPauseServiceNodeFee string `protobuf:"bytes,36,opt,name=message_fisherman_pause_service_node_fee,json=messageFishermanPauseServiceNodeFee,proto3" json:"message_fisherman_pause_service_node_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageTestScoreFee string `protobuf:"bytes,37,opt,name=message_test_score_fee,json=messageTestScoreFee,proto3" json:"message_test_score_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageProveTestScoreFee string `protobuf:"bytes,38,opt,name=message_prove_test_score_fee,json=messageProveTestScoreFee,proto3" json:"message_prove_test_score_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageStakeAppFee string `protobuf:"bytes,39,opt,name=message_stake_app_fee,json=messageStakeAppFee,proto3" json:"message_stake_app_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageEditStakeAppFee string `protobuf:"bytes,40,opt,name=message_edit_stake_app_fee,json=messageEditStakeAppFee,proto3" json:"message_edit_stake_app_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnstakeAppFee string `protobuf:"bytes,41,opt,name=message_unstake_app_fee,json=messageUnstakeAppFee,proto3" json:"message_unstake_app_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessagePauseAppFee string `protobuf:"bytes,42,opt,name=message_pause_app_fee,json=messagePauseAppFee,proto3" json:"message_pause_app_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnpauseAppFee string `protobuf:"bytes,43,opt,name=message_unpause_app_fee,json=messageUnpauseAppFee,proto3" json:"message_unpause_app_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageStakeValidatorFee string `protobuf:"bytes,44,opt,name=message_stake_validator_fee,json=messageStakeValidatorFee,proto3" json:"message_stake_validator_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageEditStakeValidatorFee string `protobuf:"bytes,45,opt,name=message_edit_stake_validator_fee,json=messageEditStakeValidatorFee,proto3" json:"message_edit_stake_validator_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnstakeValidatorFee string `protobuf:"bytes,46,opt,name=message_unstake_validator_fee,json=messageUnstakeValidatorFee,proto3" json:"message_unstake_validator_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessagePauseValidatorFee string `protobuf:"bytes,47,opt,name=message_pause_validator_fee,json=messagePauseValidatorFee,proto3" json:"message_pause_validator_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnpauseValidatorFee string `protobuf:"bytes,48,opt,name=message_unpause_validator_fee,json=messageUnpauseValidatorFee,proto3" json:"message_unpause_validator_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageStakeServiceNodeFee string `protobuf:"bytes,49,opt,name=message_stake_service_node_fee,json=messageStakeServiceNodeFee,proto3" json:"message_stake_service_node_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageEditStakeServiceNodeFee string `protobuf:"bytes,50,opt,name=message_edit_stake_service_node_fee,json=messageEditStakeServiceNodeFee,proto3" json:"message_edit_stake_service_node_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnstakeServiceNodeFee string `protobuf:"bytes,51,opt,name=message_unstake_service_node_fee,json=messageUnstakeServiceNodeFee,proto3" json:"message_unstake_service_node_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessagePauseServiceNodeFee string `protobuf:"bytes,52,opt,name=message_pause_service_node_fee,json=messagePauseServiceNodeFee,proto3" json:"message_pause_service_node_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnpauseServiceNodeFee string `protobuf:"bytes,53,opt,name=message_unpause_service_node_fee,json=messageUnpauseServiceNodeFee,proto3" json:"message_unpause_service_node_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageChangeParameterFee string `protobuf:"bytes,54,opt,name=message_change_parameter_fee,json=messageChangeParameterFee,proto3" json:"message_change_parameter_fee,omitempty"` + //@gotags: pokt:"val_type=STRING" + AclOwner string `protobuf:"bytes,55,opt,name=acl_owner,json=aclOwner,proto3" json:"acl_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + BlocksPerSessionOwner string `protobuf:"bytes,56,opt,name=blocks_per_session_owner,json=blocksPerSessionOwner,proto3" json:"blocks_per_session_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + AppMinimumStakeOwner string `protobuf:"bytes,57,opt,name=app_minimum_stake_owner,json=appMinimumStakeOwner,proto3" json:"app_minimum_stake_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + AppMaxChainsOwner string `protobuf:"bytes,58,opt,name=app_max_chains_owner,json=appMaxChainsOwner,proto3" json:"app_max_chains_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + AppBaselineStakeRateOwner string `protobuf:"bytes,59,opt,name=app_baseline_stake_rate_owner,json=appBaselineStakeRateOwner,proto3" json:"app_baseline_stake_rate_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + AppStakingAdjustmentOwner string `protobuf:"bytes,60,opt,name=app_staking_adjustment_owner,json=appStakingAdjustmentOwner,proto3" json:"app_staking_adjustment_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + AppUnstakingBlocksOwner string `protobuf:"bytes,61,opt,name=app_unstaking_blocks_owner,json=appUnstakingBlocksOwner,proto3" json:"app_unstaking_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + AppMinimumPauseBlocksOwner string `protobuf:"bytes,62,opt,name=app_minimum_pause_blocks_owner,json=appMinimumPauseBlocksOwner,proto3" json:"app_minimum_pause_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + AppMaxPausedBlocksOwner string `protobuf:"bytes,63,opt,name=app_max_paused_blocks_owner,json=appMaxPausedBlocksOwner,proto3" json:"app_max_paused_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ServiceNodeMinimumStakeOwner string `protobuf:"bytes,64,opt,name=service_node_minimum_stake_owner,json=serviceNodeMinimumStakeOwner,proto3" json:"service_node_minimum_stake_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ServiceNodeMaxChainsOwner string `protobuf:"bytes,65,opt,name=service_node_max_chains_owner,json=serviceNodeMaxChainsOwner,proto3" json:"service_node_max_chains_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ServiceNodeUnstakingBlocksOwner string `protobuf:"bytes,66,opt,name=service_node_unstaking_blocks_owner,json=serviceNodeUnstakingBlocksOwner,proto3" json:"service_node_unstaking_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ServiceNodeMinimumPauseBlocksOwner string `protobuf:"bytes,67,opt,name=service_node_minimum_pause_blocks_owner,json=serviceNodeMinimumPauseBlocksOwner,proto3" json:"service_node_minimum_pause_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ServiceNodeMaxPausedBlocksOwner string `protobuf:"bytes,68,opt,name=service_node_max_paused_blocks_owner,json=serviceNodeMaxPausedBlocksOwner,proto3" json:"service_node_max_paused_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ServiceNodesPerSessionOwner string `protobuf:"bytes,69,opt,name=service_nodes_per_session_owner,json=serviceNodesPerSessionOwner,proto3" json:"service_nodes_per_session_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + FishermanMinimumStakeOwner string `protobuf:"bytes,70,opt,name=fisherman_minimum_stake_owner,json=fishermanMinimumStakeOwner,proto3" json:"fisherman_minimum_stake_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + FishermanMaxChainsOwner string `protobuf:"bytes,71,opt,name=fisherman_max_chains_owner,json=fishermanMaxChainsOwner,proto3" json:"fisherman_max_chains_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + FishermanUnstakingBlocksOwner string `protobuf:"bytes,72,opt,name=fisherman_unstaking_blocks_owner,json=fishermanUnstakingBlocksOwner,proto3" json:"fisherman_unstaking_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + FishermanMinimumPauseBlocksOwner string `protobuf:"bytes,73,opt,name=fisherman_minimum_pause_blocks_owner,json=fishermanMinimumPauseBlocksOwner,proto3" json:"fisherman_minimum_pause_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + FishermanMaxPausedBlocksOwner string `protobuf:"bytes,74,opt,name=fisherman_max_paused_blocks_owner,json=fishermanMaxPausedBlocksOwner,proto3" json:"fisherman_max_paused_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ValidatorMinimumStakeOwner string `protobuf:"bytes,75,opt,name=validator_minimum_stake_owner,json=validatorMinimumStakeOwner,proto3" json:"validator_minimum_stake_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ValidatorUnstakingBlocksOwner string `protobuf:"bytes,76,opt,name=validator_unstaking_blocks_owner,json=validatorUnstakingBlocksOwner,proto3" json:"validator_unstaking_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ValidatorMinimumPauseBlocksOwner string `protobuf:"bytes,77,opt,name=validator_minimum_pause_blocks_owner,json=validatorMinimumPauseBlocksOwner,proto3" json:"validator_minimum_pause_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ValidatorMaxPausedBlocksOwner string `protobuf:"bytes,78,opt,name=validator_max_paused_blocks_owner,json=validatorMaxPausedBlocksOwner,proto3" json:"validator_max_paused_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ValidatorMaximumMissedBlocksOwner string `protobuf:"bytes,79,opt,name=validator_maximum_missed_blocks_owner,json=validatorMaximumMissedBlocksOwner,proto3" json:"validator_maximum_missed_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ValidatorMaxEvidenceAgeInBlocksOwner string `protobuf:"bytes,80,opt,name=validator_max_evidence_age_in_blocks_owner,json=validatorMaxEvidenceAgeInBlocksOwner,proto3" json:"validator_max_evidence_age_in_blocks_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + ProposerPercentageOfFeesOwner string `protobuf:"bytes,81,opt,name=proposer_percentage_of_fees_owner,json=proposerPercentageOfFeesOwner,proto3" json:"proposer_percentage_of_fees_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MissedBlocksBurnPercentageOwner string `protobuf:"bytes,82,opt,name=missed_blocks_burn_percentage_owner,json=missedBlocksBurnPercentageOwner,proto3" json:"missed_blocks_burn_percentage_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + DoubleSignBurnPercentageOwner string `protobuf:"bytes,83,opt,name=double_sign_burn_percentage_owner,json=doubleSignBurnPercentageOwner,proto3" json:"double_sign_burn_percentage_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageDoubleSignFeeOwner string `protobuf:"bytes,84,opt,name=message_double_sign_fee_owner,json=messageDoubleSignFeeOwner,proto3" json:"message_double_sign_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageSendFeeOwner string `protobuf:"bytes,85,opt,name=message_send_fee_owner,json=messageSendFeeOwner,proto3" json:"message_send_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageStakeFishermanFeeOwner string `protobuf:"bytes,86,opt,name=message_stake_fisherman_fee_owner,json=messageStakeFishermanFeeOwner,proto3" json:"message_stake_fisherman_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageEditStakeFishermanFeeOwner string `protobuf:"bytes,87,opt,name=message_edit_stake_fisherman_fee_owner,json=messageEditStakeFishermanFeeOwner,proto3" json:"message_edit_stake_fisherman_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnstakeFishermanFeeOwner string `protobuf:"bytes,88,opt,name=message_unstake_fisherman_fee_owner,json=messageUnstakeFishermanFeeOwner,proto3" json:"message_unstake_fisherman_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessagePauseFishermanFeeOwner string `protobuf:"bytes,89,opt,name=message_pause_fisherman_fee_owner,json=messagePauseFishermanFeeOwner,proto3" json:"message_pause_fisherman_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnpauseFishermanFeeOwner string `protobuf:"bytes,90,opt,name=message_unpause_fisherman_fee_owner,json=messageUnpauseFishermanFeeOwner,proto3" json:"message_unpause_fisherman_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageFishermanPauseServiceNodeFeeOwner string `protobuf:"bytes,91,opt,name=message_fisherman_pause_service_node_fee_owner,json=messageFishermanPauseServiceNodeFeeOwner,proto3" json:"message_fisherman_pause_service_node_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageTestScoreFeeOwner string `protobuf:"bytes,92,opt,name=message_test_score_fee_owner,json=messageTestScoreFeeOwner,proto3" json:"message_test_score_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageProveTestScoreFeeOwner string `protobuf:"bytes,93,opt,name=message_prove_test_score_fee_owner,json=messageProveTestScoreFeeOwner,proto3" json:"message_prove_test_score_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageStakeAppFeeOwner string `protobuf:"bytes,94,opt,name=message_stake_app_fee_owner,json=messageStakeAppFeeOwner,proto3" json:"message_stake_app_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageEditStakeAppFeeOwner string `protobuf:"bytes,95,opt,name=message_edit_stake_app_fee_owner,json=messageEditStakeAppFeeOwner,proto3" json:"message_edit_stake_app_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnstakeAppFeeOwner string `protobuf:"bytes,96,opt,name=message_unstake_app_fee_owner,json=messageUnstakeAppFeeOwner,proto3" json:"message_unstake_app_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessagePauseAppFeeOwner string `protobuf:"bytes,97,opt,name=message_pause_app_fee_owner,json=messagePauseAppFeeOwner,proto3" json:"message_pause_app_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnpauseAppFeeOwner string `protobuf:"bytes,98,opt,name=message_unpause_app_fee_owner,json=messageUnpauseAppFeeOwner,proto3" json:"message_unpause_app_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageStakeValidatorFeeOwner string `protobuf:"bytes,99,opt,name=message_stake_validator_fee_owner,json=messageStakeValidatorFeeOwner,proto3" json:"message_stake_validator_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageEditStakeValidatorFeeOwner string `protobuf:"bytes,100,opt,name=message_edit_stake_validator_fee_owner,json=messageEditStakeValidatorFeeOwner,proto3" json:"message_edit_stake_validator_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnstakeValidatorFeeOwner string `protobuf:"bytes,101,opt,name=message_unstake_validator_fee_owner,json=messageUnstakeValidatorFeeOwner,proto3" json:"message_unstake_validator_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessagePauseValidatorFeeOwner string `protobuf:"bytes,102,opt,name=message_pause_validator_fee_owner,json=messagePauseValidatorFeeOwner,proto3" json:"message_pause_validator_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnpauseValidatorFeeOwner string `protobuf:"bytes,103,opt,name=message_unpause_validator_fee_owner,json=messageUnpauseValidatorFeeOwner,proto3" json:"message_unpause_validator_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageStakeServiceNodeFeeOwner string `protobuf:"bytes,104,opt,name=message_stake_service_node_fee_owner,json=messageStakeServiceNodeFeeOwner,proto3" json:"message_stake_service_node_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageEditStakeServiceNodeFeeOwner string `protobuf:"bytes,105,opt,name=message_edit_stake_service_node_fee_owner,json=messageEditStakeServiceNodeFeeOwner,proto3" json:"message_edit_stake_service_node_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnstakeServiceNodeFeeOwner string `protobuf:"bytes,106,opt,name=message_unstake_service_node_fee_owner,json=messageUnstakeServiceNodeFeeOwner,proto3" json:"message_unstake_service_node_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessagePauseServiceNodeFeeOwner string `protobuf:"bytes,107,opt,name=message_pause_service_node_fee_owner,json=messagePauseServiceNodeFeeOwner,proto3" json:"message_pause_service_node_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageUnpauseServiceNodeFeeOwner string `protobuf:"bytes,108,opt,name=message_unpause_service_node_fee_owner,json=messageUnpauseServiceNodeFeeOwner,proto3" json:"message_unpause_service_node_fee_owner,omitempty"` + //@gotags: pokt:"val_type=STRING" + MessageChangeParameterFeeOwner string `protobuf:"bytes,109,opt,name=message_change_parameter_fee_owner,json=messageChangeParameterFeeOwner,proto3" json:"message_change_parameter_fee_owner,omitempty"` +} + +func (m *MockParams) GetBlocksPerSession() int32 { + return m.BlocksPerSession +} + +func (m *MockParams) GetAppMinimumStake() string { + return m.AppMinimumStake +} + +func (m *MockParams) GetAppMaxChains() int32 { + return m.AppMaxChains +} + +func (m *MockParams) GetAppBaselineStakeRate() int32 { + return m.AppBaselineStakeRate +} + +func (m *MockParams) GetAppStakingAdjustment() int32 { + return m.AppStakingAdjustment +} + +func (m *MockParams) GetAppUnstakingBlocks() int32 { + return m.AppUnstakingBlocks +} + +func (m *MockParams) GetAppMinimumPauseBlocks() int32 { + return m.AppMinimumPauseBlocks +} + +func (m *MockParams) GetAppMaxPauseBlocks() int32 { + return m.AppMaxPauseBlocks +} + +func (m *MockParams) GetServiceNodeMinimumStake() string { + return m.ServiceNodeMinimumStake +} + +func (m *MockParams) GetServiceNodeMaxChains() int32 { + return m.ServiceNodeMaxChains +} + +func (m *MockParams) GetServiceNodeUnstakingBlocks() int32 { + return m.ServiceNodeUnstakingBlocks +} + +func (m *MockParams) GetServiceNodeMinimumPauseBlocks() int32 { + return m.ServiceNodeMinimumPauseBlocks +} + +func (m *MockParams) GetServiceNodeMaxPauseBlocks() int32 { + return m.ServiceNodeMaxPauseBlocks +} + +func (m *MockParams) GetServiceNodesPerSession() int32 { + return m.ServiceNodesPerSession +} + +func (m *MockParams) GetFishermanMinimumStake() string { + return m.FishermanMinimumStake +} + +func (m *MockParams) GetFishermanMaxChains() int32 { + return m.FishermanMaxChains +} + +func (m *MockParams) GetFishermanUnstakingBlocks() int32 { + return m.FishermanUnstakingBlocks +} + +func (m *MockParams) GetFishermanMinimumPauseBlocks() int32 { + return m.FishermanMinimumPauseBlocks +} + +func (m *MockParams) GetFishermanMaxPauseBlocks() int32 { + return m.FishermanMaxPauseBlocks +} + +func (m *MockParams) GetValidatorMinimumStake() string { + return m.ValidatorMinimumStake +} + +func (m *MockParams) GetValidatorUnstakingBlocks() int32 { + return m.ValidatorUnstakingBlocks +} + +func (m *MockParams) GetValidatorMinimumPauseBlocks() int32 { + return m.ValidatorMinimumPauseBlocks +} + +func (m *MockParams) GetValidatorMaxPauseBlocks() int32 { + return m.ValidatorMaxPauseBlocks +} + +func (m *MockParams) GetValidatorMaximumMissedBlocks() int32 { + return m.ValidatorMaximumMissedBlocks +} + +func (m *MockParams) GetValidatorMaxEvidenceAgeInBlocks() int32 { + return m.ValidatorMaxEvidenceAgeInBlocks +} + +func (m *MockParams) GetProposerPercentageOfFees() int32 { + return m.ProposerPercentageOfFees +} + +func (m *MockParams) GetMissedBlocksBurnPercentage() int32 { + return m.MissedBlocksBurnPercentage +} + +func (m *MockParams) GetDoubleSignBurnPercentage() int32 { + return m.DoubleSignBurnPercentage +} + +func (m *MockParams) GetMessageDoubleSignFee() string { + return m.MessageDoubleSignFee +} + +func (m *MockParams) GetMessageSendFee() string { + return m.MessageSendFee +} + +func (m *MockParams) GetMessageStakeFishermanFee() string { + return m.MessageStakeFishermanFee +} + +func (m *MockParams) GetMessageEditStakeFishermanFee() string { + return m.MessageEditStakeFishermanFee +} + +func (m *MockParams) GetMessageUnstakeFishermanFee() string { + return m.MessageUnstakeFishermanFee +} + +func (m *MockParams) GetMessagePauseFishermanFee() string { + return m.MessagePauseFishermanFee +} + +func (m *MockParams) GetMessageUnpauseFishermanFee() string { + return m.MessageUnpauseFishermanFee +} + +func (m *MockParams) GetMessageFishermanPauseServiceNodeFee() string { + return m.MessageFishermanPauseServiceNodeFee +} + +func (m *MockParams) GetMessageTestScoreFee() string { + return m.MessageTestScoreFee +} + +func (m *MockParams) GetMessageProveTestScoreFee() string { + return m.MessageProveTestScoreFee +} + +func (m *MockParams) GetMessageStakeAppFee() string { + return m.MessageStakeAppFee +} + +func (m *MockParams) GetMessageEditStakeAppFee() string { + return m.MessageEditStakeAppFee +} + +func (m *MockParams) GetMessageUnstakeAppFee() string { + return m.MessageUnstakeAppFee +} + +func (m *MockParams) GetMessagePauseAppFee() string { + return m.MessagePauseAppFee +} + +func (m *MockParams) GetMessageUnpauseAppFee() string { + return m.MessageUnpauseAppFee +} + +func (m *MockParams) GetMessageStakeValidatorFee() string { + return m.MessageStakeValidatorFee +} + +func (m *MockParams) GetMessageEditStakeValidatorFee() string { + return m.MessageEditStakeValidatorFee +} + +func (m *MockParams) GetMessageUnstakeValidatorFee() string { + return m.MessageUnstakeValidatorFee +} + +func (m *MockParams) GetMessagePauseValidatorFee() string { + return m.MessagePauseValidatorFee +} + +func (m *MockParams) GetMessageUnpauseValidatorFee() string { + return m.MessageUnpauseValidatorFee +} + +func (m *MockParams) GetMessageStakeServiceNodeFee() string { + return m.MessageStakeServiceNodeFee +} + +func (m *MockParams) GetMessageEditStakeServiceNodeFee() string { + return m.MessageEditStakeServiceNodeFee +} + +func (m *MockParams) GetMessageUnstakeServiceNodeFee() string { + return m.MessageUnstakeServiceNodeFee +} + +func (m *MockParams) GetMessagePauseServiceNodeFee() string { + return m.MessagePauseServiceNodeFee +} + +func (m *MockParams) GetMessageUnpauseServiceNodeFee() string { + return m.MessageUnpauseServiceNodeFee +} + +func (m *MockParams) GetMessageChangeParameterFee() string { + return m.MessageChangeParameterFee +} + +func (m *MockParams) GetAclOwner() string { + return m.AclOwner +} + +func (m *MockParams) GetBlocksPerSessionOwner() string { + return m.BlocksPerSessionOwner +} + +func (m *MockParams) GetAppMinimumStakeOwner() string { + return m.AppMinimumStakeOwner +} + +func (m *MockParams) GetAppMaxChainsOwner() string { + return m.AppMaxChainsOwner +} + +func (m *MockParams) GetAppBaselineStakeRateOwner() string { + return m.AppBaselineStakeRateOwner +} + +func (m *MockParams) GetAppStakingAdjustmentOwner() string { + return m.AppStakingAdjustmentOwner +} + +func (m *MockParams) GetAppUnstakingBlocksOwner() string { + return m.AppUnstakingBlocksOwner +} + +func (m *MockParams) GetAppMinimumPauseBlocksOwner() string { + return m.AppMinimumPauseBlocksOwner +} + +func (m *MockParams) GetAppMaxPausedBlocksOwner() string { + return m.AppMaxPausedBlocksOwner +} + +func (m *MockParams) GetServiceNodeMinimumStakeOwner() string { + return m.ServiceNodeMinimumStakeOwner +} + +func (m *MockParams) GetServiceNodeMaxChainsOwner() string { + return m.ServiceNodeMaxChainsOwner +} + +func (m *MockParams) GetServiceNodeUnstakingBlocksOwner() string { + return m.ServiceNodeUnstakingBlocksOwner +} + +func (m *MockParams) GetServiceNodeMinimumPauseBlocksOwner() string { + return m.ServiceNodeMinimumPauseBlocksOwner +} + +func (m *MockParams) GetServiceNodeMaxPausedBlocksOwner() string { + return m.ServiceNodeMaxPausedBlocksOwner +} + +func (m *MockParams) GetServiceNodesPerSessionOwner() string { + return m.ServiceNodesPerSessionOwner +} + +func (m *MockParams) GetFishermanMinimumStakeOwner() string { + return m.FishermanMinimumStakeOwner +} + +func (m *MockParams) GetFishermanMaxChainsOwner() string { + return m.FishermanMaxChainsOwner +} + +func (m *MockParams) GetFishermanUnstakingBlocksOwner() string { + return m.FishermanUnstakingBlocksOwner +} + +func (m *MockParams) GetFishermanMinimumPauseBlocksOwner() string { + return m.FishermanMinimumPauseBlocksOwner +} + +func (m *MockParams) GetFishermanMaxPausedBlocksOwner() string { + return m.FishermanMaxPausedBlocksOwner +} + +func (m *MockParams) GetValidatorMinimumStakeOwner() string { + return m.ValidatorMinimumStakeOwner +} + +func (m *MockParams) GetValidatorUnstakingBlocksOwner() string { + return m.ValidatorUnstakingBlocksOwner +} + +func (m *MockParams) GetValidatorMinimumPauseBlocksOwner() string { + return m.ValidatorMinimumPauseBlocksOwner +} + +func (m *MockParams) GetValidatorMaxPausedBlocksOwner() string { + return m.ValidatorMaxPausedBlocksOwner +} + +func (m *MockParams) GetValidatorMaximumMissedBlocksOwner() string { + return m.ValidatorMaximumMissedBlocksOwner +} + +func (m *MockParams) GetValidatorMaxEvidenceAgeInBlocksOwner() string { + return m.ValidatorMaxEvidenceAgeInBlocksOwner +} + +func (m *MockParams) GetProposerPercentageOfFeesOwner() string { + return m.ProposerPercentageOfFeesOwner +} + +func (m *MockParams) GetMissedBlocksBurnPercentageOwner() string { + return m.MissedBlocksBurnPercentageOwner +} + +func (m *MockParams) GetDoubleSignBurnPercentageOwner() string { + return m.DoubleSignBurnPercentageOwner +} + +func (m *MockParams) GetMessageDoubleSignFeeOwner() string { + return m.MessageDoubleSignFeeOwner +} + +func (m *MockParams) GetMessageSendFeeOwner() string { + return m.MessageSendFeeOwner +} + +func (m *MockParams) GetMessageStakeFishermanFeeOwner() string { + return m.MessageStakeFishermanFeeOwner +} + +func (m *MockParams) GetMessageEditStakeFishermanFeeOwner() string { + return m.MessageEditStakeFishermanFeeOwner +} + +func (m *MockParams) GetMessageUnstakeFishermanFeeOwner() string { + return m.MessageUnstakeFishermanFeeOwner +} + +func (m *MockParams) GetMessagePauseFishermanFeeOwner() string { + return m.MessagePauseFishermanFeeOwner +} + +func (m *MockParams) GetMessageUnpauseFishermanFeeOwner() string { + return m.MessageUnpauseFishermanFeeOwner +} + +func (m *MockParams) GetMessageFishermanPauseServiceNodeFeeOwner() string { + return m.MessageFishermanPauseServiceNodeFeeOwner +} + +func (m *MockParams) GetMessageTestScoreFeeOwner() string { + return m.MessageTestScoreFeeOwner +} + +func (m *MockParams) GetMessageProveTestScoreFeeOwner() string { + return m.MessageProveTestScoreFeeOwner +} + +func (m *MockParams) GetMessageStakeAppFeeOwner() string { + return m.MessageStakeAppFeeOwner +} + +func (m *MockParams) GetMessageEditStakeAppFeeOwner() string { + return m.MessageEditStakeAppFeeOwner +} + +func (m *MockParams) GetMessageUnstakeAppFeeOwner() string { + return m.MessageUnstakeAppFeeOwner +} + +func (m *MockParams) GetMessagePauseAppFeeOwner() string { + return m.MessagePauseAppFeeOwner +} + +func (m *MockParams) GetMessageUnpauseAppFeeOwner() string { + return m.MessageUnpauseAppFeeOwner +} + +func (m *MockParams) GetMessageStakeValidatorFeeOwner() string { + return m.MessageStakeValidatorFeeOwner +} + +func (m *MockParams) GetMessageEditStakeValidatorFeeOwner() string { + return m.MessageEditStakeValidatorFeeOwner +} + +func (m *MockParams) GetMessageUnstakeValidatorFeeOwner() string { + return m.MessageUnstakeValidatorFeeOwner +} + +func (m *MockParams) GetMessagePauseValidatorFeeOwner() string { + return m.MessagePauseValidatorFeeOwner +} + +func (m *MockParams) GetMessageUnpauseValidatorFeeOwner() string { + return m.MessageUnpauseValidatorFeeOwner +} + +func (m *MockParams) GetMessageStakeServiceNodeFeeOwner() string { + return m.MessageStakeServiceNodeFeeOwner +} + +func (m *MockParams) GetMessageEditStakeServiceNodeFeeOwner() string { + return m.MessageEditStakeServiceNodeFeeOwner +} + +func (m *MockParams) GetMessageUnstakeServiceNodeFeeOwner() string { + return m.MessageUnstakeServiceNodeFeeOwner +} + +func (m *MockParams) GetMessagePauseServiceNodeFeeOwner() string { + return m.MessagePauseServiceNodeFeeOwner +} + +func (m *MockParams) GetMessageUnpauseServiceNodeFeeOwner() string { + return m.MessageUnpauseServiceNodeFeeOwner +} + +func (m *MockParams) GetMessageChangeParameterFeeOwner() string { + return m.MessageChangeParameterFeeOwner +} diff --git a/shared/tests/util.go b/shared/test_artifacts/util.go similarity index 92% rename from shared/tests/util.go rename to shared/test_artifacts/util.go index 2316cc85f..3f5387f3a 100644 --- a/shared/tests/util.go +++ b/shared/test_artifacts/util.go @@ -1,4 +1,4 @@ -package tests +package test_artifacts import ( "context" @@ -24,7 +24,8 @@ const ( connStringFormat = "postgres://%s:%s@%s/%s?sslmode=disable" ) -// TODO (team) cleanup and simplify +// DISCUSS(team) both the persistence module and the utility module share this code which is less than ideal +// (see call to action in generator.go to try to remove the cross module testing code) func SetupPostgresDocker() (*dockertest.Pool, *dockertest.Resource, string) { opts := dockertest.RunOptions{ Repository: "postgres", diff --git a/shared/tests/utility_module/module_test.go b/shared/tests/utility_module/module_test.go deleted file mode 100644 index 40b618044..000000000 --- a/shared/tests/utility_module/module_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package utility_module - -import ( - "log" - "math/big" - "testing" - - "github.com/pokt-network/pocket/persistence" - "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/tests" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" - "github.com/pokt-network/pocket/utility" - "github.com/stretchr/testify/require" -) - -var ( - defaultTestingChainsEdited = []string{"0002"} - defaultUnstaking = int64(2017) - defaultSendAmount = big.NewInt(10000) - defaultNonceString = types.BigIntToString(test_artifacts.DefaultAccountAmount) - defaultSendAmountString = types.BigIntToString(defaultSendAmount) - testSchema = "test_schema" -) - -// TODO(olshansky): Find a way to avoid this global test variable -var testPersistenceMod modules.PersistenceModule - -func NewTestingMempool(_ *testing.T) types.Mempool { - return types.NewMempool(1000000, 1000) -} - -func TestMain(m *testing.M) { - pool, resource, dbUrl := tests.SetupPostgresDocker() - testPersistenceMod = newTestPersistenceModule(dbUrl) - m.Run() - tests.CleanupPostgresDocker(m, pool, resource) -} - -func NewTestingUtilityContext(t *testing.T, height int64) utility.UtilityContext { - persistenceContext, err := testPersistenceMod.NewRWContext(height) - require.NoError(t, err) - - t.Cleanup(func() { - testPersistenceMod.ResetContext() - }) - - return utility.UtilityContext{ - LatestHeight: height, - Mempool: NewTestingMempool(t), - Context: &utility.Context{ - PersistenceRWContext: persistenceContext, - SavePointsM: make(map[string]struct{}), - SavePoints: make([][]byte, 0), - }, - } -} - -// TODO(andrew): Take in `t` and fail the test if there's an error -func newTestPersistenceModule(databaseUrl string) modules.PersistenceModule { - cfg := &genesis.Config{ - Base: &genesis.BaseConfig{}, - Consensus: &genesis.ConsensusConfig{}, - Utility: &genesis.UtilityConfig{}, - Persistence: &genesis.PersistenceConfig{ - PostgresUrl: databaseUrl, - NodeSchema: testSchema, - BlockStorePath: "", - }, - P2P: &genesis.P2PConfig{}, - Telemetry: &genesis.TelemetryConfig{}, - } - // TODO(andrew): Move the number of actors into local constants - genesisState, _ := test_artifacts.NewGenesisState(5, 1, 1, 1) - persistenceMod, err := persistence.Create(cfg, genesisState) - if err != nil { - log.Fatalf("Error creating persistence module: %s", err) - } - // TODO(andrew): Check for error - persistenceMod.Start() - return persistenceMod -} diff --git a/shared/types/block.go b/shared/types/block.go deleted file mode 100644 index 67c545562..000000000 --- a/shared/types/block.go +++ /dev/null @@ -1,58 +0,0 @@ -package types - -import ( - "encoding/hex" - - crypto2 "github.com/pokt-network/pocket/shared/crypto" -) - -// TODO(andrew): move block to consensus module; pocket/issues/163 -func (b *Block) ValidateBasic() Error { - if err := b.BlockHeader.ValidateBasic(); err != nil { - return err - } - for _, tx := range b.Transactions { - if tx == nil { - return EmptyTransactionErr() - } - } - return nil -} - -func (bh *BlockHeader) ValidateBasic() Error { - if bh.NetworkId == "" { - return ErrEmptyNetworkID() - } - if bh.Time.Seconds == 0 { - return ErrEmptyTimestamp() - } - if int64(bh.NumTxs) > bh.TotalTxs { - return ErrInvalidTransactionCount() - } - if bh.ProposerAddress == nil { - return ErrEmptyProposer() - } - if _, err := crypto2.NewAddressFromBytes(bh.ProposerAddress); err != nil { - return ErrNewAddressFromBytes(err) - } - hashBytes, err := hex.DecodeString(bh.Hash) - if err != nil { - return ErrHexDecodeFromString(err) - } - hashLen := len(hashBytes) - if hashLen != crypto2.SHA3HashLen { - return ErrInvalidHashLength(crypto2.ErrInvalidHashLen(hashLen)) - } - hashBytes, err = hex.DecodeString(bh.LastBlockHash) - if err != nil { - return ErrHexDecodeFromString(err) - } - hashLen = len(hashBytes) - if hashLen != crypto2.SHA3HashLen { - return ErrInvalidHashLength(crypto2.ErrInvalidHashLen(hashLen)) - } - if bh.QuorumCertificate == nil { - return ErrNilQuorumCertificate() - } - return nil -} diff --git a/shared/types/codec_test.go b/shared/types/codec_test.go deleted file mode 100644 index 8cf1aac43..000000000 --- a/shared/types/codec_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package types - -import ( - "bytes" - "testing" - - "github.com/pokt-network/pocket/shared/crypto" - "github.com/stretchr/testify/require" -) - -func TestUtilityCodec(t *testing.T) { - addr, err := crypto.GenerateAddress() - require.NoError(t, err) - v := UnstakingActor{ - Address: addr, - StakeAmount: "100", - OutputAddress: addr, - } - v2 := UnstakingActor{} - codec := GetCodec() - protoBytes, err := codec.Marshal(&v) - require.NoError(t, err) - if err := codec.Unmarshal(protoBytes, &v2); err != nil { - t.Fatal(err) - } - if !bytes.Equal(v.Address, v2.Address) || v.StakeAmount != v2.StakeAmount || !bytes.Equal(v.OutputAddress, v2.OutputAddress) { - t.Fatalf("unequal objects after marshal/unmarshal, expected %v, got %v", v, v2) - } - any, err := codec.ToAny(&v) - require.NoError(t, err) - protoMsg, err := codec.FromAny(any) - require.NoError(t, err) - v3, ok := protoMsg.(*UnstakingActor) - if !ok { - t.Fatal("any couldn't be converted back to original type") - } - if !bytes.Equal(v.Address, v3.Address) || v.StakeAmount != v3.StakeAmount || !bytes.Equal(v.OutputAddress, v3.OutputAddress) { - t.Fatalf("unequal objects after any/fromAny, expected %v, got %v", v, v2) - } -} diff --git a/shared/types/error.go b/shared/types/error.go deleted file mode 100644 index 351def312..000000000 --- a/shared/types/error.go +++ /dev/null @@ -1,244 +0,0 @@ -package types - -import ( - "errors" - "fmt" -) - -// TODO(andrew): move errors to respective modules; pocket/issues/163 -// TODO(andrew): consolidate errors into one file after recovery; pocket/issues/163 - -type Error interface { - Code() Code - error -} - -type StdErr struct { - CodeError Code - error -} - -func (se StdErr) Error() string { - return fmt.Sprintf("CODE: %v, ERROR: %s", se.Code(), se.error.Error()) -} - -func (se StdErr) Code() Code { - return se.CodeError -} - -func NewError(code Code, msg string) Error { - return StdErr{ - CodeError: code, - error: errors.New(msg), - } -} - -type Code float64 - -const ( // Explain: using these numbers as it fits nicely with the other error codes in the prototype - CodeEmptyTransactionError Code = 2 - - CodeNewAddressFromBytesError Code = 9 - - CodeHexDecodeFromStringError Code = 11 - CodeInvalidHashLengthError Code = 12 - CodeEmptyNetworkIDError Code = 13 - CodeEmptyProposerError Code = 14 - CodeEmptyTimestampError Code = 15 - CodeInvalidTransactionCountError Code = 16 - CodeEmptyAccountError Code = 17 - CodeNilPoolError Code = 18 - CodeEmptyNameError Code = 19 - CodeEmptyAddressError Code = 20 - CodeInvalidAddressLenError Code = 21 - - CodeInvalidAmountError Code = 23 - CodeProtoMarshalError Code = 25 - CodeProtoUnmarshalError Code = 26 - CodeProtoNewAnyError Code = 27 - - CodeDuplicateTransactionError Code = 35 - - CodeGetAllValidatorsError Code = 37 - - CodeStringToBigIntError Code = 40 - - CodeUpdateParamError Code = 88 - - CodeInitParamsError Code = 96 - CodeGetAllFishermenError Code = 97 - CodeGetAllServiceNodesError Code = 98 - CodeGetAllAppsError Code = 99 - - CodeGetAllPoolsError Code = 107 - CodeGetAllAccountsError Code = 108 - CodeGetAllParamsError Code = 109 - CodeInsufficientAmountError Code = 41 - CodeNegativeAmountError Code = 118 - CodeNilQuorumCertificateError Code = 119 - - EmptyTransactionError = "the transaction is empty" - - StringToBigIntError = "an error occurred converting the string primitive to big.Int, the conversion was unsuccessful with base 10" - - GetAllValidatorsError = "an error occurred getting all validators from the state" - - InvalidAmountError = "the amount field is invalid; cannot be converted to big.Int" - - InvalidAddressLenError = "the length of the address is not valid" - EmptyAddressError = "the address field is empty" - EmptyNameError = "the name field is empty" - NilPoolError = "the pool is nil" - EmptyAccountError = "the account is nil" - - NewAddressFromBytesError = "unable to convert the raw bytes to a valid address" - InvalidTransactionCountError = "the total transactions are less than the block transactions" - EmptyTimestampError = "the timestamp field is empty" - EmptyProposerError = "the proposer field is empty" - EmptyNetworkIDError = "the network id field is empty" - InvalidHashLengthError = "the length of the hash is not the correct size" - NilQuorumCertificateError = "the quorum certificate is nil" - - HexDecodeFromStringError = "an error occurred decoding the string into hex bytes" - ProtoMarshalError = "an error occurred marshalling the structure in protobuf" - ProtoUnmarshalError = "an error occurred unmarshalling the structure in protobuf" - ProtoNewAnyError = "an error occurred creating the protobuf any" - - UpdateParamError = "an error occurred updating the parameter" - - InitParamsError = "an error occurred initializing the params in genesis" - GetAllFishermenError = "an error occurred getting all of the fishermen¬" - GetAllAppsError = "an error occurred getting all of the apps" - GetAllServiceNodesError = "an error occurred getting all of the service nodes" - GetAllPoolsError = "an error occurred getting all of the pools" - GetAllAccountsError = "an error occurred getting all of the accounts" - GetAllParamsError = "an error occurred getting all of the params" - DuplicateTransactionError = "the transaction is already found in the mempool" - InsufficientAmountError = "the account has insufficient funds to complete the operation" - NegativeAmountError = "the amount is negative" -) - -func ErrDuplicateTransaction() Error { - return NewError(CodeDuplicateTransactionError, DuplicateTransactionError) -} - -func ErrStringToBigInt() Error { - return NewError(CodeStringToBigIntError, fmt.Sprintf("%s", StringToBigIntError)) -} - -// TODO: We should pass the account address here so it is easier to debug the issue -func ErrInsufficientAmount() Error { - return NewError(CodeInsufficientAmountError, fmt.Sprintf("%s", InsufficientAmountError)) -} - -func ErrNegativeAmountError() Error { - return NewError(CodeNegativeAmountError, fmt.Sprintf("%s", NegativeAmountError)) -} - -func ErrGetAllValidators(err error) Error { - return NewError(CodeGetAllValidatorsError, fmt.Sprintf("%s: %s", GetAllValidatorsError, err.Error())) -} - -func ErrGetAllFishermen(err error) Error { - return NewError(CodeGetAllFishermenError, fmt.Sprintf("%s: %s", GetAllFishermenError, err.Error())) -} - -func ErrGetAllApps(err error) Error { - return NewError(CodeGetAllAppsError, fmt.Sprintf("%s: %s", GetAllAppsError, err.Error())) -} - -func ErrGetAllServiceNodes(err error) Error { - return NewError(CodeGetAllServiceNodesError, fmt.Sprintf("%s: %s", GetAllServiceNodesError, err.Error())) -} - -func ErrGetAllPools(err error) Error { - return NewError(CodeGetAllPoolsError, fmt.Sprintf("%s: %s", GetAllPoolsError, err.Error())) -} - -func ErrGetAllAccounts(err error) Error { - return NewError(CodeGetAllAccountsError, fmt.Sprintf("%s: %s", GetAllAccountsError, err.Error())) -} - -func ErrGetAllParams(err error) Error { - return NewError(CodeGetAllParamsError, fmt.Sprintf("%s: %s", GetAllParamsError, err.Error())) -} - -func ErrHexDecodeFromString(err error) Error { - return NewError(CodeHexDecodeFromStringError, fmt.Sprintf("%s: %s", HexDecodeFromStringError, err.Error())) -} - -func ErrEmptyAccount() Error { - return NewError(CodeEmptyAccountError, EmptyAccountError) -} - -func ErrEmptyAddress() Error { - return NewError(CodeEmptyAddressError, EmptyAddressError) -} - -func ErrInvalidAddressLen(err error) Error { - return NewError(CodeInvalidAddressLenError, fmt.Sprintf("%s: %s", InvalidAddressLenError, err.Error())) -} - -func ErrInvalidAmount() Error { - return NewError(CodeInvalidAmountError, InvalidAmountError) -} - -func ErrEmptyName() Error { - return NewError(CodeEmptyNameError, EmptyNameError) -} - -func ErrNilPool() Error { - return NewError(CodeNilPoolError, NilPoolError) -} - -func ErrEmptyNetworkID() Error { - return NewError(CodeEmptyNetworkIDError, EmptyNetworkIDError) -} - -func ErrEmptyProposer() Error { - return NewError(CodeEmptyProposerError, EmptyProposerError) -} - -func ErrEmptyTimestamp() Error { - return NewError(CodeEmptyTimestampError, EmptyTimestampError) -} - -func EmptyTransactionErr() Error { - return NewError(CodeEmptyTransactionError, EmptyTransactionError) -} - -func ErrInvalidTransactionCount() Error { - return NewError(CodeInvalidTransactionCountError, InvalidTransactionCountError) -} - -func ErrInvalidHashLength(err error) Error { - return NewError(CodeInvalidHashLengthError, fmt.Sprintf("%s: %s", InvalidHashLengthError, err.Error())) -} - -func ErrNilQuorumCertificate() Error { - return NewError(CodeNilQuorumCertificateError, NilQuorumCertificateError) -} - -func ErrNewAddressFromBytes(err error) Error { - return NewError(CodeNewAddressFromBytesError, fmt.Sprintf("%s: %s", NewAddressFromBytesError, err.Error())) -} - -func ErrProtoMarshal(err error) Error { - return NewError(CodeProtoMarshalError, fmt.Sprintf("%s: %s", ProtoMarshalError, err.Error())) -} - -func ErrProtoUnmarshal(err error) Error { - return NewError(CodeProtoUnmarshalError, fmt.Sprintf("%s: %s", ProtoUnmarshalError, err.Error())) -} - -func ErrProtoNewAny(err error) Error { - return NewError(CodeProtoNewAnyError, fmt.Sprintf("%s: %s", ProtoNewAnyError, err.Error())) -} - -func ErrUpdateParam(err error) Error { - return NewError(CodeUpdateParamError, fmt.Sprintf("%s: %s", UpdateParamError, err.Error())) -} - -func ErrInitParams(err error) Error { - return NewError(CodeInitParamsError, fmt.Sprintf("%s: %s", InitParamsError, err.Error())) -} diff --git a/shared/types/genesis/proto/account.proto b/shared/types/genesis/proto/account.proto deleted file mode 100644 index bc791b61d..000000000 --- a/shared/types/genesis/proto/account.proto +++ /dev/null @@ -1,20 +0,0 @@ -syntax = "proto3"; -package genesis; - -option go_package = "github.com/pokt-network/pocket/shared/types/genesis"; - -// TODO (team) move to utility module; pocket/issues/163 -message Account { - string address = 1; - string amount = 2; -} - -// TODO(andrew): move to p2p module; pocket/issues;163 -enum Pool_Names { - DAO = 0; - FeeCollector = 1; - AppStakePool = 2; - ValidatorStakePool = 3; - ServiceNodeStakePool = 4; - FishermanStakePool = 5; -} diff --git a/shared/types/genesis/proto/actor.proto b/shared/types/genesis/proto/actor.proto deleted file mode 100644 index f3621aec2..000000000 --- a/shared/types/genesis/proto/actor.proto +++ /dev/null @@ -1,25 +0,0 @@ -syntax = "proto3"; -package genesis; - -option go_package = "github.com/pokt-network/pocket/shared/types/genesis"; - -// TODO(andrew): move to utility module; pocket/issues/163 -enum ActorType { - App = 0; - Node = 1; - Fish = 2; - Val = 3; -} - -message Actor { - string address = 1; - string public_key = 2; - repeated string chains = 3; - // TODO(andrew): Rename `generic_param` to `actor_specific_param` - string generic_param = 4; - string staked_amount = 5; - int64 paused_height = 6; - int64 unstaking_height = 7; - string output = 8; - ActorType actor_type = 9; -} diff --git a/shared/types/genesis/proto/config.proto b/shared/types/genesis/proto/config.proto deleted file mode 100644 index c44b41619..000000000 --- a/shared/types/genesis/proto/config.proto +++ /dev/null @@ -1,57 +0,0 @@ -syntax = "proto3"; -package genesis; - -option go_package = "github.com/pokt-network/pocket/shared/types/genesis"; - -message Config { - BaseConfig base = 1; - ConsensusConfig consensus = 2; - UtilityConfig utility = 3; - PersistenceConfig persistence = 4; - P2PConfig p2p = 5; - TelemetryConfig telemetry = 6; -} - -message BaseConfig { - string root_directory = 1; - // TODO: better architecture for key management (keybase, keyfiles, etc.) - string private_key = 2; -} - -message ConsensusConfig {// TODO (team) move to consensus module #163 - uint64 max_mempool_bytes = 1; // TODO(olshansky): add unit tests for this - PacemakerConfig pacemaker_config = 2; -} - -message PacemakerConfig {// TODO (team) move to consensus module #163 - uint64 timeout_msec = 1; - bool manual = 2; - uint64 debug_time_between_steps_msec = 3; -} - -message UtilityConfig {// TODO (team) move to utility module #163 - -} - -message PersistenceConfig {// TODO (team) move to persistence module #163 - string postgres_url = 1; - string node_schema = 2; - string block_store_path = 3; -} - -message P2PConfig {// TODO (team) move to p2p module #163 - uint32 consensus_port = 1; - bool use_rain_tree = 2; - ConnectionType connection_type = 3; -} - -enum ConnectionType {// TODO (team) move to p2p module #163 - EmptyConnection = 0; - TCPConnection = 1; -} - -message TelemetryConfig {// TODO (team) move to shared/telemetry - bool enabled = 1; - string address = 2; // The address the telemetry module will use to listen for metrics PULL requests (e.g. 0.0.0.0:9000 for prometheus) - string endpoint = 3; // The endpoint available to fetch recorded metrics (e.g. /metrics for prometheus) -} \ No newline at end of file diff --git a/shared/types/genesis/proto/state.proto b/shared/types/genesis/proto/state.proto deleted file mode 100644 index c8cc4274b..000000000 --- a/shared/types/genesis/proto/state.proto +++ /dev/null @@ -1,30 +0,0 @@ -syntax = "proto3"; -package genesis; - -import "google/protobuf/timestamp.proto"; -import "account.proto"; -import "actor.proto"; -import "gov.proto"; - -option go_package = "github.com/pokt-network/pocket/shared/types/genesis"; - -message GenesisState { - ConsensusGenesisState consensus = 1; - UtilityGenesisState utility = 2; -} - -message ConsensusGenesisState { // TODO (team) move to consensus module #163 - google.protobuf.Timestamp genesis_time = 1; - string chain_id = 2; - uint64 max_block_bytes = 3; -} - -message UtilityGenesisState { // TODO (team) move to utility module #163 - repeated Account pools = 1; - repeated Account accounts = 2; - repeated Actor applications = 3; - repeated Actor validators = 4; - repeated Actor service_nodes = 5; - repeated Actor fishermen = 6; - Params params = 7; -} \ No newline at end of file diff --git a/shared/types/proto/unstaking.proto b/shared/types/proto/unstaking.proto deleted file mode 100644 index 7ce3a7704..000000000 --- a/shared/types/proto/unstaking.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; -package shared; - -option go_package = "github.com/pokt-network/pocket/shared/types"; - -message UnstakingActor { - bytes address = 1; - string stake_amount = 2; - bytes output_address = 3; -} - -message UnstakingActors { - repeated UnstakingActor unstaking_actors = 1; -} \ No newline at end of file diff --git a/shared/telemetry/README.md b/telemetry/README.md similarity index 97% rename from shared/telemetry/README.md rename to telemetry/README.md index 2555ccdcb..cb9e792e0 100644 --- a/shared/telemetry/README.md +++ b/telemetry/README.md @@ -114,11 +114,11 @@ See the images below for an example of how to use the `Explore` functionality. Go to the explore page: -![](./docs/explore-loki-on-grafana-pt-1.gif) +![](docs/explore-loki-on-grafana-pt-1.gif) Type in your query and play with the results: -![](./docs/explore-loki-on-grafana-pt-2.gif) +![](docs/explore-loki-on-grafana-pt-2.gif) You should see a log stream coming out where you can click a line to explore how you've used the `pattern` keyword in LogQL to parse the log line. Now you can reference your parsed fields per your needs. @@ -168,7 +168,7 @@ $ make compose_and_watch _NOTE: Make sure you use `http` and not `https` when developing locally._ -![](./docs/browsing-existing-dashboards.gif) +![](docs/browsing-existing-dashboards.gif) # Defining your own metrics diff --git a/shared/telemetry/docs/browsing-existing-dashboards.gif b/telemetry/docs/browsing-existing-dashboards.gif similarity index 100% rename from shared/telemetry/docs/browsing-existing-dashboards.gif rename to telemetry/docs/browsing-existing-dashboards.gif diff --git a/shared/telemetry/docs/explore-loki-on-grafana-pt-1.gif b/telemetry/docs/explore-loki-on-grafana-pt-1.gif similarity index 100% rename from shared/telemetry/docs/explore-loki-on-grafana-pt-1.gif rename to telemetry/docs/explore-loki-on-grafana-pt-1.gif diff --git a/shared/telemetry/docs/explore-loki-on-grafana-pt-2.gif b/telemetry/docs/explore-loki-on-grafana-pt-2.gif similarity index 100% rename from shared/telemetry/docs/explore-loki-on-grafana-pt-2.gif rename to telemetry/docs/explore-loki-on-grafana-pt-2.gif diff --git a/shared/telemetry/errors.go b/telemetry/errors.go similarity index 100% rename from shared/telemetry/errors.go rename to telemetry/errors.go diff --git a/telemetry/module.go b/telemetry/module.go new file mode 100644 index 000000000..2c70d7052 --- /dev/null +++ b/telemetry/module.go @@ -0,0 +1,56 @@ +package telemetry + +import ( + "encoding/json" + "io/ioutil" + "log" + + "github.com/pokt-network/pocket/shared/modules" +) + +var _ modules.Module = &telemetryModule{} +var _ modules.TelemetryConfig = &TelemetryConfig{} + +const ( + TelemetryModuleName = "telemetry" +) + +// TODO(pocket/issues/99): Add a switch statement and configuration variable when support for other telemetry modules is added. +func Create(configPath, genesisPath string) (modules.TelemetryModule, error) { + tm := new(telemetryModule) + c, err := tm.InitConfig(configPath) + if err != nil { + return nil, err + } + cfg := c.(*TelemetryConfig) + if cfg.GetEnabled() { + return CreatePrometheusTelemetryModule(cfg) + } else { + return CreateNoopTelemetryModule(cfg) + } +} + +type telemetryModule struct{} + +func (t *telemetryModule) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + data, err := ioutil.ReadFile(pathToConfigJSON) + if err != nil { + return + } + // over arching configuration file + rawJSON := make(map[string]json.RawMessage) + if err = json.Unmarshal(data, &rawJSON); err != nil { + log.Fatalf("[ERROR] an error occurred unmarshalling the %s file: %v", pathToConfigJSON, err.Error()) + } + // telemetry specific configuration file + config = new(TelemetryConfig) + err = json.Unmarshal(rawJSON[t.GetModuleName()], config) + return +} + +func (t *telemetryModule) GetModuleName() string { return TelemetryModuleName } +func (t *telemetryModule) InitGenesis(_ string) (genesis modules.IGenesis, err error) { return } +func (t *telemetryModule) SetBus(bus modules.Bus) {} +func (t *telemetryModule) GetBus() modules.Bus { return nil } +func (t *telemetryModule) Start() error { return nil } +func (t *telemetryModule) Stop() error { return nil } diff --git a/shared/telemetry/noop_module.go b/telemetry/noop_module.go similarity index 83% rename from shared/telemetry/noop_module.go rename to telemetry/noop_module.go index d35ed78ac..a1cbeb9d1 100644 --- a/shared/telemetry/noop_module.go +++ b/telemetry/noop_module.go @@ -1,7 +1,6 @@ package telemetry import ( - "github.com/pokt-network/pocket/shared/types/genesis" "log" "github.com/pokt-network/pocket/shared/modules" @@ -18,11 +17,15 @@ type NoopTelemetryModule struct { bus modules.Bus } +const ( + NoOpModuleName = "noOP" +) + func NOOP() { log.Printf("\n[telemetry=noop]\n") } -func CreateNoopTelemetryModule(_ *genesis.Config) (*NoopTelemetryModule, error) { +func CreateNoopTelemetryModule(_ *TelemetryConfig) (*NoopTelemetryModule, error) { return &NoopTelemetryModule{}, nil } @@ -36,6 +39,18 @@ func (m *NoopTelemetryModule) Stop() error { return nil } +func (m *NoopTelemetryModule) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + return // No-op +} + +func (m *NoopTelemetryModule) InitGenesis(pathToGenesisJSON string) (genesis modules.IGenesis, err error) { + return // No-op +} + +func (m *NoopTelemetryModule) GetModuleName() string { + return NoOpModuleName +} + func (m *NoopTelemetryModule) SetBus(bus modules.Bus) { m.bus = bus } diff --git a/shared/telemetry/prometheus_module.go b/telemetry/prometheus_module.go similarity index 90% rename from shared/telemetry/prometheus_module.go rename to telemetry/prometheus_module.go index 475ebf65d..1c4ff2f6c 100644 --- a/shared/telemetry/prometheus_module.go +++ b/telemetry/prometheus_module.go @@ -4,8 +4,6 @@ import ( "log" "net/http" - "github.com/pokt-network/pocket/shared/types/genesis" - "github.com/pokt-network/pocket/shared/modules" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -31,14 +29,18 @@ type PrometheusTelemetryModule struct { gaugeVectors map[string]prometheus.GaugeVec } -func CreatePrometheusTelemetryModule(cfg *genesis.Config) (*PrometheusTelemetryModule, error) { +const ( + PrometheusModuleName = "prometheus" +) + +func CreatePrometheusTelemetryModule(cfg *TelemetryConfig) (*PrometheusTelemetryModule, error) { return &PrometheusTelemetryModule{ counters: map[string]prometheus.Counter{}, gauges: map[string]prometheus.Gauge{}, gaugeVectors: map[string]prometheus.GaugeVec{}, - address: cfg.Telemetry.Address, - endpoint: cfg.Telemetry.Endpoint, + address: cfg.GetAddress(), + endpoint: cfg.GetEndpoint(), }, nil } @@ -57,10 +59,22 @@ func (m *PrometheusTelemetryModule) Stop() error { return nil } +func (m *PrometheusTelemetryModule) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + return // No-op +} + +func (m *PrometheusTelemetryModule) InitGenesis(pathToGenesisJSON string) (genesis modules.IGenesis, err error) { + return // No-op +} + func (m *PrometheusTelemetryModule) SetBus(bus modules.Bus) { m.bus = bus } +func (m *PrometheusTelemetryModule) GetModuleName() string { + return PrometheusModuleName +} + func (m *PrometheusTelemetryModule) GetBus() modules.Bus { if m.bus == nil { log.Fatalf("PocketBus is not initialized") diff --git a/telemetry/proto/telemetry_config.proto b/telemetry/proto/telemetry_config.proto new file mode 100644 index 000000000..36e4f2eea --- /dev/null +++ b/telemetry/proto/telemetry_config.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; +package telemetry; + +option go_package = "github.com/pokt-network/pocket/telemetry"; + +message TelemetryConfig { + bool enabled = 1; + string address = 2; // The address the telemetry module will use to listen for metrics PULL requests (e.g. 0.0.0.0:9000 for prometheus) + string endpoint = 3; // The endpoint available to fetch recorded metrics (e.g. /metrics for prometheus) +} \ No newline at end of file diff --git a/utility/account.go b/utility/account.go index fdef65ba5..6404ec112 100644 --- a/utility/account.go +++ b/utility/account.go @@ -1,9 +1,8 @@ package utility import ( + "github.com/pokt-network/pocket/utility/types" "math/big" - - "github.com/pokt-network/pocket/shared/types" ) // 'Accounts' are structures in the utility module that closely resemble currency holding vehicles: like a bank account. diff --git a/utility/actor.go b/utility/actor.go index 35cf3c25c..1dfc28b91 100644 --- a/utility/actor.go +++ b/utility/actor.go @@ -1,12 +1,13 @@ package utility import ( - "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" - typesUtil "github.com/pokt-network/pocket/utility/types" "math" "math/big" + + typesGenesis "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/crypto" + "github.com/pokt-network/pocket/shared/modules" + typesUtil "github.com/pokt-network/pocket/utility/types" ) /* @@ -25,409 +26,395 @@ import ( // setters -func (u *UtilityContext) SetActorStakedTokens(actorType typesUtil.ActorType, tokens *big.Int, address []byte) types.Error { +func (u *UtilityContext) SetActorStakedTokens(actorType typesUtil.UtilActorType, tokens *big.Int, address []byte) typesUtil.Error { var er error store := u.Store() + switch actorType { - case typesUtil.ActorType_App: - er = store.SetAppStakeAmount(address, types.BigIntToString(tokens)) - case typesUtil.ActorType_Fish: - er = store.SetFishermanStakeAmount(address, types.BigIntToString(tokens)) - case typesUtil.ActorType_Node: - er = store.SetServiceNodeStakeAmount(address, types.BigIntToString(tokens)) - case typesUtil.ActorType_Val: - er = store.SetValidatorStakeAmount(address, types.BigIntToString(tokens)) + case typesUtil.UtilActorType_App: + er = store.SetAppStakeAmount(address, typesUtil.BigIntToString(tokens)) + case typesUtil.UtilActorType_Fish: + er = store.SetFishermanStakeAmount(address, typesUtil.BigIntToString(tokens)) + case typesUtil.UtilActorType_Node: + er = store.SetServiceNodeStakeAmount(address, typesUtil.BigIntToString(tokens)) + case typesUtil.UtilActorType_Val: + er = store.SetValidatorStakeAmount(address, typesUtil.BigIntToString(tokens)) } + if er != nil { - return types.ErrSetValidatorStakedTokens(er) + return typesUtil.ErrSetValidatorStakedTokens(er) } + return nil } -func (u *UtilityContext) SetActorUnstaking(actorType typesUtil.ActorType, unstakingHeight int64, address []byte) types.Error { +func (u *UtilityContext) SetActorUnstaking(actorType typesUtil.UtilActorType, unstakingHeight int64, address []byte) typesUtil.Error { store := u.Store() var er error + switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: er = store.SetAppUnstakingHeightAndStatus(address, unstakingHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: er = store.SetFishermanUnstakingHeightAndStatus(address, unstakingHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: er = store.SetServiceNodeUnstakingHeightAndStatus(address, unstakingHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: er = store.SetValidatorUnstakingHeightAndStatus(address, unstakingHeight, typesUtil.UnstakingStatus) } + if er != nil { - return types.ErrSetUnstakingHeightAndStatus(er) + return typesUtil.ErrSetUnstakingHeightAndStatus(er) } + return nil } -func (u *UtilityContext) DeleteActor(actorType typesUtil.ActorType, address []byte) types.Error { +func (u *UtilityContext) DeleteActor(actorType typesUtil.UtilActorType, address []byte) typesUtil.Error { var err error store := u.Store() + switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: err = store.DeleteApp(address) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: err = store.DeleteFisherman(address) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: err = store.DeleteServiceNode(address) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: err = store.DeleteValidator(address) } + if err != nil { - return types.ErrDelete(err) + return typesUtil.ErrDelete(err) } + return nil } -func (u *UtilityContext) SetActorPauseHeight(actorType typesUtil.ActorType, address []byte, height int64) types.Error { +func (u *UtilityContext) SetActorPauseHeight(actorType typesUtil.UtilActorType, address []byte, height int64) typesUtil.Error { var err error store := u.Store() + switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: err = store.SetAppPauseHeight(address, height) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: err = store.SetFishermanPauseHeight(address, height) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: err = store.SetServiceNodePauseHeight(address, height) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: err = store.SetValidatorPauseHeight(address, height) } + if err != nil { - return types.ErrSetPauseHeight(err) + return typesUtil.ErrSetPauseHeight(err) } + return nil } // getters -func (u *UtilityContext) GetActorStakedTokens(actorType typesUtil.ActorType, address []byte) (*big.Int, types.Error) { +func (u *UtilityContext) GetActorStakedTokens(actorType typesUtil.UtilActorType, address []byte) (*big.Int, typesUtil.Error) { store := u.Store() height, er := store.GetHeight() if er != nil { - return nil, types.ErrGetStakedTokens(er) + return nil, typesUtil.ErrGetStakedTokens(er) } var stakedTokens string switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: stakedTokens, er = store.GetAppStakeAmount(height, address) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: stakedTokens, er = store.GetFishermanStakeAmount(height, address) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: stakedTokens, er = store.GetServiceNodeStakeAmount(height, address) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: stakedTokens, er = store.GetValidatorStakeAmount(height, address) } + if er != nil { - return nil, types.ErrGetStakedTokens(er) + return nil, typesUtil.ErrGetStakedTokens(er) } - i, err := types.StringToBigInt(stakedTokens) + i, err := typesUtil.StringToBigInt(stakedTokens) if err != nil { return nil, err } + return i, nil } -func (u *UtilityContext) GetMaxPausedBlocks(actorType typesUtil.ActorType) (maxPausedBlocks int, err types.Error) { - var er error +func (u *UtilityContext) GetMaxPausedBlocks(actorType typesUtil.UtilActorType) (maxPausedBlocks int, err typesUtil.Error) { var paramName string store := u.Store() + height, er := store.GetHeight() + if er != nil { + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, er) + } + switch actorType { - case typesUtil.ActorType_App: - height, er := store.GetHeight() - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - maxPausedBlocks, er = store.GetIntParam(types.AppMaxPauseBlocksParamName, height) - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - paramName = types.AppMaxPauseBlocksParamName - case typesUtil.ActorType_Fish: - height, er := store.GetHeight() - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - maxPausedBlocks, er = store.GetIntParam(types.FishermanMaxPauseBlocksParamName, height) - paramName = types.FishermanMaxPauseBlocksParamName - case typesUtil.ActorType_Node: - height, er := store.GetHeight() - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - maxPausedBlocks, er = store.GetIntParam(types.ServiceNodeMaxPauseBlocksParamName, height) - paramName = types.ServiceNodeMaxPauseBlocksParamName - case typesUtil.ActorType_Val: - height, er := store.GetHeight() - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - maxPausedBlocks, er = store.GetIntParam(types.ValidatorMaxPausedBlocksParamName, height) - paramName = types.ValidatorMaxPausedBlocksParamName + case typesUtil.UtilActorType_App: + paramName = modules.AppMaxPauseBlocksParamName + case typesUtil.UtilActorType_Fish: + paramName = modules.FishermanMaxPauseBlocksParamName + case typesUtil.UtilActorType_Node: + paramName = modules.ServiceNodeMaxPauseBlocksParamName + case typesUtil.UtilActorType_Val: + paramName = modules.ValidatorMaxPausedBlocksParamName } + + maxPausedBlocks, er = store.GetIntParam(paramName, height) if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, er) } + return } -func (u *UtilityContext) GetMinimumPauseBlocks(actorType typesUtil.ActorType) (minPauseBlocks int, err types.Error) { - store := u.Store() - var er error +func (u *UtilityContext) GetMinimumPauseBlocks(actorType typesUtil.UtilActorType) (minPauseBlocks int, err typesUtil.Error) { var paramName string + + store := u.Store() + height, er := store.GetHeight() + if er != nil { + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, er) // TODO(andrew): does this need a custom error? + } + switch actorType { - case typesUtil.ActorType_App: - height, er := store.GetHeight() - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - minPauseBlocks, er = store.GetIntParam(types.AppMinimumPauseBlocksParamName, height) - paramName = types.AppMinimumPauseBlocksParamName - case typesUtil.ActorType_Fish: - height, er := store.GetHeight() - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - minPauseBlocks, er = store.GetIntParam(types.FishermanMinimumPauseBlocksParamName, height) - paramName = types.FishermanMinimumPauseBlocksParamName - case typesUtil.ActorType_Node: - height, er := store.GetHeight() - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - minPauseBlocks, er = store.GetIntParam(types.ServiceNodeMinimumPauseBlocksParamName, height) - paramName = types.ServiceNodeMinimumPauseBlocksParamName - case typesUtil.ActorType_Val: - height, er := store.GetHeight() - if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) - } - minPauseBlocks, er = store.GetIntParam(types.ValidatorMinimumPauseBlocksParamName, height) - paramName = types.ValidatorMinimumPauseBlocksParamName + case typesUtil.UtilActorType_App: + paramName = modules.AppMinimumPauseBlocksParamName + case typesUtil.UtilActorType_Fish: + paramName = modules.FishermanMinimumPauseBlocksParamName + case typesUtil.UtilActorType_Node: + paramName = modules.ServiceNodeMinimumPauseBlocksParamName + case typesUtil.UtilActorType_Val: + paramName = modules.ValidatorMinimumPauseBlocksParamName } + + minPauseBlocks, er = store.GetIntParam(paramName, height) if er != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, er) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, er) } + return } -func (u *UtilityContext) GetPauseHeight(actorType typesUtil.ActorType, address []byte) (pauseHeight int64, err types.Error) { +func (u *UtilityContext) GetPauseHeight(actorType typesUtil.UtilActorType, address []byte) (pauseHeight int64, err typesUtil.Error) { store := u.Store() height, er := store.GetHeight() if er != nil { - return typesUtil.ZeroInt, types.ErrGetPauseHeight(er) + return typesUtil.ZeroInt, typesUtil.ErrGetPauseHeight(er) } + switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: pauseHeight, er = store.GetAppPauseHeightIfExists(address, height) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: pauseHeight, er = store.GetFishermanPauseHeightIfExists(address, height) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: pauseHeight, er = store.GetServiceNodePauseHeightIfExists(address, height) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: pauseHeight, er = store.GetValidatorPauseHeightIfExists(address, height) } + if er != nil { - return typesUtil.ZeroInt, types.ErrGetPauseHeight(er) + return typesUtil.ZeroInt, typesUtil.ErrGetPauseHeight(er) } + return } -func (u *UtilityContext) GetActorStatus(actorType typesUtil.ActorType, address []byte) (status int, err types.Error) { +func (u *UtilityContext) GetActorStatus(actorType typesUtil.UtilActorType, address []byte) (status int, err typesUtil.Error) { store := u.Store() height, er := store.GetHeight() if er != nil { - return typesUtil.ZeroInt, types.ErrGetStatus(er) + return typesUtil.ZeroInt, typesUtil.ErrGetStatus(er) } + switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: status, er = store.GetAppStatus(address, height) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: status, er = store.GetFishermanStatus(address, height) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: status, er = store.GetServiceNodeStatus(address, height) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: status, er = store.GetValidatorStatus(address, height) } + if er != nil { - return typesUtil.ZeroInt, types.ErrGetStatus(er) + return typesUtil.ZeroInt, typesUtil.ErrGetStatus(er) } + return status, nil } -func (u *UtilityContext) GetMinimumStake(actorType typesUtil.ActorType) (*big.Int, types.Error) { - var minStake string - var err error +func (u *UtilityContext) GetMinimumStake(actorType typesUtil.UtilActorType) (*big.Int, typesUtil.Error) { var paramName string store := u.Store() + height, err := store.GetHeight() + if err != nil { + return nil, typesUtil.ErrGetParam(paramName, err) + } + + var minStake string switch actorType { - case typesUtil.ActorType_App: - height, er := store.GetHeight() - if er != nil { - return nil, types.ErrGetParam(paramName, er) - } - minStake, err = store.GetStringParam(types.AppMinimumStakeParamName, height) - paramName = types.AppMinimumStakeParamName - case typesUtil.ActorType_Fish: - height, er := store.GetHeight() - if er != nil { - return nil, types.ErrGetParam(paramName, er) - } - minStake, err = store.GetStringParam(types.FishermanMinimumStakeParamName, height) - paramName = types.FishermanMinimumStakeParamName - case typesUtil.ActorType_Node: - height, er := store.GetHeight() - if er != nil { - return nil, types.ErrGetParam(paramName, er) - } - minStake, err = store.GetStringParam(types.ServiceNodeMinimumStakeParamName, height) - paramName = types.ServiceNodeMinimumStakeParamName - case typesUtil.ActorType_Val: - height, er := store.GetHeight() - if er != nil { - return nil, types.ErrGetParam(paramName, er) - } - minStake, err = store.GetStringParam(types.ValidatorMinimumStakeParamName, height) - paramName = types.ValidatorMinimumStakeParamName + case typesUtil.UtilActorType_App: + paramName = modules.AppMinimumStakeParamName + case typesUtil.UtilActorType_Fish: + paramName = modules.FishermanMinimumStakeParamName + case typesUtil.UtilActorType_Node: + paramName = modules.ServiceNodeMinimumStakeParamName + case typesUtil.UtilActorType_Val: + paramName = modules.ValidatorMinimumStakeParamName } + + minStake, err = store.GetStringParam(paramName, height) if err != nil { - return nil, types.ErrGetParam(paramName, err) + return nil, typesUtil.ErrGetParam(paramName, err) } - return types.StringToBigInt(minStake) + + return typesUtil.StringToBigInt(minStake) } -func (u *UtilityContext) GetStakeAmount(actorType typesUtil.ActorType, address []byte) (*big.Int, types.Error) { +func (u *UtilityContext) GetStakeAmount(actorType typesUtil.UtilActorType, address []byte) (*big.Int, typesUtil.Error) { var stakeAmount string store := u.Store() height, err := store.GetHeight() if err != nil { - return nil, types.ErrGetStakeAmount(err) + return nil, typesUtil.ErrGetStakeAmount(err) } + switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: stakeAmount, err = store.GetAppStakeAmount(height, address) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: stakeAmount, err = store.GetFishermanStakeAmount(height, address) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: stakeAmount, err = store.GetServiceNodeStakeAmount(height, address) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: stakeAmount, err = store.GetValidatorStakeAmount(height, address) } + if err != nil { - return nil, types.ErrGetStakeAmount(err) + return nil, typesUtil.ErrGetStakeAmount(err) } - return types.StringToBigInt(stakeAmount) + + return typesUtil.StringToBigInt(stakeAmount) } -func (u *UtilityContext) GetUnstakingHeight(actorType typesUtil.ActorType) (unstakingHeight int64, er types.Error) { - var err error - var paramName string - var unstakingBlocks int +func (u *UtilityContext) GetUnstakingHeight(actorType typesUtil.UtilActorType) (unstakingHeight int64, er typesUtil.Error) { store := u.Store() height, err := store.GetHeight() if err != nil { - return typesUtil.ZeroInt, types.ErrGetStakeAmount(err) + return typesUtil.ZeroInt, typesUtil.ErrGetStakeAmount(err) } + + var paramName string + var unstakingBlocks int switch actorType { - case typesUtil.ActorType_App: - unstakingBlocks, err = store.GetIntParam(types.AppUnstakingBlocksParamName, height) - paramName = types.AppUnstakingBlocksParamName - case typesUtil.ActorType_Fish: - unstakingBlocks, err = store.GetIntParam(types.FishermanUnstakingBlocksParamName, height) - paramName = types.FishermanUnstakingBlocksParamName - case typesUtil.ActorType_Node: - unstakingBlocks, err = store.GetIntParam(types.ServiceNodeUnstakingBlocksParamName, height) - paramName = types.ServiceNodeUnstakingBlocksParamName - case typesUtil.ActorType_Val: - unstakingBlocks, err = store.GetIntParam(types.ValidatorUnstakingBlocksParamName, height) - paramName = types.ValidatorUnstakingBlocksParamName + case typesUtil.UtilActorType_App: + paramName = modules.AppUnstakingBlocksParamName + case typesUtil.UtilActorType_Fish: + paramName = modules.FishermanUnstakingBlocksParamName + case typesUtil.UtilActorType_Node: + paramName = modules.ServiceNodeUnstakingBlocksParamName + case typesUtil.UtilActorType_Val: + paramName = modules.ValidatorUnstakingBlocksParamName } + + unstakingBlocks, err = store.GetIntParam(paramName, height) if err != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, err) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, err) } + return u.CalculateUnstakingHeight(int64(unstakingBlocks)) } -func (u *UtilityContext) GetMaxChains(actorType typesUtil.ActorType) (maxChains int, er types.Error) { - var err error - var paramName string +func (u *UtilityContext) GetMaxChains(actorType typesUtil.UtilActorType) (maxChains int, er typesUtil.Error) { store := u.Store() height, err := store.GetHeight() if err != nil { - return typesUtil.ZeroInt, types.ErrGetStakeAmount(err) + return typesUtil.ZeroInt, typesUtil.ErrGetStakeAmount(err) } + + var paramName string switch actorType { - case typesUtil.ActorType_App: - maxChains, err = store.GetIntParam(types.AppMaxChainsParamName, height) - paramName = types.AppMinimumStakeParamName - case typesUtil.ActorType_Fish: - maxChains, err = store.GetIntParam(types.FishermanMaxChainsParamName, height) - paramName = types.FishermanMinimumStakeParamName - case typesUtil.ActorType_Node: - maxChains, err = store.GetIntParam(types.ServiceNodeMaxChainsParamName, height) - paramName = types.ServiceNodeMinimumStakeParamName + case typesUtil.UtilActorType_App: + paramName = modules.AppMinimumStakeParamName + case typesUtil.UtilActorType_Fish: + paramName = modules.FishermanMinimumStakeParamName + case typesUtil.UtilActorType_Node: + paramName = modules.ServiceNodeMinimumStakeParamName } + + maxChains, err = store.GetIntParam(paramName, height) if err != nil { - return 0, types.ErrGetParam(paramName, err) + return 0, typesUtil.ErrGetParam(paramName, err) } + return } -func (u *UtilityContext) GetActorExists(actorType typesUtil.ActorType, address []byte) (bool, types.Error) { - var exists bool +func (u *UtilityContext) GetActorExists(actorType typesUtil.UtilActorType, address []byte) (bool, typesUtil.Error) { store := u.Store() height, err := store.GetHeight() if err != nil { - return false, types.ErrGetExists(err) + return false, typesUtil.ErrGetExists(err) } + + var exists bool switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: exists, err = store.GetAppExists(address, height) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: exists, err = store.GetFishermanExists(address, height) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: exists, err = store.GetServiceNodeExists(address, height) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: exists, err = store.GetValidatorExists(address, height) } + if err != nil { - return false, types.ErrGetExists(err) + return false, typesUtil.ErrGetExists(err) } + return exists, nil } -func (u *UtilityContext) GetActorOutputAddress(actorType typesUtil.ActorType, operator []byte) (output []byte, err types.Error) { - var er error +func (u *UtilityContext) GetActorOutputAddress(actorType typesUtil.UtilActorType, operator []byte) (output []byte, err typesUtil.Error) { store := u.Store() height, er := store.GetHeight() if er != nil { - return nil, types.ErrGetOutputAddress(operator, er) + return nil, typesUtil.ErrGetOutputAddress(operator, er) } + switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: output, er = store.GetAppOutputAddress(operator, height) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: output, er = store.GetFishermanOutputAddress(operator, height) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: output, er = store.GetServiceNodeOutputAddress(operator, height) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: output, er = store.GetValidatorOutputAddress(operator, height) } + if er != nil { - return nil, types.ErrGetOutputAddress(operator, er) + return nil, typesUtil.ErrGetOutputAddress(operator, er) + } return output, nil } // calculators -func (u *UtilityContext) BurnActor(actorType typesUtil.ActorType, percentage int, address []byte) types.Error { +func (u *UtilityContext) BurnActor(actorType typesUtil.UtilActorType, percentage int, address []byte) typesUtil.Error { tokens, err := u.GetActorStakedTokens(actorType, address) if err != nil { return err @@ -442,7 +429,7 @@ func (u *UtilityContext) BurnActor(actorType typesUtil.ActorType, percentage int } newTokensAfterBurn := big.NewInt(0).Sub(tokens, truncatedTokens) // remove from pool - if err := u.SubPoolAmount(typesGenesis.Pool_Names_ValidatorStakePool.String(), types.BigIntToString(truncatedTokens)); err != nil { + if err := u.SubPoolAmount(typesGenesis.Pool_Names_ValidatorStakePool.String(), typesUtil.BigIntToString(truncatedTokens)); err != nil { return err } // remove from validator @@ -467,8 +454,8 @@ func (u *UtilityContext) BurnActor(actorType typesUtil.ActorType, percentage int return nil } -func (u *UtilityContext) CalculateAppRelays(stakedTokens string) (string, types.Error) { - tokens, err := types.StringToBigInt(stakedTokens) +func (u *UtilityContext) CalculateAppRelays(stakedTokens string) (string, typesUtil.Error) { + tokens, err := typesUtil.StringToBigInt(stakedTokens) if err != nil { return typesUtil.EmptyString, err } @@ -502,27 +489,27 @@ func (u *UtilityContext) CalculateAppRelays(stakedTokens string) (string, types. if i := result.Cmp(max); i < -1 { result = max } - return types.BigIntToString(result), nil + return typesUtil.BigIntToString(result), nil } -func (u *UtilityContext) CheckAboveMinStake(actorType typesUtil.ActorType, amount string) (a *big.Int, err types.Error) { +func (u *UtilityContext) CheckAboveMinStake(actorType typesUtil.UtilActorType, amount string) (a *big.Int, err typesUtil.Error) { minStake, er := u.GetMinimumStake(actorType) if er != nil { return nil, er } - a, err = types.StringToBigInt(amount) + a, err = typesUtil.StringToBigInt(amount) if err != nil { return nil, err } - if types.BigIntLessThan(a, minStake) { - return nil, types.ErrMinimumStake() + if typesUtil.BigIntLessThan(a, minStake) { + return nil, typesUtil.ErrMinimumStake() } return // for convenience this returns amount as a big.Int } -func (u *UtilityContext) CheckBelowMaxChains(actorType typesUtil.ActorType, chains []string) types.Error { +func (u *UtilityContext) CheckBelowMaxChains(actorType typesUtil.UtilActorType, chains []string) typesUtil.Error { // validators don't have chains field - if actorType == typesUtil.ActorType_Val { + if actorType == typesUtil.UtilActorType_Val { return nil } @@ -531,12 +518,12 @@ func (u *UtilityContext) CheckBelowMaxChains(actorType typesUtil.ActorType, chai return err } if len(chains) > maxChains { - return types.ErrMaxChains(maxChains) + return typesUtil.ErrMaxChains(maxChains) } return nil } -func (u *UtilityContext) CalculateUnstakingHeight(unstakingBlocks int64) (int64, types.Error) { +func (u *UtilityContext) CalculateUnstakingHeight(unstakingBlocks int64) (int64, typesUtil.Error) { latestHeight, err := u.GetLatestHeight() if err != nil { return typesUtil.ZeroInt, err @@ -546,10 +533,10 @@ func (u *UtilityContext) CalculateUnstakingHeight(unstakingBlocks int64) (int64, // util -func (u *UtilityContext) BytesToPublicKey(publicKey []byte) (crypto.PublicKey, types.Error) { +func (u *UtilityContext) BytesToPublicKey(publicKey []byte) (crypto.PublicKey, typesUtil.Error) { pk, er := crypto.NewPublicKeyFromBytes(publicKey) if er != nil { - return nil, types.ErrNewPublicKeyFromBytes(er) + return nil, typesUtil.ErrNewPublicKeyFromBytes(er) } return pk, nil } diff --git a/utility/block.go b/utility/block.go index c4566fe3a..6c09cd8cf 100644 --- a/utility/block.go +++ b/utility/block.go @@ -3,8 +3,10 @@ package utility import ( "math/big" - "github.com/pokt-network/pocket/shared/types" - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" + typesCons "github.com/pokt-network/pocket/consensus/types" // TODO (andrew) importing consensus and persistence in this file? + typesGenesis "github.com/pokt-network/pocket/persistence/types" + "github.com/pokt-network/pocket/shared/modules" + typesUtil "github.com/pokt-network/pocket/utility/types" ) @@ -22,11 +24,11 @@ import ( // TODO(andrew): consolidate with `utility/types/actor.go` var ( - actorTypes = []typesUtil.ActorType{ - typesUtil.ActorType_App, - typesUtil.ActorType_Node, - typesUtil.ActorType_Fish, - typesUtil.ActorType_Val, + UtilActorTypes = []typesUtil.UtilActorType{ + typesUtil.UtilActorType_App, + typesUtil.UtilActorType_Node, + typesUtil.UtilActorType_Fish, + typesUtil.UtilActorType_Val, } ) @@ -67,14 +69,14 @@ func (u *UtilityContext) ApplyBlock(latestHeight int64, proposerAddress []byte, return u.GetAppHash() } -func (u *UtilityContext) BeginBlock(previousBlockByzantineValidators [][]byte) types.Error { +func (u *UtilityContext) BeginBlock(previousBlockByzantineValidators [][]byte) typesUtil.Error { if err := u.HandleByzantineValidators(previousBlockByzantineValidators); err != nil { return err } return nil } -func (u *UtilityContext) EndBlock(proposer []byte) types.Error { +func (u *UtilityContext) EndBlock(proposer []byte) typesUtil.Error { // reward the block proposer if err := u.HandleProposalRewards(proposer); err != nil { return err @@ -90,17 +92,17 @@ func (u *UtilityContext) EndBlock(proposer []byte) types.Error { return nil } -func (u *UtilityContext) GetAppHash() ([]byte, types.Error) { +func (u *UtilityContext) GetAppHash() ([]byte, typesUtil.Error) { // Get the root hash of the merkle state tree for state consensus integrity appHash, er := u.Context.AppHash() if er != nil { - return nil, types.ErrAppHash(er) + return nil, typesUtil.ErrAppHash(er) } return appHash, nil } // HandleByzantineValidators handles the validators who either didn't sign at all or disagreed with the 2/3+ majority -func (u *UtilityContext) HandleByzantineValidators(lastBlockByzantineValidators [][]byte) types.Error { +func (u *UtilityContext) HandleByzantineValidators(lastBlockByzantineValidators [][]byte) typesUtil.Error { latestBlockHeight, err := u.GetLatestHeight() if err != nil { return err @@ -119,7 +121,7 @@ func (u *UtilityContext) HandleByzantineValidators(lastBlockByzantineValidators // handle if over the threshold if numberOfMissedBlocks >= maxMissedBlocks { // pause the validator and reset missed blocks - if err = u.PauseValidatorAndSetMissedBlocks(address, latestBlockHeight, typesUtil.HeightNotUsed); err != nil { + if err = u.PauseValidatorAndSetMissedBlocks(address, latestBlockHeight, int(typesUtil.HeightNotUsed)); err != nil { return err } // burn validator for missing blocks @@ -127,7 +129,7 @@ func (u *UtilityContext) HandleByzantineValidators(lastBlockByzantineValidators if err != nil { return err } - if err = u.BurnActor(typesUtil.ActorType_Val, burnPercentage, address); err != nil { + if err = u.BurnActor(typesUtil.UtilActorType_Val, burnPercentage, address); err != nil { return err } } else if err := u.SetValidatorMissedBlocks(address, numberOfMissedBlocks); err != nil { @@ -137,29 +139,29 @@ func (u *UtilityContext) HandleByzantineValidators(lastBlockByzantineValidators return nil } -func (u *UtilityContext) UnstakeActorsThatAreReady() (err types.Error) { +func (u *UtilityContext) UnstakeActorsThatAreReady() (err typesUtil.Error) { var er error store := u.Store() latestHeight, err := u.GetLatestHeight() if err != nil { return err } - for _, actorType := range typesUtil.ActorTypes { - var readyToUnstake []*types.UnstakingActor - poolName := actorType.GetActorPoolName() - switch actorType { - case typesUtil.ActorType_App: + for _, utilActorType := range typesUtil.ActorTypes { + var readyToUnstake []modules.IUnstakingActor + poolName := utilActorType.GetActorPoolName() + switch utilActorType { + case typesUtil.UtilActorType_App: readyToUnstake, er = store.GetAppsReadyToUnstake(latestHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: readyToUnstake, er = store.GetFishermenReadyToUnstake(latestHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: readyToUnstake, er = store.GetServiceNodesReadyToUnstake(latestHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: readyToUnstake, er = store.GetValidatorsReadyToUnstake(latestHeight, typesUtil.UnstakingStatus) } if er != nil { - return types.ErrGetReadyToUnstake(er) + return typesUtil.ErrGetReadyToUnstake(er) } for _, actor := range readyToUnstake { if err = u.SubPoolAmount(poolName, actor.GetStakeAmount()); err != nil { @@ -168,7 +170,7 @@ func (u *UtilityContext) UnstakeActorsThatAreReady() (err types.Error) { if err = u.AddAccountAmountString(actor.GetOutputAddress(), actor.GetStakeAmount()); err != nil { return err } - if err = u.DeleteActor(actorType, actor.GetAddress()); err != nil { + if err = u.DeleteActor(utilActorType, actor.GetAddress()); err != nil { return err } } @@ -176,13 +178,13 @@ func (u *UtilityContext) UnstakeActorsThatAreReady() (err types.Error) { return nil } -func (u *UtilityContext) BeginUnstakingMaxPaused() (err types.Error) { +func (u *UtilityContext) BeginUnstakingMaxPaused() (err typesUtil.Error) { latestHeight, err := u.GetLatestHeight() if err != nil { return err } - for _, actorType := range actorTypes { - maxPausedBlocks, err := u.GetMaxPausedBlocks(actorType) + for _, UtilActorType := range UtilActorTypes { + maxPausedBlocks, err := u.GetMaxPausedBlocks(UtilActorType) if err != nil { return err } @@ -191,37 +193,37 @@ func (u *UtilityContext) BeginUnstakingMaxPaused() (err types.Error) { if beforeHeight < 0 { beforeHeight = 0 } - if err := u.UnstakeActorPausedBefore(beforeHeight, actorType); err != nil { + if err := u.UnstakeActorPausedBefore(beforeHeight, UtilActorType); err != nil { return err } } return nil } -func (u *UtilityContext) UnstakeActorPausedBefore(pausedBeforeHeight int64, actorType typesUtil.ActorType) (err types.Error) { +func (u *UtilityContext) UnstakeActorPausedBefore(pausedBeforeHeight int64, UtilActorType typesUtil.UtilActorType) (err typesUtil.Error) { var er error store := u.Store() - unstakingHeight, err := u.GetUnstakingHeight(actorType) + unstakingHeight, err := u.GetUnstakingHeight(UtilActorType) if err != nil { return err } - switch actorType { - case typesUtil.ActorType_App: + switch UtilActorType { + case typesUtil.UtilActorType_App: er = store.SetAppStatusAndUnstakingHeightIfPausedBefore(pausedBeforeHeight, unstakingHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: er = store.SetFishermanStatusAndUnstakingHeightIfPausedBefore(pausedBeforeHeight, unstakingHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: er = store.SetServiceNodeStatusAndUnstakingHeightIfPausedBefore(pausedBeforeHeight, unstakingHeight, typesUtil.UnstakingStatus) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: er = store.SetValidatorsStatusAndUnstakingHeightIfPausedBefore(pausedBeforeHeight, unstakingHeight, typesUtil.UnstakingStatus) } if er != nil { - return types.ErrSetStatusPausedBefore(er, pausedBeforeHeight) + return typesUtil.ErrSetStatusPausedBefore(er, pausedBeforeHeight) } return nil } -func (u *UtilityContext) HandleProposalRewards(proposer []byte) types.Error { +func (u *UtilityContext) HandleProposalRewards(proposer []byte) typesUtil.Error { feePoolName := typesGenesis.Pool_Names_FeeCollector.String() feesAndRewardsCollected, err := u.GetPoolAmount(feePoolName) if err != nil { @@ -236,7 +238,7 @@ func (u *UtilityContext) HandleProposalRewards(proposer []byte) types.Error { } daoCutPercentage := 100 - proposerCutPercentage if daoCutPercentage < 0 || daoCutPercentage > 100 { - return types.ErrInvalidProposerCutPercentage() + return typesUtil.ErrInvalidProposerCutPercentage() } amountToProposerFloat := new(big.Float).SetInt(feesAndRewardsCollected) amountToProposerFloat.Mul(amountToProposerFloat, big.NewFloat(float64(proposerCutPercentage))) @@ -253,32 +255,32 @@ func (u *UtilityContext) HandleProposalRewards(proposer []byte) types.Error { } // GetValidatorMissedBlocks gets the total blocks that a validator has not signed a certain window of time denominated by blocks -func (u *UtilityContext) GetValidatorMissedBlocks(address []byte) (int, types.Error) { +func (u *UtilityContext) GetValidatorMissedBlocks(address []byte) (int, typesUtil.Error) { store := u.Store() height, er := store.GetHeight() if er != nil { - return typesUtil.ZeroInt, types.ErrGetMissedBlocks(er) + return typesUtil.ZeroInt, typesUtil.ErrGetMissedBlocks(er) } missedBlocks, er := store.GetValidatorMissedBlocks(address, height) if er != nil { - return typesUtil.ZeroInt, types.ErrGetMissedBlocks(er) + return typesUtil.ZeroInt, typesUtil.ErrGetMissedBlocks(er) } return missedBlocks, nil } -func (u *UtilityContext) PauseValidatorAndSetMissedBlocks(address []byte, pauseHeight int64, missedBlocks int) types.Error { +func (u *UtilityContext) PauseValidatorAndSetMissedBlocks(address []byte, pauseHeight int64, missedBlocks int) typesUtil.Error { store := u.Store() if err := store.SetValidatorPauseHeightAndMissedBlocks(address, pauseHeight, missedBlocks); err != nil { - return types.ErrSetPauseHeight(err) + return typesUtil.ErrSetPauseHeight(err) } return nil } -func (u *UtilityContext) SetValidatorMissedBlocks(address []byte, missedBlocks int) types.Error { +func (u *UtilityContext) SetValidatorMissedBlocks(address []byte, missedBlocks int) typesUtil.Error { store := u.Store() er := store.SetValidatorMissedBlocks(address, missedBlocks) if er != nil { - return types.ErrSetMissedBlocks(er) + return typesUtil.ErrSetMissedBlocks(er) } return nil } @@ -295,9 +297,9 @@ func (u *UtilityContext) StoreBlock(blockProtoBytes []byte) error { // OPTIMIZE: Ideally we'd pass in the block proto struct to utility so we don't // have to unmarshal it here, but that's a major design decision for the interfaces. codec := u.Codec() - block := &types.Block{} + block := &typesCons.Block{} if err := codec.Unmarshal(blockProtoBytes, block); err != nil { - return types.ErrProtoUnmarshal(err) + return typesUtil.ErrProtoUnmarshal(err) } header := block.BlockHeader if err := store.InsertBlock(uint64(header.Height), header.Hash, header.ProposerAddress, header.QuorumCertificate); err != nil { diff --git a/utility/context.go b/utility/context.go index f75d6dd23..460b7cfa1 100644 --- a/utility/context.go +++ b/utility/context.go @@ -2,15 +2,14 @@ package utility import ( "encoding/hex" - + "github.com/pokt-network/pocket/shared/codec" "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types" typesUtil "github.com/pokt-network/pocket/utility/types" ) type UtilityContext struct { LatestHeight int64 - Mempool types.Mempool + Mempool typesUtil.Mempool Context *Context // IMPROVE: Consider renmaming to PersistenceContext } @@ -23,7 +22,7 @@ type Context struct { func (u *UtilityModule) NewContext(height int64) (modules.UtilityContext, error) { ctx, err := u.GetBus().GetPersistenceModule().NewRWContext(height) if err != nil { - return nil, types.ErrNewPersistenceContext(err) + return nil, typesUtil.ErrNewPersistenceContext(err) } return &UtilityContext{ LatestHeight: height, @@ -53,44 +52,44 @@ func (u *UtilityContext) ReleaseContext() { u.Context = nil } -func (u *UtilityContext) GetLatestHeight() (int64, types.Error) { +func (u *UtilityContext) GetLatestHeight() (int64, typesUtil.Error) { return u.LatestHeight, nil } -func (u *UtilityContext) Codec() types.Codec { - return types.GetCodec() +func (u *UtilityContext) Codec() codec.Codec { + return codec.GetCodec() } -func (u *UtilityContext) RevertLastSavePoint() types.Error { +func (u *UtilityContext) RevertLastSavePoint() typesUtil.Error { if len(u.Context.SavePointsM) == typesUtil.ZeroInt { - return types.ErrEmptySavePoints() + return typesUtil.ErrEmptySavePoints() } var key []byte popIndex := len(u.Context.SavePoints) - 1 key, u.Context.SavePoints = u.Context.SavePoints[popIndex], u.Context.SavePoints[:popIndex] delete(u.Context.SavePointsM, hex.EncodeToString(key)) if err := u.Context.PersistenceRWContext.RollbackToSavePoint(key); err != nil { - return types.ErrRollbackSavePoint(err) + return typesUtil.ErrRollbackSavePoint(err) } return nil } -func (u *UtilityContext) NewSavePoint(transactionHash []byte) types.Error { +func (u *UtilityContext) NewSavePoint(transactionHash []byte) typesUtil.Error { if err := u.Context.PersistenceRWContext.NewSavePoint(transactionHash); err != nil { - return types.ErrNewSavePoint(err) + return typesUtil.ErrNewSavePoint(err) } txHash := hex.EncodeToString(transactionHash) if _, exists := u.Context.SavePointsM[txHash]; exists { - return types.ErrDuplicateSavePoint() + return typesUtil.ErrDuplicateSavePoint() } u.Context.SavePoints = append(u.Context.SavePoints, transactionHash) u.Context.SavePointsM[txHash] = struct{}{} return nil } -func (c *Context) Reset() types.Error { +func (c *Context) Reset() typesUtil.Error { if err := c.PersistenceRWContext.Reset(); err != nil { - return types.ErrResetContext(err) + return typesUtil.ErrResetContext(err) } return nil } diff --git a/utility/doc/CHANGELOG.md b/utility/doc/CHANGELOG.md index 9c5cb5aeb..b8d67fb90 100644 --- a/utility/doc/CHANGELOG.md +++ b/utility/doc/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.0.0.2] - 2022-08-25 +**Encapsulate structures previously in shared [#163](github.com/pokt-network/pocket/issues/163)** +- Ensured proto structures implement shared interfaces +- `UtilityConfig` uses shared interfaces in order to accept `MockUtilityConfig` in test_artifacts +- Moved all utilty tests from shared to tests package +- Left `TODO` for tests package still importing persistence for `NewTestPersistenceModule` + - This is one of the last places where cross-module importing exists + ## [0.0.1] - 2022-07-20 ### Code cleanup diff --git a/utility/doc/README.md b/utility/doc/README.md index 746956157..53f95468e 100644 --- a/utility/doc/README.md +++ b/utility/doc/README.md @@ -185,25 +185,21 @@ $ make test_utility_types && make test_utility_module ```bash utility -├── account.go # utility context for accounts & pools -├── actor.go # utility context for apps, fish, nodes, and validators -├── block.go # utility context for blocks -├── doc # contains the documentation and changelog -├── gov.go # utility context for dao & parameters -├── module.go # module implementation and interfaces -├── proto # protobuf3 messages that auto-generate into the types directory -│   ├── actor.proto -│   ├── message.proto -│   ├── transaction.proto -│   └── vote.proto -├── test # utility unit tests +├── account.go # utility context for accounts & pools +├── actor.go # utility context for apps, fish, nodes, and validators +├── block.go # utility context for blocks +├── gov.go # utility context for dao & parameters +├── module.go # module implementation and interfaces ├── transaction.go # utility context for transactions including handlers +├── doc # contains the documentation and changelog +├── test # utility unit tests ├── types # stateless (without relying on persistence) library of utility types +│   ├── proto # protobuf3 messages that auto-generate into the types directory │   ├── actor.go +│   ├── error.go +│   ├── mempool.go │   ├── message.go # payloads of transactions │   ├── transaction.go # the finite unit of the block -│   ├── utils.go +│   ├── util.go │   ├── vote.go # vote structure for double sign transaction -└── utility - └── types ``` diff --git a/utility/gov.go b/utility/gov.go index d37c79129..d062ef643 100644 --- a/utility/gov.go +++ b/utility/gov.go @@ -2,262 +2,262 @@ package utility import ( "fmt" + "github.com/pokt-network/pocket/shared/modules" "log" "math/big" - "github.com/pokt-network/pocket/shared/types" typesUtil "github.com/pokt-network/pocket/utility/types" "google.golang.org/protobuf/types/known/wrapperspb" ) -func (u *UtilityContext) UpdateParam(paramName string, value interface{}) types.Error { +func (u *UtilityContext) UpdateParam(paramName string, value interface{}) typesUtil.Error { store := u.Store() switch t := value.(type) { case *wrapperspb.Int32Value: if err := store.SetParam(paramName, (int(t.Value))); err != nil { - return types.ErrUpdateParam(err) + return typesUtil.ErrUpdateParam(err) } return nil case *wrapperspb.StringValue: if err := store.SetParam(paramName, t.Value); err != nil { - return types.ErrUpdateParam(err) + return typesUtil.ErrUpdateParam(err) } return nil case *wrapperspb.BytesValue: if err := store.SetParam(paramName, t.Value); err != nil { - return types.ErrUpdateParam(err) + return typesUtil.ErrUpdateParam(err) } return nil default: break } log.Fatalf("unhandled value type %T for %v", value, value) - return types.ErrUnknownParam(paramName) + return typesUtil.ErrUnknownParam(paramName) } -func (u *UtilityContext) GetBlocksPerSession() (int, types.Error) { +func (u *UtilityContext) GetBlocksPerSession() (int, typesUtil.Error) { store := u.Store() height, err := store.GetHeight() if err != nil { - return typesUtil.ZeroInt, types.ErrGetParam(types.BlocksPerSessionParamName, err) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(modules.BlocksPerSessionParamName, err) } blocksPerSession, err := store.GetBlocksPerSession(height) if err != nil { - return typesUtil.ZeroInt, types.ErrGetParam(types.BlocksPerSessionParamName, err) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(modules.BlocksPerSessionParamName, err) } return blocksPerSession, nil } -func (u *UtilityContext) GetAppMinimumStake() (*big.Int, types.Error) { - return u.getBigIntParam(types.AppMinimumStakeParamName) +func (u *UtilityContext) GetAppMinimumStake() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.AppMinimumStakeParamName) } -func (u *UtilityContext) GetAppMaxChains() (int, types.Error) { - return u.getIntParam(types.AppMaxChainsParamName) +func (u *UtilityContext) GetAppMaxChains() (int, typesUtil.Error) { + return u.getIntParam(modules.AppMaxChainsParamName) } -func (u *UtilityContext) GetBaselineAppStakeRate() (int, types.Error) { - return u.getIntParam(types.AppBaselineStakeRateParamName) +func (u *UtilityContext) GetBaselineAppStakeRate() (int, typesUtil.Error) { + return u.getIntParam(modules.AppBaselineStakeRateParamName) } -func (u *UtilityContext) GetStabilityAdjustment() (int, types.Error) { - return u.getIntParam(types.AppStakingAdjustmentParamName) +func (u *UtilityContext) GetStabilityAdjustment() (int, typesUtil.Error) { + return u.getIntParam(modules.AppStakingAdjustmentParamName) } -func (u *UtilityContext) GetAppUnstakingBlocks() (int64, types.Error) { - return u.getInt64Param(types.AppUnstakingBlocksParamName) +func (u *UtilityContext) GetAppUnstakingBlocks() (int64, typesUtil.Error) { + return u.getInt64Param(modules.AppUnstakingBlocksParamName) } -func (u *UtilityContext) GetAppMinimumPauseBlocks() (int, types.Error) { - return u.getIntParam(types.AppMinimumPauseBlocksParamName) +func (u *UtilityContext) GetAppMinimumPauseBlocks() (int, typesUtil.Error) { + return u.getIntParam(modules.AppMinimumPauseBlocksParamName) } -func (u *UtilityContext) GetAppMaxPausedBlocks() (maxPausedBlocks int, err types.Error) { - return u.getIntParam(types.AppMaxPauseBlocksParamName) +func (u *UtilityContext) GetAppMaxPausedBlocks() (maxPausedBlocks int, err typesUtil.Error) { + return u.getIntParam(modules.AppMaxPauseBlocksParamName) } -func (u *UtilityContext) GetServiceNodeMinimumStake() (*big.Int, types.Error) { - return u.getBigIntParam(types.ServiceNodeMinimumStakeParamName) +func (u *UtilityContext) GetServiceNodeMinimumStake() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.ServiceNodeMinimumStakeParamName) } -func (u *UtilityContext) GetServiceNodeMaxChains() (int, types.Error) { - return u.getIntParam(types.ServiceNodeMaxChainsParamName) +func (u *UtilityContext) GetServiceNodeMaxChains() (int, typesUtil.Error) { + return u.getIntParam(modules.ServiceNodeMaxChainsParamName) } -func (u *UtilityContext) GetServiceNodeUnstakingBlocks() (int64, types.Error) { - return u.getInt64Param(types.ServiceNodeUnstakingBlocksParamName) +func (u *UtilityContext) GetServiceNodeUnstakingBlocks() (int64, typesUtil.Error) { + return u.getInt64Param(modules.ServiceNodeUnstakingBlocksParamName) } -func (u *UtilityContext) GetServiceNodeMinimumPauseBlocks() (int, types.Error) { - return u.getIntParam(types.ServiceNodeMinimumPauseBlocksParamName) +func (u *UtilityContext) GetServiceNodeMinimumPauseBlocks() (int, typesUtil.Error) { + return u.getIntParam(modules.ServiceNodeMinimumPauseBlocksParamName) } -func (u *UtilityContext) GetServiceNodeMaxPausedBlocks() (maxPausedBlocks int, err types.Error) { - return u.getIntParam(types.ServiceNodeMaxPauseBlocksParamName) +func (u *UtilityContext) GetServiceNodeMaxPausedBlocks() (maxPausedBlocks int, err typesUtil.Error) { + return u.getIntParam(modules.ServiceNodeMaxPauseBlocksParamName) } -func (u *UtilityContext) GetValidatorMinimumStake() (*big.Int, types.Error) { - return u.getBigIntParam(types.ValidatorMinimumStakeParamName) +func (u *UtilityContext) GetValidatorMinimumStake() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.ValidatorMinimumStakeParamName) } -func (u *UtilityContext) GetValidatorUnstakingBlocks() (int64, types.Error) { - return u.getInt64Param(types.ValidatorUnstakingBlocksParamName) +func (u *UtilityContext) GetValidatorUnstakingBlocks() (int64, typesUtil.Error) { + return u.getInt64Param(modules.ValidatorUnstakingBlocksParamName) } -func (u *UtilityContext) GetValidatorMinimumPauseBlocks() (int, types.Error) { - return u.getIntParam(types.ValidatorMinimumPauseBlocksParamName) +func (u *UtilityContext) GetValidatorMinimumPauseBlocks() (int, typesUtil.Error) { + return u.getIntParam(modules.ValidatorMinimumPauseBlocksParamName) } -func (u *UtilityContext) GetValidatorMaxPausedBlocks() (maxPausedBlocks int, err types.Error) { - return u.getIntParam(types.ValidatorMaxPausedBlocksParamName) +func (u *UtilityContext) GetValidatorMaxPausedBlocks() (maxPausedBlocks int, err typesUtil.Error) { + return u.getIntParam(modules.ValidatorMaxPausedBlocksParamName) } -func (u *UtilityContext) GetProposerPercentageOfFees() (proposerPercentage int, err types.Error) { - return u.getIntParam(types.ProposerPercentageOfFeesParamName) +func (u *UtilityContext) GetProposerPercentageOfFees() (proposerPercentage int, err typesUtil.Error) { + return u.getIntParam(modules.ProposerPercentageOfFeesParamName) } -func (u *UtilityContext) GetValidatorMaxMissedBlocks() (maxMissedBlocks int, err types.Error) { - return u.getIntParam(types.ValidatorMaximumMissedBlocksParamName) +func (u *UtilityContext) GetValidatorMaxMissedBlocks() (maxMissedBlocks int, err typesUtil.Error) { + return u.getIntParam(modules.ValidatorMaximumMissedBlocksParamName) } -func (u *UtilityContext) GetMaxEvidenceAgeInBlocks() (maxMissedBlocks int, err types.Error) { - return u.getIntParam(types.ValidatorMaxEvidenceAgeInBlocksParamName) +func (u *UtilityContext) GetMaxEvidenceAgeInBlocks() (maxMissedBlocks int, err typesUtil.Error) { + return u.getIntParam(modules.ValidatorMaxEvidenceAgeInBlocksParamName) } -func (u *UtilityContext) GetDoubleSignBurnPercentage() (burnPercentage int, err types.Error) { - return u.getIntParam(types.DoubleSignBurnPercentageParamName) +func (u *UtilityContext) GetDoubleSignBurnPercentage() (burnPercentage int, err typesUtil.Error) { + return u.getIntParam(modules.DoubleSignBurnPercentageParamName) } -func (u *UtilityContext) GetMissedBlocksBurnPercentage() (burnPercentage int, err types.Error) { - return u.getIntParam(types.MissedBlocksBurnPercentageParamName) +func (u *UtilityContext) GetMissedBlocksBurnPercentage() (burnPercentage int, err typesUtil.Error) { + return u.getIntParam(modules.MissedBlocksBurnPercentageParamName) } -func (u *UtilityContext) GetFishermanMinimumStake() (*big.Int, types.Error) { - return u.getBigIntParam(types.FishermanMinimumStakeParamName) +func (u *UtilityContext) GetFishermanMinimumStake() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.FishermanMinimumStakeParamName) } -func (u *UtilityContext) GetFishermanMaxChains() (int, types.Error) { - return u.getIntParam(types.FishermanMaxChainsParamName) +func (u *UtilityContext) GetFishermanMaxChains() (int, typesUtil.Error) { + return u.getIntParam(modules.FishermanMaxChainsParamName) } -func (u *UtilityContext) GetFishermanUnstakingBlocks() (int64, types.Error) { - return u.getInt64Param(types.FishermanUnstakingBlocksParamName) +func (u *UtilityContext) GetFishermanUnstakingBlocks() (int64, typesUtil.Error) { + return u.getInt64Param(modules.FishermanUnstakingBlocksParamName) } -func (u *UtilityContext) GetFishermanMinimumPauseBlocks() (int, types.Error) { - return u.getIntParam(types.FishermanMinimumPauseBlocksParamName) +func (u *UtilityContext) GetFishermanMinimumPauseBlocks() (int, typesUtil.Error) { + return u.getIntParam(modules.FishermanMinimumPauseBlocksParamName) } -func (u *UtilityContext) GetFishermanMaxPausedBlocks() (maxPausedBlocks int, err types.Error) { - return u.getIntParam(types.FishermanMaxPauseBlocksParamName) +func (u *UtilityContext) GetFishermanMaxPausedBlocks() (maxPausedBlocks int, err typesUtil.Error) { + return u.getIntParam(modules.FishermanMaxPauseBlocksParamName) } -func (u *UtilityContext) GetMessageDoubleSignFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageDoubleSignFee) +func (u *UtilityContext) GetMessageDoubleSignFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageDoubleSignFee) } -func (u *UtilityContext) GetMessageSendFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageSendFee) +func (u *UtilityContext) GetMessageSendFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageSendFee) } -func (u *UtilityContext) GetMessageStakeFishermanFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageStakeFishermanFee) +func (u *UtilityContext) GetMessageStakeFishermanFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageStakeFishermanFee) } -func (u *UtilityContext) GetMessageEditStakeFishermanFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageEditStakeFishermanFee) +func (u *UtilityContext) GetMessageEditStakeFishermanFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageEditStakeFishermanFee) } -func (u *UtilityContext) GetMessageUnstakeFishermanFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageUnstakeFishermanFee) +func (u *UtilityContext) GetMessageUnstakeFishermanFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageUnstakeFishermanFee) } -func (u *UtilityContext) GetMessagePauseFishermanFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessagePauseFishermanFee) +func (u *UtilityContext) GetMessagePauseFishermanFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessagePauseFishermanFee) } -func (u *UtilityContext) GetMessageUnpauseFishermanFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageUnpauseFishermanFee) +func (u *UtilityContext) GetMessageUnpauseFishermanFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageUnpauseFishermanFee) } -func (u *UtilityContext) GetMessageFishermanPauseServiceNodeFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageFishermanPauseServiceNodeFee) +func (u *UtilityContext) GetMessageFishermanPauseServiceNodeFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageFishermanPauseServiceNodeFee) } -func (u *UtilityContext) GetMessageTestScoreFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageTestScoreFee) +func (u *UtilityContext) GetMessageTestScoreFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageTestScoreFee) } -func (u *UtilityContext) GetMessageProveTestScoreFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageProveTestScoreFee) +func (u *UtilityContext) GetMessageProveTestScoreFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageProveTestScoreFee) } -func (u *UtilityContext) GetMessageStakeAppFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageStakeAppFee) +func (u *UtilityContext) GetMessageStakeAppFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageStakeAppFee) } -func (u *UtilityContext) GetMessageEditStakeAppFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageEditStakeAppFee) +func (u *UtilityContext) GetMessageEditStakeAppFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageEditStakeAppFee) } -func (u *UtilityContext) GetMessageUnstakeAppFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageUnstakeAppFee) +func (u *UtilityContext) GetMessageUnstakeAppFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageUnstakeAppFee) } -func (u *UtilityContext) GetMessagePauseAppFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessagePauseAppFee) +func (u *UtilityContext) GetMessagePauseAppFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessagePauseAppFee) } -func (u *UtilityContext) GetMessageUnpauseAppFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageUnpauseAppFee) +func (u *UtilityContext) GetMessageUnpauseAppFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageUnpauseAppFee) } -func (u *UtilityContext) GetMessageStakeValidatorFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageStakeValidatorFee) +func (u *UtilityContext) GetMessageStakeValidatorFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageStakeValidatorFee) } -func (u *UtilityContext) GetMessageEditStakeValidatorFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageEditStakeValidatorFee) +func (u *UtilityContext) GetMessageEditStakeValidatorFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageEditStakeValidatorFee) } -func (u *UtilityContext) GetMessageUnstakeValidatorFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageUnstakeValidatorFee) +func (u *UtilityContext) GetMessageUnstakeValidatorFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageUnstakeValidatorFee) } -func (u *UtilityContext) GetMessagePauseValidatorFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessagePauseValidatorFee) +func (u *UtilityContext) GetMessagePauseValidatorFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessagePauseValidatorFee) } -func (u *UtilityContext) GetMessageUnpauseValidatorFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageUnpauseValidatorFee) +func (u *UtilityContext) GetMessageUnpauseValidatorFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageUnpauseValidatorFee) } -func (u *UtilityContext) GetMessageStakeServiceNodeFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageStakeServiceNodeFee) +func (u *UtilityContext) GetMessageStakeServiceNodeFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageStakeServiceNodeFee) } -func (u *UtilityContext) GetMessageEditStakeServiceNodeFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageEditStakeServiceNodeFee) +func (u *UtilityContext) GetMessageEditStakeServiceNodeFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageEditStakeServiceNodeFee) } -func (u *UtilityContext) GetMessageUnstakeServiceNodeFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageUnstakeServiceNodeFee) +func (u *UtilityContext) GetMessageUnstakeServiceNodeFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageUnstakeServiceNodeFee) } -func (u *UtilityContext) GetMessagePauseServiceNodeFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessagePauseServiceNodeFee) +func (u *UtilityContext) GetMessagePauseServiceNodeFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessagePauseServiceNodeFee) } -func (u *UtilityContext) GetMessageUnpauseServiceNodeFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageUnpauseServiceNodeFee) +func (u *UtilityContext) GetMessageUnpauseServiceNodeFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageUnpauseServiceNodeFee) } -func (u *UtilityContext) GetMessageChangeParameterFee() (*big.Int, types.Error) { - return u.getBigIntParam(types.MessageChangeParameterFee) +func (u *UtilityContext) GetMessageChangeParameterFee() (*big.Int, typesUtil.Error) { + return u.getBigIntParam(modules.MessageChangeParameterFee) } -func (u *UtilityContext) GetDoubleSignFeeOwner() (owner []byte, err types.Error) { - return u.getByteArrayParam(types.MessageDoubleSignFeeOwner) +func (u *UtilityContext) GetDoubleSignFeeOwner() (owner []byte, err typesUtil.Error) { + return u.getByteArrayParam(modules.MessageDoubleSignFeeOwner) } func (u *UtilityContext) GetParamOwner(paramName string) ([]byte, error) { @@ -270,228 +270,228 @@ func (u *UtilityContext) GetParamOwner(paramName string) ([]byte, error) { return nil, err } switch paramName { - case types.AclOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.BlocksPerSessionParamName: - return store.GetBytesParam(types.BlocksPerSessionOwner, height) - case types.AppMaxChainsParamName: - return store.GetBytesParam(types.AppMaxChainsOwner, height) - case types.AppMinimumStakeParamName: - return store.GetBytesParam(types.AppMinimumStakeOwner, height) - case types.AppBaselineStakeRateParamName: - return store.GetBytesParam(types.AppBaselineStakeRateOwner, height) - case types.AppStakingAdjustmentParamName: - return store.GetBytesParam(types.AppStakingAdjustmentOwner, height) - case types.AppUnstakingBlocksParamName: - return store.GetBytesParam(types.AppUnstakingBlocksOwner, height) - case types.AppMinimumPauseBlocksParamName: - return store.GetBytesParam(types.AppMinimumPauseBlocksOwner, height) - case types.AppMaxPauseBlocksParamName: - return store.GetBytesParam(types.AppMaxPausedBlocksOwner, height) - case types.ServiceNodesPerSessionParamName: - return store.GetBytesParam(types.ServiceNodesPerSessionOwner, height) - case types.ServiceNodeMinimumStakeParamName: - return store.GetBytesParam(types.ServiceNodeMinimumStakeOwner, height) - case types.ServiceNodeMaxChainsParamName: - return store.GetBytesParam(types.ServiceNodeMaxChainsOwner, height) - case types.ServiceNodeUnstakingBlocksParamName: - return store.GetBytesParam(types.ServiceNodeUnstakingBlocksOwner, height) - case types.ServiceNodeMinimumPauseBlocksParamName: - return store.GetBytesParam(types.ServiceNodeMinimumPauseBlocksOwner, height) - case types.ServiceNodeMaxPauseBlocksParamName: - return store.GetBytesParam(types.ServiceNodeMaxPausedBlocksOwner, height) - case types.FishermanMinimumStakeParamName: - return store.GetBytesParam(types.FishermanMinimumStakeOwner, height) - case types.FishermanMaxChainsParamName: - return store.GetBytesParam(types.FishermanMaxChainsOwner, height) - case types.FishermanUnstakingBlocksParamName: - return store.GetBytesParam(types.FishermanUnstakingBlocksOwner, height) - case types.FishermanMinimumPauseBlocksParamName: - return store.GetBytesParam(types.FishermanMinimumPauseBlocksOwner, height) - case types.FishermanMaxPauseBlocksParamName: - return store.GetBytesParam(types.FishermanMaxPausedBlocksOwner, height) - case types.ValidatorMinimumStakeParamName: - return store.GetBytesParam(types.ValidatorMinimumStakeOwner, height) - case types.ValidatorUnstakingBlocksParamName: - return store.GetBytesParam(types.ValidatorUnstakingBlocksOwner, height) - case types.ValidatorMinimumPauseBlocksParamName: - return store.GetBytesParam(types.ValidatorMinimumPauseBlocksOwner, height) - case types.ValidatorMaxPausedBlocksParamName: - return store.GetBytesParam(types.ValidatorMaxPausedBlocksOwner, height) - case types.ValidatorMaximumMissedBlocksParamName: - return store.GetBytesParam(types.ValidatorMaximumMissedBlocksOwner, height) - case types.ProposerPercentageOfFeesParamName: - return store.GetBytesParam(types.ProposerPercentageOfFeesOwner, height) - case types.ValidatorMaxEvidenceAgeInBlocksParamName: - return store.GetBytesParam(types.ValidatorMaxEvidenceAgeInBlocksOwner, height) - case types.MissedBlocksBurnPercentageParamName: - return store.GetBytesParam(types.MissedBlocksBurnPercentageOwner, height) - case types.DoubleSignBurnPercentageParamName: - return store.GetBytesParam(types.DoubleSignBurnPercentageOwner, height) - case types.MessageDoubleSignFee: - return store.GetBytesParam(types.MessageDoubleSignFeeOwner, height) - case types.MessageSendFee: - return store.GetBytesParam(types.MessageSendFeeOwner, height) - case types.MessageStakeFishermanFee: - return store.GetBytesParam(types.MessageStakeFishermanFeeOwner, height) - case types.MessageEditStakeFishermanFee: - return store.GetBytesParam(types.MessageEditStakeFishermanFeeOwner, height) - case types.MessageUnstakeFishermanFee: - return store.GetBytesParam(types.MessageUnstakeFishermanFeeOwner, height) - case types.MessagePauseFishermanFee: - return store.GetBytesParam(types.MessagePauseFishermanFeeOwner, height) - case types.MessageUnpauseFishermanFee: - return store.GetBytesParam(types.MessageUnpauseFishermanFeeOwner, height) - case types.MessageFishermanPauseServiceNodeFee: - return store.GetBytesParam(types.MessageFishermanPauseServiceNodeFeeOwner, height) - case types.MessageTestScoreFee: - return store.GetBytesParam(types.MessageTestScoreFeeOwner, height) - case types.MessageProveTestScoreFee: - return store.GetBytesParam(types.MessageProveTestScoreFeeOwner, height) - case types.MessageStakeAppFee: - return store.GetBytesParam(types.MessageStakeAppFeeOwner, height) - case types.MessageEditStakeAppFee: - return store.GetBytesParam(types.MessageEditStakeAppFeeOwner, height) - case types.MessageUnstakeAppFee: - return store.GetBytesParam(types.MessageUnstakeAppFeeOwner, height) - case types.MessagePauseAppFee: - return store.GetBytesParam(types.MessagePauseAppFeeOwner, height) - case types.MessageUnpauseAppFee: - return store.GetBytesParam(types.MessageUnpauseAppFeeOwner, height) - case types.MessageStakeValidatorFee: - return store.GetBytesParam(types.MessageStakeValidatorFeeOwner, height) - case types.MessageEditStakeValidatorFee: - return store.GetBytesParam(types.MessageEditStakeValidatorFeeOwner, height) - case types.MessageUnstakeValidatorFee: - return store.GetBytesParam(types.MessageUnstakeValidatorFeeOwner, height) - case types.MessagePauseValidatorFee: - return store.GetBytesParam(types.MessagePauseValidatorFeeOwner, height) - case types.MessageUnpauseValidatorFee: - return store.GetBytesParam(types.MessageUnpauseValidatorFeeOwner, height) - case types.MessageStakeServiceNodeFee: - return store.GetBytesParam(types.MessageStakeServiceNodeFeeOwner, height) - case types.MessageEditStakeServiceNodeFee: - return store.GetBytesParam(types.MessageEditStakeServiceNodeFeeOwner, height) - case types.MessageUnstakeServiceNodeFee: - return store.GetBytesParam(types.MessageUnstakeServiceNodeFeeOwner, height) - case types.MessagePauseServiceNodeFee: - return store.GetBytesParam(types.MessagePauseServiceNodeFeeOwner, height) - case types.MessageUnpauseServiceNodeFee: - return store.GetBytesParam(types.MessageUnpauseServiceNodeFeeOwner, height) - case types.MessageChangeParameterFee: - return store.GetBytesParam(types.MessageChangeParameterFeeOwner, height) - case types.BlocksPerSessionOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.AppMaxChainsOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.AppMinimumStakeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.AppBaselineStakeRateOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.AppStakingAdjustmentOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.AppUnstakingBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.AppMinimumPauseBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.AppMaxPausedBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ServiceNodeMinimumStakeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ServiceNodeMaxChainsOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ServiceNodeUnstakingBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ServiceNodeMinimumPauseBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ServiceNodeMaxPausedBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ServiceNodesPerSessionOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.FishermanMinimumStakeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.FishermanMaxChainsOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.FishermanUnstakingBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.FishermanMinimumPauseBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.FishermanMaxPausedBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ValidatorMinimumStakeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ValidatorUnstakingBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ValidatorMinimumPauseBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ValidatorMaxPausedBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ValidatorMaximumMissedBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ProposerPercentageOfFeesOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.ValidatorMaxEvidenceAgeInBlocksOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MissedBlocksBurnPercentageOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.DoubleSignBurnPercentageOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageSendFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageStakeFishermanFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageEditStakeFishermanFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageUnstakeFishermanFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessagePauseFishermanFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageUnpauseFishermanFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageFishermanPauseServiceNodeFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageTestScoreFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageProveTestScoreFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageStakeAppFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageEditStakeAppFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageUnstakeAppFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessagePauseAppFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageUnpauseAppFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageStakeValidatorFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageEditStakeValidatorFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageUnstakeValidatorFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessagePauseValidatorFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageUnpauseValidatorFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageStakeServiceNodeFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageEditStakeServiceNodeFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageUnstakeServiceNodeFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessagePauseServiceNodeFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageUnpauseServiceNodeFeeOwner: - return store.GetBytesParam(types.AclOwner, height) - case types.MessageChangeParameterFeeOwner: - return store.GetBytesParam(types.AclOwner, height) + case modules.AclOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.BlocksPerSessionParamName: + return store.GetBytesParam(modules.BlocksPerSessionOwner, height) + case modules.AppMaxChainsParamName: + return store.GetBytesParam(modules.AppMaxChainsOwner, height) + case modules.AppMinimumStakeParamName: + return store.GetBytesParam(modules.AppMinimumStakeOwner, height) + case modules.AppBaselineStakeRateParamName: + return store.GetBytesParam(modules.AppBaselineStakeRateOwner, height) + case modules.AppStakingAdjustmentParamName: + return store.GetBytesParam(modules.AppStakingAdjustmentOwner, height) + case modules.AppUnstakingBlocksParamName: + return store.GetBytesParam(modules.AppUnstakingBlocksOwner, height) + case modules.AppMinimumPauseBlocksParamName: + return store.GetBytesParam(modules.AppMinimumPauseBlocksOwner, height) + case modules.AppMaxPauseBlocksParamName: + return store.GetBytesParam(modules.AppMaxPausedBlocksOwner, height) + case modules.ServiceNodesPerSessionParamName: + return store.GetBytesParam(modules.ServiceNodesPerSessionOwner, height) + case modules.ServiceNodeMinimumStakeParamName: + return store.GetBytesParam(modules.ServiceNodeMinimumStakeOwner, height) + case modules.ServiceNodeMaxChainsParamName: + return store.GetBytesParam(modules.ServiceNodeMaxChainsOwner, height) + case modules.ServiceNodeUnstakingBlocksParamName: + return store.GetBytesParam(modules.ServiceNodeUnstakingBlocksOwner, height) + case modules.ServiceNodeMinimumPauseBlocksParamName: + return store.GetBytesParam(modules.ServiceNodeMinimumPauseBlocksOwner, height) + case modules.ServiceNodeMaxPauseBlocksParamName: + return store.GetBytesParam(modules.ServiceNodeMaxPausedBlocksOwner, height) + case modules.FishermanMinimumStakeParamName: + return store.GetBytesParam(modules.FishermanMinimumStakeOwner, height) + case modules.FishermanMaxChainsParamName: + return store.GetBytesParam(modules.FishermanMaxChainsOwner, height) + case modules.FishermanUnstakingBlocksParamName: + return store.GetBytesParam(modules.FishermanUnstakingBlocksOwner, height) + case modules.FishermanMinimumPauseBlocksParamName: + return store.GetBytesParam(modules.FishermanMinimumPauseBlocksOwner, height) + case modules.FishermanMaxPauseBlocksParamName: + return store.GetBytesParam(modules.FishermanMaxPausedBlocksOwner, height) + case modules.ValidatorMinimumStakeParamName: + return store.GetBytesParam(modules.ValidatorMinimumStakeOwner, height) + case modules.ValidatorUnstakingBlocksParamName: + return store.GetBytesParam(modules.ValidatorUnstakingBlocksOwner, height) + case modules.ValidatorMinimumPauseBlocksParamName: + return store.GetBytesParam(modules.ValidatorMinimumPauseBlocksOwner, height) + case modules.ValidatorMaxPausedBlocksParamName: + return store.GetBytesParam(modules.ValidatorMaxPausedBlocksOwner, height) + case modules.ValidatorMaximumMissedBlocksParamName: + return store.GetBytesParam(modules.ValidatorMaximumMissedBlocksOwner, height) + case modules.ProposerPercentageOfFeesParamName: + return store.GetBytesParam(modules.ProposerPercentageOfFeesOwner, height) + case modules.ValidatorMaxEvidenceAgeInBlocksParamName: + return store.GetBytesParam(modules.ValidatorMaxEvidenceAgeInBlocksOwner, height) + case modules.MissedBlocksBurnPercentageParamName: + return store.GetBytesParam(modules.MissedBlocksBurnPercentageOwner, height) + case modules.DoubleSignBurnPercentageParamName: + return store.GetBytesParam(modules.DoubleSignBurnPercentageOwner, height) + case modules.MessageDoubleSignFee: + return store.GetBytesParam(modules.MessageDoubleSignFeeOwner, height) + case modules.MessageSendFee: + return store.GetBytesParam(modules.MessageSendFeeOwner, height) + case modules.MessageStakeFishermanFee: + return store.GetBytesParam(modules.MessageStakeFishermanFeeOwner, height) + case modules.MessageEditStakeFishermanFee: + return store.GetBytesParam(modules.MessageEditStakeFishermanFeeOwner, height) + case modules.MessageUnstakeFishermanFee: + return store.GetBytesParam(modules.MessageUnstakeFishermanFeeOwner, height) + case modules.MessagePauseFishermanFee: + return store.GetBytesParam(modules.MessagePauseFishermanFeeOwner, height) + case modules.MessageUnpauseFishermanFee: + return store.GetBytesParam(modules.MessageUnpauseFishermanFeeOwner, height) + case modules.MessageFishermanPauseServiceNodeFee: + return store.GetBytesParam(modules.MessageFishermanPauseServiceNodeFeeOwner, height) + case modules.MessageTestScoreFee: + return store.GetBytesParam(modules.MessageTestScoreFeeOwner, height) + case modules.MessageProveTestScoreFee: + return store.GetBytesParam(modules.MessageProveTestScoreFeeOwner, height) + case modules.MessageStakeAppFee: + return store.GetBytesParam(modules.MessageStakeAppFeeOwner, height) + case modules.MessageEditStakeAppFee: + return store.GetBytesParam(modules.MessageEditStakeAppFeeOwner, height) + case modules.MessageUnstakeAppFee: + return store.GetBytesParam(modules.MessageUnstakeAppFeeOwner, height) + case modules.MessagePauseAppFee: + return store.GetBytesParam(modules.MessagePauseAppFeeOwner, height) + case modules.MessageUnpauseAppFee: + return store.GetBytesParam(modules.MessageUnpauseAppFeeOwner, height) + case modules.MessageStakeValidatorFee: + return store.GetBytesParam(modules.MessageStakeValidatorFeeOwner, height) + case modules.MessageEditStakeValidatorFee: + return store.GetBytesParam(modules.MessageEditStakeValidatorFeeOwner, height) + case modules.MessageUnstakeValidatorFee: + return store.GetBytesParam(modules.MessageUnstakeValidatorFeeOwner, height) + case modules.MessagePauseValidatorFee: + return store.GetBytesParam(modules.MessagePauseValidatorFeeOwner, height) + case modules.MessageUnpauseValidatorFee: + return store.GetBytesParam(modules.MessageUnpauseValidatorFeeOwner, height) + case modules.MessageStakeServiceNodeFee: + return store.GetBytesParam(modules.MessageStakeServiceNodeFeeOwner, height) + case modules.MessageEditStakeServiceNodeFee: + return store.GetBytesParam(modules.MessageEditStakeServiceNodeFeeOwner, height) + case modules.MessageUnstakeServiceNodeFee: + return store.GetBytesParam(modules.MessageUnstakeServiceNodeFeeOwner, height) + case modules.MessagePauseServiceNodeFee: + return store.GetBytesParam(modules.MessagePauseServiceNodeFeeOwner, height) + case modules.MessageUnpauseServiceNodeFee: + return store.GetBytesParam(modules.MessageUnpauseServiceNodeFeeOwner, height) + case modules.MessageChangeParameterFee: + return store.GetBytesParam(modules.MessageChangeParameterFeeOwner, height) + case modules.BlocksPerSessionOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.AppMaxChainsOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.AppMinimumStakeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.AppBaselineStakeRateOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.AppStakingAdjustmentOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.AppUnstakingBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.AppMinimumPauseBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.AppMaxPausedBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ServiceNodeMinimumStakeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ServiceNodeMaxChainsOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ServiceNodeUnstakingBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ServiceNodeMinimumPauseBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ServiceNodeMaxPausedBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ServiceNodesPerSessionOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.FishermanMinimumStakeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.FishermanMaxChainsOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.FishermanUnstakingBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.FishermanMinimumPauseBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.FishermanMaxPausedBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ValidatorMinimumStakeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ValidatorUnstakingBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ValidatorMinimumPauseBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ValidatorMaxPausedBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ValidatorMaximumMissedBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ProposerPercentageOfFeesOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.ValidatorMaxEvidenceAgeInBlocksOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MissedBlocksBurnPercentageOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.DoubleSignBurnPercentageOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageSendFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageStakeFishermanFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageEditStakeFishermanFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageUnstakeFishermanFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessagePauseFishermanFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageUnpauseFishermanFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageFishermanPauseServiceNodeFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageTestScoreFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageProveTestScoreFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageStakeAppFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageEditStakeAppFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageUnstakeAppFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessagePauseAppFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageUnpauseAppFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageStakeValidatorFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageEditStakeValidatorFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageUnstakeValidatorFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessagePauseValidatorFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageUnpauseValidatorFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageStakeServiceNodeFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageEditStakeServiceNodeFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageUnstakeServiceNodeFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessagePauseServiceNodeFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageUnpauseServiceNodeFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) + case modules.MessageChangeParameterFeeOwner: + return store.GetBytesParam(modules.AclOwner, height) default: - return nil, types.ErrUnknownParam(paramName) + return nil, typesUtil.ErrUnknownParam(paramName) } } -func (u *UtilityContext) GetFee(msg typesUtil.Message, actorType typesUtil.ActorType) (amount *big.Int, err types.Error) { +func (u *UtilityContext) GetFee(msg typesUtil.Message, actorType typesUtil.UtilActorType) (amount *big.Int, err typesUtil.Error) { switch x := msg.(type) { case *typesUtil.MessageDoubleSign: return u.GetMessageDoubleSignFee() @@ -499,113 +499,113 @@ func (u *UtilityContext) GetFee(msg typesUtil.Message, actorType typesUtil.Actor return u.GetMessageSendFee() case *typesUtil.MessageStake: switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: return u.GetMessageStakeAppFee() - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: return u.GetMessageStakeFishermanFee() - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: return u.GetMessageStakeServiceNodeFee() - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: return u.GetMessageStakeValidatorFee() } case *typesUtil.MessageEditStake: switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: return u.GetMessageEditStakeAppFee() - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: return u.GetMessageEditStakeFishermanFee() - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: return u.GetMessageEditStakeServiceNodeFee() - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: return u.GetMessageEditStakeValidatorFee() } case *typesUtil.MessageUnstake: switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: return u.GetMessageUnstakeAppFee() - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: return u.GetMessageUnstakeFishermanFee() - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: return u.GetMessageUnstakeServiceNodeFee() - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: return u.GetMessageUnstakeValidatorFee() } case *typesUtil.MessageUnpause: switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: return u.GetMessageUnpauseAppFee() - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: return u.GetMessageUnpauseFishermanFee() - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: return u.GetMessageUnpauseServiceNodeFee() - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: return u.GetMessageUnpauseValidatorFee() } case *typesUtil.MessageChangeParameter: return u.GetMessageChangeParameterFee() default: - return nil, types.ErrUnknownMessage(x) + return nil, typesUtil.ErrUnknownMessage(x) } return nil, nil } -func (u *UtilityContext) GetMessageChangeParameterSignerCandidates(msg *typesUtil.MessageChangeParameter) ([][]byte, types.Error) { +func (u *UtilityContext) GetMessageChangeParameterSignerCandidates(msg *typesUtil.MessageChangeParameter) ([][]byte, typesUtil.Error) { owner, err := u.GetParamOwner(msg.ParameterKey) if err != nil { - return nil, types.ErrGetParam(msg.ParameterKey, err) + return nil, typesUtil.ErrGetParam(msg.ParameterKey, err) } return [][]byte{owner}, nil } -func (u *UtilityContext) getBigIntParam(paramName string) (*big.Int, types.Error) { +func (u *UtilityContext) getBigIntParam(paramName string) (*big.Int, typesUtil.Error) { store := u.Store() height, err := store.GetHeight() if err != nil { - return nil, types.ErrGetParam(paramName, err) + return nil, typesUtil.ErrGetParam(paramName, err) } value, err := store.GetStringParam(paramName, height) if err != nil { fmt.Printf("err: %v\n", err) - return nil, types.ErrGetParam(paramName, err) + return nil, typesUtil.ErrGetParam(paramName, err) } - return types.StringToBigInt(value) + return typesUtil.StringToBigInt(value) } -func (u *UtilityContext) getIntParam(paramName string) (int, types.Error) { +func (u *UtilityContext) getIntParam(paramName string) (int, typesUtil.Error) { store := u.Store() height, err := store.GetHeight() if err != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, err) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, err) } value, err := store.GetIntParam(paramName, height) if err != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, err) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, err) } return value, nil } -func (u *UtilityContext) getInt64Param(paramName string) (int64, types.Error) { +func (u *UtilityContext) getInt64Param(paramName string) (int64, typesUtil.Error) { store := u.Store() height, err := store.GetHeight() if err != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, err) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, err) } value, err := store.GetIntParam(paramName, height) if err != nil { - return typesUtil.ZeroInt, types.ErrGetParam(paramName, err) + return typesUtil.ZeroInt, typesUtil.ErrGetParam(paramName, err) } return int64(value), nil } -func (u *UtilityContext) getByteArrayParam(paramName string) ([]byte, types.Error) { +func (u *UtilityContext) getByteArrayParam(paramName string) ([]byte, typesUtil.Error) { store := u.Store() height, err := store.GetHeight() if err != nil { - return nil, types.ErrGetParam(paramName, err) + return nil, typesUtil.ErrGetParam(paramName, err) } value, er := store.GetBytesParam(paramName, height) if er != nil { - return nil, types.ErrGetParam(paramName, er) + return nil, typesUtil.ErrGetParam(paramName, er) } return value, nil } diff --git a/utility/module.go b/utility/module.go index ed3a1288f..9cfc65a96 100644 --- a/utility/module.go +++ b/utility/module.go @@ -3,25 +3,38 @@ package utility import ( "log" + "github.com/pokt-network/pocket/utility/types" + "github.com/pokt-network/pocket/shared/modules" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" ) var _ modules.UtilityModule = &UtilityModule{} +var _ modules.UtilityConfig = &types.UtilityConfig{} type UtilityModule struct { bus modules.Bus Mempool types.Mempool } -func Create(_ *genesis.Config, _ *genesis.GenesisState) (modules.UtilityModule, error) { +const ( + UtilityModuleName = "utility" +) + +func Create(configPath, genesisPath string) (modules.UtilityModule, error) { return &UtilityModule{ // TODO: Add `maxTransactionBytes` and `maxTransactions` to cfg.Utility Mempool: types.NewMempool(1000, 1000), }, nil } +func (u *UtilityModule) InitConfig(pathToConfigJSON string) (config modules.IConfig, err error) { + return // No-op +} + +func (u *UtilityModule) InitGenesis(pathToGenesisJSON string) (genesis modules.IGenesis, err error) { + return // No-op +} + func (u *UtilityModule) Start() error { return nil } @@ -30,6 +43,10 @@ func (u *UtilityModule) Stop() error { return nil } +func (u *UtilityModule) GetModuleName() string { + return UtilityModuleName +} + func (u *UtilityModule) SetBus(bus modules.Bus) { u.bus = bus } diff --git a/utility/proto/actor_types.proto b/utility/proto/actor_types.proto index b0b21fb78..409cd0fc7 100644 --- a/utility/proto/actor_types.proto +++ b/utility/proto/actor_types.proto @@ -3,9 +3,6 @@ package utility; option go_package = "github.com/pokt-network/pocket/utility/types"; -enum ActorType { - App = 0; - Node = 1; - Fish = 2; - Val = 3; - } \ No newline at end of file +message UtilityConfig { + +} \ No newline at end of file diff --git a/utility/proto/vote.proto b/utility/proto/vote.proto deleted file mode 100644 index b66815828..000000000 --- a/utility/proto/vote.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; -package utility; - -option go_package = "github.com/pokt-network/pocket/utility/types"; - -// TECHDEBT: Consolidate this week consensus -message Vote { - bytes public_key = 1; - int64 height = 2; - uint32 round = 3; - uint32 type = 4; - bytes block_hash = 5; -} \ No newline at end of file diff --git a/shared/tests/utility_module/account_test.go b/utility/test/account_test.go similarity index 75% rename from shared/tests/utility_module/account_test.go rename to utility/test/account_test.go index ba86ffd1c..a98736c1b 100644 --- a/shared/tests/utility_module/account_test.go +++ b/utility/test/account_test.go @@ -1,4 +1,4 @@ -package utility_module +package test import ( "bytes" @@ -8,11 +8,11 @@ import ( "sort" "testing" - "github.com/pokt-network/pocket/persistence" + "github.com/pokt-network/pocket/shared/modules" + "github.com/pokt-network/pocket/shared/test_artifacts" + "github.com/pokt-network/pocket/utility/types" + "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/tests" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" "github.com/pokt-network/pocket/utility" "github.com/stretchr/testify/require" ) @@ -24,11 +24,11 @@ func TestUtilityContext_AddAccountAmount(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) acc := GetAllTestingAccounts(t, ctx)[0] - initialAmount, err := types.StringToBigInt(acc.Amount) + initialAmount, err := types.StringToBigInt(acc.GetAmount()) require.NoError(t, err) addAmount := big.NewInt(1) - addrBz, er := hex.DecodeString(acc.Address) + addrBz, er := hex.DecodeString(acc.GetAddress()) require.NoError(t, er) require.NoError(t, ctx.AddAccountAmount(addrBz, addAmount), "add account amount") afterAmount, err := ctx.GetAccountAmount(addrBz) @@ -36,19 +36,19 @@ func TestUtilityContext_AddAccountAmount(t *testing.T) { expected := initialAmount.Add(initialAmount, addAmount) require.True(t, afterAmount.Cmp(expected) == 0, fmt.Sprintf("amounts are not equal, expected %v, got %v", initialAmount, afterAmount)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) // TODO (team) need a golang specific solution for teardown } func TestUtilityContext_AddAccountAmountString(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) acc := GetAllTestingAccounts(t, ctx)[0] - initialAmount, err := types.StringToBigInt(acc.Amount) + initialAmount, err := types.StringToBigInt(acc.GetAmount()) require.NoError(t, err) addAmount := big.NewInt(1) addAmountString := types.BigIntToString(addAmount) - addrBz, er := hex.DecodeString(acc.Address) + addrBz, er := hex.DecodeString(acc.GetAddress()) require.NoError(t, er) require.NoError(t, ctx.AddAccountAmountString(addrBz, addAmountString), "add account amount string") afterAmount, err := ctx.GetAccountAmount(addrBz) @@ -56,24 +56,24 @@ func TestUtilityContext_AddAccountAmountString(t *testing.T) { expected := initialAmount.Add(initialAmount, addAmount) require.True(t, afterAmount.Cmp(expected) == 0, fmt.Sprintf("amounts are not equal, expected %v, got %v", initialAmount, afterAmount)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_AddPoolAmount(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) pool := GetAllTestingPools(t, ctx)[0] - initialAmount, err := types.StringToBigInt(pool.Amount) + initialAmount, err := types.StringToBigInt(pool.GetAmount()) require.NoError(t, err) addAmount := big.NewInt(1) - require.NoError(t, ctx.AddPoolAmount(pool.Address, addAmount), "add pool amount") - afterAmount, err := ctx.GetPoolAmount(pool.Address) + require.NoError(t, ctx.AddPoolAmount(pool.GetAddress(), addAmount), "add pool amount") + afterAmount, err := ctx.GetPoolAmount(pool.GetAddress()) require.NoError(t, err) expected := initialAmount.Add(initialAmount, addAmount) require.Equal(t, afterAmount, expected, "amounts are not equal") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_HandleMessageSend(t *testing.T) { @@ -82,28 +82,28 @@ func TestUtilityContext_HandleMessageSend(t *testing.T) { sendAmount := big.NewInt(1000000) sendAmountString := types.BigIntToString(sendAmount) - senderBalanceBefore, err := types.StringToBigInt(accs[0].Amount) + senderBalanceBefore, err := types.StringToBigInt(accs[0].GetAmount()) require.NoError(t, err) - recipientBalanceBefore, err := types.StringToBigInt(accs[1].Amount) + recipientBalanceBefore, err := types.StringToBigInt(accs[1].GetAmount()) require.NoError(t, err) - addrBz, er := hex.DecodeString(accs[0].Address) + addrBz, er := hex.DecodeString(accs[0].GetAddress()) require.NoError(t, er) - addrBz2, er := hex.DecodeString(accs[1].Address) + addrBz2, er := hex.DecodeString(accs[1].GetAddress()) require.NoError(t, er) msg := NewTestingSendMessage(t, addrBz, addrBz2, sendAmountString) err = ctx.HandleMessageSend(&msg) require.NoError(t, err, "handle message send") accs = GetAllTestingAccounts(t, ctx) - senderBalanceAfter, err := types.StringToBigInt(accs[0].Amount) + senderBalanceAfter, err := types.StringToBigInt(accs[0].GetAmount()) require.NoError(t, err) - recipientBalanceAfter, err := types.StringToBigInt(accs[1].Amount) + recipientBalanceAfter, err := types.StringToBigInt(accs[1].GetAmount()) require.NoError(t, err) require.True(t, big.NewInt(0).Sub(senderBalanceBefore, senderBalanceAfter).Cmp(sendAmount) == 0, fmt.Sprintf("unexpected sender balance")) require.True(t, big.NewInt(0).Sub(recipientBalanceAfter, recipientBalanceBefore).Cmp(sendAmount) == 0, fmt.Sprintf("unexpected recipient balance")) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageSendSignerCandidates(t *testing.T) { @@ -112,16 +112,16 @@ func TestUtilityContext_GetMessageSendSignerCandidates(t *testing.T) { sendAmount := big.NewInt(1000000) sendAmountString := types.BigIntToString(sendAmount) - addrBz, er := hex.DecodeString(accs[0].Address) + addrBz, er := hex.DecodeString(accs[0].GetAddress()) require.NoError(t, er) - addrBz2, er := hex.DecodeString(accs[1].Address) + addrBz2, er := hex.DecodeString(accs[1].GetAddress()) require.NoError(t, er) msg := NewTestingSendMessage(t, addrBz, addrBz2, sendAmountString) candidates, err := ctx.GetMessageSendSignerCandidates(&msg) require.NoError(t, err) require.True(t, len(candidates) == 1, fmt.Sprintf("wrong number of candidates, expected %d, got %d", 1, len(candidates))) require.True(t, bytes.Equal(candidates[0], addrBz), fmt.Sprintf("unexpected signer candidate")) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_InsertPool(t *testing.T) { @@ -139,7 +139,7 @@ func TestUtilityContext_InsertPool(t *testing.T) { gotAmountString := types.BigIntToString(gotAmount) require.True(t, amount == gotAmountString, fmt.Sprintf("unexpected amount, expected %s got %s", amount, gotAmountString)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_SetAccountAmount(t *testing.T) { @@ -153,7 +153,7 @@ func TestUtilityContext_SetAccountAmount(t *testing.T) { gotAmount, err := ctx.GetAccountAmount(addr) require.NoError(t, err) require.True(t, gotAmount.Cmp(amount) == 0, fmt.Sprintf("unexpected amounts: expected %v, got %v", amount, gotAmount)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_SetAccountWithAmountString(t *testing.T) { @@ -168,23 +168,23 @@ func TestUtilityContext_SetAccountWithAmountString(t *testing.T) { gotAmount, err := ctx.GetAccountAmount(addr) require.NoError(t, err) require.True(t, gotAmount.Cmp(amount) == 0, fmt.Sprintf("unexpected amounts: expected %v, got %v", amount, gotAmount)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_SetPoolAmount(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) pool := GetAllTestingPools(t, ctx)[0] - beforeAmount := pool.Amount + beforeAmount := pool.GetAmount() beforeAmountBig, err := types.StringToBigInt(beforeAmount) require.NoError(t, err) expectedAfterAmount := big.NewInt(100) - require.NoError(t, ctx.SetPoolAmount(pool.Address, expectedAfterAmount), "set pool amount") - amount, err := ctx.GetPoolAmount(pool.Address) + require.NoError(t, ctx.SetPoolAmount(pool.GetAddress(), expectedAfterAmount), "set pool amount") + amount, err := ctx.GetPoolAmount(pool.GetAddress()) require.NoError(t, err) require.True(t, beforeAmountBig.Cmp(amount) != 0, fmt.Sprintf("no amount change in pool")) require.True(t, expectedAfterAmount.Cmp(amount) == 0, fmt.Sprintf("unexpected pool amount; expected %v got %v", expectedAfterAmount, amount)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_SubPoolAmount(t *testing.T) { @@ -192,28 +192,28 @@ func TestUtilityContext_SubPoolAmount(t *testing.T) { pool := GetAllTestingPools(t, ctx)[0] beforeAmountBig := big.NewInt(1000000000000000) - ctx.SetPoolAmount(pool.Address, beforeAmountBig) + ctx.SetPoolAmount(pool.GetAddress(), beforeAmountBig) subAmountBig := big.NewInt(100) subAmount := types.BigIntToString(subAmountBig) - require.NoError(t, ctx.SubPoolAmount(pool.Address, subAmount), "sub pool amount") - amount, err := ctx.GetPoolAmount(pool.Address) + require.NoError(t, ctx.SubPoolAmount(pool.GetAddress(), subAmount), "sub pool amount") + amount, err := ctx.GetPoolAmount(pool.GetAddress()) require.NoError(t, err) require.True(t, beforeAmountBig.Cmp(amount) != 0, fmt.Sprintf("no amount change in pool")) expected := beforeAmountBig.Sub(beforeAmountBig, subAmountBig) require.True(t, expected.Cmp(amount) == 0, fmt.Sprintf("unexpected pool amount; expected %v got %v", expected, amount)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_SubtractAccountAmount(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) acc := GetAllTestingAccounts(t, ctx)[0] - beforeAmount := acc.Amount + beforeAmount := acc.GetAmount() beforeAmountBig, err := types.StringToBigInt(beforeAmount) require.NoError(t, err) subAmountBig := big.NewInt(100) - addrBz, er := hex.DecodeString(acc.Address) + addrBz, er := hex.DecodeString(acc.GetAddress()) require.NoError(t, er) require.NoError(t, ctx.SubtractAccountAmount(addrBz, subAmountBig), "sub account amount") amount, err := ctx.GetAccountAmount(addrBz) @@ -221,23 +221,23 @@ func TestUtilityContext_SubtractAccountAmount(t *testing.T) { require.True(t, beforeAmountBig.Cmp(amount) != 0, fmt.Sprintf("no amount change in pool")) expected := beforeAmountBig.Sub(beforeAmountBig, subAmountBig) require.True(t, expected.Cmp(amount) == 0, fmt.Sprintf("unexpected acc amount; expected %v got %v", expected, amount)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } -func GetAllTestingAccounts(t *testing.T, ctx utility.UtilityContext) []*genesis.Account { - accs, err := (ctx.Context.PersistenceRWContext).(persistence.PostgresContext).GetAllAccounts(0) +func GetAllTestingAccounts(t *testing.T, ctx utility.UtilityContext) []modules.Account { + accs, err := (ctx.Context.PersistenceRWContext).GetAllAccounts(0) + require.NoError(t, err) sort.Slice(accs, func(i, j int) bool { - return accs[i].Address < accs[j].Address + return accs[i].GetAddress() < accs[j].GetAddress() }) - require.NoError(t, err) return accs } -func GetAllTestingPools(t *testing.T, ctx utility.UtilityContext) []*genesis.Account { - accs, err := (ctx.Context.PersistenceRWContext).(persistence.PostgresContext).GetAllPools(0) +func GetAllTestingPools(t *testing.T, ctx utility.UtilityContext) []modules.Account { + accs, err := (ctx.Context.PersistenceRWContext).GetAllPools(0) + require.NoError(t, err) sort.Slice(accs, func(i, j int) bool { - return accs[i].Address < accs[j].Address + return accs[i].GetAddress() < accs[j].GetAddress() }) - require.NoError(t, err) return accs } diff --git a/shared/tests/utility_module/actor_test.go b/utility/test/actor_test.go similarity index 72% rename from shared/tests/utility_module/actor_test.go rename to utility/test/actor_test.go index eabc1a47b..eece20852 100644 --- a/shared/tests/utility_module/actor_test.go +++ b/utility/test/actor_test.go @@ -1,19 +1,16 @@ -package utility_module +package test import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/shared/modules" + "github.com/pokt-network/pocket/shared/test_artifacts" "math" "math/big" "sort" "testing" - "github.com/pokt-network/pocket/persistence" "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/tests" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" "github.com/pokt-network/pocket/utility" typesUtil "github.com/pokt-network/pocket/utility/types" "github.com/stretchr/testify/require" @@ -52,14 +49,14 @@ func TestUtilityContext_HandleMessageStake(t *testing.T) { actor := GetActorByAddr(t, ctx, pubKey.Address().Bytes(), actorType) require.Equal(t, actor.GetAddress(), pubKey.Address().String(), "incorrect actor address") - if actorType != typesUtil.ActorType_Val { + if actorType != typesUtil.UtilActorType_Val { require.Equal(t, actor.GetChains(), msg.Chains, "incorrect actor chains") } - require.Equal(t, actor.GetPausedHeight(), types.HeightNotUsed, "incorrect actor height") + require.Equal(t, actor.GetPausedHeight(), typesUtil.HeightNotUsed, "incorrect actor height") require.Equal(t, actor.GetStakedAmount(), test_artifacts.DefaultStakeAmountString, "incorrect actor stake amount") - require.Equal(t, actor.GetUnstakingHeight(), types.HeightNotUsed, "incorrect actor unstaking height") + require.Equal(t, actor.GetUnstakingHeight(), typesUtil.HeightNotUsed, "incorrect actor unstaking height") require.Equal(t, actor.GetOutput(), outputAddress.String(), "incorrect actor output address") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -86,14 +83,14 @@ func TestUtilityContext_HandleMessageEditStake(t *testing.T) { require.NoError(t, err, "handle edit stake message") actor = GetActorByAddr(t, ctx, addrBz, actorType) - if actorType != typesUtil.ActorType_Val { + if actorType != typesUtil.UtilActorType_Val { require.Equal(t, actor.GetChains(), msgChainsEdited.Chains, "incorrect edited chains") } require.Equal(t, actor.GetStakedAmount(), test_artifacts.DefaultStakeAmountString, "incorrect staked tokens") - require.Equal(t, actor.GetUnstakingHeight(), types.HeightNotUsed, "incorrect unstaking height") + require.Equal(t, actor.GetUnstakingHeight(), typesUtil.HeightNotUsed, "incorrect unstaking height") amountEdited := test_artifacts.DefaultAccountAmount.Add(test_artifacts.DefaultAccountAmount, big.NewInt(1)) - amountEditedString := types.BigIntToString(amountEdited) + amountEditedString := typesUtil.BigIntToString(amountEdited) msgAmountEdited := proto.Clone(msg).(*typesUtil.MessageEditStake) msgAmountEdited.Amount = amountEditedString @@ -101,7 +98,7 @@ func TestUtilityContext_HandleMessageEditStake(t *testing.T) { require.NoError(t, err, "handle edit stake message") actor = GetActorByAddr(t, ctx, addrBz, actorType) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -113,14 +110,14 @@ func TestUtilityContext_HandleMessageUnpause(t *testing.T) { ctx := NewTestingUtilityContext(t, 1) var err error switch actorType { - case typesUtil.ActorType_Val: - err = ctx.Context.SetParam(types.ValidatorMinimumPauseBlocksParamName, 0) - case typesUtil.ActorType_Node: - err = ctx.Context.SetParam(types.ServiceNodeMinimumPauseBlocksParamName, 0) - case typesUtil.ActorType_App: - err = ctx.Context.SetParam(types.AppMinimumPauseBlocksParamName, 0) - case typesUtil.ActorType_Fish: - err = ctx.Context.SetParam(types.FishermanMinimumPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Val: + err = ctx.Context.SetParam(modules.ValidatorMinimumPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Node: + err = ctx.Context.SetParam(modules.ServiceNodeMinimumPauseBlocksParamName, 0) + case typesUtil.UtilActorType_App: + err = ctx.Context.SetParam(modules.AppMinimumPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Fish: + err = ctx.Context.SetParam(modules.FishermanMinimumPauseBlocksParamName, 0) default: t.Fatalf("unexpected actor type %s", actorType.GetActorName()) } @@ -145,8 +142,8 @@ func TestUtilityContext_HandleMessageUnpause(t *testing.T) { require.NoError(t, err, "handle unpause message") actor = GetActorByAddr(t, ctx, addrBz, actorType) - require.Equal(t, actor.PausedHeight, int64(-1)) - tests.CleanupTest(ctx) + require.Equal(t, actor.GetPausedHeight(), int64(-1)) + test_artifacts.CleanupTest(ctx) }) } } @@ -157,14 +154,14 @@ func TestUtilityContext_HandleMessageUnstake(t *testing.T) { ctx := NewTestingUtilityContext(t, 1) var err error switch actorType { - case typesUtil.ActorType_App: - err = ctx.Context.SetParam(types.AppMinimumPauseBlocksParamName, 0) - case typesUtil.ActorType_Val: - err = ctx.Context.SetParam(types.ValidatorMinimumPauseBlocksParamName, 0) - case typesUtil.ActorType_Fish: - err = ctx.Context.SetParam(types.FishermanMinimumPauseBlocksParamName, 0) - case typesUtil.ActorType_Node: - err = ctx.Context.SetParam(types.ServiceNodeMinimumPauseBlocksParamName, 0) + case typesUtil.UtilActorType_App: + err = ctx.Context.SetParam(modules.AppMinimumPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Val: + err = ctx.Context.SetParam(modules.ValidatorMinimumPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Fish: + err = ctx.Context.SetParam(modules.FishermanMinimumPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Node: + err = ctx.Context.SetParam(modules.ServiceNodeMinimumPauseBlocksParamName, 0) default: t.Fatalf("unexpected actor type %s", actorType.GetActorName()) } @@ -183,8 +180,8 @@ func TestUtilityContext_HandleMessageUnstake(t *testing.T) { require.NoError(t, err, "handle unstake message") actor = GetActorByAddr(t, ctx, addrBz, actorType) - require.Equal(t, actor.UnstakingHeight, defaultUnstaking, "actor should be unstaking") - tests.CleanupTest(ctx) + require.Equal(t, actor.GetUnstakingHeight(), defaultUnstaking, "actor should be unstaking") + test_artifacts.CleanupTest(ctx) }) } } @@ -198,14 +195,14 @@ func TestUtilityContext_BeginUnstakingMaxPaused(t *testing.T) { addrBz, err := hex.DecodeString(actor.GetAddress()) require.NoError(t, err) switch actorType { - case typesUtil.ActorType_App: - err = ctx.Context.SetParam(types.AppMaxPauseBlocksParamName, 0) - case typesUtil.ActorType_Val: - err = ctx.Context.SetParam(types.ValidatorMaxPausedBlocksParamName, 0) - case typesUtil.ActorType_Fish: - err = ctx.Context.SetParam(types.FishermanMaxPauseBlocksParamName, 0) - case typesUtil.ActorType_Node: - err = ctx.Context.SetParam(types.ServiceNodeMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_App: + err = ctx.Context.SetParam(modules.AppMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Val: + err = ctx.Context.SetParam(modules.ValidatorMaxPausedBlocksParamName, 0) + case typesUtil.UtilActorType_Fish: + err = ctx.Context.SetParam(modules.FishermanMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Node: + err = ctx.Context.SetParam(modules.ServiceNodeMaxPauseBlocksParamName, 0) default: t.Fatalf("unexpected actor type %s", actorType.GetActorName()) } @@ -219,7 +216,7 @@ func TestUtilityContext_BeginUnstakingMaxPaused(t *testing.T) { status, err := ctx.GetActorStatus(actorType, addrBz) require.Equal(t, status, typesUtil.UnstakingStatus, "actor should be unstaking") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -227,10 +224,10 @@ func TestUtilityContext_BeginUnstakingMaxPaused(t *testing.T) { func TestUtilityContext_CalculateRelays(t *testing.T) { ctx := NewTestingUtilityContext(t, 1) actor := GetAllTestingApps(t, ctx)[0] - newMaxRelays, err := ctx.CalculateAppRelays(actor.StakedAmount) + newMaxRelays, err := ctx.CalculateAppRelays(actor.GetStakedAmount()) require.NoError(t, err) - require.True(t, actor.GenericParam == newMaxRelays, fmt.Sprintf("unexpected max relay calculation; got %v wanted %v", actor.GenericParam, newMaxRelays)) - tests.CleanupTest(ctx) + require.True(t, actor.GetGenericParam() == newMaxRelays, fmt.Sprintf("unexpected max relay calculation; got %v wanted %v", actor.GetGenericParam(), newMaxRelays)) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_CalculateUnstakingHeight(t *testing.T) { @@ -240,13 +237,13 @@ func TestUtilityContext_CalculateUnstakingHeight(t *testing.T) { var unstakingBlocks int64 var err error switch actorType { - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: unstakingBlocks, err = ctx.GetValidatorUnstakingBlocks() - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: unstakingBlocks, err = ctx.GetServiceNodeUnstakingBlocks() case actorType: unstakingBlocks, err = ctx.GetAppUnstakingBlocks() - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: unstakingBlocks, err = ctx.GetFishermanUnstakingBlocks() default: t.Fatalf("unexpected actor type %s", actorType.GetActorName()) @@ -257,7 +254,7 @@ func TestUtilityContext_CalculateUnstakingHeight(t *testing.T) { require.NoError(t, err) require.Equal(t, unstakingBlocks, unstakingHeight, "unexpected unstaking height") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -275,7 +272,7 @@ func TestUtilityContext_Delete(t *testing.T) { actor = GetActorByAddr(t, ctx, addrBz, actorType) // TODO Delete actor is currently a NO-OP. We need to better define - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -297,7 +294,7 @@ func TestUtilityContext_GetExists(t *testing.T) { exists, err = ctx.GetActorExists(actorType, randAddr) require.NoError(t, err) require.False(t, exists, "actor that shouldn't exist does") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -314,7 +311,7 @@ func TestUtilityContext_GetOutputAddress(t *testing.T) { require.NoError(t, err) require.Equal(t, hex.EncodeToString(outputAddress), actor.GetOutput(), "unexpected output address") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -340,7 +337,7 @@ func TestUtilityContext_GetPauseHeightIfExists(t *testing.T) { _, err = ctx.GetPauseHeight(actorType, randAddr) require.Error(t, err, "non existent actor should error") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -365,7 +362,7 @@ func TestUtilityContext_GetMessageEditStakeSignerCandidates(t *testing.T) { require.Equal(t, len(candidates), 2, "unexpected number of candidates") require.Equal(t, hex.EncodeToString(candidates[0]), actor.GetOutput(), "incorrect output candidate") require.Equal(t, hex.EncodeToString(candidates[1]), actor.GetAddress(), "incorrect addr candidate") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -375,39 +372,39 @@ func TestUtilityContext_UnstakesPausedBefore(t *testing.T) { actor := GetAllTestingApps(t, ctx)[0] addrBz, err := hex.DecodeString(actor.GetAddress()) require.NoError(t, err) - require.True(t, actor.UnstakingHeight == -1, fmt.Sprintf("wrong starting status")) - require.NoError(t, ctx.SetActorPauseHeight(typesUtil.ActorType_App, addrBz, 0), "set actor pause height") - err = ctx.Context.SetParam(types.AppMaxPauseBlocksParamName, 0) + require.True(t, actor.GetUnstakingHeight() == -1, fmt.Sprintf("wrong starting status")) + require.NoError(t, ctx.SetActorPauseHeight(typesUtil.UtilActorType_App, addrBz, 0), "set actor pause height") + err = ctx.Context.SetParam(modules.AppMaxPauseBlocksParamName, 0) require.NoError(t, err) - require.NoError(t, ctx.UnstakeActorPausedBefore(0, typesUtil.ActorType_App), "unstake actor pause before") - require.NoError(t, ctx.UnstakeActorPausedBefore(1, typesUtil.ActorType_App), "unstake actor pause before height 1") + require.NoError(t, ctx.UnstakeActorPausedBefore(0, typesUtil.UtilActorType_App), "unstake actor pause before") + require.NoError(t, ctx.UnstakeActorPausedBefore(1, typesUtil.UtilActorType_App), "unstake actor pause before height 1") actor = GetAllTestingApps(t, ctx)[0] - require.True(t, actor.UnstakingHeight != -1, fmt.Sprintf("status does not equal unstaking")) + require.True(t, actor.GetUnstakingHeight() != -1, fmt.Sprintf("status does not equal unstaking")) unstakingBlocks, err := ctx.GetAppUnstakingBlocks() require.NoError(t, err) - require.True(t, actor.UnstakingHeight == unstakingBlocks+1, fmt.Sprintf("incorrect unstaking height")) - tests.CleanupTest(ctx) + require.True(t, actor.GetUnstakingHeight() == unstakingBlocks+1, fmt.Sprintf("incorrect unstaking height")) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_UnstakesThatAreReady(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) - ctx.SetPoolAmount(genesis.Pool_Names_AppStakePool.String(), big.NewInt(math.MaxInt64)) - err := ctx.Context.SetParam(types.AppUnstakingBlocksParamName, 0) + ctx.SetPoolAmount("AppStakePool", big.NewInt(math.MaxInt64)) + err := ctx.Context.SetParam(modules.AppUnstakingBlocksParamName, 0) require.NoError(t, err) actors := GetAllTestingApps(t, ctx) for _, actor := range actors { addrBz, err := hex.DecodeString(actor.GetAddress()) require.NoError(t, err) - require.True(t, actor.UnstakingHeight == -1, fmt.Sprintf("wrong starting status")) - require.NoError(t, ctx.SetActorPauseHeight(typesUtil.ActorType_App, addrBz, 1), "set actor pause height") + require.True(t, actor.GetUnstakingHeight() == -1, fmt.Sprintf("wrong starting status")) + require.NoError(t, ctx.SetActorPauseHeight(typesUtil.UtilActorType_App, addrBz, 1), "set actor pause height") } - require.NoError(t, ctx.UnstakeActorPausedBefore(2, typesUtil.ActorType_App), "set actor pause before") + require.NoError(t, ctx.UnstakeActorPausedBefore(2, typesUtil.UtilActorType_App), "set actor pause before") require.NoError(t, ctx.UnstakeActorsThatAreReady(), "unstake actors that are ready") appAfter := GetAllTestingApps(t, ctx)[0] - require.True(t, appAfter.UnstakingHeight == 0, fmt.Sprintf("apps still exists after unstake that are ready() call")) + require.True(t, appAfter.GetUnstakingHeight() == 0, fmt.Sprintf("apps still exists after unstake that are ready() call")) // TODO (Team) we need to better define what 'deleted' really is in the postgres world. // We might not need to 'unstakeActorsThatAreReady' if we are already filtering by unstakingHeight - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnpauseSignerCandidates(t *testing.T) { @@ -428,7 +425,7 @@ func TestUtilityContext_GetMessageUnpauseSignerCandidates(t *testing.T) { require.Equal(t, len(candidates), 2, "unexpected number of candidates") require.Equal(t, hex.EncodeToString(candidates[0]), actor.GetOutput(), "incorrect output candidate") require.Equal(t, hex.EncodeToString(candidates[1]), actor.GetAddress(), "incorrect addr candidate") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -450,7 +447,7 @@ func TestUtilityContext_GetMessageUnstakeSignerCandidates(t *testing.T) { require.Equal(t, len(candidates), 2, "unexpected number of candidates") require.Equal(t, hex.EncodeToString(candidates[0]), actor.GetOutput(), "incorrect output candidate") require.Equal(t, hex.EncodeToString(candidates[1]), actor.GetAddress(), "incorrect addr candidate") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -461,7 +458,7 @@ func TestUtilityContext_UnstakePausedBefore(t *testing.T) { ctx := NewTestingUtilityContext(t, 1) actor := GetFirstActor(t, ctx, actorType) - require.Equal(t, actor.UnstakingHeight, int64(-1), "wrong starting status") + require.Equal(t, actor.GetUnstakingHeight(), int64(-1), "wrong starting status") addrBz, err := hex.DecodeString(actor.GetAddress()) require.NoError(t, err) err = ctx.SetActorPauseHeight(actorType, addrBz, 0) @@ -469,14 +466,14 @@ func TestUtilityContext_UnstakePausedBefore(t *testing.T) { var er error switch actorType { - case typesUtil.ActorType_App: - er = ctx.Context.SetParam(types.AppMaxPauseBlocksParamName, 0) - case typesUtil.ActorType_Val: - er = ctx.Context.SetParam(types.ValidatorMaxPausedBlocksParamName, 0) - case typesUtil.ActorType_Fish: - er = ctx.Context.SetParam(types.FishermanMaxPauseBlocksParamName, 0) - case typesUtil.ActorType_Node: - er = ctx.Context.SetParam(types.ServiceNodeMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_App: + er = ctx.Context.SetParam(modules.AppMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Val: + er = ctx.Context.SetParam(modules.ValidatorMaxPausedBlocksParamName, 0) + case typesUtil.UtilActorType_Fish: + er = ctx.Context.SetParam(modules.FishermanMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Node: + er = ctx.Context.SetParam(modules.ServiceNodeMaxPauseBlocksParamName, 0) default: t.Fatalf("unexpected actor type %s", actorType.GetActorName()) } @@ -489,24 +486,24 @@ func TestUtilityContext_UnstakePausedBefore(t *testing.T) { require.NoError(t, err, "error unstaking actor pause before height 1") actor = GetActorByAddr(t, ctx, addrBz, actorType) - require.Equal(t, actor.UnstakingHeight, defaultUnstaking, "status does not equal unstaking") + require.Equal(t, actor.GetUnstakingHeight(), defaultUnstaking, "status does not equal unstaking") var unstakingBlocks int64 switch actorType { - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: unstakingBlocks, err = ctx.GetValidatorUnstakingBlocks() - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: unstakingBlocks, err = ctx.GetServiceNodeUnstakingBlocks() case actorType: unstakingBlocks, err = ctx.GetAppUnstakingBlocks() - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: unstakingBlocks, err = ctx.GetFishermanUnstakingBlocks() default: t.Fatalf("unexpected actor type %s", actorType.GetActorName()) } require.NoError(t, err, "error getting unstaking blocks") require.Equal(t, actor.GetUnstakingHeight(), unstakingBlocks+1, "incorrect unstaking height") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) }) } } @@ -518,18 +515,18 @@ func TestUtilityContext_UnstakeActorsThatAreReady(t *testing.T) { poolName := actorType.GetActorPoolName() var err1, err2 error switch actorType { - case typesUtil.ActorType_App: - err1 = ctx.Context.SetParam(types.AppUnstakingBlocksParamName, 0) - err2 = ctx.Context.SetParam(types.AppMaxPauseBlocksParamName, 0) - case typesUtil.ActorType_Val: - err1 = ctx.Context.SetParam(types.ValidatorUnstakingBlocksParamName, 0) - err2 = ctx.Context.SetParam(types.ValidatorMaxPausedBlocksParamName, 0) - case typesUtil.ActorType_Fish: - err1 = ctx.Context.SetParam(types.FishermanUnstakingBlocksParamName, 0) - err2 = ctx.Context.SetParam(types.FishermanMaxPauseBlocksParamName, 0) - case typesUtil.ActorType_Node: - err1 = ctx.Context.SetParam(types.ServiceNodeUnstakingBlocksParamName, 0) - err2 = ctx.Context.SetParam(types.ServiceNodeMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_App: + err1 = ctx.Context.SetParam(modules.AppUnstakingBlocksParamName, 0) + err2 = ctx.Context.SetParam(modules.AppMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Val: + err1 = ctx.Context.SetParam(modules.ValidatorUnstakingBlocksParamName, 0) + err2 = ctx.Context.SetParam(modules.ValidatorMaxPausedBlocksParamName, 0) + case typesUtil.UtilActorType_Fish: + err1 = ctx.Context.SetParam(modules.FishermanUnstakingBlocksParamName, 0) + err2 = ctx.Context.SetParam(modules.FishermanMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Node: + err1 = ctx.Context.SetParam(modules.ServiceNodeUnstakingBlocksParamName, 0) + err2 = ctx.Context.SetParam(modules.ServiceNodeMaxPauseBlocksParamName, 0) default: t.Fatalf("unexpected actor type %s", actorType.GetActorName()) } @@ -542,7 +539,7 @@ func TestUtilityContext_UnstakeActorsThatAreReady(t *testing.T) { for _, actor := range actors { addrBz, err := hex.DecodeString(actor.GetAddress()) require.NoError(t, err) - require.Equal(t, actor.UnstakingHeight, int64(-1), "wrong starting staked status") + require.Equal(t, actor.GetUnstakingHeight(), int64(-1), "wrong starting staked status") err = ctx.SetActorPauseHeight(actorType, addrBz, 1) require.NoError(t, err, "error setting actor pause height") } @@ -553,31 +550,31 @@ func TestUtilityContext_UnstakeActorsThatAreReady(t *testing.T) { err = ctx.UnstakeActorsThatAreReady() require.NoError(t, err, "error unstaking actors that are ready") // TODO Delete() is no op - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } } // Helpers -func GetAllTestingActors(t *testing.T, ctx utility.UtilityContext, actorType typesUtil.ActorType) (actors []*genesis.Actor) { - actors = make([]*genesis.Actor, 0) +func GetAllTestingActors(t *testing.T, ctx utility.UtilityContext, actorType typesUtil.UtilActorType) (actors []modules.Actor) { + actors = make([]modules.Actor, 0) switch actorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: apps := GetAllTestingApps(t, ctx) for _, a := range apps { actors = append(actors, a) } - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: nodes := GetAllTestingNodes(t, ctx) for _, a := range nodes { actors = append(actors, a) } - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: vals := GetAllTestingValidators(t, ctx) for _, a := range vals { actors = append(actors, a) } - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: fish := GetAllTestingFish(t, ctx) for _, a := range fish { actors = append(actors, a) @@ -589,11 +586,11 @@ func GetAllTestingActors(t *testing.T, ctx utility.UtilityContext, actorType typ return } -func GetFirstActor(t *testing.T, ctx utility.UtilityContext, actorType typesUtil.ActorType) *genesis.Actor { +func GetFirstActor(t *testing.T, ctx utility.UtilityContext, actorType typesUtil.UtilActorType) modules.Actor { return GetAllTestingActors(t, ctx, actorType)[0] } -func GetActorByAddr(t *testing.T, ctx utility.UtilityContext, addr []byte, actorType typesUtil.ActorType) (actor *genesis.Actor) { +func GetActorByAddr(t *testing.T, ctx utility.UtilityContext, addr []byte, actorType typesUtil.UtilActorType) (actor modules.Actor) { actors := GetAllTestingActors(t, ctx, actorType) for _, a := range actors { if a.GetAddress() == hex.EncodeToString(addr) { @@ -603,29 +600,29 @@ func GetActorByAddr(t *testing.T, ctx utility.UtilityContext, addr []byte, actor return } -func GetAllTestingApps(t *testing.T, ctx utility.UtilityContext) []*genesis.Actor { - actors, err := (ctx.Context.PersistenceRWContext).(persistence.PostgresContext).GetAllApps(ctx.LatestHeight) +func GetAllTestingApps(t *testing.T, ctx utility.UtilityContext) []modules.Actor { + actors, err := (ctx.Context.PersistenceRWContext).GetAllApps(ctx.LatestHeight) require.NoError(t, err) return actors } -func GetAllTestingValidators(t *testing.T, ctx utility.UtilityContext) []*genesis.Actor { - actors, err := (ctx.Context.PersistenceRWContext).(persistence.PostgresContext).GetAllValidators(ctx.LatestHeight) +func GetAllTestingValidators(t *testing.T, ctx utility.UtilityContext) []modules.Actor { + actors, err := (ctx.Context.PersistenceRWContext).GetAllValidators(ctx.LatestHeight) require.NoError(t, err) sort.Slice(actors, func(i, j int) bool { - return actors[i].Address < actors[j].Address + return actors[i].GetAddress() < actors[j].GetAddress() }) return actors } -func GetAllTestingFish(t *testing.T, ctx utility.UtilityContext) []*genesis.Actor { - actors, err := (ctx.Context.PersistenceRWContext).(persistence.PostgresContext).GetAllFishermen(ctx.LatestHeight) +func GetAllTestingFish(t *testing.T, ctx utility.UtilityContext) []modules.Actor { + actors, err := (ctx.Context.PersistenceRWContext).GetAllFishermen(ctx.LatestHeight) require.NoError(t, err) return actors } -func GetAllTestingNodes(t *testing.T, ctx utility.UtilityContext) []*genesis.Actor { - actors, err := (ctx.Context.PersistenceRWContext).(persistence.PostgresContext).GetAllServiceNodes(ctx.LatestHeight) +func GetAllTestingNodes(t *testing.T, ctx utility.UtilityContext) []modules.Actor { + actors, err := (ctx.Context.PersistenceRWContext).GetAllServiceNodes(ctx.LatestHeight) require.NoError(t, err) return actors } diff --git a/shared/tests/utility_module/block_test.go b/utility/test/block_test.go similarity index 86% rename from shared/tests/utility_module/block_test.go rename to utility/test/block_test.go index a294be62a..c1441e405 100644 --- a/shared/tests/utility_module/block_test.go +++ b/utility/test/block_test.go @@ -1,14 +1,14 @@ -package utility_module +package test import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/shared/modules" + "github.com/pokt-network/pocket/shared/test_artifacts" "math" "math/big" "testing" - "github.com/pokt-network/pocket/shared/tests" - "github.com/pokt-network/pocket/shared/types" typesUtil "github.com/pokt-network/pocket/utility/types" "github.com/stretchr/testify/require" ) @@ -64,7 +64,7 @@ func TestUtilityContext_ApplyBlock(t *testing.T) { proposerBalanceDifference := big.NewInt(0).Sub(proposerAfterBalance, proposerBeforeBalance) require.Equal(t, expectedProposerBalanceDifference, proposerBalanceDifference, "unexpected before / after balance difference") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_BeginBlock(t *testing.T) { @@ -77,10 +77,10 @@ func TestUtilityContext_BeginBlock(t *testing.T) { txBz, err := tx.Bytes() require.NoError(t, err) - addrBz, er := hex.DecodeString(proposer.Address) + addrBz, er := hex.DecodeString(proposer.GetAddress()) require.NoError(t, er) - byzantineBz, er := hex.DecodeString(byzantine.Address) + byzantineBz, er := hex.DecodeString(byzantine.GetAddress()) require.NoError(t, er) // apply block @@ -94,7 +94,7 @@ func TestUtilityContext_BeginBlock(t *testing.T) { // require.NoError(t, err) // require.False(t, missed != 1, fmt.Sprintf("wrong missed blocks amount; expected %v got %v", 1, byzantine.MissedBlocks)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_BeginUnstakingMaxPausedActors(t *testing.T) { @@ -104,14 +104,14 @@ func TestUtilityContext_BeginUnstakingMaxPausedActors(t *testing.T) { var err error switch actorType { - case typesUtil.ActorType_App: - err = ctx.Context.SetParam(types.AppMaxPauseBlocksParamName, 0) - case typesUtil.ActorType_Val: - err = ctx.Context.SetParam(types.ValidatorMaxPausedBlocksParamName, 0) - case typesUtil.ActorType_Fish: - err = ctx.Context.SetParam(types.FishermanMaxPauseBlocksParamName, 0) - case typesUtil.ActorType_Node: - err = ctx.Context.SetParam(types.ServiceNodeMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_App: + err = ctx.Context.SetParam(modules.AppMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Val: + err = ctx.Context.SetParam(modules.ValidatorMaxPausedBlocksParamName, 0) + case typesUtil.UtilActorType_Fish: + err = ctx.Context.SetParam(modules.FishermanMaxPauseBlocksParamName, 0) + case typesUtil.UtilActorType_Node: + err = ctx.Context.SetParam(modules.ServiceNodeMaxPauseBlocksParamName, 0) default: t.Fatalf("unexpected actor type %s", actorType.GetActorName()) } @@ -127,7 +127,7 @@ func TestUtilityContext_BeginUnstakingMaxPausedActors(t *testing.T) { status, err := ctx.GetActorStatus(actorType, addrBz) require.Equal(t, typesUtil.UnstakingStatus, status, "incorrect status") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } } @@ -169,7 +169,7 @@ func TestUtilityContext_EndBlock(t *testing.T) { proposerBalanceDifference := big.NewInt(0).Sub(proposerAfterBalance, proposerBeforeBalance) require.False(t, proposerBalanceDifference.Cmp(expectedProposerBalanceDifference) != 0, fmt.Sprintf("unexpected before / after balance difference: expected %v got %v", expectedProposerBalanceDifference, proposerBalanceDifference)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetAppHash(t *testing.T) { @@ -182,7 +182,7 @@ func TestUtilityContext_GetAppHash(t *testing.T) { require.NoError(t, er) require.Equal(t, appHashSource, appHashTest, "unexpected appHash") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_UnstakeValidatorsActorsThatAreReady(t *testing.T) { @@ -191,14 +191,15 @@ func TestUtilityContext_UnstakeValidatorsActorsThatAreReady(t *testing.T) { poolName := actorType.GetActorPoolName() ctx.SetPoolAmount(poolName, big.NewInt(math.MaxInt64)) - err := ctx.Context.SetParam(types.AppUnstakingBlocksParamName, 0) + err := ctx.Context.SetParam(modules.AppUnstakingBlocksParamName, 0) require.NoError(t, err) - err = ctx.Context.SetParam(types.AppMaxPauseBlocksParamName, 0) + err = ctx.Context.SetParam(modules.AppMaxPauseBlocksParamName, 0) require.NoError(t, err) actors := GetAllTestingActors(t, ctx, actorType) for _, actor := range actors { + // require.Equal(t, int32(typesUtil.StakedStatus), actor.GetStatus(), "wrong starting status") addrBz, er := hex.DecodeString(actor.GetAddress()) require.NoError(t, er) er = ctx.SetActorPauseHeight(actorType, addrBz, 1) @@ -217,6 +218,6 @@ func TestUtilityContext_UnstakeValidatorsActorsThatAreReady(t *testing.T) { // TODO: We need to better define what 'deleted' really is in the postgres world. // We might not need to 'unstakeActorsThatAreReady' if we are already filtering by unstakingHeight - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } } diff --git a/shared/tests/utility_module/gov_test.go b/utility/test/gov_test.go similarity index 59% rename from shared/tests/utility_module/gov_test.go rename to utility/test/gov_test.go index 8d336dc9a..2dcb852fc 100644 --- a/shared/tests/utility_module/gov_test.go +++ b/utility/test/gov_test.go @@ -1,22 +1,24 @@ -package utility_module +package test import ( "encoding/hex" "fmt" + "github.com/pokt-network/pocket/shared/codec" + "github.com/pokt-network/pocket/shared/modules" + "github.com/pokt-network/pocket/shared/test_artifacts" "testing" - "github.com/pokt-network/pocket/shared/tests" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" typesUtil "github.com/pokt-network/pocket/utility/types" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/wrapperspb" ) // TODO(andrew): Remove the use of `require.True` and `require.False` in all cases. +// TODO(andrew): Use require.Equal and avoid the use of formatted strings. Ditto elsewhere. +// TODO(andrew): Use reflection to iterate over all the params and test them. Suggestion: [Google's go-cmp] (https://github.com/google/go-cmp) +// CLEANUP: cleanup this file as part of https://github.com/pokt-network/pocket/issues/76 -func DefaultTestingParams(_ *testing.T) *genesis.Params { +func DefaultTestingParams(_ *testing.T) modules.Params { return test_artifacts.DefaultParams() } @@ -25,10 +27,9 @@ func TestUtilityContext_GetAppMaxChains(t *testing.T) { defaultParams := DefaultTestingParams(t) maxChains, err := ctx.GetAppMaxChains() require.NoError(t, err) - // TODO(andrew): Use require.Equal and avoid the use of formatted strings. Ditto elsewhere. - require.False(t, int(defaultParams.AppMaxChains) != maxChains, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParams.AppMaxChains, maxChains)) + require.False(t, int(defaultParams.GetAppMaxChains()) != maxChains, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParams.GetAppMaxChains(), maxChains)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetAppMaxPausedBlocks(t *testing.T) { @@ -36,81 +37,81 @@ func TestUtilityContext_GetAppMaxPausedBlocks(t *testing.T) { defaultParams := DefaultTestingParams(t) gotParam, err := ctx.GetAppMaxPausedBlocks() require.NoError(t, err) - require.False(t, int(defaultParams.AppMaxPauseBlocks) != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParams.AppMaxPausedBlocksOwner, gotParam)) + require.False(t, int(defaultParams.GetAppMaxPauseBlocks()) != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParams.GetAppMaxPausedBlocksOwner(), gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetAppMinimumPauseBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.AppMinimumPauseBlocks) + defaultParam := int(defaultParams.GetAppMinimumPauseBlocks()) gotParam, err := ctx.GetAppMinimumPauseBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetAppMinimumStake(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.AppMinimumStake + defaultParam := defaultParams.GetAppMinimumStake() gotParam, err := ctx.GetAppMinimumStake() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetAppUnstakingBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int64(defaultParams.AppUnstakingBlocks) + defaultParam := int64(defaultParams.GetAppUnstakingBlocks()) gotParam, err := ctx.GetAppUnstakingBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetBaselineAppStakeRate(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.AppBaselineStakeRate) + defaultParam := int(defaultParams.GetAppBaselineStakeRate()) gotParam, err := ctx.GetBaselineAppStakeRate() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetBlocksPerSession(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.BlocksPerSession) + defaultParam := int(defaultParams.GetBlocksPerSession()) gotParam, err := ctx.GetBlocksPerSession() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetDoubleSignBurnPercentage(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.DoubleSignBurnPercentage) + defaultParam := int(defaultParams.GetDoubleSignBurnPercentage()) gotParam, err := ctx.GetDoubleSignBurnPercentage() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetDoubleSignFeeOwner(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageDoubleSignFeeOwner + defaultParam := defaultParams.GetMessageDoubleSignFeeOwner() gotParam, err := ctx.GetDoubleSignFeeOwner() require.NoError(t, err) @@ -119,84 +120,84 @@ func TestUtilityContext_GetDoubleSignFeeOwner(t *testing.T) { require.Equal(t, defaultParamTx, gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetFishermanMaxChains(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.FishermanMaxChains) + defaultParam := int(defaultParams.GetFishermanMaxChains()) gotParam, err := ctx.GetFishermanMaxChains() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetFishermanMaxPausedBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.FishermanMaxPauseBlocks) + defaultParam := int(defaultParams.GetFishermanMaxPauseBlocks()) gotParam, err := ctx.GetFishermanMaxPausedBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetFishermanMinimumPauseBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.FishermanMinimumPauseBlocks) + defaultParam := int(defaultParams.GetFishermanMinimumPauseBlocks()) gotParam, err := ctx.GetFishermanMinimumPauseBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetFishermanMinimumStake(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.FishermanMinimumStake + defaultParam := defaultParams.GetFishermanMinimumStake() gotParam, err := ctx.GetFishermanMinimumStake() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetFishermanUnstakingBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int64(defaultParams.FishermanUnstakingBlocks) + defaultParam := int64(defaultParams.GetFishermanUnstakingBlocks()) gotParam, err := ctx.GetFishermanUnstakingBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMaxEvidenceAgeInBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.ValidatorMaxEvidenceAgeInBlocks) + defaultParam := int(defaultParams.GetValidatorMaxEvidenceAgeInBlocks()) gotParam, err := ctx.GetMaxEvidenceAgeInBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageChangeParameterFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageChangeParameterFee + defaultParam := defaultParams.GetMessageChangeParameterFee() gotParam, err := ctx.GetMessageChangeParameterFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageDoubleSignFee(t *testing.T) { @@ -205,435 +206,435 @@ func TestUtilityContext_GetMessageDoubleSignFee(t *testing.T) { defaultParam := defaultParams.GetMessageDoubleSignFee() gotParam, err := ctx.GetMessageDoubleSignFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageEditStakeAppFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageEditStakeAppFee + defaultParam := defaultParams.GetMessageEditStakeAppFee() gotParam, err := ctx.GetMessageEditStakeAppFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageEditStakeFishermanFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageEditStakeFishermanFee + defaultParam := defaultParams.GetMessageEditStakeFishermanFee() gotParam, err := ctx.GetMessageEditStakeFishermanFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageEditStakeServiceNodeFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageEditStakeServiceNodeFee + defaultParam := defaultParams.GetMessageEditStakeServiceNodeFee() gotParam, err := ctx.GetMessageEditStakeServiceNodeFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageEditStakeValidatorFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageEditStakeValidatorFee + defaultParam := defaultParams.GetMessageEditStakeValidatorFee() gotParam, err := ctx.GetMessageEditStakeValidatorFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageFishermanPauseServiceNodeFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageFishermanPauseServiceNodeFee + defaultParam := defaultParams.GetMessageFishermanPauseServiceNodeFee() gotParam, err := ctx.GetMessageFishermanPauseServiceNodeFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessagePauseAppFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessagePauseAppFee + defaultParam := defaultParams.GetMessagePauseAppFee() gotParam, err := ctx.GetMessagePauseAppFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessagePauseFishermanFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessagePauseFishermanFee + defaultParam := defaultParams.GetMessagePauseFishermanFee() gotParam, err := ctx.GetMessagePauseFishermanFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessagePauseServiceNodeFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessagePauseServiceNodeFee + defaultParam := defaultParams.GetMessagePauseServiceNodeFee() gotParam, err := ctx.GetMessagePauseServiceNodeFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessagePauseValidatorFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessagePauseValidatorFee + defaultParam := defaultParams.GetMessagePauseValidatorFee() gotParam, err := ctx.GetMessagePauseValidatorFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageProveTestScoreFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageProveTestScoreFee + defaultParam := defaultParams.GetMessageProveTestScoreFee() gotParam, err := ctx.GetMessageProveTestScoreFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageSendFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageSendFee + defaultParam := defaultParams.GetMessageSendFee() gotParam, err := ctx.GetMessageSendFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageStakeAppFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageStakeAppFee + defaultParam := defaultParams.GetMessageStakeAppFee() gotParam, err := ctx.GetMessageStakeAppFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageStakeFishermanFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageStakeFishermanFee + defaultParam := defaultParams.GetMessageStakeFishermanFee() gotParam, err := ctx.GetMessageStakeFishermanFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageStakeServiceNodeFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageStakeServiceNodeFee + defaultParam := defaultParams.GetMessageStakeServiceNodeFee() gotParam, err := ctx.GetMessageStakeServiceNodeFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageStakeValidatorFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageStakeValidatorFee + defaultParam := defaultParams.GetMessageStakeValidatorFee() gotParam, err := ctx.GetMessageStakeValidatorFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageTestScoreFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageTestScoreFee + defaultParam := defaultParams.GetMessageTestScoreFee() gotParam, err := ctx.GetMessageTestScoreFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnpauseAppFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageUnpauseAppFee + defaultParam := defaultParams.GetMessageUnpauseAppFee() gotParam, err := ctx.GetMessageUnpauseAppFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnpauseFishermanFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageUnpauseFishermanFee + defaultParam := defaultParams.GetMessageUnpauseFishermanFee() gotParam, err := ctx.GetMessageUnpauseFishermanFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnpauseServiceNodeFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageUnpauseServiceNodeFee + defaultParam := defaultParams.GetMessageUnpauseServiceNodeFee() gotParam, err := ctx.GetMessageUnpauseServiceNodeFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnpauseValidatorFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageUnpauseValidatorFee + defaultParam := defaultParams.GetMessageUnpauseValidatorFee() gotParam, err := ctx.GetMessageUnpauseValidatorFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnstakeAppFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageUnstakeAppFee + defaultParam := defaultParams.GetMessageUnstakeAppFee() gotParam, err := ctx.GetMessageUnstakeAppFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnstakeFishermanFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageUnstakeFishermanFee + defaultParam := defaultParams.GetMessageUnstakeFishermanFee() gotParam, err := ctx.GetMessageUnstakeFishermanFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnstakeServiceNodeFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageUnstakeServiceNodeFee + defaultParam := defaultParams.GetMessageUnstakeServiceNodeFee() gotParam, err := ctx.GetMessageUnstakeServiceNodeFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMessageUnstakeValidatorFee(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.MessageUnstakeValidatorFee + defaultParam := defaultParams.GetMessageUnstakeValidatorFee() gotParam, err := ctx.GetMessageUnstakeValidatorFee() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetMissedBlocksBurnPercentage(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.MissedBlocksBurnPercentage) + defaultParam := int(defaultParams.GetMissedBlocksBurnPercentage()) gotParam, err := ctx.GetMissedBlocksBurnPercentage() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetProposerPercentageOfFees(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.ProposerPercentageOfFees) + defaultParam := int(defaultParams.GetProposerPercentageOfFees()) gotParam, err := ctx.GetProposerPercentageOfFees() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetServiceNodeMaxChains(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.ServiceNodeMaxChains) + defaultParam := int(defaultParams.GetServiceNodeMaxChains()) gotParam, err := ctx.GetServiceNodeMaxChains() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetServiceNodeMaxPausedBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.ServiceNodeMaxPauseBlocks) + defaultParam := int(defaultParams.GetServiceNodeMaxPauseBlocks()) gotParam, err := ctx.GetServiceNodeMaxPausedBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetServiceNodeMinimumPauseBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.ServiceNodeMinimumPauseBlocks) + defaultParam := int(defaultParams.GetServiceNodeMinimumPauseBlocks()) gotParam, err := ctx.GetServiceNodeMinimumPauseBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetServiceNodeMinimumStake(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.ServiceNodeMinimumStake + defaultParam := defaultParams.GetServiceNodeMinimumStake() gotParam, err := ctx.GetServiceNodeMinimumStake() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetServiceNodeUnstakingBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int64(defaultParams.ServiceNodeUnstakingBlocks) + defaultParam := int64(defaultParams.GetServiceNodeUnstakingBlocks()) gotParam, err := ctx.GetServiceNodeUnstakingBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetStakingAdjustment(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.AppStakingAdjustment) + defaultParam := int(defaultParams.GetAppStakingAdjustment()) gotParam, err := ctx.GetStabilityAdjustment() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetValidatorMaxMissedBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.ValidatorMaximumMissedBlocks) + defaultParam := int(defaultParams.GetValidatorMaximumMissedBlocks()) gotParam, err := ctx.GetValidatorMaxMissedBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetValidatorMaxPausedBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.ValidatorMaxPauseBlocks) + defaultParam := int(defaultParams.GetValidatorMaxPauseBlocks()) gotParam, err := ctx.GetValidatorMaxPausedBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetValidatorMinimumPauseBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.ValidatorMinimumPauseBlocks) + defaultParam := int(defaultParams.GetValidatorMinimumPauseBlocks()) gotParam, err := ctx.GetValidatorMinimumPauseBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetValidatorMinimumStake(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.ValidatorMinimumStake + defaultParam := defaultParams.GetValidatorMinimumStake() gotParam, err := ctx.GetValidatorMinimumStake() require.NoError(t, err) - require.False(t, defaultParam != types.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) + require.False(t, defaultParam != typesUtil.BigIntToString(gotParam), fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_GetValidatorUnstakingBlocks(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int64(defaultParams.ValidatorUnstakingBlocks) + defaultParam := int64(defaultParams.GetValidatorUnstakingBlocks()) gotParam, err := ctx.GetValidatorUnstakingBlocks() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_HandleMessageChangeParameter(t *testing.T) { - cdc := types.GetCodec() + cdc := codec.GetCodec() ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := int(defaultParams.MissedBlocksBurnPercentage) + defaultParam := int(defaultParams.GetMissedBlocksBurnPercentage()) gotParam, err := ctx.GetMissedBlocksBurnPercentage() require.NoError(t, err) require.False(t, defaultParam != gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) newParamValue := int32(2) paramOwnerPK := test_artifacts.DefaultParamsOwner - any, err := cdc.ToAny(&wrapperspb.Int32Value{ + any, er := cdc.ToAny(&wrapperspb.Int32Value{ Value: newParamValue, }) - require.NoError(t, err) + require.NoError(t, er) msg := &typesUtil.MessageChangeParameter{ Owner: paramOwnerPK.Address(), - ParameterKey: types.MissedBlocksBurnPercentageParamName, + ParameterKey: modules.MissedBlocksBurnPercentageParamName, ParameterValue: any, } require.NoError(t, ctx.HandleMessageChangeParameter(msg), "handle message change param") @@ -641,448 +642,447 @@ func TestUtilityContext_HandleMessageChangeParameter(t *testing.T) { require.NoError(t, err) require.False(t, int(newParamValue) != gotParam, fmt.Sprintf("wrong param value after handling, expected %v got %v", newParamValue, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } -// TODO(andrew): Use reflection to iterate over all the params and test them. func TestUtilityContext_GetParamOwner(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) defaultParams := DefaultTestingParams(t) - defaultParam := defaultParams.AclOwner - gotParam, err := ctx.GetParamOwner(types.AclOwner) + defaultParam := defaultParams.GetAclOwner() + gotParam, err := ctx.GetParamOwner(modules.AclOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.BlocksPerSessionOwner - gotParam, err = ctx.GetParamOwner(types.BlocksPerSessionParamName) + defaultParam = defaultParams.GetBlocksPerSessionOwner() + gotParam, err = ctx.GetParamOwner(modules.BlocksPerSessionParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AppMaxChainsOwner - gotParam, err = ctx.GetParamOwner(types.AppMaxChainsParamName) + defaultParam = defaultParams.GetAppMaxChainsOwner() + gotParam, err = ctx.GetParamOwner(modules.AppMaxChainsParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AppMinimumStakeOwner - gotParam, err = ctx.GetParamOwner(types.AppMinimumStakeParamName) + defaultParam = defaultParams.GetAppMinimumStakeOwner() + gotParam, err = ctx.GetParamOwner(modules.AppMinimumStakeParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AppBaselineStakeRateOwner - gotParam, err = ctx.GetParamOwner(types.AppBaselineStakeRateParamName) + defaultParam = defaultParams.GetAppBaselineStakeRateOwner() + gotParam, err = ctx.GetParamOwner(modules.AppBaselineStakeRateParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AppStakingAdjustmentOwner - gotParam, err = ctx.GetParamOwner(types.AppStakingAdjustmentOwner) + defaultParam = defaultParams.GetAppStakingAdjustmentOwner() + gotParam, err = ctx.GetParamOwner(modules.AppStakingAdjustmentOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AppUnstakingBlocksOwner - gotParam, err = ctx.GetParamOwner(types.AppUnstakingBlocksParamName) + defaultParam = defaultParams.GetAppUnstakingBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.AppUnstakingBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AppMinimumPauseBlocksOwner - gotParam, err = ctx.GetParamOwner(types.AppMinimumPauseBlocksParamName) + defaultParam = defaultParams.GetAppMinimumPauseBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.AppMinimumPauseBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AppMaxPausedBlocksOwner - gotParam, err = ctx.GetParamOwner(types.AppMaxPauseBlocksParamName) + defaultParam = defaultParams.GetAppMaxPausedBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.AppMaxPauseBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ServiceNodesPerSessionOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodesPerSessionParamName) + defaultParam = defaultParams.GetServiceNodesPerSessionOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodesPerSessionParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ServiceNodeMinimumStakeOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMinimumStakeParamName) + defaultParam = defaultParams.GetServiceNodeMinimumStakeOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMinimumStakeParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ServiceNodeMaxChainsOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMaxChainsParamName) + defaultParam = defaultParams.GetServiceNodeMaxChainsOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMaxChainsParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ServiceNodeUnstakingBlocksOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeUnstakingBlocksParamName) + defaultParam = defaultParams.GetServiceNodeUnstakingBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeUnstakingBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ServiceNodeMinimumPauseBlocksOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMinimumPauseBlocksParamName) + defaultParam = defaultParams.GetServiceNodeMinimumPauseBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMinimumPauseBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ServiceNodeMaxPausedBlocksOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMaxPauseBlocksParamName) + defaultParam = defaultParams.GetServiceNodeMaxPausedBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMaxPauseBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.FishermanMinimumStakeOwner - gotParam, err = ctx.GetParamOwner(types.FishermanMinimumStakeParamName) + defaultParam = defaultParams.GetFishermanMinimumStakeOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanMinimumStakeParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) defaultParam = defaultParams.GetServiceNodeMaxChainsOwner() - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMaxPauseBlocksParamName) + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMaxPauseBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.FishermanUnstakingBlocksOwner - gotParam, err = ctx.GetParamOwner(types.FishermanUnstakingBlocksParamName) + defaultParam = defaultParams.GetFishermanUnstakingBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanUnstakingBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.FishermanMinimumPauseBlocksOwner - gotParam, err = ctx.GetParamOwner(types.FishermanMinimumPauseBlocksParamName) + defaultParam = defaultParams.GetFishermanMinimumPauseBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanMinimumPauseBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.FishermanMaxPausedBlocksOwner - gotParam, err = ctx.GetParamOwner(types.FishermanMaxPauseBlocksParamName) + defaultParam = defaultParams.GetFishermanMaxPausedBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanMaxPauseBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ValidatorMinimumStakeOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMinimumStakeParamName) + defaultParam = defaultParams.GetValidatorMinimumStakeOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMinimumStakeParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ValidatorUnstakingBlocksOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorUnstakingBlocksParamName) + defaultParam = defaultParams.GetValidatorUnstakingBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorUnstakingBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ValidatorMinimumPauseBlocksOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMinimumPauseBlocksParamName) + defaultParam = defaultParams.GetValidatorMinimumPauseBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMinimumPauseBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ValidatorMaxPausedBlocksOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMaxPausedBlocksParamName) + defaultParam = defaultParams.GetValidatorMaxPausedBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMaxPausedBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ValidatorMaximumMissedBlocksOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMaximumMissedBlocksParamName) + defaultParam = defaultParams.GetValidatorMaximumMissedBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMaximumMissedBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ProposerPercentageOfFeesOwner - gotParam, err = ctx.GetParamOwner(types.ProposerPercentageOfFeesParamName) + defaultParam = defaultParams.GetProposerPercentageOfFeesOwner() + gotParam, err = ctx.GetParamOwner(modules.ProposerPercentageOfFeesParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.ValidatorMaxEvidenceAgeInBlocksOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMaxEvidenceAgeInBlocksParamName) + defaultParam = defaultParams.GetValidatorMaxEvidenceAgeInBlocksOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMaxEvidenceAgeInBlocksParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MissedBlocksBurnPercentageOwner - gotParam, err = ctx.GetParamOwner(types.MissedBlocksBurnPercentageParamName) + defaultParam = defaultParams.GetMissedBlocksBurnPercentageOwner() + gotParam, err = ctx.GetParamOwner(modules.MissedBlocksBurnPercentageParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.DoubleSignBurnPercentageOwner - gotParam, err = ctx.GetParamOwner(types.DoubleSignBurnPercentageParamName) + defaultParam = defaultParams.GetDoubleSignBurnPercentageOwner() + gotParam, err = ctx.GetParamOwner(modules.DoubleSignBurnPercentageParamName) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageDoubleSignFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageDoubleSignFee) + defaultParam = defaultParams.GetMessageDoubleSignFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageDoubleSignFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageSendFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageSendFee) + defaultParam = defaultParams.GetMessageSendFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageSendFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageStakeFishermanFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageStakeFishermanFee) + defaultParam = defaultParams.GetMessageStakeFishermanFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageStakeFishermanFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageEditStakeFishermanFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageEditStakeFishermanFee) + defaultParam = defaultParams.GetMessageEditStakeFishermanFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageEditStakeFishermanFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageUnstakeFishermanFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnstakeFishermanFee) + defaultParam = defaultParams.GetMessageUnstakeFishermanFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnstakeFishermanFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessagePauseFishermanFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessagePauseFishermanFee) + defaultParam = defaultParams.GetMessagePauseFishermanFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessagePauseFishermanFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageUnpauseFishermanFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnpauseFishermanFee) + defaultParam = defaultParams.GetMessageUnpauseFishermanFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnpauseFishermanFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageTestScoreFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageTestScoreFee) + defaultParam = defaultParams.GetMessageTestScoreFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageTestScoreFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageFishermanPauseServiceNodeFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageFishermanPauseServiceNodeFee) + defaultParam = defaultParams.GetMessageFishermanPauseServiceNodeFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageFishermanPauseServiceNodeFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageProveTestScoreFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageProveTestScoreFee) + defaultParam = defaultParams.GetMessageProveTestScoreFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageProveTestScoreFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageStakeAppFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageStakeAppFee) + defaultParam = defaultParams.GetMessageStakeAppFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageStakeAppFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageEditStakeAppFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageEditStakeAppFee) + defaultParam = defaultParams.GetMessageEditStakeAppFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageEditStakeAppFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageUnstakeAppFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnstakeAppFee) + defaultParam = defaultParams.GetMessageUnstakeAppFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnstakeAppFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessagePauseAppFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessagePauseAppFee) + defaultParam = defaultParams.GetMessagePauseAppFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessagePauseAppFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageUnpauseAppFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnpauseAppFee) + defaultParam = defaultParams.GetMessageUnpauseAppFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnpauseAppFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageStakeValidatorFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageStakeValidatorFee) + defaultParam = defaultParams.GetMessageStakeValidatorFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageStakeValidatorFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageEditStakeValidatorFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageEditStakeValidatorFee) + defaultParam = defaultParams.GetMessageEditStakeValidatorFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageEditStakeValidatorFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageUnstakeValidatorFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnstakeValidatorFee) + defaultParam = defaultParams.GetMessageUnstakeValidatorFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnstakeValidatorFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessagePauseValidatorFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessagePauseValidatorFee) + defaultParam = defaultParams.GetMessagePauseValidatorFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessagePauseValidatorFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageUnpauseValidatorFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnpauseValidatorFee) + defaultParam = defaultParams.GetMessageUnpauseValidatorFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnpauseValidatorFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageStakeServiceNodeFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageStakeServiceNodeFee) + defaultParam = defaultParams.GetMessageStakeServiceNodeFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageStakeServiceNodeFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageEditStakeServiceNodeFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageEditStakeServiceNodeFee) + defaultParam = defaultParams.GetMessageEditStakeServiceNodeFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageEditStakeServiceNodeFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageUnstakeServiceNodeFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnstakeServiceNodeFee) + defaultParam = defaultParams.GetMessageUnstakeServiceNodeFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnstakeServiceNodeFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessagePauseServiceNodeFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessagePauseServiceNodeFee) + defaultParam = defaultParams.GetMessagePauseServiceNodeFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessagePauseServiceNodeFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageUnpauseServiceNodeFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnpauseServiceNodeFee) + defaultParam = defaultParams.GetMessageUnpauseServiceNodeFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnpauseServiceNodeFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.MessageChangeParameterFeeOwner - gotParam, err = ctx.GetParamOwner(types.MessageChangeParameterFee) + defaultParam = defaultParams.GetMessageChangeParameterFeeOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageChangeParameterFee) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) // owners - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.BlocksPerSessionOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.BlocksPerSessionOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.AppMaxChainsOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.AppMaxChainsOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.AppMinimumStakeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.AppMinimumStakeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.AppBaselineStakeRateOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.AppBaselineStakeRateOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.AppStakingAdjustmentOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.AppStakingAdjustmentOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.AppUnstakingBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.AppUnstakingBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.AppMinimumPauseBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.AppMinimumPauseBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.AppMaxPausedBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.AppMaxPausedBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMinimumPauseBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMinimumPauseBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMaxChainsOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMaxChainsOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeUnstakingBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeUnstakingBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMinimumStakeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMinimumStakeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodeMaxPausedBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodeMaxPausedBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ServiceNodesPerSessionOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ServiceNodesPerSessionOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.FishermanMinimumStakeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanMinimumStakeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.FishermanMaxChainsOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanMaxChainsOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.FishermanUnstakingBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanUnstakingBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.FishermanMinimumPauseBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanMinimumPauseBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.FishermanMaxPausedBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.FishermanMaxPausedBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMinimumStakeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMinimumStakeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorUnstakingBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorUnstakingBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMinimumPauseBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMinimumPauseBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMaxPausedBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMaxPausedBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMaxPausedBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMaxPausedBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ProposerPercentageOfFeesOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ProposerPercentageOfFeesOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.ValidatorMaxEvidenceAgeInBlocksOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.ValidatorMaxEvidenceAgeInBlocksOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MissedBlocksBurnPercentageOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MissedBlocksBurnPercentageOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.DoubleSignBurnPercentageOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.DoubleSignBurnPercentageOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageSendFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageSendFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageStakeFishermanFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageStakeFishermanFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageEditStakeFishermanFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageEditStakeFishermanFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnstakeFishermanFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnstakeFishermanFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessagePauseFishermanFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessagePauseFishermanFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnpauseFishermanFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnpauseFishermanFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageFishermanPauseServiceNodeFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageFishermanPauseServiceNodeFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageTestScoreFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageTestScoreFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageProveTestScoreFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageProveTestScoreFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageStakeAppFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageStakeAppFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageEditStakeAppFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageEditStakeAppFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnstakeAppFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnstakeAppFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessagePauseAppFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessagePauseAppFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnpauseAppFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnpauseAppFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageStakeValidatorFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageStakeValidatorFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageEditStakeValidatorFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageEditStakeValidatorFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnstakeValidatorFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnstakeValidatorFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessagePauseValidatorFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessagePauseValidatorFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnpauseValidatorFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnpauseValidatorFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageStakeServiceNodeFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageStakeServiceNodeFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageEditStakeServiceNodeFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageEditStakeServiceNodeFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnstakeServiceNodeFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnstakeServiceNodeFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessagePauseServiceNodeFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessagePauseServiceNodeFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageUnpauseServiceNodeFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageUnpauseServiceNodeFeeOwner) require.NoError(t, err) require.False(t, hex.EncodeToString(gotParam) != defaultParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - defaultParam = defaultParams.AclOwner - gotParam, err = ctx.GetParamOwner(types.MessageChangeParameterFeeOwner) + defaultParam = defaultParams.GetAclOwner() + gotParam, err = ctx.GetParamOwner(modules.MessageChangeParameterFeeOwner) require.NoError(t, err) defaultParamBz, err := hex.DecodeString(defaultParam) require.NoError(t, err) require.Equal(t, defaultParamBz, gotParam, fmt.Sprintf("unexpected param value: expected %v got %v", defaultParam, gotParam)) - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } diff --git a/shared/tests/utility_module/message_test.go b/utility/test/message_test.go similarity index 92% rename from shared/tests/utility_module/message_test.go rename to utility/test/message_test.go index 218cce5a2..571b9ee25 100644 --- a/shared/tests/utility_module/message_test.go +++ b/utility/test/message_test.go @@ -1,4 +1,4 @@ -package utility_module +package test import ( "github.com/pokt-network/pocket/utility/types" diff --git a/utility/test/module_test.go b/utility/test/module_test.go new file mode 100644 index 000000000..e8785baf1 --- /dev/null +++ b/utility/test/module_test.go @@ -0,0 +1,116 @@ +package test + +import ( + "encoding/json" + "io/ioutil" + "log" + "math/big" + "os" + "testing" + + "github.com/pokt-network/pocket/shared/test_artifacts" + utilTypes "github.com/pokt-network/pocket/utility/types" + + "github.com/pokt-network/pocket/persistence" + "github.com/pokt-network/pocket/shared/modules" + "github.com/pokt-network/pocket/utility" + "github.com/stretchr/testify/require" +) + +var ( + defaultTestingChainsEdited = []string{"0002"} + defaultUnstaking = int64(2017) + defaultSendAmount = big.NewInt(10000) + defaultNonceString = utilTypes.BigIntToString(test_artifacts.DefaultAccountAmount) + defaultSendAmountString = utilTypes.BigIntToString(defaultSendAmount) + testSchema = "test_schema" +) + +var testPersistenceMod modules.PersistenceModule + +func NewTestingMempool(_ *testing.T) utilTypes.Mempool { + return utilTypes.NewMempool(1000000, 1000) +} + +func TestMain(m *testing.M) { + pool, resource, dbUrl := test_artifacts.SetupPostgresDocker() + testPersistenceMod = newTestPersistenceModule(dbUrl) + m.Run() + os.Remove(testingConfigFilePath) + os.Remove(testingGenesisFilePath) + test_artifacts.CleanupPostgresDocker(m, pool, resource) +} + +func NewTestingUtilityContext(t *testing.T, height int64) utility.UtilityContext { + persistenceContext, err := testPersistenceMod.NewRWContext(height) + require.NoError(t, err) + + t.Cleanup(func() { + testPersistenceMod.ResetContext() + }) + + return utility.UtilityContext{ + LatestHeight: height, + Mempool: NewTestingMempool(t), + Context: &utility.Context{ + PersistenceRWContext: persistenceContext, + SavePointsM: make(map[string]struct{}), + SavePoints: make([][]byte, 0), + }, + } +} + +// TODO(andrew): Take in `t` and fail the test if there's an error +func newTestPersistenceModule(databaseUrl string) modules.PersistenceModule { + cfg := modules.Config{ + Persistence: &test_artifacts.MockPersistenceConfig{ + PostgresUrl: databaseUrl, + NodeSchema: testSchema, + BlockStorePath: "", + }, + } + // TODO(andrew): Move the number of actors into local constants + genesisState, _ := test_artifacts.NewGenesisState(5, 1, 1, 1) + createTestingGenesisAndConfigFiles(cfg, genesisState) + persistenceMod, err := persistence.Create(testingConfigFilePath, testingGenesisFilePath) // TODO (Drewsky) this is the last remaining cross module import and needs a fix... + if err != nil { + log.Fatalf("Error creating persistence module: %s", err) + } + persistenceMod.Start() // TODO: Check for error + return persistenceMod +} + +const ( + testingGenesisFilePath = "genesis.json" + testingConfigFilePath = "config.json" +) + +func createTestingGenesisAndConfigFiles(cfg modules.Config, genesisState modules.GenesisState) { + config, err := json.Marshal(cfg.Persistence) + if err != nil { + log.Fatal(err) + } + genesis, err := json.Marshal(genesisState.PersistenceGenesisState) + if err != nil { + log.Fatal(err) + } + genesisFile := make(map[string]json.RawMessage) + configFile := make(map[string]json.RawMessage) + persistenceModuleName := new(persistence.PersistenceModule).GetModuleName() + genesisFile[test_artifacts.GetGenesisFileName(persistenceModuleName)] = genesis + configFile[persistenceModuleName] = config + genesisFileBz, err := json.MarshalIndent(genesisFile, "", " ") + if err != nil { + log.Fatal(err) + } + configFileBz, err := json.MarshalIndent(configFile, "", " ") + if err != nil { + log.Fatal(err) + } + if err := ioutil.WriteFile(testingGenesisFilePath, genesisFileBz, 0777); err != nil { + log.Fatal(err) + } + if err := ioutil.WriteFile(testingConfigFilePath, configFileBz, 0777); err != nil { + log.Fatal(err) + } +} diff --git a/shared/tests/utility_module/transaction_test.go b/utility/test/transaction_test.go similarity index 76% rename from shared/tests/utility_module/transaction_test.go rename to utility/test/transaction_test.go index 50c3aa1f4..eadbb4808 100644 --- a/shared/tests/utility_module/transaction_test.go +++ b/utility/test/transaction_test.go @@ -1,20 +1,20 @@ -package utility_module +package test import ( "encoding/hex" "math/big" "testing" + "github.com/pokt-network/pocket/shared/codec" + "github.com/pokt-network/pocket/shared/test_artifacts" + "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/tests" - "github.com/pokt-network/pocket/shared/types" - "github.com/pokt-network/pocket/shared/types/genesis/test_artifacts" "github.com/pokt-network/pocket/utility" typesUtil "github.com/pokt-network/pocket/utility/types" "github.com/stretchr/testify/require" ) -// TODO: Clean up the readability (e.g. spacing, naming, etc) of these tests and extend them to cover the entire context. +// TODO(olshansky): Clean up the readability (e.g. spacing, naming, etc) of these tests and extend them to cover the entire context func TestUtilityContext_AnteHandleMessage(t *testing.T) { ctx := NewTestingUtilityContext(t, 0) @@ -30,7 +30,7 @@ func TestUtilityContext_AnteHandleMessage(t *testing.T) { require.NoError(t, err) require.Equal(t, expectedAfterBalance, amount, "unexpected after balance") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func TestUtilityContext_ApplyTransaction(t *testing.T) { @@ -47,10 +47,10 @@ func TestUtilityContext_ApplyTransaction(t *testing.T) { require.NoError(t, err) require.Equal(t, expectedAfterBalance, amount, "unexpected after balance") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } -// TODO: Fix this test once txIndexer is implemented by postgres context +// TODO: (#168) Fix this test once txIndexer is implemented by postgres context func TestUtilityContext_CheckTransaction(t *testing.T) { // ctx := NewTestingUtilityContext(t, 0) // tx, _, _, _ := newTestingTransaction(t, ctx) @@ -72,22 +72,22 @@ func TestUtilityContext_GetSignerCandidates(t *testing.T) { accs := GetAllTestingAccounts(t, ctx) sendAmount := big.NewInt(1000000) - sendAmountString := types.BigIntToString(sendAmount) - addrBz, er := hex.DecodeString(accs[0].Address) + sendAmountString := typesUtil.BigIntToString(sendAmount) + addrBz, er := hex.DecodeString(accs[0].GetAddress()) require.NoError(t, er) - addrBz2, er := hex.DecodeString(accs[1].Address) + addrBz2, er := hex.DecodeString(accs[1].GetAddress()) require.NoError(t, er) msg := NewTestingSendMessage(t, addrBz, addrBz2, sendAmountString) candidates, err := ctx.GetSignerCandidates(&msg) require.NoError(t, err) require.Equal(t, len(candidates), 1, "wrong number of candidates") - require.Equal(t, hex.EncodeToString(candidates[0]), accs[0].Address, "unexpected signer candidate") + require.Equal(t, hex.EncodeToString(candidates[0]), accs[0].GetAddress(), "unexpected signer candidate") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } -// TODO(andrew): Fix this test once txIndexer is implemented by postgres context +// TODO: (#168) Fix this test once txIndexer is implemented by postgres context func TestUtilityContext_GetTransactionsForProposal(t *testing.T) { // ctx := NewTestingUtilityContext(t, 0) // tx, _, _, _ := newTestingTransaction(t, ctx) @@ -95,7 +95,7 @@ func TestUtilityContext_GetTransactionsForProposal(t *testing.T) { // txBz, err := tx.Bytes() // require.NoError(t, err) // require.NoError(t, ctx.CheckTransaction(txBz)) - // txs, er := ctx.GetTransactionsForProposal(proposer.Address, 10000, nil) + // txs, er := ctx.GetTransactionsForProposal(proposer.GetAddress(), 10000, nil) // require.NoError(t, er) // require.True(t, len(txs) == 1, fmt.Sprintf("incorrect txs amount returned; expected %v got %v", 1, len(txs))) // require.True(t, bytes.Equal(txs[0], txBz), fmt.Sprintf("unexpected transaction returned; expected tx: %s, got %s", hex.EncodeToString(txBz), hex.EncodeToString(txs[0]))) @@ -109,33 +109,33 @@ func TestUtilityContext_HandleMessage(t *testing.T) { accs := GetAllTestingAccounts(t, ctx) sendAmount := big.NewInt(1000000) - sendAmountString := types.BigIntToString(sendAmount) - senderBalanceBefore, err := types.StringToBigInt(accs[0].Amount) + sendAmountString := typesUtil.BigIntToString(sendAmount) + senderBalanceBefore, err := typesUtil.StringToBigInt(accs[0].GetAmount()) require.NoError(t, err) - recipientBalanceBefore, err := types.StringToBigInt(accs[1].Amount) + recipientBalanceBefore, err := typesUtil.StringToBigInt(accs[1].GetAmount()) require.NoError(t, err) - addrBz, er := hex.DecodeString(accs[0].Address) + addrBz, er := hex.DecodeString(accs[0].GetAddress()) require.NoError(t, er) - addrBz2, er := hex.DecodeString(accs[1].Address) + addrBz2, er := hex.DecodeString(accs[1].GetAddress()) require.NoError(t, er) msg := NewTestingSendMessage(t, addrBz, addrBz2, sendAmountString) require.NoError(t, ctx.HandleMessageSend(&msg)) accs = GetAllTestingAccounts(t, ctx) - senderBalanceAfter, err := types.StringToBigInt(accs[0].Amount) + senderBalanceAfter, err := typesUtil.StringToBigInt(accs[0].GetAmount()) require.NoError(t, err) - recipientBalanceAfter, err := types.StringToBigInt(accs[1].Amount) + recipientBalanceAfter, err := typesUtil.StringToBigInt(accs[1].GetAmount()) require.NoError(t, err) require.Equal(t, big.NewInt(0).Sub(senderBalanceBefore, senderBalanceAfter), sendAmount, "unexpected sender balance") require.Equal(t, big.NewInt(0).Sub(recipientBalanceAfter, recipientBalanceBefore), sendAmount, "unexpected recipient balance") - tests.CleanupTest(ctx) + test_artifacts.CleanupTest(ctx) } func newTestingTransaction(t *testing.T, ctx utility.UtilityContext) (transaction *typesUtil.Transaction, startingAmount, amountSent *big.Int, signer crypto.PrivateKey) { - cdc := types.GetCodec() + cdc := codec.GetCodec() recipient := GetAllTestingAccounts(t, ctx)[1] signer, err := crypto.GeneratePrivateKey() @@ -145,7 +145,7 @@ func newTestingTransaction(t *testing.T, ctx utility.UtilityContext) (transactio signerAddr := signer.Address() require.NoError(t, ctx.SetAccountAmount(signerAddr, startingAmount)) amountSent = defaultSendAmount - addrBz, err := hex.DecodeString(recipient.Address) + addrBz, err := hex.DecodeString(recipient.GetAddress()) require.NoError(t, err) msg := NewTestingSendMessage(t, signerAddr, addrBz, defaultSendAmountString) any, err := cdc.ToAny(&msg) diff --git a/utility/transaction.go b/utility/transaction.go index 17b3b20dd..f0e5a85d9 100644 --- a/utility/transaction.go +++ b/utility/transaction.go @@ -2,14 +2,12 @@ package utility import ( "bytes" - + typesGenesis "github.com/pokt-network/pocket/persistence/types" "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" - typesGenesis "github.com/pokt-network/pocket/shared/types/genesis" typesUtil "github.com/pokt-network/pocket/utility/types" ) -func (u *UtilityContext) ApplyTransaction(tx *typesUtil.Transaction) types.Error { +func (u *UtilityContext) ApplyTransaction(tx *typesUtil.Transaction) typesUtil.Error { msg, err := u.AnteHandleMessage(tx) if err != nil { return err @@ -21,7 +19,7 @@ func (u *UtilityContext) CheckTransaction(transactionProtoBytes []byte) error { // validate transaction txHash := typesUtil.TransactionHash(transactionProtoBytes) if u.Mempool.Contains(txHash) { - return types.ErrDuplicateTransaction() + return typesUtil.ErrDuplicateTransaction() } store := u.Store() txExists, err := store.TransactionExists(txHash) @@ -30,12 +28,12 @@ func (u *UtilityContext) CheckTransaction(transactionProtoBytes []byte) error { } // TODO non-ordered nonce requires non-pruned tx indexer if txExists { - return types.ErrTransactionAlreadyCommitted() + return typesUtil.ErrTransactionAlreadyCommitted() } cdc := u.Codec() transaction := &typesUtil.Transaction{} if err := cdc.Unmarshal(transactionProtoBytes, transaction); err != nil { - return types.ErrProtoUnmarshal(err) + return typesUtil.ErrProtoUnmarshal(err) } if err := transaction.ValidateBasic(); err != nil { return err @@ -86,7 +84,7 @@ func (u *UtilityContext) GetProposalTransactions(proposer []byte, maxTransaction } // CLEANUP: Exposed for testing purposes only -func (u *UtilityContext) AnteHandleMessage(tx *typesUtil.Transaction) (typesUtil.Message, types.Error) { +func (u *UtilityContext) AnteHandleMessage(tx *typesUtil.Transaction) (typesUtil.Message, typesUtil.Error) { msg, err := tx.Message() if err != nil { return nil, err @@ -97,16 +95,16 @@ func (u *UtilityContext) AnteHandleMessage(tx *typesUtil.Transaction) (typesUtil } pubKey, er := crypto.NewPublicKeyFromBytes(tx.Signature.PublicKey) if er != nil { - return nil, types.ErrNewPublicKeyFromBytes(er) + return nil, typesUtil.ErrNewPublicKeyFromBytes(er) } address := pubKey.Address() accountAmount, err := u.GetAccountAmount(address) if err != nil { - return nil, types.ErrGetAccountAmount(err) + return nil, typesUtil.ErrGetAccountAmount(err) } accountAmount.Sub(accountAmount, fee) if accountAmount.Sign() == -1 { - return nil, types.ErrInsufficientAmount() + return nil, typesUtil.ErrInsufficientAmount() } signerCandidates, err := u.GetSignerCandidates(msg) if err != nil { @@ -120,7 +118,7 @@ func (u *UtilityContext) AnteHandleMessage(tx *typesUtil.Transaction) (typesUtil } } if !isValidSigner { - return nil, types.ErrInvalidSigner() + return nil, typesUtil.ErrInvalidSigner() } if err := u.SetAccountAmount(address, accountAmount); err != nil { return nil, err @@ -132,7 +130,7 @@ func (u *UtilityContext) AnteHandleMessage(tx *typesUtil.Transaction) (typesUtil return msg, nil } -func (u *UtilityContext) HandleMessage(msg typesUtil.Message) types.Error { +func (u *UtilityContext) HandleMessage(msg typesUtil.Message) typesUtil.Error { switch x := msg.(type) { case *typesUtil.MessageDoubleSign: return u.HandleMessageDoubleSign(x) @@ -149,13 +147,13 @@ func (u *UtilityContext) HandleMessage(msg typesUtil.Message) types.Error { case *typesUtil.MessageChangeParameter: return u.HandleMessageChangeParameter(x) default: - return types.ErrUnknownMessage(x) + return typesUtil.ErrUnknownMessage(x) } } -func (u *UtilityContext) HandleMessageSend(message *typesUtil.MessageSend) types.Error { +func (u *UtilityContext) HandleMessageSend(message *typesUtil.MessageSend) typesUtil.Error { // convert the amount to big.Int - amount, err := types.StringToBigInt(message.Amount) + amount, err := typesUtil.StringToBigInt(message.Amount) if err != nil { return err } @@ -169,7 +167,7 @@ func (u *UtilityContext) HandleMessageSend(message *typesUtil.MessageSend) types // if they go negative, they don't have sufficient funds // NOTE: we don't use the u.SubtractAccountAmount() function because Utility needs to do this check if fromAccountAmount.Sign() == -1 { - return types.ErrInsufficientAmount() + return typesUtil.ErrInsufficientAmount() } // add the amount to the recipient's account if err = u.AddAccountAmount(message.ToAddress, amount); err != nil { @@ -182,7 +180,7 @@ func (u *UtilityContext) HandleMessageSend(message *typesUtil.MessageSend) types return nil } -func (u *UtilityContext) HandleStakeMessage(message *typesUtil.MessageStake) types.Error { +func (u *UtilityContext) HandleStakeMessage(message *typesUtil.MessageStake) typesUtil.Error { publicKey, err := u.BytesToPublicKey(message.PublicKey) if err != nil { return err @@ -200,7 +198,7 @@ func (u *UtilityContext) HandleStakeMessage(message *typesUtil.MessageStake) typ // calculate new signer account amount signerAccountAmount.Sub(signerAccountAmount, amount) if signerAccountAmount.Sign() == -1 { - return types.ErrInsufficientAmount() + return typesUtil.ErrInsufficientAmount() } // validators don't have chains field if err = u.CheckBelowMaxChains(message.ActorType, message.Chains); err != nil { @@ -209,7 +207,7 @@ func (u *UtilityContext) HandleStakeMessage(message *typesUtil.MessageStake) typ // ensure actor doesn't already exist if exists, err := u.GetActorExists(message.ActorType, publicKey.Address()); err != nil || exists { if exists { - return types.ErrAlreadyExists() + return typesUtil.ErrAlreadyExists() } return err } @@ -225,30 +223,30 @@ func (u *UtilityContext) HandleStakeMessage(message *typesUtil.MessageStake) typ store := u.Store() // insert actor switch message.ActorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: maxRelays, err := u.CalculateAppRelays(message.Amount) if err != nil { return err } er = store.InsertApp(publicKey.Address(), publicKey.Bytes(), message.OutputAddress, false, typesUtil.StakedStatus, maxRelays, message.Amount, message.Chains, typesUtil.HeightNotUsed, typesUtil.HeightNotUsed) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: er = store.InsertFisherman(publicKey.Address(), publicKey.Bytes(), message.OutputAddress, false, typesUtil.StakedStatus, message.ServiceUrl, message.Amount, message.Chains, typesUtil.HeightNotUsed, typesUtil.HeightNotUsed) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: er = store.InsertServiceNode(publicKey.Address(), publicKey.Bytes(), message.OutputAddress, false, typesUtil.StakedStatus, message.ServiceUrl, message.Amount, message.Chains, typesUtil.HeightNotUsed, typesUtil.HeightNotUsed) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: er = store.InsertValidator(publicKey.Address(), publicKey.Bytes(), message.OutputAddress, false, typesUtil.StakedStatus, message.ServiceUrl, message.Amount, typesUtil.HeightNotUsed, typesUtil.HeightNotUsed) } if er != nil { - return types.ErrInsert(er) + return typesUtil.ErrInsert(er) } return nil } -func (u *UtilityContext) HandleEditStakeMessage(message *typesUtil.MessageEditStake) types.Error { +func (u *UtilityContext) HandleEditStakeMessage(message *typesUtil.MessageEditStake) typesUtil.Error { // ensure actor exists if exists, err := u.GetActorExists(message.ActorType, message.Address); err != nil || !exists { if !exists { - return types.ErrNotExists() + return typesUtil.ErrNotExists() } return err } @@ -256,14 +254,14 @@ func (u *UtilityContext) HandleEditStakeMessage(message *typesUtil.MessageEditSt if err != nil { return err } - amount, err := types.StringToBigInt(message.Amount) + amount, err := typesUtil.StringToBigInt(message.Amount) if err != nil { return err } // ensure new stake >= current stake amount.Sub(amount, currentStakeAmount) if amount.Sign() == -1 { - return types.ErrStakeLess() + return typesUtil.ErrStakeLess() } // ensure signer has sufficient funding for the stake signerAccountAmount, err := u.GetAccountAmount(message.Signer) @@ -272,7 +270,7 @@ func (u *UtilityContext) HandleEditStakeMessage(message *typesUtil.MessageEditSt } signerAccountAmount.Sub(signerAccountAmount, amount) if signerAccountAmount.Sign() == -1 { - return types.ErrInsufficientAmount() + return typesUtil.ErrInsufficientAmount() } if err = u.CheckBelowMaxChains(message.ActorType, message.Chains); err != nil { return err @@ -288,29 +286,29 @@ func (u *UtilityContext) HandleEditStakeMessage(message *typesUtil.MessageEditSt store := u.Store() var er error switch message.ActorType { - case typesUtil.ActorType_App: + case typesUtil.UtilActorType_App: maxRelays, err := u.CalculateAppRelays(message.Amount) if err != nil { return err } er = store.UpdateApp(message.Address, maxRelays, message.Amount, message.Chains) - case typesUtil.ActorType_Fish: + case typesUtil.UtilActorType_Fish: er = store.UpdateFisherman(message.Address, message.ServiceUrl, message.Amount, message.Chains) - case typesUtil.ActorType_Node: + case typesUtil.UtilActorType_Node: er = store.UpdateServiceNode(message.Address, message.ServiceUrl, message.Amount, message.Chains) - case typesUtil.ActorType_Val: + case typesUtil.UtilActorType_Val: er = store.UpdateValidator(message.Address, message.ServiceUrl, message.Amount) } if er != nil { - return types.ErrInsert(er) + return typesUtil.ErrInsert(er) } return nil } -func (u *UtilityContext) HandleUnstakeMessage(message *typesUtil.MessageUnstake) types.Error { +func (u *UtilityContext) HandleUnstakeMessage(message *typesUtil.MessageUnstake) typesUtil.Error { if status, err := u.GetActorStatus(message.ActorType, message.Address); err != nil || status != typesUtil.StakedStatus { if status != typesUtil.StakedStatus { - return types.ErrInvalidStatus(status, typesUtil.StakedStatus) + return typesUtil.ErrInvalidStatus(status, typesUtil.StakedStatus) } return err } @@ -324,13 +322,13 @@ func (u *UtilityContext) HandleUnstakeMessage(message *typesUtil.MessageUnstake) return nil } -func (u *UtilityContext) HandleUnpauseMessage(message *typesUtil.MessageUnpause) types.Error { +func (u *UtilityContext) HandleUnpauseMessage(message *typesUtil.MessageUnpause) typesUtil.Error { pausedHeight, err := u.GetPauseHeight(message.ActorType, message.Address) if err != nil { return err } if pausedHeight == typesUtil.HeightNotUsed { - return types.ErrNotPaused() + return typesUtil.ErrNotPaused() } minPauseBlocks, err := u.GetMinimumPauseBlocks(message.ActorType) if err != nil { @@ -341,15 +339,15 @@ func (u *UtilityContext) HandleUnpauseMessage(message *typesUtil.MessageUnpause) return err } if latestHeight < int64(minPauseBlocks)+pausedHeight { - return types.ErrNotReadyToUnpause() + return typesUtil.ErrNotReadyToUnpause() } - if err = u.SetActorPauseHeight(message.ActorType, message.Address, types.HeightNotUsed); err != nil { + if err = u.SetActorPauseHeight(message.ActorType, message.Address, typesUtil.HeightNotUsed); err != nil { return err } return nil } -func (u *UtilityContext) HandleMessageDoubleSign(message *typesUtil.MessageDoubleSign) types.Error { +func (u *UtilityContext) HandleMessageDoubleSign(message *typesUtil.MessageDoubleSign) typesUtil.Error { latestHeight, err := u.GetLatestHeight() if err != nil { return err @@ -360,11 +358,11 @@ func (u *UtilityContext) HandleMessageDoubleSign(message *typesUtil.MessageDoubl return err } if evidenceAge > int64(maxEvidenceAge) { - return types.ErrMaxEvidenceAge() + return typesUtil.ErrMaxEvidenceAge() } pk, er := crypto.NewPublicKeyFromBytes(message.VoteB.PublicKey) if er != nil { - return types.ErrNewPublicKeyFromBytes(er) + return typesUtil.ErrNewPublicKeyFromBytes(er) } doubleSigner := pk.Address() // burn validator for double signing blocks @@ -372,22 +370,22 @@ func (u *UtilityContext) HandleMessageDoubleSign(message *typesUtil.MessageDoubl if err != nil { return err } - if err := u.BurnActor(typesUtil.ActorType_Val, burnPercentage, doubleSigner); err != nil { + if err := u.BurnActor(typesUtil.UtilActorType_Val, burnPercentage, doubleSigner); err != nil { return err } return nil } -func (u *UtilityContext) HandleMessageChangeParameter(message *typesUtil.MessageChangeParameter) types.Error { +func (u *UtilityContext) HandleMessageChangeParameter(message *typesUtil.MessageChangeParameter) typesUtil.Error { cdc := u.Codec() v, err := cdc.FromAny(message.ParameterValue) if err != nil { - return types.ErrProtoFromAny(err) + return typesUtil.ErrProtoFromAny(err) } return u.UpdateParam(message.ParameterKey, v) } -func (u *UtilityContext) GetSignerCandidates(msg typesUtil.Message) ([][]byte, types.Error) { +func (u *UtilityContext) GetSignerCandidates(msg typesUtil.Message) ([][]byte, typesUtil.Error) { switch x := msg.(type) { case *typesUtil.MessageDoubleSign: return u.GetMessageDoubleSignSignerCandidates(x) @@ -402,14 +400,14 @@ func (u *UtilityContext) GetSignerCandidates(msg typesUtil.Message) ([][]byte, t case *typesUtil.MessageChangeParameter: return u.GetMessageChangeParameterSignerCandidates(x) default: - return nil, types.ErrUnknownMessage(x) + return nil, typesUtil.ErrUnknownMessage(x) } } -func (u *UtilityContext) GetMessageStakeSignerCandidates(msg *typesUtil.MessageStake) ([][]byte, types.Error) { +func (u *UtilityContext) GetMessageStakeSignerCandidates(msg *typesUtil.MessageStake) ([][]byte, typesUtil.Error) { pk, er := crypto.NewPublicKeyFromBytes(msg.PublicKey) if er != nil { - return nil, types.ErrNewPublicKeyFromBytes(er) + return nil, typesUtil.ErrNewPublicKeyFromBytes(er) } candidates := make([][]byte, 0) candidates = append(candidates, msg.OutputAddress) @@ -417,7 +415,7 @@ func (u *UtilityContext) GetMessageStakeSignerCandidates(msg *typesUtil.MessageS return candidates, nil } -func (u *UtilityContext) GetMessageEditStakeSignerCandidates(msg *typesUtil.MessageEditStake) ([][]byte, types.Error) { +func (u *UtilityContext) GetMessageEditStakeSignerCandidates(msg *typesUtil.MessageEditStake) ([][]byte, typesUtil.Error) { output, err := u.GetActorOutputAddress(msg.ActorType, msg.Address) if err != nil { return nil, err @@ -428,7 +426,7 @@ func (u *UtilityContext) GetMessageEditStakeSignerCandidates(msg *typesUtil.Mess return candidates, nil } -func (u *UtilityContext) GetMessageUnstakeSignerCandidates(msg *typesUtil.MessageUnstake) ([][]byte, types.Error) { +func (u *UtilityContext) GetMessageUnstakeSignerCandidates(msg *typesUtil.MessageUnstake) ([][]byte, typesUtil.Error) { output, err := u.GetActorOutputAddress(msg.ActorType, msg.Address) if err != nil { return nil, err @@ -439,7 +437,7 @@ func (u *UtilityContext) GetMessageUnstakeSignerCandidates(msg *typesUtil.Messag return candidates, nil } -func (u *UtilityContext) GetMessageUnpauseSignerCandidates(msg *typesUtil.MessageUnpause) ([][]byte, types.Error) { +func (u *UtilityContext) GetMessageUnpauseSignerCandidates(msg *typesUtil.MessageUnpause) ([][]byte, typesUtil.Error) { output, err := u.GetActorOutputAddress(msg.ActorType, msg.Address) if err != nil { return nil, err @@ -450,10 +448,10 @@ func (u *UtilityContext) GetMessageUnpauseSignerCandidates(msg *typesUtil.Messag return candidates, nil } -func (u *UtilityContext) GetMessageSendSignerCandidates(msg *typesUtil.MessageSend) ([][]byte, types.Error) { +func (u *UtilityContext) GetMessageSendSignerCandidates(msg *typesUtil.MessageSend) ([][]byte, typesUtil.Error) { return [][]byte{msg.FromAddress}, nil } -func (u *UtilityContext) GetMessageDoubleSignSignerCandidates(msg *typesUtil.MessageDoubleSign) ([][]byte, types.Error) { +func (u *UtilityContext) GetMessageDoubleSignSignerCandidates(msg *typesUtil.MessageDoubleSign) ([][]byte, typesUtil.Error) { return [][]byte{msg.ReporterAddress}, nil } diff --git a/utility/types/actor.go b/utility/types/actor.go index 044fd78ee..4bd6682cb 100644 --- a/utility/types/actor.go +++ b/utility/types/actor.go @@ -1,7 +1,6 @@ package types import ( - "github.com/pokt-network/pocket/shared/types/genesis" "log" ) @@ -13,30 +12,30 @@ const ( // TODO(andrew): consolidate with genesis and `types/block.go` var ( - ActorTypes = []ActorType{ // TODO (andrew) consolidate with genesis - ActorType_App, - ActorType_Node, - ActorType_Fish, - ActorType_Val, + ActorTypes = []UtilActorType{ // TODO (andrew) consolidate with genesis + UtilActorType_App, + UtilActorType_Node, + UtilActorType_Fish, + UtilActorType_Val, } ) -func (actorType ActorType) GetActorPoolName() string { - switch actorType { - case ActorType_App: - return genesis.Pool_Names_AppStakePool.String() - case ActorType_Val: - return genesis.Pool_Names_ValidatorStakePool.String() - case ActorType_Fish: - return genesis.Pool_Names_FishermanStakePool.String() - case ActorType_Node: - return genesis.Pool_Names_ServiceNodeStakePool.String() +func (x UtilActorType) GetActorPoolName() string { + switch x { + case UtilActorType_App: + return "AppStakePool" + case UtilActorType_Val: + return "ValidatorStakePool" + case UtilActorType_Fish: + return "FishermanStakePool" + case UtilActorType_Node: + return "ServiceNodeStakePool" default: - log.Fatalf("unknown actor type: %v", actorType) + log.Fatalf("unknown actor type: %v", x) } return "" } -func (at ActorType) GetActorName() string { - return ActorType_name[int32(at)] +func (x UtilActorType) GetActorName() string { + return UtilActorType_name[int32(x)] } diff --git a/shared/types/errors.go b/utility/types/error.go similarity index 66% rename from shared/types/errors.go rename to utility/types/error.go index 9e7106ee9..cc96ca346 100644 --- a/shared/types/errors.go +++ b/utility/types/error.go @@ -2,33 +2,76 @@ package types import ( "encoding/hex" + "errors" "fmt" ) -const ( - CodeOK Code = 0 - CodeInvalidSignerError Code = 3 - CodeDecodeMessageError Code = 4 - CodeUnmarshalTransaction Code = 5 - CodeUnknownMessageError Code = 6 - CodeAppHashError Code = 7 - CodeNewPublicKeyFromBytesError Code = 8 +type Error interface { + Code() Code + error +} - CodeSignatureVerificationFailedError Code = 10 +type StdErr struct { + CodeError Code + error +} - CodeInvalidNonceError Code = 22 +func (se StdErr) Error() string { + return fmt.Sprintf("CODE: %v, ERROR: %s", se.Code(), se.error.Error()) +} - CodeProtoFromAnyError Code = 28 - CodeNewFeeFromStringError Code = 29 - CodeEmptyNonceError Code = 30 - CodeEmptyPublicKeyError Code = 31 - CodeEmptySignatureError Code = 32 +func (se StdErr) Code() Code { + return se.CodeError +} - CodeTransactionSignError Code = 36 +func NewError(code Code, msg string) Error { + return StdErr{ + CodeError: code, + error: errors.New(msg), + } +} - CodeInterfaceConversionError Code = 38 - CodeGetAccountAmountError Code = 39 +type Code float64 +const ( + CodeOK Code = 0 + CodeEmptyTransactionError Code = 2 + CodeInvalidSignerError Code = 3 + CodeDecodeMessageError Code = 4 + CodeUnmarshalTransaction Code = 5 + CodeUnknownMessageError Code = 6 + CodeAppHashError Code = 7 + CodeNewPublicKeyFromBytesError Code = 8 + CodeNewAddressFromBytesError Code = 9 + CodeSignatureVerificationFailedError Code = 10 + CodeHexDecodeFromStringError Code = 11 + CodeInvalidHashLengthError Code = 12 + CodeEmptyNetworkIDError Code = 13 + CodeEmptyProposerError Code = 14 + CodeEmptyTimestampError Code = 15 + CodeInvalidTransactionCountError Code = 16 + CodeEmptyAccountError Code = 17 + CodeNilPoolError Code = 18 + CodeEmptyNameError Code = 19 + CodeEmptyAddressError Code = 20 + CodeInvalidAddressLenError Code = 21 + CodeInvalidNonceError Code = 22 + CodeInvalidAmountError Code = 23 + CodeProtoMarshalError Code = 25 + CodeProtoUnmarshalError Code = 26 + CodeProtoNewAnyError Code = 27 + CodeProtoFromAnyError Code = 28 + CodeNewFeeFromStringError Code = 29 + CodeEmptyNonceError Code = 30 + CodeEmptyPublicKeyError Code = 31 + CodeEmptySignatureError Code = 32 + CodeDuplicateTransactionError Code = 35 + CodeTransactionSignError Code = 36 + CodeGetAllValidatorsError Code = 37 + CodeInterfaceConversionError Code = 38 + CodeGetAccountAmountError Code = 39 + CodeStringToBigIntError Code = 40 + CodeInsufficientAmountError Code = 41 CodeAddAccountAmountError Code = 42 CodeSetAccountError Code = 43 CodeGetParamError Code = 44 @@ -75,41 +118,47 @@ const ( CodeUnknownParamError Code = 85 CodeUnauthorizedParamChangeError Code = 86 CodeInvalidParamValueError Code = 87 - - CodeGetServiceNodesPerSessionAtError Code = 89 - CodeGetBlockHashError Code = 90 - CodeGetServiceNodeCountError Code = 91 - CodeEmptyParamKeyError Code = 92 - CodeEmptyParamValueError Code = 93 - CodeGetOutputAddressError Code = 94 - CodeTransactionAlreadyCommittedError Code = 95 - - CodeNewPersistenceContextError Code = 100 - CodeGetAppHashError Code = 101 - CodeNewSavePointError Code = 102 - CodeRollbackSavePointError Code = 103 - CodeResetContextError Code = 104 - CodeCommitContextError Code = 105 - CodeReleaseContextError Code = 106 - - CodeSetPoolError Code = 110 - CodeDuplicateSavePointError Code = 111 - CodeSavePointNotFoundError Code = 112 - CodeEmptySavePointsError Code = 113 - CodeInvalidEvidenceTypeError Code = 114 - CodeExportStateError Code = 115 - CodeUnequalHeightsError Code = 116 - CodeSetMissedBlocksError Code = 117 - - CodeMissingRequiredArgError Code = 118 // TODO(derrandz): revisit whether this is needed - CodeSocketRequestTimedOutError Code = 119 - CodeUndefinedSocketTypeError Code = 120 - CodePeerHangUpError Code = 121 - CodeUnexpectedSocketError Code = 122 - CodePayloadTooBigError Code = 123 - CodeSocketIOStartFailedError Code = 124 - CodeGetStakeAmountError Code = 125 - CodeStakeLessError Code = 126 + CodeUpdateParamError Code = 88 + CodeGetServiceNodesPerSessionAtError Code = 89 + CodeGetBlockHashError Code = 90 + CodeGetServiceNodeCountError Code = 91 + CodeEmptyParamKeyError Code = 92 + CodeEmptyParamValueError Code = 93 + CodeGetOutputAddressError Code = 94 + CodeTransactionAlreadyCommittedError Code = 95 + CodeInitParamsError Code = 96 + CodeGetAllFishermenError Code = 97 + CodeGetAllServiceNodesError Code = 98 + CodeGetAllAppsError Code = 99 + CodeNewPersistenceContextError Code = 100 + CodeGetAppHashError Code = 101 + CodeNewSavePointError Code = 102 + CodeRollbackSavePointError Code = 103 + CodeResetContextError Code = 104 + CodeCommitContextError Code = 105 + CodeReleaseContextError Code = 106 + CodeGetAllPoolsError Code = 107 + CodeGetAllAccountsError Code = 108 + CodeGetAllParamsError Code = 109 + CodeSetPoolError Code = 110 + CodeDuplicateSavePointError Code = 111 + CodeSavePointNotFoundError Code = 112 + CodeEmptySavePointsError Code = 113 + CodeInvalidEvidenceTypeError Code = 114 + CodeExportStateError Code = 115 + CodeUnequalHeightsError Code = 116 + CodeSetMissedBlocksError Code = 117 + CodeNegativeAmountError Code = 118 + CodeNilQuorumCertificateError Code = 119 + CodeMissingRequiredArgError Code = 120 + CodeSocketRequestTimedOutError Code = 121 + CodeUndefinedSocketTypeError Code = 122 + CodePeerHangUpError Code = 123 + CodeUnexpectedSocketError Code = 124 + CodePayloadTooBigError Code = 125 + CodeSocketIOStartFailedError Code = 126 + CodeGetStakeAmountError Code = 127 + CodeStakeLessError Code = 128 GetStakedTokensError = "an error occurred getting the validator staked tokens" SetValidatorStakedTokensError = "an error occurred setting the validator staked tokens" @@ -197,14 +246,44 @@ const ( ExportStateError = "an error occurred exporting the state" UnequalHeightsError = "the heights are not equal" SetMissedBlocksError = "an error occurred setting missed blocks" - - MissingRequiredArgError = "socket error: missing required argument." - SocketRequestTimedOutError = "socket error: request timed out while waiting on ACK." - UndefinedSocketTypeError = "socket error: undefined given socket type." - PeerHangUpError = "socket error: Peer hang up." - UnexpectedSocketError = "socket error: Unexpected peer error." - PayloadTooBigError = "socket error: payload size is too big. " - SocketIOStartFailedError = "socket error: failed to start socket reading/writing (io)" + MissingRequiredArgError = "socket error: missing required argument." + SocketRequestTimedOutError = "socket error: request timed out while waiting on ACK." + UndefinedSocketTypeError = "socket error: undefined given socket type." + PeerHangUpError = "socket error: Peer hang up." + UnexpectedSocketError = "socket error: Unexpected peer error." + PayloadTooBigError = "socket error: payload size is too big. " + SocketIOStartFailedError = "socket error: failed to start socket reading/writing (io)" + EmptyTransactionError = "the transaction is empty" + StringToBigIntError = "an error occurred converting the string primitive to big.Int, the conversion was unsuccessful with base 10" + GetAllValidatorsError = "an error occurred getting all validators from the state" + InvalidAmountError = "the amount field is invalid; cannot be converted to big.Int" + InvalidAddressLenError = "the length of the address is not valid" + EmptyAddressError = "the address field is empty" + EmptyNameError = "the name field is empty" + NilPoolError = "the pool is nil" + EmptyAccountError = "the account is nil" + NewAddressFromBytesError = "unable to convert the raw bytes to a valid address" + InvalidTransactionCountError = "the total transactions are less than the block transactions" + EmptyTimestampError = "the timestamp field is empty" + EmptyProposerError = "the proposer field is empty" + EmptyNetworkIDError = "the network id field is empty" + InvalidHashLengthError = "the length of the hash is not the correct size" + NilQuorumCertificateError = "the quorum certificate is nil" + HexDecodeFromStringError = "an error occurred decoding the string into hex bytes" + ProtoMarshalError = "an error occurred marshalling the structure in protobuf" + ProtoUnmarshalError = "an error occurred unmarshalling the structure in protobuf" + ProtoNewAnyError = "an error occurred creating the protobuf any" + UpdateParamError = "an error occurred updating the parameter" + InitParamsError = "an error occurred initializing the params in genesis" + GetAllFishermenError = "an error occurred getting all of the fishermen¬" + GetAllAppsError = "an error occurred getting all of the apps" + GetAllServiceNodesError = "an error occurred getting all of the service nodes" + GetAllPoolsError = "an error occurred getting all of the pools" + GetAllAccountsError = "an error occurred getting all of the accounts" + GetAllParamsError = "an error occurred getting all of the params" + DuplicateTransactionError = "the transaction is already found in the mempool" + InsufficientAmountError = "the account has insufficient funds to complete the operation" + NegativeAmountError = "the amount is negative" ) func ErrUnknownParam(paramName string) Error { @@ -580,4 +659,129 @@ func ErrSocketIOStartFailed(socketType string) error { return NewError(CodeSocketIOStartFailedError, fmt.Sprintf("%s: (%s socket)", SocketIOStartFailedError, socketType)) } +func ErrDuplicateTransaction() Error { + return NewError(CodeDuplicateTransactionError, DuplicateTransactionError) +} + +func ErrStringToBigInt() Error { + return NewError(CodeStringToBigIntError, StringToBigIntError) +} + +// TODO: We should pass the account address here so it is easier to debug the issue +func ErrInsufficientAmount() Error { + return NewError(CodeInsufficientAmountError, fmt.Sprintf("%s", InsufficientAmountError)) +} + +func ErrNegativeAmountError() Error { + return NewError(CodeNegativeAmountError, fmt.Sprintf("%s", NegativeAmountError)) +} + +func ErrGetAllValidators(err error) Error { + return NewError(CodeGetAllValidatorsError, fmt.Sprintf("%s: %s", GetAllValidatorsError, err.Error())) +} + +func ErrGetAllFishermen(err error) Error { + return NewError(CodeGetAllFishermenError, fmt.Sprintf("%s: %s", GetAllFishermenError, err.Error())) +} + +func ErrGetAllApps(err error) Error { + return NewError(CodeGetAllAppsError, fmt.Sprintf("%s: %s", GetAllAppsError, err.Error())) +} + +func ErrGetAllServiceNodes(err error) Error { + return NewError(CodeGetAllServiceNodesError, fmt.Sprintf("%s: %s", GetAllServiceNodesError, err.Error())) +} + +func ErrGetAllPools(err error) Error { + return NewError(CodeGetAllPoolsError, fmt.Sprintf("%s: %s", GetAllPoolsError, err.Error())) +} + +func ErrGetAllAccounts(err error) Error { + return NewError(CodeGetAllAccountsError, fmt.Sprintf("%s: %s", GetAllAccountsError, err.Error())) +} + +func ErrGetAllParams(err error) Error { + return NewError(CodeGetAllParamsError, fmt.Sprintf("%s: %s", GetAllParamsError, err.Error())) +} + +func ErrHexDecodeFromString(err error) Error { + return NewError(CodeHexDecodeFromStringError, fmt.Sprintf("%s: %s", HexDecodeFromStringError, err.Error())) +} + +func ErrEmptyAccount() Error { + return NewError(CodeEmptyAccountError, EmptyAccountError) +} + +func ErrEmptyAddress() Error { + return NewError(CodeEmptyAddressError, EmptyAddressError) +} + +func ErrInvalidAddressLen(err error) Error { + return NewError(CodeInvalidAddressLenError, fmt.Sprintf("%s: %s", InvalidAddressLenError, err.Error())) +} + +func ErrInvalidAmount() Error { + return NewError(CodeInvalidAmountError, InvalidAmountError) +} + +func ErrEmptyName() Error { + return NewError(CodeEmptyNameError, EmptyNameError) +} + +func ErrNilPool() Error { + return NewError(CodeNilPoolError, NilPoolError) +} + +func ErrEmptyNetworkID() Error { + return NewError(CodeEmptyNetworkIDError, EmptyNetworkIDError) +} + +func ErrEmptyProposer() Error { + return NewError(CodeEmptyProposerError, EmptyProposerError) +} + +func ErrEmptyTimestamp() Error { + return NewError(CodeEmptyTimestampError, EmptyTimestampError) +} + +func EmptyTransactionErr() Error { + return NewError(CodeEmptyTransactionError, EmptyTransactionError) +} + +func ErrInvalidTransactionCount() Error { + return NewError(CodeInvalidTransactionCountError, InvalidTransactionCountError) +} + +func ErrInvalidHashLength(err error) Error { + return NewError(CodeInvalidHashLengthError, fmt.Sprintf("%s: %s", InvalidHashLengthError, err.Error())) +} + +func ErrNilQuorumCertificate() Error { + return NewError(CodeNilQuorumCertificateError, NilQuorumCertificateError) +} + +func ErrNewAddressFromBytes(err error) Error { + return NewError(CodeNewAddressFromBytesError, fmt.Sprintf("%s: %s", NewAddressFromBytesError, err.Error())) +} + +func ErrProtoMarshal(err error) Error { + return NewError(CodeProtoMarshalError, fmt.Sprintf("%s: %s", ProtoMarshalError, err.Error())) +} + +func ErrProtoUnmarshal(err error) Error { + return NewError(CodeProtoUnmarshalError, fmt.Sprintf("%s: %s", ProtoUnmarshalError, err.Error())) +} + +func ErrProtoNewAny(err error) Error { + return NewError(CodeProtoNewAnyError, fmt.Sprintf("%s: %s", ProtoNewAnyError, err.Error())) +} + +func ErrUpdateParam(err error) Error { + return NewError(CodeUpdateParamError, fmt.Sprintf("%s: %s", UpdateParamError, err.Error())) +} + +func ErrInitParams(err error) Error { + return NewError(CodeInitParamsError, fmt.Sprintf("%s: %s", InitParamsError, err.Error())) +} + // TODO: Consider adding `ErrUnknownActorType` everywhere we do a switch-case on actor type. diff --git a/shared/types/mempool.go b/utility/types/mempool.go similarity index 97% rename from shared/types/mempool.go rename to utility/types/mempool.go index e7342a86d..e08535ec0 100644 --- a/shared/types/mempool.go +++ b/utility/types/mempool.go @@ -22,7 +22,6 @@ type Mempool interface { var _ Mempool = &FIFOMempool{} -// TODO(pocket/issues/163): Move implementation to utility #163 type FIFOMempool struct { l sync.RWMutex hashMap map[string]struct{} diff --git a/utility/types/message.go b/utility/types/message.go index 68c36d852..77b81d4b4 100644 --- a/utility/types/message.go +++ b/utility/types/message.go @@ -7,7 +7,6 @@ import ( "strings" cryptoPocket "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" "google.golang.org/protobuf/proto" ) @@ -22,7 +21,7 @@ validations possible before even checking the state storage layer. const ( MillionInt = 1000000 ZeroInt = 0 - HeightNotUsed = -1 + HeightNotUsed = int64(-1) EmptyString = "" HttpsPrefix = "https://" HttpPrefix = "http://" @@ -40,11 +39,11 @@ type Message interface { proto.Message SetSigner(signer []byte) - ValidateBasic() types.Error - GetActorType() ActorType + ValidateBasic() Error + GetActorType() UtilActorType } -func (msg *MessageStake) ValidateBasic() types.Error { +func (msg *MessageStake) ValidateBasic() Error { if err := ValidatePublicKey(msg.GetPublicKey()); err != nil { return err } @@ -54,14 +53,14 @@ func (msg *MessageStake) ValidateBasic() types.Error { return ValidateStaker(msg) } -func (msg *MessageEditStake) ValidateBasic() types.Error { +func (msg *MessageEditStake) ValidateBasic() Error { if err := ValidateAddress(msg.GetAddress()); err != nil { return err } return ValidateStaker(msg) } -func (msg *MessageDoubleSign) ValidateBasic() types.Error { +func (msg *MessageDoubleSign) ValidateBasic() Error { if err := msg.VoteA.ValidateBasic(); err != nil { return err } @@ -69,24 +68,24 @@ func (msg *MessageDoubleSign) ValidateBasic() types.Error { return err } if !bytes.Equal(msg.VoteA.PublicKey, msg.VoteB.PublicKey) { - return types.ErrUnequalPublicKeys() + return ErrUnequalPublicKeys() } if msg.VoteA.Type != msg.VoteB.Type { - return types.ErrUnequalVoteTypes() + return ErrUnequalVoteTypes() } if msg.VoteA.Height != msg.VoteB.Height { - return types.ErrUnequalHeights() + return ErrUnequalHeights() } if msg.VoteA.Round != msg.VoteB.Round { - return types.ErrUnequalRounds() + return ErrUnequalRounds() } if bytes.Equal(msg.VoteA.BlockHash, msg.VoteB.BlockHash) { - return types.ErrEqualVotes() + return ErrEqualVotes() } return nil } -func (msg *MessageSend) ValidateBasic() types.Error { +func (msg *MessageSend) ValidateBasic() Error { if err := ValidateAddress(msg.FromAddress); err != nil { return err } @@ -99,12 +98,12 @@ func (msg *MessageSend) ValidateBasic() types.Error { return nil } -func (msg *MessageChangeParameter) ValidateBasic() types.Error { +func (msg *MessageChangeParameter) ValidateBasic() Error { if msg.ParameterKey == "" { - return types.ErrEmptyParamKey() + return ErrEmptyParamKey() } if msg.ParameterValue == nil { - return types.ErrEmptyParamValue() + return ErrEmptyParamValue() } if err := ValidateAddress(msg.Owner); err != nil { return err @@ -112,67 +111,67 @@ func (msg *MessageChangeParameter) ValidateBasic() types.Error { return nil } -func (msg *MessageUnstake) ValidateBasic() types.Error { return ValidateAddress(msg.Address) } -func (msg *MessageUnpause) ValidateBasic() types.Error { return ValidateAddress(msg.Address) } -func (msg *MessageStake) SetSigner(signer []byte) { msg.Signer = signer } -func (msg *MessageEditStake) SetSigner(signer []byte) { msg.Signer = signer } -func (msg *MessageUnstake) SetSigner(signer []byte) { msg.Signer = signer } -func (msg *MessageUnpause) SetSigner(signer []byte) { msg.Signer = signer } -func (msg *MessageDoubleSign) SetSigner(signer []byte) { msg.ReporterAddress = signer } -func (msg *MessageSend) SetSigner(signer []byte) { /*no op*/ } -func (msg *MessageChangeParameter) SetSigner(signer []byte) { msg.Signer = signer } -func (x *MessageChangeParameter) GetActorType() ActorType { return -1 } -func (x *MessageDoubleSign) GetActorType() ActorType { return -1 } +func (msg *MessageUnstake) ValidateBasic() Error { return ValidateAddress(msg.Address) } +func (msg *MessageUnpause) ValidateBasic() Error { return ValidateAddress(msg.Address) } +func (msg *MessageStake) SetSigner(signer []byte) { msg.Signer = signer } +func (msg *MessageEditStake) SetSigner(signer []byte) { msg.Signer = signer } +func (msg *MessageUnstake) SetSigner(signer []byte) { msg.Signer = signer } +func (msg *MessageUnpause) SetSigner(signer []byte) { msg.Signer = signer } +func (msg *MessageDoubleSign) SetSigner(signer []byte) { msg.ReporterAddress = signer } +func (msg *MessageSend) SetSigner(signer []byte) { /*no op*/ } +func (msg *MessageChangeParameter) SetSigner(signer []byte) { msg.Signer = signer } +func (x *MessageChangeParameter) GetActorType() UtilActorType { return -1 } +func (x *MessageDoubleSign) GetActorType() UtilActorType { return -1 } // helpers -func ValidateAddress(address []byte) types.Error { +func ValidateAddress(address []byte) Error { if address == nil { - return types.ErrEmptyAddress() + return ErrEmptyAddress() } addrLen := len(address) if addrLen != cryptoPocket.AddressLen { - return types.ErrInvalidAddressLen(cryptoPocket.ErrInvalidAddressLen(addrLen)) + return ErrInvalidAddressLen(cryptoPocket.ErrInvalidAddressLen(addrLen)) } return nil } -func ValidateOutputAddress(address []byte) types.Error { +func ValidateOutputAddress(address []byte) Error { if address == nil { - return types.ErrNilOutputAddress() + return ErrNilOutputAddress() } addrLen := len(address) if addrLen != cryptoPocket.AddressLen { - return types.ErrInvalidAddressLen(cryptoPocket.ErrInvalidAddressLen(addrLen)) + return ErrInvalidAddressLen(cryptoPocket.ErrInvalidAddressLen(addrLen)) } return nil } -func ValidatePublicKey(publicKey []byte) types.Error { +func ValidatePublicKey(publicKey []byte) Error { if publicKey == nil { - return types.ErrEmptyPublicKey() + return ErrEmptyPublicKey() } pubKeyLen := len(publicKey) if pubKeyLen != cryptoPocket.PublicKeyLen { - return types.ErrInvalidPublicKeylen(cryptoPocket.ErrInvalidPublicKeyLen(pubKeyLen)) + return ErrInvalidPublicKeylen(cryptoPocket.ErrInvalidPublicKeyLen(pubKeyLen)) } return nil } -func ValidateHash(hash []byte) types.Error { +func ValidateHash(hash []byte) Error { if hash == nil { - return types.ErrEmptyHash() + return ErrEmptyHash() } hashLen := len(hash) if hashLen != cryptoPocket.SHA3HashLen { - return types.ErrInvalidHashLength(cryptoPocket.ErrInvalidHashLen(hashLen)) + return ErrInvalidHashLength(cryptoPocket.ErrInvalidHashLen(hashLen)) } return nil } -func ValidateRelayChains(chains []string) types.Error { +func ValidateRelayChains(chains []string) Error { if chains == nil { - return types.ErrEmptyRelayChains() + return ErrEmptyRelayChains() } for _, chain := range chains { relayChain := RelayChain(chain) @@ -183,46 +182,46 @@ func ValidateRelayChains(chains []string) types.Error { return nil } -func ValidateAmount(amount string) types.Error { +func ValidateAmount(amount string) Error { if amount == "" { - return types.ErrEmptyAmount() + return ErrEmptyAmount() } - if _, err := types.StringToBigInt(amount); err != nil { + if _, err := StringToBigInt(amount); err != nil { return err } return nil } -func ValidateActorType(_ ActorType) types.Error { +func ValidateActorType(_ UtilActorType) Error { // TODO (team) not sure if there's anything we can do here return nil } -func ValidateServiceUrl(actorType ActorType, uri string) types.Error { - if actorType == ActorType_App { +func ValidateServiceUrl(actorType UtilActorType, uri string) Error { + if actorType == UtilActorType_App { return nil } uri = strings.ToLower(uri) _, err := url.ParseRequestURI(uri) if err != nil { - return types.ErrInvalidServiceUrl(err.Error()) + return ErrInvalidServiceUrl(err.Error()) } if !(uri[:8] == HttpsPrefix || uri[:7] == HttpPrefix) { - return types.ErrInvalidServiceUrl(InvalidURLPrefix) + return ErrInvalidServiceUrl(InvalidURLPrefix) } temp := strings.Split(uri, Colon) if len(temp) != 3 { - return types.ErrInvalidServiceUrl(PortRequired) + return ErrInvalidServiceUrl(PortRequired) } port, err := strconv.Atoi(temp[2]) if err != nil { - return types.ErrInvalidServiceUrl(NonNumberPort) + return ErrInvalidServiceUrl(NonNumberPort) } if port > MaxPort || port < 0 { - return types.ErrInvalidServiceUrl(PortOutOfRange) + return ErrInvalidServiceUrl(PortOutOfRange) } if !strings.Contains(uri, Period) { - return types.ErrInvalidServiceUrl(NoPeriod) + return ErrInvalidServiceUrl(NoPeriod) } return nil } @@ -237,25 +236,25 @@ const ( type RelayChain string // TODO: Consider adding a governance parameter for a list of valid relay chains -func (rc *RelayChain) Validate() types.Error { +func (rc *RelayChain) Validate() Error { if rc == nil || *rc == "" { - return types.ErrEmptyRelayChain() + return ErrEmptyRelayChain() } rcLen := len(*rc) if rcLen != RelayChainLength { - return types.ErrInvalidRelayChainLength(rcLen, RelayChainLength) + return ErrInvalidRelayChainLength(rcLen, RelayChainLength) } return nil } type MessageStaker interface { - GetActorType() ActorType + GetActorType() UtilActorType GetAmount() string GetChains() []string GetServiceUrl() string } -func ValidateStaker(msg MessageStaker) types.Error { +func ValidateStaker(msg MessageStaker) Error { if err := ValidateActorType(msg.GetActorType()); err != nil { return err } diff --git a/utility/types/message_test.go b/utility/types/message_test.go index 5546da3d5..2ddbae64b 100644 --- a/utility/types/message_test.go +++ b/utility/types/message_test.go @@ -1,11 +1,11 @@ package types import ( + "github.com/pokt-network/pocket/shared/codec" "math/big" "testing" "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/wrapperspb" @@ -14,7 +14,7 @@ import ( var ( defaultTestingChains = []string{"0001"} defaultAmountBig = big.NewInt(1000000) - defaultAmount = types.BigIntToString(defaultAmountBig) + defaultAmount = BigIntToString(defaultAmountBig) defaultUnusedLength = -1 ) @@ -22,7 +22,7 @@ func TestMessage_ChangeParameter_ValidateBasic(t *testing.T) { owner, err := crypto.GenerateAddress() require.NoError(t, err) - codec := types.GetCodec() + codec := codec.GetCodec() paramKey := "key" paramValueRaw := wrapperspb.Int32(1) paramValueAny, err := codec.ToAny(paramValueRaw) @@ -39,15 +39,15 @@ func TestMessage_ChangeParameter_ValidateBasic(t *testing.T) { msgMissingOwner := proto.Clone(&msg).(*MessageChangeParameter) msgMissingOwner.Owner = nil - require.Equal(t, types.ErrEmptyAddress().Code(), msgMissingOwner.ValidateBasic().Code()) + require.Equal(t, ErrEmptyAddress().Code(), msgMissingOwner.ValidateBasic().Code()) msgMissingParamKey := proto.Clone(&msg).(*MessageChangeParameter) msgMissingParamKey.ParameterKey = "" - require.Equal(t, types.ErrEmptyParamKey().Code(), msgMissingParamKey.ValidateBasic().Code()) + require.Equal(t, ErrEmptyParamKey().Code(), msgMissingParamKey.ValidateBasic().Code()) msgMissingParamValue := proto.Clone(&msg).(*MessageChangeParameter) msgMissingParamValue.ParameterValue = nil - require.Equal(t, types.ErrEmptyParamValue().Code(), msgMissingParamValue.ValidateBasic().Code()) + require.Equal(t, ErrEmptyParamValue().Code(), msgMissingParamValue.ValidateBasic().Code()) } func TestMessage_DoubleSign_ValidateBasic(t *testing.T) { @@ -56,14 +56,14 @@ func TestMessage_DoubleSign_ValidateBasic(t *testing.T) { hashA := crypto.SHA3Hash(pk.Bytes()) hashB := crypto.SHA3Hash(pk.Address()) - voteA := &Vote{ + voteA := &LegacyVote{ PublicKey: pk.Bytes(), Height: 1, Round: 2, Type: DoubleSignEvidenceType, BlockHash: hashA, } - voteB := &Vote{ + voteB := &LegacyVote{ PublicKey: pk.Bytes(), Height: 1, Round: 2, @@ -82,32 +82,32 @@ func TestMessage_DoubleSign_ValidateBasic(t *testing.T) { pk2, err := crypto.GeneratePublicKey() require.NoError(t, err) msgUnequalPubKeys := new(MessageDoubleSign) - msgUnequalPubKeys.VoteA = proto.Clone(msg.VoteA).(*Vote) - msgUnequalPubKeys.VoteB = proto.Clone(msg.VoteB).(*Vote) + msgUnequalPubKeys.VoteA = proto.Clone(msg.VoteA).(*LegacyVote) + msgUnequalPubKeys.VoteB = proto.Clone(msg.VoteB).(*LegacyVote) msgUnequalPubKeys.VoteA.PublicKey = pk2.Bytes() er = msgUnequalPubKeys.ValidateBasic() - require.Equal(t, types.ErrUnequalPublicKeys().Code(), er.Code()) + require.Equal(t, ErrUnequalPublicKeys().Code(), er.Code()) msgUnequalHeights := new(MessageDoubleSign) - msgUnequalHeights.VoteA = proto.Clone(msg.VoteA).(*Vote) - msgUnequalHeights.VoteB = proto.Clone(msg.VoteB).(*Vote) + msgUnequalHeights.VoteA = proto.Clone(msg.VoteA).(*LegacyVote) + msgUnequalHeights.VoteB = proto.Clone(msg.VoteB).(*LegacyVote) msgUnequalHeights.VoteA.Height = 2 er = msgUnequalHeights.ValidateBasic() - require.Equal(t, types.ErrUnequalHeights().Code(), er.Code()) + require.Equal(t, ErrUnequalHeights().Code(), er.Code()) msgUnequalRounds := new(MessageDoubleSign) - msgUnequalRounds.VoteA = proto.Clone(msg.VoteA).(*Vote) - msgUnequalRounds.VoteB = proto.Clone(msg.VoteB).(*Vote) + msgUnequalRounds.VoteA = proto.Clone(msg.VoteA).(*LegacyVote) + msgUnequalRounds.VoteB = proto.Clone(msg.VoteB).(*LegacyVote) msgUnequalRounds.VoteA.Round = 1 er = msgUnequalRounds.ValidateBasic() - require.Equal(t, types.ErrUnequalRounds().Code(), er.Code()) + require.Equal(t, ErrUnequalRounds().Code(), er.Code()) msgEqualVoteHash := new(MessageDoubleSign) - msgEqualVoteHash.VoteA = proto.Clone(msg.VoteA).(*Vote) - msgEqualVoteHash.VoteB = proto.Clone(msg.VoteB).(*Vote) + msgEqualVoteHash.VoteA = proto.Clone(msg.VoteA).(*LegacyVote) + msgEqualVoteHash.VoteB = proto.Clone(msg.VoteB).(*LegacyVote) msgEqualVoteHash.VoteB.BlockHash = hashA er = msgEqualVoteHash.ValidateBasic() - require.Equal(t, types.ErrEqualVotes().Code(), er.Code()) + require.Equal(t, ErrEqualVotes().Code(), er.Code()) } func TestMessage_EditStake_ValidateBasic(t *testing.T) { @@ -125,33 +125,33 @@ func TestMessage_EditStake_ValidateBasic(t *testing.T) { msgMissingAmount := proto.Clone(&msg).(*MessageEditStake) msgMissingAmount.Amount = "" er := msgMissingAmount.ValidateBasic() - require.Equal(t, types.ErrEmptyAmount().Code(), er.Code()) + require.Equal(t, ErrEmptyAmount().Code(), er.Code()) msgInvalidAmount := proto.Clone(&msg).(*MessageEditStake) msgInvalidAmount.Amount = "sdk" er = msgInvalidAmount.ValidateBasic() - require.Equal(t, types.ErrStringToBigInt().Code(), er.Code()) + require.Equal(t, ErrStringToBigInt().Code(), er.Code()) msgEmptyAddress := proto.Clone(&msg).(*MessageEditStake) msgEmptyAddress.Address = nil er = msgEmptyAddress.ValidateBasic() - require.Equal(t, types.ErrEmptyAddress().Code(), er.Code()) + require.Equal(t, ErrEmptyAddress().Code(), er.Code()) msgInvalidAddress := proto.Clone(&msg).(*MessageEditStake) msgInvalidAddress.Address = []byte("badAddr") er = msgInvalidAddress.ValidateBasic() - expectedErr := types.ErrInvalidAddressLen(crypto.ErrInvalidAddressLen(defaultUnusedLength)) + expectedErr := ErrInvalidAddressLen(crypto.ErrInvalidAddressLen(defaultUnusedLength)) require.Equal(t, expectedErr.Code(), er.Code()) msgEmptyRelayChains := proto.Clone(&msg).(*MessageEditStake) msgEmptyRelayChains.Chains = nil er = msgEmptyRelayChains.ValidateBasic() - require.Equal(t, types.ErrEmptyRelayChains().Code(), er.Code()) + require.Equal(t, ErrEmptyRelayChains().Code(), er.Code()) msgInvalidRelayChains := proto.Clone(&msg).(*MessageEditStake) msgInvalidRelayChains.Chains = []string{"notAValidRelayChain"} er = msgInvalidRelayChains.ValidateBasic() - expectedErr = types.ErrInvalidRelayChainLength(0, RelayChainLength) + expectedErr = ErrInvalidRelayChainLength(0, RelayChainLength) require.Equal(t, expectedErr.Code(), er.Code()) } @@ -173,22 +173,22 @@ func TestMessageSend_ValidateBasic(t *testing.T) { msgMissingAddress := proto.Clone(&msg).(*MessageSend) msgMissingAddress.FromAddress = nil er = msgMissingAddress.ValidateBasic() - require.Equal(t, types.ErrEmptyAddress().Code(), er.Code()) + require.Equal(t, ErrEmptyAddress().Code(), er.Code()) msgMissingToAddress := proto.Clone(&msg).(*MessageSend) msgMissingToAddress.ToAddress = nil er = msgMissingToAddress.ValidateBasic() - require.Equal(t, types.ErrEmptyAddress().Code(), er.Code()) + require.Equal(t, ErrEmptyAddress().Code(), er.Code()) msgMissingAmount := proto.Clone(&msg).(*MessageSend) msgMissingAmount.Amount = "" er = msgMissingAmount.ValidateBasic() - require.Equal(t, types.ErrEmptyAmount().Code(), er.Code()) + require.Equal(t, ErrEmptyAmount().Code(), er.Code()) msgInvalidAmount := proto.Clone(&msg).(*MessageSend) msgInvalidAmount.Amount = "" er = msgInvalidAmount.ValidateBasic() - require.Equal(t, types.ErrEmptyAmount().Code(), er.Code()) + require.Equal(t, ErrEmptyAmount().Code(), er.Code()) } func TestMessageStake_ValidateBasic(t *testing.T) { @@ -207,22 +207,22 @@ func TestMessageStake_ValidateBasic(t *testing.T) { msgEmptyPubKey := proto.Clone(&msg).(*MessageStake) msgEmptyPubKey.PublicKey = nil er = msgEmptyPubKey.ValidateBasic() - require.Equal(t, types.ErrEmptyPublicKey().Code(), er.Code()) + require.Equal(t, ErrEmptyPublicKey().Code(), er.Code()) msgEmptyChains := proto.Clone(&msg).(*MessageStake) msgEmptyChains.Chains = nil er = msgEmptyChains.ValidateBasic() - require.Equal(t, types.ErrEmptyRelayChains().Code(), er.Code()) + require.Equal(t, ErrEmptyRelayChains().Code(), er.Code()) msgEmptyAmount := proto.Clone(&msg).(*MessageStake) msgEmptyAmount.Amount = "" er = msgEmptyAmount.ValidateBasic() - require.Equal(t, types.ErrEmptyAmount().Code(), er.Code()) + require.Equal(t, ErrEmptyAmount().Code(), er.Code()) msgEmptyOutputAddress := proto.Clone(&msg).(*MessageStake) msgEmptyOutputAddress.OutputAddress = nil er = msgEmptyOutputAddress.ValidateBasic() - require.Equal(t, types.ErrNilOutputAddress().Code(), er.Code()) + require.Equal(t, ErrNilOutputAddress().Code(), er.Code()) } func TestMessageUnstake_ValidateBasic(t *testing.T) { @@ -238,7 +238,7 @@ func TestMessageUnstake_ValidateBasic(t *testing.T) { msgMissingAddress := proto.Clone(&msg).(*MessageUnstake) msgMissingAddress.Address = nil er = msgMissingAddress.ValidateBasic() - require.Equal(t, types.ErrEmptyAddress().Code(), er.Code()) + require.Equal(t, ErrEmptyAddress().Code(), er.Code()) } func TestMessageUnpause_ValidateBasic(t *testing.T) { @@ -254,7 +254,7 @@ func TestMessageUnpause_ValidateBasic(t *testing.T) { msgMissingAddress := proto.Clone(&msg).(*MessageUnpause) msgMissingAddress.Address = nil er = msgMissingAddress.ValidateBasic() - require.Equal(t, types.ErrEmptyAddress().Code(), er.Code()) + require.Equal(t, ErrEmptyAddress().Code(), er.Code()) } func TestRelayChain_Validate(t *testing.T) { @@ -263,12 +263,12 @@ func TestRelayChain_Validate(t *testing.T) { require.NoError(t, err) relayChainInvalidLength := RelayChain("001") - expectedError := types.ErrInvalidRelayChainLength(0, RelayChainLength) + expectedError := ErrInvalidRelayChainLength(0, RelayChainLength) err = relayChainInvalidLength.Validate() require.Equal(t, expectedError.Code(), err.Code()) relayChainEmpty := RelayChain("") - expectedError = types.ErrEmptyRelayChain() + expectedError = ErrEmptyRelayChain() err = relayChainEmpty.Validate() require.Equal(t, expectedError.Code(), err.Code()) } diff --git a/utility/proto/message.proto b/utility/types/proto/message.proto similarity index 64% rename from utility/proto/message.proto rename to utility/types/proto/message.proto index 64d71a0f5..4471b9642 100644 --- a/utility/proto/message.proto +++ b/utility/types/proto/message.proto @@ -3,15 +3,20 @@ package utility; option go_package = "github.com/pokt-network/pocket/utility/types"; -import "actor_types.proto"; -import "vote.proto"; import "google/protobuf/any.proto"; +enum UtilActorType { // TODO (team) deprecate for persistence/actorType + App = 0; + Node = 1; + Fish = 2; + Val = 3; +} + message MessageSend { bytes from_address = 1; bytes to_address = 2; string amount = 3; - ActorType actor_type = 4; + UtilActorType actor_type = 4; } message MessageStake { @@ -21,7 +26,7 @@ message MessageStake { string service_url = 4; bytes output_address = 5; optional bytes signer = 6; - ActorType actor_type = 7; + UtilActorType actor_type = 7; } message MessageEditStake { @@ -30,19 +35,19 @@ message MessageEditStake { string amount = 3; string service_url = 4; optional bytes signer = 5; - ActorType actor_type = 6; + UtilActorType actor_type = 6; } message MessageUnstake { bytes address = 1; optional bytes signer = 2; - ActorType actor_type = 3; + UtilActorType actor_type = 3; } message MessageUnpause { bytes address = 1; optional bytes signer = 2; - ActorType actor_type = 3; + UtilActorType actor_type = 3; } message MessageChangeParameter { @@ -53,7 +58,16 @@ message MessageChangeParameter { } message MessageDoubleSign { - utility.Vote vote_a = 1; - utility.Vote vote_b = 2; + utility.LegacyVote vote_a = 1; + utility.LegacyVote vote_b = 2; optional bytes reporter_address = 3; +} + +// TECHDEBT: Consolidate this with consensus +message LegacyVote { + bytes public_key = 1; + int64 height = 2; + uint32 round = 3; + uint32 type = 4; + bytes block_hash = 5; } \ No newline at end of file diff --git a/utility/proto/transaction.proto b/utility/types/proto/transaction.proto similarity index 91% rename from utility/proto/transaction.proto rename to utility/types/proto/transaction.proto index 7fa03ce31..082c02516 100644 --- a/utility/proto/transaction.proto +++ b/utility/types/proto/transaction.proto @@ -5,7 +5,7 @@ option go_package = "github.com/pokt-network/pocket/utility/types"; import "google/protobuf/any.proto"; -// TECHDEBT: Consolidate this week consensus +// TECHDEBT: Consolidate this with consensus message Transaction { google.protobuf.Any msg = 1; Signature signature = 2; diff --git a/utility/types/proto/util_config.proto b/utility/types/proto/util_config.proto new file mode 100644 index 000000000..409cd0fc7 --- /dev/null +++ b/utility/types/proto/util_config.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; +package utility; + +option go_package = "github.com/pokt-network/pocket/utility/types"; + +message UtilityConfig { + +} \ No newline at end of file diff --git a/utility/types/transaction.go b/utility/types/transaction.go index 1fa93b890..a0275af96 100644 --- a/utility/types/transaction.go +++ b/utility/types/transaction.go @@ -3,41 +3,41 @@ package types import ( "bytes" "encoding/hex" + "github.com/pokt-network/pocket/shared/codec" "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" ) -func TransactionFromBytes(transaction []byte) (*Transaction, types.Error) { +func TransactionFromBytes(transaction []byte) (*Transaction, Error) { tx := &Transaction{} - if err := types.GetCodec().Unmarshal(transaction, tx); err != nil { - return nil, types.ErrUnmarshalTransaction(err) + if err := codec.GetCodec().Unmarshal(transaction, tx); err != nil { + return nil, ErrUnmarshalTransaction(err) } return tx, nil } -func (tx *Transaction) ValidateBasic() types.Error { +func (tx *Transaction) ValidateBasic() Error { if tx.Nonce == "" { - return types.ErrEmptyNonce() + return ErrEmptyNonce() } - if _, err := types.GetCodec().FromAny(tx.Msg); err != nil { - return types.ErrProtoFromAny(err) + if _, err := codec.GetCodec().FromAny(tx.Msg); err != nil { + return ErrProtoFromAny(err) } if tx.Signature == nil || tx.Signature.Signature == nil { - return types.ErrEmptySignature() + return ErrEmptySignature() } if tx.Signature.PublicKey == nil { - return types.ErrEmptyPublicKey() + return ErrEmptyPublicKey() } publicKey, err := crypto.NewPublicKeyFromBytes(tx.Signature.PublicKey) if err != nil { - return types.ErrNewPublicKeyFromBytes(err) + return ErrNewPublicKeyFromBytes(err) } signBytes, err := tx.SignBytes() if err != nil { - return types.ErrProtoMarshal(err) + return ErrProtoMarshal(err) } if ok := publicKey.Verify(signBytes, tx.Signature.Signature); !ok { - return types.ErrSignatureVerificationFailed() + return ErrSignatureVerificationFailed() } if _, err := tx.Message(); err != nil { return err @@ -45,20 +45,20 @@ func (tx *Transaction) ValidateBasic() types.Error { return nil } -func (tx *Transaction) Message() (Message, types.Error) { - codec := types.GetCodec() +func (tx *Transaction) Message() (Message, Error) { + codec := codec.GetCodec() msg, er := codec.FromAny(tx.Msg) if er != nil { - return nil, er + return nil, ErrProtoMarshal(er) } message, ok := msg.(Message) if !ok { - return nil, types.ErrDecodeMessage() + return nil, ErrDecodeMessage() } return message, nil } -func (tx *Transaction) Sign(privateKey crypto.PrivateKey) types.Error { +func (tx *Transaction) Sign(privateKey crypto.PrivateKey) Error { publicKey := privateKey.PublicKey() bz, err := tx.SignBytes() if err != nil { @@ -66,7 +66,7 @@ func (tx *Transaction) Sign(privateKey crypto.PrivateKey) types.Error { } signature, er := privateKey.Sign(bz) if er != nil { - return types.ErrTransactionSign(er) + return ErrTransactionSign(er) } tx.Signature = &Signature{ PublicKey: publicKey.Bytes(), @@ -75,29 +75,29 @@ func (tx *Transaction) Sign(privateKey crypto.PrivateKey) types.Error { return nil } -func (tx *Transaction) Hash() (string, types.Error) { +func (tx *Transaction) Hash() (string, Error) { b, err := tx.Bytes() if err != nil { - return "", types.ErrProtoMarshal(err) + return "", ErrProtoMarshal(err) } return TransactionHash(b), nil } -func (tx *Transaction) SignBytes() ([]byte, types.Error) { +func (tx *Transaction) SignBytes() ([]byte, Error) { // transaction := proto.Clone(tx).(*Transaction) transaction := *tx transaction.Signature = nil - bz, err := types.GetCodec().Marshal(&transaction) + bz, err := codec.GetCodec().Marshal(&transaction) if err != nil { - return nil, types.ErrProtoMarshal(err) + return nil, ErrProtoMarshal(err) } return bz, nil } -func (tx *Transaction) Bytes() ([]byte, types.Error) { - bz, err := types.GetCodec().Marshal(tx) +func (tx *Transaction) Bytes() ([]byte, Error) { + bz, err := codec.GetCodec().Marshal(tx) if err != nil { - return nil, types.ErrProtoMarshal(err) + return nil, ErrProtoMarshal(err) } return bz, nil } diff --git a/utility/types/transaction_test.go b/utility/types/transaction_test.go index b20f62186..07860fa2a 100644 --- a/utility/types/transaction_test.go +++ b/utility/types/transaction_test.go @@ -1,10 +1,10 @@ package types import ( + "github.com/pokt-network/pocket/shared/codec" "testing" "github.com/pokt-network/pocket/shared/crypto" - "github.com/pokt-network/pocket/shared/types" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" ) @@ -25,7 +25,7 @@ func NewTestingMsg(_ *testing.T) Message { } func NewUnsignedTestingTransaction(t *testing.T) Transaction { - codec := types.GetCodec() + codec := codec.GetCodec() msg := NewTestingMsg(t) anyMsg, err := codec.ToAny(msg) @@ -33,7 +33,7 @@ func NewUnsignedTestingTransaction(t *testing.T) Transaction { return Transaction{ Msg: anyMsg, - Nonce: types.BigIntToString(types.RandBigInt()), + Nonce: BigIntToString(RandBigInt()), } } @@ -95,32 +95,32 @@ func TestTransaction_ValidateBasic(t *testing.T) { txNoNonce := proto.Clone(&tx).(*Transaction) txNoNonce.Nonce = "" er = txNoNonce.ValidateBasic() - require.Equal(t, types.ErrEmptyNonce().Code(), er.Code()) + require.Equal(t, ErrEmptyNonce().Code(), er.Code()) txInvalidMessageAny := proto.Clone(&tx).(*Transaction) txInvalidMessageAny.Msg = nil er = txInvalidMessageAny.ValidateBasic() - require.Equal(t, types.ErrProtoFromAny(er).Code(), er.Code()) + require.Equal(t, ErrProtoFromAny(er).Code(), er.Code()) txEmptySig := proto.Clone(&tx).(*Transaction) txEmptySig.Signature = nil er = txEmptySig.ValidateBasic() - require.Equal(t, types.ErrEmptySignature().Code(), er.Code()) + require.Equal(t, ErrEmptySignature().Code(), er.Code()) txEmptyPublicKey := proto.Clone(&tx).(*Transaction) txEmptyPublicKey.Signature.PublicKey = nil er = txEmptyPublicKey.ValidateBasic() - require.Equal(t, types.ErrEmptyPublicKey().Code(), er.Code()) + require.Equal(t, ErrEmptyPublicKey().Code(), er.Code()) txInvalidPublicKey := proto.Clone(&tx).(*Transaction) txInvalidPublicKey.Signature.PublicKey = []byte("publickey") err = txInvalidPublicKey.ValidateBasic() - require.Equal(t, types.ErrNewPublicKeyFromBytes(err).Code(), err.Code()) + require.Equal(t, ErrNewPublicKeyFromBytes(err).Code(), err.Code()) txInvalidSignature := proto.Clone(&tx).(*Transaction) tx.Signature.PublicKey = testingSenderPublicKey.Bytes() txInvalidSignature.Signature.Signature = []byte("signature") er = txInvalidSignature.ValidateBasic() - require.Equal(t, types.ErrSignatureVerificationFailed().Code(), er.Code()) + require.Equal(t, ErrSignatureVerificationFailed().Code(), er.Code()) } diff --git a/shared/types/int.go b/utility/types/util.go similarity index 70% rename from shared/types/int.go rename to utility/types/util.go index 94924b306..a151a08b9 100644 --- a/shared/types/int.go +++ b/utility/types/util.go @@ -2,13 +2,11 @@ package types import ( "crypto/rand" - "encoding/binary" "math/big" ) const ( - HeightNotUsed = int64(-1) - EmptyString = "" + DefaultDenomination = 10 ) var max *big.Int @@ -25,7 +23,7 @@ func RandBigInt() *big.Int { func StringToBigInt(s string) (*big.Int, Error) { b := big.Int{} - i, ok := b.SetString(s, 10) + i, ok := b.SetString(s, DefaultDenomination) if !ok { return nil, ErrStringToBigInt() } @@ -33,7 +31,7 @@ func StringToBigInt(s string) (*big.Int, Error) { } func BigIntToString(b *big.Int) string { - return b.Text(10) + return b.Text(DefaultDenomination) } func BigIntLessThan(a, b *big.Int) bool { @@ -42,9 +40,3 @@ func BigIntLessThan(a, b *big.Int) bool { } return false } - -func Int64ToBytes(i int64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(i)) - return b -} diff --git a/shared/types/int_test.go b/utility/types/util_test.go similarity index 100% rename from shared/types/int_test.go rename to utility/types/util_test.go diff --git a/utility/types/vote.go b/utility/types/vote.go index 53f9fe091..d3d67c7b0 100644 --- a/utility/types/vote.go +++ b/utility/types/vote.go @@ -1,14 +1,12 @@ package types -import "github.com/pokt-network/pocket/shared/types" - const ( DoubleSignEvidenceType = 1 ) // TODO NOTE: there's no signature validation on the vote because we are unsure the current mode of vote signing // TODO *Needs to add signatures to vote structure* -func (v *Vote) ValidateBasic() types.Error { +func (v *LegacyVote) ValidateBasic() Error { if err := ValidatePublicKey(v.PublicKey); err != nil { return err } @@ -16,10 +14,10 @@ func (v *Vote) ValidateBasic() types.Error { return err } if v.Height < 0 { - return types.ErrInvalidBlockHeight() + return ErrInvalidBlockHeight() } if v.Type != DoubleSignEvidenceType { - return types.ErrInvalidEvidenceType() + return ErrInvalidEvidenceType() } return nil }