From 2a7ed4c7c3b3b097070d510e75f6ac11cd5035fb Mon Sep 17 00:00:00 2001 From: unknown <33382781+YuKimura45z@users.noreply.github.com> Date: Fri, 31 Jan 2020 15:05:12 +0900 Subject: [PATCH 1/3] =?UTF-8?q?[update]0.38.0=E9=80=94=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/go.yml | 8 +- .golangci.yml | 60 +++ Dockerfile | 2 +- Makefile | 33 ++ app/app.go | 424 ++++++++++++++++++ app/export.go | 169 +++++++ app/sim_test.go | 298 ++++++++++++ cmd/trustcli/main.go | 78 +++- cmd/trustd/genaccounts.go | 27 +- cmd/trustd/main.go | 75 +++- go.mod | 20 +- go.sum | 96 +++- old/x/trust/alias.go | 35 ++ old/x/trust/client/cli/query.go | 50 +++ old/x/trust/client/cli/tx.go | 124 +++++ old/x/trust/client/rest/query.go | 30 ++ old/x/trust/client/rest/rest.go | 17 + old/x/trust/client/rest/tx.go | 141 ++++++ old/x/trust/genesis.go | 35 ++ old/x/trust/handler.go | 48 ++ .../x}/trust/internal/keeper/distribute.go | 0 old/x/trust/internal/keeper/keeper.go | 62 +++ .../x}/trust/internal/keeper/keeper_test.go | 0 old/x/trust/internal/keeper/querier.go | 40 ++ {x => old/x}/trust/internal/keeper/store.go | 0 old/x/trust/internal/types/codec.go | 19 + old/x/trust/internal/types/errors.go | 23 + old/x/trust/internal/types/key.go | 12 + {x => old/x}/trust/internal/types/msgs.go | 0 .../x}/trust/internal/types/msgs_test.go | 0 old/x/trust/internal/types/querier.go | 12 + old/x/trust/module.go | 130 ++++++ {x => old/x}/trust/spec/01-concepts.md | 0 x/.gitkeep | 0 x/trust/README.md | 7 + x/trust/abci.go | 18 + x/trust/alias.go | 39 +- x/trust/client/cli/query.go | 53 +-- x/trust/client/cli/tx.go | 135 ++---- x/trust/client/rest/query.go | 34 +- x/trust/client/rest/rest.go | 14 +- x/trust/client/rest/tx.go | 136 +----- x/trust/genesis.go | 34 +- x/trust/handler.go | 49 +- x/trust/internal/keeper/keeper.go | 75 ++-- x/trust/internal/keeper/params.go | 22 + x/trust/internal/keeper/querier.go | 38 +- x/trust/internal/types/codec.go | 19 +- x/trust/internal/types/errors.go | 22 +- x/trust/internal/types/events.go | 15 + x/trust/internal/types/expected_keepers.go | 24 + x/trust/internal/types/genesis.go | 29 ++ x/trust/internal/types/key.go | 8 +- x/trust/internal/types/msg.go | 47 ++ x/trust/internal/types/params.go | 60 +++ x/trust/internal/types/querier.go | 26 +- x/trust/module.go | 107 +++-- x/trust/spec/README.md | 17 + 58 files changed, 2560 insertions(+), 536 deletions(-) create mode 100644 .golangci.yml create mode 100644 Makefile create mode 100644 app/app.go create mode 100644 app/export.go create mode 100644 app/sim_test.go create mode 100644 old/x/trust/alias.go create mode 100644 old/x/trust/client/cli/query.go create mode 100644 old/x/trust/client/cli/tx.go create mode 100644 old/x/trust/client/rest/query.go create mode 100644 old/x/trust/client/rest/rest.go create mode 100644 old/x/trust/client/rest/tx.go create mode 100644 old/x/trust/genesis.go create mode 100644 old/x/trust/handler.go rename {x => old/x}/trust/internal/keeper/distribute.go (100%) create mode 100644 old/x/trust/internal/keeper/keeper.go rename {x => old/x}/trust/internal/keeper/keeper_test.go (100%) create mode 100644 old/x/trust/internal/keeper/querier.go rename {x => old/x}/trust/internal/keeper/store.go (100%) create mode 100644 old/x/trust/internal/types/codec.go create mode 100644 old/x/trust/internal/types/errors.go create mode 100644 old/x/trust/internal/types/key.go rename {x => old/x}/trust/internal/types/msgs.go (100%) rename {x => old/x}/trust/internal/types/msgs_test.go (100%) create mode 100644 old/x/trust/internal/types/querier.go create mode 100644 old/x/trust/module.go rename {x => old/x}/trust/spec/01-concepts.md (100%) create mode 100644 x/.gitkeep create mode 100644 x/trust/README.md create mode 100644 x/trust/abci.go create mode 100644 x/trust/internal/keeper/params.go create mode 100644 x/trust/internal/types/events.go create mode 100644 x/trust/internal/types/expected_keepers.go create mode 100644 x/trust/internal/types/genesis.go create mode 100644 x/trust/internal/types/msg.go create mode 100644 x/trust/internal/types/params.go create mode 100644 x/trust/spec/README.md diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 14bd4f2..195363c 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -25,4 +25,10 @@ jobs: fi - name: Build - run: go build -v . + run: | + go build -v ./cmd/trustcli + go build -v ./cmd/trustd + + - name: Test + run: | + go test ./app diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..57c59b1 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,60 @@ +linters: + enable: + - bodyclose + - deadcode + - depguard + - dogsled + - dupl + - errcheck + # - funlen + # - gochecknoglobals + # - gochecknoinits + - goconst + - gocritic + # - gocyclo + # - godox + - gofmt + - goimports + - golint + - gosec + - gosimple + - govet + - ineffassign + - interfacer + - lll + - misspell + # - maligned + - nakedret + - prealloc + - scopelint + - staticcheck + - structcheck + - stylecheck + - typecheck + - unconvert + # - unparam + - unused + - varcheck + # - whitespace + # - wsl + # - gocognit + +linters-settings: + govet: + check-shadowing: true + errcheck: + # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; + # default is false: such cases aren't reported by default. + check-blank: true + golint: + # minimal confidence for issues, default is 0.8 + min-confidence: 0 + prealloc: + # XXX: we don't recommend using this linter before doing performance profiling. + # For most programs usage of prealloc will be a premature optimization. + + # Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. + # True by default. + simple: false + range-loops: true # Report preallocation suggestions on range loops, true by default + for-loops: true # Report preallocation suggestions on for loops, false by default diff --git a/Dockerfile b/Dockerfile index ba8e2b7..5530f5b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ RUN go install ./cmd/trustd RUN go install ./cmd/trustcli # Final image -FROM alpine:edge +FROM ubuntu:latest # Install ca-certificates RUN apk add --update ca-certificates diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..14bc343 --- /dev/null +++ b/Makefile @@ -0,0 +1,33 @@ +PACKAGES=$(shell go list ./... | grep -v '/simulation') + +VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') +COMMIT := $(shell git log -1 --format='%H') + +# TODO: Update the ldflags with the app, client & server names +ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=NewApp \ + -X github.com/cosmos/cosmos-sdk/version.ServerName=asd \ + -X github.com/cosmos/cosmos-sdk/version.ClientName=ascli \ + -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ + -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) + +BUILD_FLAGS := -ldflags '$(ldflags)' + +all: install + +install: go.sum + go install -mod=readonly $(BUILD_FLAGS) ./cmd/aud + go install -mod=readonly $(BUILD_FLAGS) ./cmd/acli + +go.sum: go.mod + @echo "--> Ensure dependencies have not been modified" + GO111MODULE=on go mod verify + +# Uncomment when you have some tests +# test: +# @go test -mod=readonly $(PACKAGES) + +# look into .golangci.yml for enabling / disabling linters +lint: + @echo "--> Running linter" + @golangci-lint run + @go mod verify \ No newline at end of file diff --git a/app/app.go b/app/app.go new file mode 100644 index 0000000..88b9956 --- /dev/null +++ b/app/app.go @@ -0,0 +1,424 @@ +package app + +import ( + "encoding/json" + "io" + "os" + + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tmos "github.com/tendermint/tendermint/libs/os" + dbm "github.com/tendermint/tm-db" + + bam "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/version" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/crisis" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/evidence" + "github.com/cosmos/cosmos-sdk/x/genutil" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/params" + paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/supply" + "github.com/cosmos/cosmos-sdk/x/upgrade" + upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" + "github.com/lcnem/trust/x/trust" +) + +const appName = "trust" + +var ( + // TODO: rename your cli + + // DefaultCLIHome default home directories for the application CLI + DefaultCLIHome = os.ExpandEnv("$HOME/.trustcli") + + // TODO: rename your daemon + + // DefaultNodeHome sets the folder where the applcation data and configuration will be stored + DefaultNodeHome = os.ExpandEnv("$HOME/.trustd") + + // ModuleBasics The module BasicManager is in charge of setting up basic, + // non-dependant module elements, such as codec registration + // and genesis verification. + ModuleBasics = module.NewBasicManager( + genutil.AppModuleBasic{}, + auth.AppModuleBasic{}, + bank.AppModuleBasic{}, + staking.AppModuleBasic{}, + mint.AppModuleBasic{}, + distr.AppModuleBasic{}, + gov.NewAppModuleBasic(paramsclient.ProposalHandler, distr.ProposalHandler, upgradeclient.ProposalHandler), + params.AppModuleBasic{}, + crisis.AppModuleBasic{}, + slashing.AppModuleBasic{}, + supply.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + // TODO: Add your module(s) AppModuleBasic + trust.AppModuleBasic{}, + ) + + // module account permissions + maccPerms = map[string][]string{ + auth.FeeCollectorName: nil, + distr.ModuleName: nil, + mint.ModuleName: {supply.Minter}, + staking.BondedPoolName: {supply.Burner, supply.Staking}, + staking.NotBondedPoolName: {supply.Burner, supply.Staking}, + gov.ModuleName: {supply.Burner}, + } +) + +// MakeCodec creates the application codec. The codec is sealed before it is +// returned. +func MakeCodec() *codec.Codec { + var cdc = codec.New() + + ModuleBasics.RegisterCodec(cdc) + vesting.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + + return cdc.Seal() +} + +// NewApp extended ABCI application +type NewApp struct { + *bam.BaseApp + cdc *codec.Codec + + invCheckPeriod uint + + // keys to access the substores + keys map[string]*sdk.KVStoreKey + tKeys map[string]*sdk.TransientStoreKey + + // subspaces + subspaces map[string]params.Subspace + + // keepers + accountKeeper auth.AccountKeeper + bankKeeper bank.Keeper + supplyKeeper supply.Keeper + stakingKeeper staking.Keeper + slashingKeeper slashing.Keeper + mintKeeper mint.Keeper + distrKeeper distr.Keeper + govKeeper gov.Keeper + crisisKeeper crisis.Keeper + paramsKeeper params.Keeper + upgradeKeeper upgrade.Keeper + evidenceKeeper evidence.Keeper + // TODO: Add your module(s) + trustKeeper trust.Keeper + + // Module Manager + mm *module.Manager + + // simulation manager + sm *module.SimulationManager +} + +// verify app interface at compile time +var _ simapp.App = (*NewApp)(nil) + +// NewtrustApp is a constructor function for trustApp +func NewInitApp( + logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, + invCheckPeriod uint, skipUpgradeHeights map[int64]bool, baseAppOptions ...func(*bam.BaseApp), +) *NewApp { + // First define the top level codec that will be shared by the different modules + cdc := MakeCodec() + + // BaseApp handles interactions with Tendermint through the ABCI protocol + bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) + bApp.SetCommitMultiStoreTracer(traceStore) + bApp.SetAppVersion(version.Version) + + // TODO: Add the keys that module requires + keys := sdk.NewKVStoreKeys( + bam.MainStoreKey, auth.StoreKey, staking.StoreKey, + supply.StoreKey, mint.StoreKey, distr.StoreKey, slashing.StoreKey, + gov.StoreKey, params.StoreKey, evidence.StoreKey, upgrade.StoreKey, + trust.StoreKey, + ) + tKeys := sdk.NewTransientStoreKeys(staking.TStoreKey, params.TStoreKey) + + // Here you initialize your application with the store keys it requires + var app = &NewApp{ + BaseApp: bApp, + cdc: cdc, + invCheckPeriod: invCheckPeriod, + keys: keys, + tKeys: tKeys, + subspaces: make(map[string]params.Subspace), + } + + // The ParamsKeeper handles parameter storage for the application + app.paramsKeeper = params.NewKeeper(app.cdc, keys[params.StoreKey], tKeys[params.TStoreKey]) + // Set specific supspaces + app.paramsKeeper = params.NewKeeper(app.cdc, keys[params.StoreKey], tKeys[params.TStoreKey]) + app.subspaces[auth.ModuleName] = app.paramsKeeper.Subspace(auth.DefaultParamspace) + app.subspaces[bank.ModuleName] = app.paramsKeeper.Subspace(bank.DefaultParamspace) + app.subspaces[staking.ModuleName] = app.paramsKeeper.Subspace(staking.DefaultParamspace) + app.subspaces[mint.ModuleName] = app.paramsKeeper.Subspace(mint.DefaultParamspace) + app.subspaces[distr.ModuleName] = app.paramsKeeper.Subspace(distr.DefaultParamspace) + app.subspaces[slashing.ModuleName] = app.paramsKeeper.Subspace(slashing.DefaultParamspace) + app.subspaces[gov.ModuleName] = app.paramsKeeper.Subspace(gov.DefaultParamspace).WithKeyTable(gov.ParamKeyTable()) + app.subspaces[crisis.ModuleName] = app.paramsKeeper.Subspace(crisis.DefaultParamspace) + app.subspaces[evidence.ModuleName] = app.paramsKeeper.Subspace(evidence.DefaultParamspace) + + // The AccountKeeper handles address -> account lookups + app.accountKeeper = auth.NewAccountKeeper( + app.cdc, + keys[auth.StoreKey], + app.subspaces[auth.ModuleName], + auth.ProtoBaseAccount, + ) + + // The BankKeeper allows you perform sdk.Coins interactions + app.bankKeeper = bank.NewBaseKeeper( + app.accountKeeper, + app.subspaces[bank.ModuleName], + app.ModuleAccountAddrs(), + ) + + // The SupplyKeeper collects transaction fees and renders them to the fee distribution module + app.supplyKeeper = supply.NewKeeper( + app.cdc, + keys[supply.StoreKey], + app.accountKeeper, + app.bankKeeper, + maccPerms, + ) + + // The staking keeper + stakingKeeper := staking.NewKeeper( + app.cdc, + keys[staking.StoreKey], + app.supplyKeeper, + app.subspaces[staking.ModuleName], + ) + + app.distrKeeper = distr.NewKeeper( + app.cdc, + keys[distr.StoreKey], + app.subspaces[distr.ModuleName], + &stakingKeeper, + app.supplyKeeper, + auth.FeeCollectorName, + app.ModuleAccountAddrs(), + ) + + app.slashingKeeper = slashing.NewKeeper( + app.cdc, + keys[slashing.StoreKey], + &stakingKeeper, + app.subspaces[slashing.ModuleName], + ) + + app.crisisKeeper = crisis.NewKeeper( + app.subspaces[crisis.ModuleName], invCheckPeriod, app.supplyKeeper, auth.FeeCollectorName, + ) + + app.upgradeKeeper = upgrade.NewKeeper(skipUpgradeHeights, keys[upgrade.StoreKey], app.cdc) + + // create evidence keeper with evidence router + evidenceKeeper := evidence.NewKeeper( + app.cdc, keys[evidence.StoreKey], app.subspaces[evidence.ModuleName], &stakingKeeper, app.slashingKeeper, + ) + evidenceRouter := evidence.NewRouter() + + // TODO: register evidence routes + evidenceKeeper.SetRouter(evidenceRouter) + + app.evidenceKeeper = *evidenceKeeper + + // register the proposal types + govRouter := gov.NewRouter() + govRouter.AddRoute(gov.RouterKey, gov.ProposalHandler). + AddRoute(params.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). + AddRoute(distr.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.distrKeeper)). + AddRoute(upgrade.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.upgradeKeeper)) + app.govKeeper = gov.NewKeeper( + app.cdc, keys[gov.StoreKey], app.subspaces[gov.ModuleName], + app.supplyKeeper, &stakingKeeper, govRouter, + ) + + // register the staking hooks + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks + app.stakingKeeper = *stakingKeeper.SetHooks( + staking.NewMultiStakingHooks( + app.distrKeeper.Hooks(), + app.slashingKeeper.Hooks(), + ), + ) + + // TODO: Add your module(s) keepers + app.trustKeeper = trust.NewKeeper(app.cdc,keys[trust.StoreKey]) + + // NOTE: Any module instantiated in the module manager that is later modified + // must be passed by reference here. + app.mm = module.NewManager( + genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx), + auth.NewAppModule(app.accountKeeper), + bank.NewAppModule(app.bankKeeper, app.accountKeeper), + crisis.NewAppModule(&app.crisisKeeper), + supply.NewAppModule(app.supplyKeeper, app.accountKeeper), + gov.NewAppModule(app.govKeeper, app.accountKeeper, app.supplyKeeper), + mint.NewAppModule(app.mintKeeper), + slashing.NewAppModule(app.slashingKeeper, app.accountKeeper, app.stakingKeeper), + distr.NewAppModule(app.distrKeeper, app.accountKeeper, app.supplyKeeper, app.stakingKeeper), + staking.NewAppModule(app.stakingKeeper, app.accountKeeper, app.supplyKeeper), + upgrade.NewAppModule(app.upgradeKeeper), + evidence.NewAppModule(app.evidenceKeeper), + // TODO: Add your module(s) + staking.NewAppModule(app.stakingKeeper, app.accountKeeper, app.supplyKeeper), + ) + // During begin block slashing happens after distr.BeginBlocker so that + // there is nothing left over in the validator fee pool, so as to keep the + // CanWithdrawInvariant invariant. + + app.mm.SetOrderBeginBlockers(distr.ModuleName, slashing.ModuleName) + app.mm.SetOrderEndBlockers(staking.ModuleName) + + // Sets the order of Genesis - Order matters, genutil is to always come last + // NOTE: The genutils module must occur after staking so that pools are + // properly initialized with tokens from genesis accounts. + app.mm.SetOrderInitGenesis( + distr.ModuleName, + staking.ModuleName, + auth.ModuleName, + bank.ModuleName, + slashing.ModuleName, + gov.ModuleName, + mint.ModuleName, + // TODO: Add your module(s) + trust.ModuleName, + supply.ModuleName, + crisis.ModuleName, + genutil.ModuleName, + evidence.ModuleName, + ) + + // register all module routes and module queriers + app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) + + // The initChainer handles translating the genesis.json file into initial state for the network + app.SetInitChainer(app.InitChainer) + app.SetBeginBlocker(app.BeginBlocker) + app.SetEndBlocker(app.EndBlocker) + + // The AnteHandler handles signature verification and transaction pre-processing + app.SetAnteHandler( + auth.NewAnteHandler( + app.accountKeeper, + app.supplyKeeper, + auth.DefaultSigVerificationGasConsumer, + ), + ) + + // create the simulation manager and define the order of the modules for deterministic simulations + // + // NOTE: This is not required for apps that don't use the simulator for fuzz testing + // transactions. + app.sm = module.NewSimulationManager( + auth.NewAppModule(app.accountKeeper), + bank.NewAppModule(app.bankKeeper, app.accountKeeper), + supply.NewAppModule(app.supplyKeeper, app.accountKeeper), + gov.NewAppModule(app.govKeeper, app.accountKeeper, app.supplyKeeper), + mint.NewAppModule(app.mintKeeper), + distr.NewAppModule(app.distrKeeper, app.accountKeeper, app.supplyKeeper, app.stakingKeeper), + staking.NewAppModule(app.stakingKeeper, app.accountKeeper, app.supplyKeeper), + slashing.NewAppModule(app.slashingKeeper, app.accountKeeper, app.stakingKeeper), + // TODO: Add your module(s) + trust.NewAppModule(app.trustKeeper), + ) + + app.sm.RegisterStoreDecoders() + + // initialize stores + app.MountKVStores(keys) + app.MountTransientStores(tKeys) + + if loadLatest { + err := app.LoadLatestVersion(app.keys[bam.MainStoreKey]) + if err != nil { + tmos.Exit(err.Error()) + } + } + + return app +} + +// GenesisState represents chain state at the start of the chain. Any initial state (account balances) are stored here. +type GenesisState map[string]json.RawMessage + +// NewDefaultGenesisState generates the default state for the application. +func NewDefaultGenesisState() GenesisState { + return ModuleBasics.DefaultGenesis() +} + +// InitChainer application update at chain initialization +func (app *NewApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { + var genesisState simapp.GenesisState + + app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) + + return app.mm.InitGenesis(ctx, genesisState) +} + +// BeginBlocker application updates every begin block +func (app *NewApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + return app.mm.BeginBlock(ctx, req) +} + +// EndBlocker application updates every end block +func (app *NewApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + return app.mm.EndBlock(ctx, req) +} + +// LoadHeight loads a particular height +func (app *NewApp) LoadHeight(height int64) error { + return app.LoadVersion(height, app.keys[bam.MainStoreKey]) +} + +// ModuleAccountAddrs returns all the app's module account addresses. +func (app *NewApp) ModuleAccountAddrs() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range maccPerms { + modAccAddrs[supply.NewModuleAddress(acc).String()] = true + } + + return modAccAddrs +} + +// Codec returns the application's sealed codec. +func (app *NewApp) Codec() *codec.Codec { + return app.cdc +} + +// SimulationManager implements the SimulationApp interface +func (app *NewApp) SimulationManager() *module.SimulationManager { + return app.sm +} + +// GetMaccPerms returns a mapping of the application's module account permissions. +func GetMaccPerms() map[string][]string { + modAccPerms := make(map[string][]string) + for k, v := range maccPerms { + modAccPerms[k] = v + } + return modAccPerms +} diff --git a/app/export.go b/app/export.go new file mode 100644 index 0000000..ad76bd0 --- /dev/null +++ b/app/export.go @@ -0,0 +1,169 @@ +package app + +import ( + "encoding/json" + "log" + + abci "github.com/tendermint/tendermint/abci/types" + tmtypes "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +// ExportAppStateAndValidators exports the state of the application for a genesis +// file. +func (app *NewApp) ExportAppStateAndValidators( + forZeroHeight bool, jailWhiteList []string, +) (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { + + // as if they could withdraw from the start of the next block + ctx := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) + + if forZeroHeight { + app.prepForZeroHeightGenesis(ctx, jailWhiteList) + } + + genState := app.mm.ExportGenesis(ctx) + appState, err = codec.MarshalJSONIndent(app.cdc, genState) + if err != nil { + return nil, nil, err + } + + validators = staking.WriteValidators(ctx, app.stakingKeeper) + return appState, validators, nil +} + +// prepare for fresh start at zero height +// NOTE zero height genesis is a temporary feature which will be deprecated +// in favour of export at a block height +func (app *NewApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []string) { + applyWhiteList := false + + //Check if there is a whitelist + if len(jailWhiteList) > 0 { + applyWhiteList = true + } + + whiteListMap := make(map[string]bool) + + for _, addr := range jailWhiteList { + _, err := sdk.ValAddressFromBech32(addr) + if err != nil { + log.Fatal(err) + } + whiteListMap[addr] = true + } + + /* Handle fee distribution state. */ + + // withdraw all validator commission + app.stakingKeeper.IterateValidators(ctx, func(_ int64, val staking.ValidatorI) (stop bool) { + _, err := app.distrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + if err != nil { + log.Fatal(err) + } + return false + }) + + // withdraw all delegator rewards + dels := app.stakingKeeper.GetAllDelegations(ctx) + for _, delegation := range dels { + _, err := app.distrKeeper.WithdrawDelegationRewards(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress) + if err != nil { + log.Fatal(err) + } + } + + // clear validator slash events + app.distrKeeper.DeleteAllValidatorSlashEvents(ctx) + + // clear validator historical rewards + app.distrKeeper.DeleteAllValidatorHistoricalRewards(ctx) + + // set context height to zero + height := ctx.BlockHeight() + ctx = ctx.WithBlockHeight(0) + + // reinitialize all validators + app.stakingKeeper.IterateValidators(ctx, func(_ int64, val staking.ValidatorI) (stop bool) { + + // donate any unwithdrawn outstanding reward fraction tokens to the community pool + scraps := app.distrKeeper.GetValidatorOutstandingRewards(ctx, val.GetOperator()) + feePool := app.distrKeeper.GetFeePool(ctx) + feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) + app.distrKeeper.SetFeePool(ctx, feePool) + + app.distrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + return false + }) + + // reinitialize all delegations + for _, del := range dels { + app.distrKeeper.Hooks().BeforeDelegationCreated(ctx, del.DelegatorAddress, del.ValidatorAddress) + app.distrKeeper.Hooks().AfterDelegationModified(ctx, del.DelegatorAddress, del.ValidatorAddress) + } + + // reset context height + ctx = ctx.WithBlockHeight(height) + + /* Handle staking state. */ + + // iterate through redelegations, reset creation height + app.stakingKeeper.IterateRedelegations(ctx, func(_ int64, red staking.Redelegation) (stop bool) { + for i := range red.Entries { + red.Entries[i].CreationHeight = 0 + } + app.stakingKeeper.SetRedelegation(ctx, red) + return false + }) + + // iterate through unbonding delegations, reset creation height + app.stakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd staking.UnbondingDelegation) (stop bool) { + for i := range ubd.Entries { + ubd.Entries[i].CreationHeight = 0 + } + app.stakingKeeper.SetUnbondingDelegation(ctx, ubd) + return false + }) + + // Iterate through validators by power descending, reset bond heights, and + // update bond intra-tx counters. + store := ctx.KVStore(app.keys[staking.StoreKey]) + iter := sdk.KVStoreReversePrefixIterator(store, staking.ValidatorsKey) + counter := int16(0) + + for ; iter.Valid(); iter.Next() { + addr := sdk.ValAddress(iter.Key()[1:]) + validator, found := app.stakingKeeper.GetValidator(ctx, addr) + if !found { + panic("expected validator, not found") + } + + validator.UnbondingHeight = 0 + if applyWhiteList && !whiteListMap[addr.String()] { + validator.Jailed = true + } + + app.stakingKeeper.SetValidator(ctx, validator) + counter++ + } + + iter.Close() + + _ = app.stakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + + /* Handle slashing state. */ + + // reset start height on signing infos + app.slashingKeeper.IterateValidatorSigningInfos( + ctx, + func(addr sdk.ConsAddress, info slashing.ValidatorSigningInfo) (stop bool) { + info.StartHeight = 0 + app.slashingKeeper.SetValidatorSigningInfo(ctx, addr, info) + return false + }, + ) +} diff --git a/app/sim_test.go b/app/sim_test.go new file mode 100644 index 0000000..31056bb --- /dev/null +++ b/app/sim_test.go @@ -0,0 +1,298 @@ +package app + +import ( + "encoding/json" + "fmt" + "math/rand" + "os" + "testing" + + "github.com/lcnem/trust/x/trust" + "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + dbm "github.com/tendermint/tm-db" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/supply" +) + +func init() { + simapp.GetSimulatorFlags() +} + +type StoreKeysPrefixes struct { + A sdk.StoreKey + B sdk.StoreKey + Prefixes [][]byte +} + +// fauxMerkleModeOpt returns a BaseApp option to use a dbStoreAdapter instead of +// an IAVLStore for faster simulation speed. +func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { + bapp.SetFauxMerkleMode() +} + +// interBlockCacheOpt returns a BaseApp option function that sets the persistent +// inter-block write-through cache. +func interBlockCacheOpt() func(*baseapp.BaseApp) { + return baseapp.SetInterBlockCache(store.NewCommitKVStoreCacheManager()) +} + +func TestFullAppSimulation(t *testing.T) { + config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation") + if skip { + t.Skip("skipping application simulation") + } + require.NoError(t, err, "simulation setup failed") + + defer func() { + db.Close() + require.NoError(t, os.RemoveAll(dir)) + }() + + app := NewInitApp(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, fauxMerkleModeOpt) + require.Equal(t, appName, app.Name()) + + // run randomized simulation + _, simParams, simErr := simulation.SimulateFromSeed( + t, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), + simapp.SimulationOperations(app, app.Codec(), config), + app.ModuleAccountAddrs(), config, + ) + + // export state and simParams before the simulation error is checked + err = simapp.CheckExportSimulation(app, config, simParams) + require.NoError(t, err) + require.NoError(t, simErr) + + if config.Commit { + simapp.PrintStats(db) + } +} + +func TestAppImportExport(t *testing.T) { + config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation") + if skip { + t.Skip("skipping application import/export simulation") + } + require.NoError(t, err, "simulation setup failed") + + defer func() { + db.Close() + require.NoError(t, os.RemoveAll(dir)) + }() + + app := NewInitApp(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, fauxMerkleModeOpt) + require.Equal(t, appName, app.Name()) + + // Run randomized simulation + _, simParams, simErr := simulation.SimulateFromSeed( + t, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), + simapp.SimulationOperations(app, app.Codec(), config), + app.ModuleAccountAddrs(), config, + ) + + // export state and simParams before the simulation error is checked + err = simapp.CheckExportSimulation(app, config, simParams) + require.NoError(t, err) + require.NoError(t, simErr) + + if config.Commit { + simapp.PrintStats(db) + } + + fmt.Printf("exporting genesis...\n") + + appState, _, err := app.ExportAppStateAndValidators(false, []string{}) + require.NoError(t, err) + + fmt.Printf("importing genesis...\n") + + _, newDB, newDir, _, _, err := simapp.SetupSimulation("leveldb-app-sim-2", "Simulation-2") + require.NoError(t, err, "simulation setup failed") + + defer func() { + newDB.Close() + require.NoError(t, os.RemoveAll(newDir)) + }() + + newApp := NewInitApp(log.NewNopLogger(), newDB, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, fauxMerkleModeOpt) + require.Equal(t, appName, newApp.Name()) + + var genesisState GenesisState + err = app.Codec().UnmarshalJSON(appState, &genesisState) + require.NoError(t, err) + + ctxA := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) + ctxB := newApp.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) + newApp.mm.InitGenesis(ctxB, genesisState) + + fmt.Printf("comparing stores...\n") + + storeKeysPrefixes := []StoreKeysPrefixes{ + {app.keys[baseapp.MainStoreKey], newApp.keys[baseapp.MainStoreKey], [][]byte{}}, + {app.keys[auth.StoreKey], newApp.keys[auth.StoreKey], [][]byte{}}, + {app.keys[staking.StoreKey], newApp.keys[staking.StoreKey], + [][]byte{ + staking.UnbondingQueueKey, staking.RedelegationQueueKey, staking.ValidatorQueueKey, + }}, // ordering may change but it doesn't matter + {app.keys[slashing.StoreKey], newApp.keys[slashing.StoreKey], [][]byte{}}, + {app.keys[mint.StoreKey], newApp.keys[mint.StoreKey], [][]byte{}}, + {app.keys[distr.StoreKey], newApp.keys[distr.StoreKey], [][]byte{}}, + {app.keys[supply.StoreKey], newApp.keys[supply.StoreKey], [][]byte{}}, + {app.keys[params.StoreKey], newApp.keys[params.StoreKey], [][]byte{}}, + {app.keys[gov.StoreKey], newApp.keys[gov.StoreKey], [][]byte{}}, + // TODO: Add your module(s) + {app.keys[trust.StoreKey], newApp.keys[trust.StoreKey], [][]byte{}}, + } + + for _, skp := range storeKeysPrefixes { + storeA := ctxA.KVStore(skp.A) + storeB := ctxB.KVStore(skp.B) + + failedKVAs, failedKVBs := sdk.DiffKVStores(storeA, storeB, skp.Prefixes) + require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare") + + fmt.Printf("compared %d key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B) + require.Equal(t, len(failedKVAs), 0, simapp.GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, app.Codec(), failedKVAs, failedKVBs)) + } +} + +func TestAppSimulationAfterImport(t *testing.T) { + config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation") + if skip { + t.Skip("skipping application simulation after import") + } + require.NoError(t, err, "simulation setup failed") + + defer func() { + db.Close() + require.NoError(t, os.RemoveAll(dir)) + }() + + app := NewInitApp(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, fauxMerkleModeOpt) + require.Equal(t, appName, app.Name()) + + // Run randomized simulation + stopEarly, simParams, simErr := simulation.SimulateFromSeed( + t, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), + simapp.SimulationOperations(app, app.Codec(), config), + app.ModuleAccountAddrs(), config, + ) + + // export state and simParams before the simulation error is checked + err = simapp.CheckExportSimulation(app, config, simParams) + require.NoError(t, err) + require.NoError(t, simErr) + + if config.Commit { + simapp.PrintStats(db) + } + + if stopEarly { + fmt.Println("can't export or import a zero-validator genesis, exiting test...") + return + } + + fmt.Printf("exporting genesis...\n") + + appState, _, err := app.ExportAppStateAndValidators(true, []string{}) + require.NoError(t, err) + + fmt.Printf("importing genesis...\n") + + _, newDB, newDir, _, _, err := simapp.SetupSimulation("leveldb-app-sim-2", "Simulation-2") + require.NoError(t, err, "simulation setup failed") + + defer func() { + newDB.Close() + require.NoError(t, os.RemoveAll(newDir)) + }() + + newApp := NewInitApp(log.NewNopLogger(), newDB, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, fauxMerkleModeOpt) + require.Equal(t, appName, newApp.Name()) + + newApp.InitChain(abci.RequestInitChain{ + AppStateBytes: appState, + }) + + _, _, err = simulation.SimulateFromSeed( + t, os.Stdout, newApp.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), + simapp.SimulationOperations(newApp, newApp.Codec(), config), + newApp.ModuleAccountAddrs(), config, + ) + require.NoError(t, err) +} + +func TestAppStateDeterminism(t *testing.T) { + if !simapp.FlagEnabledValue { + t.Skip("skipping application simulation") + } + + config := simapp.NewConfigFromFlags() + config.InitialBlockHeight = 1 + config.ExportParamsPath = "" + config.OnOperation = false + config.AllInvariants = false + config.ChainID = helpers.SimAppChainID + + numSeeds := 3 + numTimesToRunPerSeed := 5 + appHashList := make([]json.RawMessage, numTimesToRunPerSeed) + + for i := 0; i < numSeeds; i++ { + config.Seed = rand.Int63() + + for j := 0; j < numTimesToRunPerSeed; j++ { + var logger log.Logger + if simapp.FlagVerboseValue { + logger = log.TestingLogger() + } else { + logger = log.NewNopLogger() + } + + db := dbm.NewMemDB() + + app := NewInitApp(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, interBlockCacheOpt()) + + fmt.Printf( + "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", + config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, + ) + + _, _, err := simulation.SimulateFromSeed( + t, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), + simapp.SimulationOperations(app, app.Codec(), config), + app.ModuleAccountAddrs(), config, + ) + require.NoError(t, err) + + if config.Commit { + simapp.PrintStats(db) + } + + appHash := app.LastCommitID().Hash + appHashList[j] = appHash + + if j != 0 { + require.Equal( + t, appHashList[0], appHashList[j], + "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, + ) + } + } + } +} diff --git a/cmd/trustcli/main.go b/cmd/trustcli/main.go index 2b90208..dcd05d6 100644 --- a/cmd/trustcli/main.go +++ b/cmd/trustcli/main.go @@ -1,27 +1,38 @@ package main import ( + "fmt" "os" "path" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/lcd" "github.com/cosmos/cosmos-sdk/client/rpc" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/cosmos/cosmos-sdk/x/auth" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" + "github.com/cosmos/cosmos-sdk/x/bank" bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - app "github.com/lcnem/trust" + "github.com/spf13/cobra" "github.com/spf13/viper" - amino "github.com/tendermint/go-amino" + + "github.com/tendermint/go-amino" "github.com/tendermint/tendermint/libs/cli" + + "github.com/lcnem/trust/app" + ) func main() { + // Configure cobra to sort commands cobra.EnableCommandSorting = false + // Instantiate the codec for the command line application cdc := app.MakeCodec() // Read in the configuration file for the sdk @@ -31,13 +42,17 @@ func main() { config.SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) config.Seal() + // TODO: setup keybase, viper object, etc. to be passed into + // the below functions and eliminate global vars, like we do + // with the cdc + rootCmd := &cobra.Command{ Use: "trustcli", - Short: "trust Client", + Short: "Command line interface for interacting with appd", } // Add --chain-id to persistent flags and mark it required - rootCmd.PersistentFlags().String(client.FlagChainID, "", "Chain ID of tendermint node") + rootCmd.PersistentFlags().String(flags.FlagChainID, "", "Chain ID of tendermint node") rootCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error { return initConfig(rootCmd) } @@ -48,27 +63,25 @@ func main() { client.ConfigCmd(app.DefaultCLIHome), queryCmd(cdc), txCmd(cdc), - client.LineBreak, + flags.LineBreak, lcd.ServeCommand(cdc, registerRoutes), - client.LineBreak, + flags.LineBreak, keys.Commands(), - client.LineBreak, + flags.LineBreak, version.Cmd, - client.NewCompletionCmd(rootCmd, true), + flags.NewCompletionCmd(rootCmd, true), ) - executor := cli.PrepareMainCmd(rootCmd, "TRUST", app.DefaultCLIHome) + // Add flags and prefix all env exposed with TR + executor := cli.PrepareMainCmd(rootCmd, "TR", app.DefaultCLIHome) + err := executor.Execute() if err != nil { - panic(err) + fmt.Printf("Failed executing CLI command: %s, exiting...\n", err) + os.Exit(1) } } -func registerRoutes(rs *lcd.RestServer) { - client.RegisterRoutes(rs.CliCtx, rs.Mux) - app.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux) -} - func queryCmd(cdc *amino.Codec) *cobra.Command { queryCmd := &cobra.Command{ Use: "query", @@ -78,12 +91,12 @@ func queryCmd(cdc *amino.Codec) *cobra.Command { queryCmd.AddCommand( authcmd.GetAccountCmd(cdc), - client.LineBreak, + flags.LineBreak, rpc.ValidatorCommand(cdc), rpc.BlockCommand(), authcmd.QueryTxsByEventsCmd(cdc), authcmd.QueryTxCmd(cdc), - client.LineBreak, + flags.LineBreak, ) // add modules' query commands @@ -100,21 +113,42 @@ func txCmd(cdc *amino.Codec) *cobra.Command { txCmd.AddCommand( bankcmd.SendTxCmd(cdc), - client.LineBreak, + flags.LineBreak, authcmd.GetSignCommand(cdc), authcmd.GetMultiSignCommand(cdc), - client.LineBreak, + flags.LineBreak, authcmd.GetBroadcastCommand(cdc), authcmd.GetEncodeCommand(cdc), - client.LineBreak, + authcmd.GetDecodeCommand(cdc), + flags.LineBreak, ) // add modules' tx commands app.ModuleBasics.AddTxCommands(txCmd, cdc) + // remove auth and bank commands as they're mounted under the root tx command + var cmdsToRemove []*cobra.Command + + for _, cmd := range txCmd.Commands() { + if cmd.Use == auth.ModuleName || cmd.Use == bank.ModuleName { + cmdsToRemove = append(cmdsToRemove, cmd) + } + } + + txCmd.RemoveCommand(cmdsToRemove...) + return txCmd } +// registerRoutes registers the routes from the different modules for the LCD. +// NOTE: details on the routes added for each module are in the module documentation +// NOTE: If making updates here you also need to update the test helper in client/lcd/test_helper.go +func registerRoutes(rs *lcd.RestServer) { + client.RegisterRoutes(rs.CliCtx, rs.Mux) + authrest.RegisterTxRoutes(rs.CliCtx, rs.Mux) + app.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux) +} + func initConfig(cmd *cobra.Command) error { home, err := cmd.PersistentFlags().GetString(cli.HomeFlag) if err != nil { @@ -129,11 +163,11 @@ func initConfig(cmd *cobra.Command) error { return err } } - if err := viper.BindPFlag(client.FlagChainID, cmd.PersistentFlags().Lookup(client.FlagChainID)); err != nil { + if err := viper.BindPFlag(flags.FlagChainID, cmd.PersistentFlags().Lookup(flags.FlagChainID)); err != nil { return err } if err := viper.BindPFlag(cli.EncodingFlag, cmd.PersistentFlags().Lookup(cli.EncodingFlag)); err != nil { return err } return viper.BindPFlag(cli.OutputFlag, cmd.PersistentFlags().Lookup(cli.OutputFlag)) -} \ No newline at end of file +} diff --git a/cmd/trustd/genaccounts.go b/cmd/trustd/genaccounts.go index 5c8192d..90df73f 100644 --- a/cmd/trustd/genaccounts.go +++ b/cmd/trustd/genaccounts.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "errors" "fmt" @@ -9,12 +10,14 @@ import ( "github.com/tendermint/tendermint/libs/cli" - "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" + authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/genutil" ) @@ -39,14 +42,20 @@ the address will be looked up in the local Keybase. The list of initial tokens m contain valid denominations. Accounts may optionally be supplied with vesting parameters. `, Args: cobra.ExactArgs(2), - RunE: func(_ *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, args []string) error { config := ctx.Config config.SetRoot(viper.GetString(cli.HomeFlag)) addr, err := sdk.AccAddressFromBech32(args[0]) + inBuf := bufio.NewReader(cmd.InOrStdin()) if err != nil { // attempt to lookup address from Keybase if no address was provided - kb, err := keys.NewKeyBaseFromDir(viper.GetString(flagClientHome)) + kb, err := keys.NewKeyring( + sdk.KeyringServiceName(), + viper.GetString(flags.FlagKeyringBackend), + viper.GetString(flagClientHome), + inBuf, + ) if err != nil { return err } @@ -76,16 +85,17 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa baseAccount := auth.NewBaseAccount(addr, coins.Sort(), nil, 0, 0) if !vestingAmt.IsZero() { - baseVestingAccount := auth.NewBaseVestingAccount( - baseAccount, vestingAmt.Sort(), sdk.Coins{}, sdk.Coins{}, vestingEnd, - ) + baseVestingAccount, err := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd) + if err != nil { + return fmt.Errorf("failed to create base vesting account: %w", err) + } switch { case vestingStart != 0 && vestingEnd != 0: - genAccount = auth.NewContinuousVestingAccountRaw(baseVestingAccount, vestingStart) + genAccount = authvesting.NewContinuousVestingAccountRaw(baseVestingAccount, vestingStart) case vestingEnd != 0: - genAccount = auth.NewDelayedVestingAccountRaw(baseVestingAccount) + genAccount = authvesting.NewDelayedVestingAccountRaw(baseVestingAccount) default: return errors.New("invalid vesting parameters; must supply start and end time or end time") @@ -133,6 +143,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa } cmd.Flags().String(cli.HomeFlag, defaultNodeHome, "node's home directory") + cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") cmd.Flags().String(flagClientHome, defaultClientHome, "client's home directory") cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") cmd.Flags().Uint64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") diff --git a/cmd/trustd/main.go b/cmd/trustd/main.go index 9a627ef..fccad89 100644 --- a/cmd/trustd/main.go +++ b/cmd/trustd/main.go @@ -4,25 +4,33 @@ import ( "encoding/json" "io" - "github.com/cosmos/cosmos-sdk/server" - "github.com/spf13/cobra" + "github.com/spf13/viper" + + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/log" + tmtypes "github.com/tendermint/tendermint/types" + dbm "github.com/tendermint/tm-db" + "github.com/lcnem/trust/app" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client/debug" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" "github.com/cosmos/cosmos-sdk/x/staking" - app "github.com/lcnem/trust" - abci "github.com/tendermint/tendermint/abci/types" - tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" ) -func main() { - cobra.EnableCommandSorting = false +const flagInvCheckPeriod = "inv-check-period" + +var invCheckPeriod uint +func main() { cdc := app.MakeCodec() config := sdk.GetConfig() @@ -32,28 +40,33 @@ func main() { config.Seal() ctx := server.NewDefaultContext() - + cobra.EnableCommandSorting = false rootCmd := &cobra.Command{ Use: "trustd", - Short: "trust App Daemon (server)", + Short: "Trust Daemon (server)", PersistentPreRunE: server.PersistentPreRunEFn(ctx), } - // CLI commands to initialize the chain + + rootCmd.AddCommand(genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome)) + rootCmd.AddCommand(genutilcli.CollectGenTxsCmd(ctx, cdc, auth.GenesisAccountIterator{}, app.DefaultNodeHome)) + rootCmd.AddCommand(genutilcli.MigrateGenesisCmd(ctx, cdc)) rootCmd.AddCommand( - genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome), - genutilcli.CollectGenTxsCmd(ctx, cdc, auth.GenesisAccountIterator{}, app.DefaultNodeHome), genutilcli.GenTxCmd( ctx, cdc, app.ModuleBasics, staking.AppModuleBasic{}, auth.GenesisAccountIterator{}, app.DefaultNodeHome, app.DefaultCLIHome, ), - genutilcli.ValidateGenesisCmd(ctx, cdc, app.ModuleBasics), - AddGenesisAccountCmd(ctx, cdc, app.DefaultNodeHome, app.DefaultCLIHome), ) + rootCmd.AddCommand(genutilcli.ValidateGenesisCmd(ctx, cdc, app.ModuleBasics)) + rootCmd.AddCommand(AddGenesisAccountCmd(ctx, cdc, app.DefaultNodeHome, app.DefaultCLIHome)) + rootCmd.AddCommand(flags.NewCompletionCmd(rootCmd, true)) + rootCmd.AddCommand(debug.Cmd(cdc)) server.AddCommands(ctx, cdc, rootCmd, newApp, exportAppStateAndTMValidators) // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "TRUST", app.DefaultNodeHome) + executor := cli.PrepareBaseCmd(rootCmd, "TR", app.DefaultNodeHome) + rootCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, + 0, "Assert registered invariants every N blocks") err := executor.Execute() if err != nil { panic(err) @@ -61,7 +74,25 @@ func main() { } func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { - return app.NewTrustApp(logger, db) + var cache sdk.MultiStorePersistentCache + + if viper.GetBool(server.FlagInterBlockCache) { + cache = store.NewCommitKVStoreCacheManager() + } + + skipUpgradeHeights := make(map[int64]bool) + for _, h := range viper.GetIntSlice(server.FlagUnsafeSkipUpgrades) { + skipUpgradeHeights[int64(h)] = true + } + + return app.NewInitApp( + logger, db, traceStore, true, invCheckPeriod, skipUpgradeHeights, + baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning"))), + baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), + baseapp.SetHaltHeight(viper.GetUint64(server.FlagHaltHeight)), + baseapp.SetHaltTime(viper.GetUint64(server.FlagHaltTime)), + baseapp.SetInterBlockCache(cache), + ) } func exportAppStateAndTMValidators( @@ -69,15 +100,15 @@ func exportAppStateAndTMValidators( ) (json.RawMessage, []tmtypes.GenesisValidator, error) { if height != -1 { - trustApp := app.NewTrustApp(logger, db) - err := trustApp.LoadHeight(height) + aApp := app.NewInitApp(logger, db, traceStore, false, uint(1), map[int64]bool{}) + err := aApp.LoadHeight(height) if err != nil { return nil, nil, err } - return trustApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) + return aApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) } - trustApp := app.NewTrustApp(logger, db) + aApp := app.NewInitApp(logger, db, traceStore, true, uint(1), map[int64]bool{}) - return trustApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) + return aApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) } diff --git a/go.mod b/go.mod index 29cb8c9..91ad518 100644 --- a/go.mod +++ b/go.mod @@ -3,13 +3,21 @@ module github.com/lcnem/trust go 1.13 require ( - github.com/cosmos/cosmos-sdk v0.34.4-0.20190922212952-dc838ddd73d6 + github.com/btcsuite/btcd v0.0.0-20190807005414-4063feeff79a // indirect + github.com/cosmos/cosmos-sdk v0.38.0 + github.com/golang/mock v1.3.1 // indirect github.com/gorilla/mux v1.7.3 + github.com/onsi/ginkgo v1.8.0 // indirect + github.com/onsi/gomega v1.5.0 // indirect + github.com/prometheus/client_golang v1.1.0 // indirect + github.com/rcrowley/go-metrics v0.0.0-20190706150252-9beb055b7962 // indirect + github.com/spf13/afero v1.2.2 // indirect github.com/spf13/cobra v0.0.5 - github.com/spf13/viper v1.4.0 + github.com/spf13/viper v1.6.2 github.com/stretchr/testify v1.4.0 - github.com/tendermint/go-amino v0.15.0 - github.com/tendermint/tendermint v0.32.3 - github.com/tendermint/tm-db v0.2.0 - github.com/KimuraYu45z/pagerank-go v0.0.0-20190929124623-c0d3bdb5a499 + github.com/tendermint/go-amino v0.15.1 + github.com/tendermint/tendermint v0.33.0 + github.com/tendermint/tm-db v0.4.0 + golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297 // indirect + golang.org/x/text v0.3.2 // indirect ) diff --git a/go.sum b/go.sum index 6b8e621..d9782a3 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,17 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/99designs/keyring v1.1.2 h1:JJauROcU6x6Nh9uZb+8JgXFvyo0GUESLo1ixhpA0Kmw= github.com/99designs/keyring v1.1.2/go.mod h1:657DQuMrBZRtuL/voxVyiyb6zpMehlm5vLB9Qwrv904= +github.com/99designs/keyring v1.1.3/go.mod h1:657DQuMrBZRtuL/voxVyiyb6zpMehlm5vLB9Qwrv904= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/ChainSafe/go-schnorrkel v0.0.0-20200102211924-4bcbc698314f h1:4O1om+UVU+Hfcihr1timk8YNXHxzZWgCo7ofnrZRApw= +github.com/ChainSafe/go-schnorrkel v0.0.0-20200102211924-4bcbc698314f/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= +github.com/KimuraYu45z/pagerank-go v0.0.0-20190929124623-c0d3bdb5a499 h1:nl5FTCrmNSDvvKACSNjjnBMG1/aBagBPiwGX0WfQ7TE= +github.com/KimuraYu45z/pagerank-go v0.0.0-20190929124623-c0d3bdb5a499/go.mod h1:p6iuwttTlVa82fJ75kcwh8qODW+s4bxjoBPPPRNw06M= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= +github.com/Workiva/go-datastructures v1.0.50/go.mod h1:Z+F2Rca0qCsVYDS8z7bAGm8f3UkzuWYS/oBZz5a7VVA= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= @@ -16,18 +22,24 @@ github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLM github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0 h1:HWo1m869IqiPhD389kmkxeTalrjNbbJTC8LXupb+sl0= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d h1:xG8Pj6Y6J760xwETNmMzmlt38QSwz0BLp1cZ09g27uw= github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d/go.mod h1:d3C0AkH6BRcvO8T0UEPu53cnw4IbV63x1bEjildYhO0= +github.com/btcsuite/btcd v0.0.0-20190807005414-4063feeff79a h1:We35J+0yvVFrEXbtViYUW8H/wNOhqjIF3PsrW4yYmGw= +github.com/btcsuite/btcd v0.0.0-20190807005414-4063feeff79a/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI= github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= github.com/btcsuite/btcutil v0.0.0-20180706230648-ab6388e0c60a h1:RQMUrEILyYJEoAT34XS/kLu40vC0+po/UfxrBBA4qZE= github.com/btcsuite/btcutil v0.0.0-20180706230648-ab6388e0c60a/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= +github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d h1:yJzD/yFppdVCf6ApMkVy8cUxV0XrxdP9rVf6D87/Mng= +github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= @@ -38,10 +50,13 @@ github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7 github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/cosmos-sdk v0.34.4-0.20190922212952-dc838ddd73d6 h1:hoxUOx9JRLNKlXQPNT6rRCGHomdkMUqPaqYQpjoAUVs= github.com/cosmos/cosmos-sdk v0.34.4-0.20190922212952-dc838ddd73d6/go.mod h1:gwKdI16dOjylNYJkaHbcx0TcEIHyRs1xyc5qROmjCJE= +github.com/cosmos/cosmos-sdk v0.38.0/go.mod h1:9ZZex0GKpyNCvilvVAPBoB+0n3A/aO1+/UhPVEaiCy4= github.com/cosmos/go-bip39 v0.0.0-20180618194314-52158e4697b8 h1:Iwin12wRQtyZhH6FV3ykFcdGNlYEzoeR0jN8Vn+JWsI= github.com/cosmos/go-bip39 v0.0.0-20180618194314-52158e4697b8/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= +github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/ledger-cosmos-go v0.10.3 h1:Qhi5yTR5Pg1CaTpd00pxlGwNl4sFRdtK1J96OTjeFFc= github.com/cosmos/ledger-cosmos-go v0.10.3/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0WAaXvHnVc7ZmE8iUY= +github.com/cosmos/ledger-cosmos-go v0.11.1/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0WAaXvHnVc7ZmE8iUY= github.com/cosmos/ledger-go v0.9.2 h1:Nnao/dLwaVTk1Q5U9THldpUMMXU94BOTWPddSmVB6pI= github.com/cosmos/ledger-go v0.9.2/go.mod h1:oZJ2hHAZROdlHiwTg4t7kP+GKIIkBT+o6c9QWFanOyI= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= @@ -55,6 +70,8 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZm github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/dvsekhvalnov/jose2go v0.0.0-20180829124132-7f401d37b68a h1:mq+R6XEM6lJX5VlLyZIrUSP8tSuJp82xTK89hvBwJbU= github.com/dvsekhvalnov/jose2go v0.0.0-20180829124132-7f401d37b68a/go.mod h1:7BvyPhdbLxMXIYTFPLsyJRFMsKmOZnQmzh6Gb+uquuM= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/etcd-io/bbolt v1.3.2/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= github.com/etcd-io/bbolt v1.3.3 h1:gSJmxrs37LgTqR/oyJBWok6k6SvXEUerFTbltIhXkBM= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= @@ -73,9 +90,11 @@ github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeME github.com/go-kit/kit v0.6.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.8.0 h1:Wz+5lgoB0kkuqLEc6NVmwRknTKP6dTGbSqvhZtBI/j0= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0 h1:MP4Eh7ZCb31lleYCFuwm0oe4/YGak+5l1vA2NOE80nA= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= @@ -86,12 +105,14 @@ github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/gogo/protobuf v1.3.0 h1:G8O7TerXerS4F6sx9OV7/nRfJdnXgHZu/S/7F2SN+UE= github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129 h1:tT8iWCYw4uOem71yYA3htfH+LNopJvcqZQshm56G5L4= github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= @@ -102,10 +123,12 @@ github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf h1:+RRA9JqSOZFfKrOeqr2z77+8R2RKyh8PG66dcu1V0ck= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= @@ -118,8 +141,12 @@ github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgf github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= +github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f h1:8N8XWLZelZNibkhM1FuF+3Ad3YIbgirjdMiVA0eUkaM= +github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= +github.com/gtank/ristretto255 v0.1.2/go.mod h1:Ph5OpO6c7xKUGROZfWVLiJf9icMDwUeIvY4OmlYW69o= github.com/hashicorp/golang-lru v0.5.3 h1:YPkqC67at8FYaadspW/6uE0COsBxS2656RLEr8Bppgk= github.com/hashicorp/golang-lru v0.5.3/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= @@ -131,6 +158,9 @@ github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d h1:Z+RDyXzjKE0i2sTjZ/b1uxiGtPhFy34Ou/Tk0qwN0kM= github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d/go.mod h1:JJNrCn9otv/2QP4D7SMJBgaleKpOf66PnW6F5WGNRIc= @@ -148,61 +178,89 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/libp2p/go-buffer-pool v0.0.1 h1:9Rrn/H46cXjaA2HQ5Y8lyhOS1NhTkZ4yuEs2r3Eechg= github.com/libp2p/go-buffer-pool v0.0.1/go.mod h1:xtyIz9PMobb13WaxR6Zo1Pd1zXJKYg0a8KiIvDp3TzQ= +github.com/libp2p/go-buffer-pool v0.0.2/go.mod h1:MvaB6xw5vOrDl8rYZGLFdKAuk/hRoRZd1Vi32+RXyFM= github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-isatty v0.0.9 h1:d5US/mDsogSGW37IV293h//ZFaeajb69h+EHFsv2xGg= github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.4.0 h1:u3Z1r+oOXJIkxqw34zVhyPgjBsm6X2wn21NWs/HfSeg= github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo= +github.com/pelletier/go-toml v1.6.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3 h1:9iH4JKXLzFbOAdtqv/a+j8aewx2Y8lAjAydhbaScPF8= github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.1.0 h1:BQ53HtBmfOitExawJ6LokA4x8ov/z0SYYb0+HxJfRI8= +github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90 h1:S/YWwWx/RA8rT8tKFRuGUZhuA90OyIBpPCXkcbwU8DE= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20181020173914-7e9e6cabbd39/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.0 h1:7etb9YClo3a6HjLzfl6rIQaU+FDfi0VSX39io3aQ+DM= github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.6.0 h1:kRhiuYSXR3+uv2IbVbZhUxK5zVD/2pp3Gd2PpvPkpEo= +github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084 h1:sofwID9zm4tzrgykg80hfFph1mryUeLRsUfoocVVmRY= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/rakyll/statik v0.1.6 h1:uICcfUXpgqtw2VopbIncslhAmE5hwc4g20TEyEENBNs= github.com/rakyll/statik v0.1.6/go.mod h1:OEi9wJV/fMUAGx1eNjq75DKDsJVuEv1U0oYdX6GX8Zs= github.com/rcrowley/go-metrics v0.0.0-20180503174638-e2704e165165 h1:nkcn14uNmFEuGCb2mBZbBb24RdNRL08b/wb+xBOYpuk= github.com/rcrowley/go-metrics v0.0.0-20180503174638-e2704e165165/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rcrowley/go-metrics v0.0.0-20190706150252-9beb055b7962 h1:eUm8ma4+yPknhXtkYlWh3tMkE6gBjXZToDned9s2gbQ= +github.com/rcrowley/go-metrics v0.0.0-20190706150252-9beb055b7962/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rs/cors v1.6.0 h1:G9tHG9lebljV9mfp9SNPDL36nCDxmo3zTlAf1YgvzmI= github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.1 h1:qgMbHoJbPbw579P+1zVY+6n4nIFuIchaIjzZ/I/Yq8M= github.com/spf13/afero v1.2.1/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.1/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= @@ -219,6 +277,8 @@ github.com/spf13/viper v1.0.0/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7Sr github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.4.0 h1:yXHLWeravcrgGyFSyCgdYpXQ9dR9c/WED3pg1RhxqEU= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= +github.com/spf13/viper v1.6.1/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k= +github.com/spf13/viper v1.6.2/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -231,32 +291,38 @@ github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJy github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stumble/gorocksdb v0.0.3 h1:9UU+QA1pqFYJuf9+5p7z1IqdE5k0mma4UAeu2wmX8kA= github.com/stumble/gorocksdb v0.0.3/go.mod h1:v6IHdFBXk5DJ1K4FZ0xi+eY737quiiBxYtSWXadLybY= +github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965 h1:1oFLiOyVl+W7bnBzGhf7BbIv9loSFQcieWWYIjLqcAw= github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA= +github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA= +github.com/tecbot/gorocksdb v0.0.0-20191017175515-d217d93fd4c5/go.mod h1:ahpPrc7HpcfEWDQRZEmnXMzHY03mLDYMCxeDzy46i+8= github.com/tendermint/btcd v0.1.1 h1:0VcxPfflS2zZ3RiOAHkBiFUcPvbtRj5O7zHmcJWHV7s= github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U= github.com/tendermint/crypto v0.0.0-20190823183015-45b1026d81ae h1:AOXNM7c2Vvo45SjAgeWF8Wy+NS7/NCqzRNpUc+HPAec= github.com/tendermint/crypto v0.0.0-20190823183015-45b1026d81ae/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= +github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= github.com/tendermint/go-amino v0.14.1 h1:o2WudxNfdLNBwMyl2dqOJxiro5rfrEaU0Ugs6offJMk= github.com/tendermint/go-amino v0.14.1/go.mod h1:i/UKE5Uocn+argJJBb12qTZsCDBcAYMbR92AaJVmKso= github.com/tendermint/go-amino v0.15.0 h1:TC4e66P59W7ML9+bxio17CPKnxW3nKIRAYskntMAoRk= github.com/tendermint/go-amino v0.15.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= +github.com/tendermint/go-amino v0.15.1/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= github.com/tendermint/iavl v0.12.4 h1:hd1woxUGISKkfUWBA4mmmTwOua6PQZTJM/F0FDrmMV8= github.com/tendermint/iavl v0.12.4/go.mod h1:8LHakzt8/0G3/I8FUU0ReNx98S/EP6eyPJkAUvEXT/o= +github.com/tendermint/iavl v0.13.0/go.mod h1:7nSUPdrsHEZ2nNZa+9gaIrcJciWd1jCQZXtcyARU82k= github.com/tendermint/tendermint v0.32.1/go.mod h1:jmPDAKuNkev9793/ivn/fTBnfpA9mGBww8MPRNPNxnU= github.com/tendermint/tendermint v0.32.3 h1:GEnWpGQ795h5oTFNbfBLsY0LW/CW2j6p6HtiYNfxsgg= github.com/tendermint/tendermint v0.32.3/go.mod h1:ZK2c29jl1QRYznIRyRWRDsmm1yvtPzBRT00x4t1JToY= +github.com/tendermint/tendermint v0.33.0/go.mod h1:s5UoymnPIY+GcA3mMte4P9gpMP8vS7UH7HBXikT1pHI= github.com/tendermint/tm-db v0.1.1 h1:G3Xezy3sOk9+ekhjZ/kjArYIs1SmwV+1OUgNkj7RgV0= github.com/tendermint/tm-db v0.1.1/go.mod h1:0cPKWu2Mou3IlxecH+MEUSYc1Ch537alLe6CpFrKzgw= github.com/tendermint/tm-db v0.2.0 h1:rJxgdqn6fIiVJZy4zLpY1qVlyD0TU6vhkT4kEf71TQQ= github.com/tendermint/tm-db v0.2.0/go.mod h1:0cPKWu2Mou3IlxecH+MEUSYc1Ch537alLe6CpFrKzgw= +github.com/tendermint/tm-db v0.4.0/go.mod h1:+Cwhgowrf7NBGXmsqFMbwEtbo80XmyrlY5Jsk95JubQ= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/KimuraYu45z/pagerank-go v0.0.0-20190929124623-c0d3bdb5a499 h1:nl5FTCrmNSDvvKACSNjjnBMG1/aBagBPiwGX0WfQ7TE= -github.com/KimuraYu45z/pagerank-go v0.0.0-20190929124623-c0d3bdb5a499/go.mod h1:p6iuwttTlVa82fJ75kcwh8qODW+s4bxjoBPPPRNw06M= github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= @@ -274,17 +340,26 @@ golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a h1:YX8ljsm6wXlHZO+aRz9Exq golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413 h1:ULYEB3JvPRE/IfO+9uO7vKV/xzVTO7XPAwm8xbf4w2g= +golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297 h1:k7pJ2yAPLPgbskkFdhRCsA77k2fySZ1zf2zCjvQCiIM= +golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -301,29 +376,42 @@ golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2 h1:67iHsV9djwGdZpdZNbLuQj6FOzCaZe3w+vhLjn5AcFA= google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/grpc v1.13.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.22.0 h1:J0UbZOIrCAl+fpTOf8YLs4dJo8L/owV4LYVtAXQoPkw= google.golang.org/grpc v1.22.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0 h1:2dTRdpdFEEhJYQD8EMLB61nnrzSCTbG38PhqdhvOltg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -331,6 +419,8 @@ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33 gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= +gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= @@ -338,5 +428,7 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/old/x/trust/alias.go b/old/x/trust/alias.go new file mode 100644 index 0000000..b46c55a --- /dev/null +++ b/old/x/trust/alias.go @@ -0,0 +1,35 @@ +package trust + +import ( + "github.com/lcnem/trust/x/trust/internal/keeper" + "github.com/lcnem/trust/x/trust/internal/types" +) + +// nolint +const ( + ModuleName = types.ModuleName + RouterKey = types.RouterKey + StoreKey = types.StoreKey +) + +// nolint +var ( + NewKeeper = keeper.NewKeeper + NewQuerier = keeper.NewQuerier + NewMsgEvaluate = types.NewMsgEvaluate + NewMsgDistributeTokenByScore = types.NewMsgDistributeTokenByScore + NewMsgDistributeTokenByEvaluation = types.NewMsgDistributeTokenByEvaluation + ModuleCdc = types.ModuleCdc + RegisterCodec = types.RegisterCodec +) + +type ( + // Keeper keeper.Keeper + Keeper = keeper.Keeper + // MsgEvaluate types.MsgEvaluate + MsgEvaluate = types.MsgEvaluate + // MsgDistributeTokenByScore types.MsgDistributeTokenByScore + MsgDistributeTokenByScore = types.MsgDistributeTokenByScore + // MsgDistributeTokenByEvaluation types.MsgDistributeTokenByEvaluation + MsgDistributeTokenByEvaluation = types.MsgDistributeTokenByEvaluation +) diff --git a/old/x/trust/client/cli/query.go b/old/x/trust/client/cli/query.go new file mode 100644 index 0000000..a5ca533 --- /dev/null +++ b/old/x/trust/client/cli/query.go @@ -0,0 +1,50 @@ +package cli + +import ( + "encoding/json" + "fmt" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/lcnem/trust/x/trust/internal/types" + "github.com/spf13/cobra" +) + +// GetQueryCmd returns query commands +func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { + coinQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the trust module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + coinQueryCmd.AddCommand(client.GetCommands( + getCmdAccountScores(storeKey, cdc), + )...) + return coinQueryCmd +} + +func getCmdAccountScores(queryRoute string, cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "account-scores [address] [topic_ids[,]]", + Short: "get account scores", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + + bz, _ := cdc.MarshalJSON(types.QueryAccountScoresParam{Address: args[0], TopicIDs: args[1]}) + + res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryAccountScores), bz) + if err != nil { + fmt.Printf(err.Error()) + return nil + } + var scores map[string]float64 + json.Unmarshal(res, &scores) + + return cliCtx.PrintOutput(scores) + }, + } +} diff --git a/old/x/trust/client/cli/tx.go b/old/x/trust/client/cli/tx.go new file mode 100644 index 0000000..afe0e23 --- /dev/null +++ b/old/x/trust/client/cli/tx.go @@ -0,0 +1,124 @@ +package cli + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/lcnem/trust/x/trust/internal/types" +) + +// GetTxCmd is GetTxCmd +func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { + coinTxCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Trust transaction subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + coinTxCmd.AddCommand(client.PostCommands( + getCmdEvaluate(cdc), + getCmdDistributeTokenByScore(cdc), + getCmdDistributeTokenByEvaluation(cdc), + )...) + + return coinTxCmd +} + +func getCmdEvaluate(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "evaluate [topic_id] [to_address] [weight1000]", + Short: "evaluate", + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + + toAddress, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } + + weight1000, ok := sdk.NewIntFromString(args[2]) + if !ok { + return sdk.ErrUnknownRequest(args[2]) + } + + msg := types.NewMsgEvaluate(args[0], cliCtx.GetFromAddress(), toAddress, weight1000) + err = msg.ValidateBasic() + if err != nil { + return err + } + + return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + }, + } +} + +func getCmdDistributeTokenByScore(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "distribute-by-score [topic_id] [amount]", + Short: "distribute your token by score", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + + fromAddress := cliCtx.GetFromAddress() + + coin, err := sdk.ParseCoin(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgDistributeTokenByScore(args[0], fromAddress, coin) + err = msg.ValidateBasic() + if err != nil { + return err + } + + return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + }, + } +} + +func getCmdDistributeTokenByEvaluation(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "distribute-by-evaluation [topic_id] [address] [amount]", + Short: "distribute your token by evaluation", + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + + address, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } + + fromAddress := cliCtx.GetFromAddress() + + coin, err := sdk.ParseCoin(args[2]) + if err != nil { + return err + } + + msg := types.NewMsgDistributeTokenByEvaluation(args[0], address, fromAddress, coin) + err = msg.ValidateBasic() + if err != nil { + return err + } + + return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + }, + } +} diff --git a/old/x/trust/client/rest/query.go b/old/x/trust/client/rest/query.go new file mode 100644 index 0000000..9417d8f --- /dev/null +++ b/old/x/trust/client/rest/query.go @@ -0,0 +1,30 @@ +package rest + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/lcnem/trust/x/trust/internal/types" + + "github.com/cosmos/cosmos-sdk/types/rest" + + "github.com/gorilla/mux" +) + +func getAccountScoresHandler(cliCtx context.CLIContext, storeName string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + bz, _ := cliCtx.Codec.MarshalJSON(types.QueryAccountScoresParam{Address: mux.Vars(r)["address"], TopicIDs: mux.Vars(r)["topic-ids"]}) + + res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", storeName, types.QueryAccountScores), bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) + return + } + var scores map[string]float64 + json.Unmarshal(res, &scores) + + rest.PostProcessResponse(w, cliCtx, scores) + } +} diff --git a/old/x/trust/client/rest/rest.go b/old/x/trust/client/rest/rest.go new file mode 100644 index 0000000..422a3c0 --- /dev/null +++ b/old/x/trust/client/rest/rest.go @@ -0,0 +1,17 @@ +package rest + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/gorilla/mux" +) + +// RegisterRoutes - Central function to define routes that get registered by the main application +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeName string) { + r.HandleFunc(fmt.Sprintf("/%s/scores/{address}", storeName), getAccountScoresHandler(cliCtx, storeName)).Queries("topic-ids", "{topic-ids}").Methods("GET") + r.HandleFunc(fmt.Sprintf("/%s/evaluate", storeName), evaluateHandler(cliCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/%s/distribute-by-score", storeName), distributeByScoreHandler(cliCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/%s/distribute-by-evaluation", storeName), distributeByEvaluationHandler(cliCtx)).Methods("POST") +} diff --git a/old/x/trust/client/rest/tx.go b/old/x/trust/client/rest/tx.go new file mode 100644 index 0000000..2e0e3a0 --- /dev/null +++ b/old/x/trust/client/rest/tx.go @@ -0,0 +1,141 @@ +package rest + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/lcnem/trust/x/trust/internal/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" +) + +type evaluateReq struct { + BaseReq rest.BaseReq `json:"base_req"` + TopicID string `json:"topic_id"` + FromAddress string `json:"from_address"` + ToAddress string `json:"to_address"` + Weight1000 sdk.Int `json:"weight1000"` +} + +func evaluateHandler(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req evaluateReq + + if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") + return + } + + baseReq := req.BaseReq.Sanitize() + if !baseReq.ValidateBasic(w) { + return + } + + toAddress, err := sdk.AccAddressFromBech32(req.ToAddress) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + // create the message + msg := types.NewMsgEvaluate(req.TopicID, fromAddress, toAddress, req.Weight1000) + err = msg.ValidateBasic() + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) + } +} + +type distributeByScoreReq struct { + BaseReq rest.BaseReq `json:"base_req"` + TopicID string `json:"topic_id"` + FromAddress string `json:"from_address"` + Amount sdk.Coin `json:"amount"` +} + +func distributeByScoreHandler(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req distributeByScoreReq + if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") + return + } + + baseReq := req.BaseReq.Sanitize() + if !baseReq.ValidateBasic(w) { + return + } + + fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + // create the message + msg := types.NewMsgDistributeTokenByScore(req.TopicID, fromAddress, req.Amount) + err = msg.ValidateBasic() + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) + } +} + +type distributeByEvaluationReq struct { + BaseReq rest.BaseReq `json:"base_req"` + TopicID string `json:"topic_id"` + Address string `json:"address"` + FromAddress string `json:"from_address"` + Amount sdk.Coin `json:"amount"` +} + +func distributeByEvaluationHandler(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req distributeByEvaluationReq + if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") + return + } + + baseReq := req.BaseReq.Sanitize() + if !baseReq.ValidateBasic(w) { + return + } + + fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + Address, err := sdk.AccAddressFromBech32(req.Address) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + // create the message + msg := types.NewMsgDistributeTokenByEvaluation(req.TopicID, Address, fromAddress, req.Amount) + err = msg.ValidateBasic() + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) + } +} diff --git a/old/x/trust/genesis.go b/old/x/trust/genesis.go new file mode 100644 index 0000000..c527c36 --- /dev/null +++ b/old/x/trust/genesis.go @@ -0,0 +1,35 @@ +package trust + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// GenesisState is genesis state +type GenesisState struct { +} + +// NewGenesisState is a constructor of GenesisState +func NewGenesisState(master string) GenesisState { + return GenesisState{} +} + +// ValidateGenesis checks the Genesis +func ValidateGenesis(data GenesisState) error { + return nil +} + +// DefaultGenesisState returns default genesis state +func DefaultGenesisState() GenesisState { + return GenesisState{} +} + +// InitGenesis inits genesis +func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// ExportGenesis exports genesis +func ExportGenesis(ctx sdk.Context, k Keeper) GenesisState { + return GenesisState{} +} diff --git a/old/x/trust/handler.go b/old/x/trust/handler.go new file mode 100644 index 0000000..0f7c772 --- /dev/null +++ b/old/x/trust/handler.go @@ -0,0 +1,48 @@ +package trust + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// NewHandler returns a handler for "coin" type messages. +func NewHandler(keeper Keeper) sdk.Handler { + return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + switch msg := msg.(type) { + case MsgEvaluate: + return handleMsgEvaluate(ctx, keeper, msg) + case MsgDistributeTokenByScore: + return handleMsgDistributeTokenByScore(ctx, keeper, msg) + case MsgDistributeTokenByEvaluation: + return handleMsgDistributeTokenByEvaluation(ctx, keeper, msg) + default: + errMsg := fmt.Sprintf("Unrecognized coin Msg type: %v", msg.Type()) + return sdk.ErrUnknownRequest(errMsg).Result() + } + } +} + +func handleMsgEvaluate(ctx sdk.Context, keeper Keeper, msg MsgEvaluate) sdk.Result { + keeper.SetEvaluation(ctx, msg.TopicID, msg.FromAddress, msg.ToAddress, msg.Weight1000) + + return sdk.Result{} +} + +func handleMsgDistributeTokenByScore(ctx sdk.Context, keeper Keeper, msg MsgDistributeTokenByScore) sdk.Result { + err := keeper.DistributeTokenByScore(ctx, msg.TopicID, msg.FromAddress, msg.Amount) + if err != nil { + return sdk.ResultFromError(err) + } + + return sdk.Result{} +} + +func handleMsgDistributeTokenByEvaluation(ctx sdk.Context, keeper Keeper, msg MsgDistributeTokenByEvaluation) sdk.Result { + err := keeper.DistributeTokenByEvaluation(ctx, msg.TopicID, msg.Address, msg.FromAddress, msg.Amount) + if err != nil { + return sdk.ResultFromError(err) + } + + return sdk.Result{} +} diff --git a/x/trust/internal/keeper/distribute.go b/old/x/trust/internal/keeper/distribute.go similarity index 100% rename from x/trust/internal/keeper/distribute.go rename to old/x/trust/internal/keeper/distribute.go diff --git a/old/x/trust/internal/keeper/keeper.go b/old/x/trust/internal/keeper/keeper.go new file mode 100644 index 0000000..a826707 --- /dev/null +++ b/old/x/trust/internal/keeper/keeper.go @@ -0,0 +1,62 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/bank" + + "github.com/KimuraYu45z/pagerank-go" +) + +// Keeper maintains the link to storage and exposes getter/setter methods for the various parts of the state machine +type Keeper struct { + cdc *codec.Codec // The wire codec for binary encoding/decoding. + + storeKey sdk.StoreKey // Unexposed key to access store from sdk.Context + + BankKeeper bank.Keeper +} + +// NewKeeper creates new instances of the coin Keeper +func NewKeeper(cdc *codec.Codec, storeKey sdk.StoreKey, bankKeeper bank.Keeper) Keeper { + return Keeper{ + cdc: cdc, + storeKey: storeKey, + BankKeeper: bankKeeper, + } +} + +// GetAccountScores returns the score +func (k Keeper) GetAccountScores(ctx sdk.Context, topicIDs []string, accAddress sdk.AccAddress) pagerank.Vector { + account := accAddress.String() + scoreVector := pagerank.Vector{} + + for _, topicID := range topicIDs { + s := k.getScoreVectorUnmarshaled(ctx, topicID) + scoreVector[topicID] = s[account] + } + + return scoreVector +} + +// SetEvaluation sets the evaluation +func (k Keeper) SetEvaluation(ctx sdk.Context, topicID string, fromAddress sdk.AccAddress, toAddress sdk.AccAddress, weight1000 sdk.Int) { + from := fromAddress.String() + to := toAddress.String() + + linkMatrix := k.getLinkMatrixUnmarshaled(ctx, topicID) + stochasticMatrix := pagerank.GetStochastixMatrix(linkMatrix) + scoreVector := k.getScoreVectorUnmarshaled(ctx, topicID) + + setEvaluationAndTransition(from, to, weight1000.Int64(), &linkMatrix, &stochasticMatrix, &scoreVector) + + k.setLinkMatrixMarshaled(ctx, topicID, linkMatrix) + k.setStochasticMatrixMarshaled(ctx, topicID, stochasticMatrix) + k.setScoreVectorMarshaled(ctx, topicID, scoreVector) +} + +func setEvaluationAndTransition(from string, to string, weight1000 int64, linkMatrix *pagerank.Matrix, stochasticMatrix *pagerank.Matrix, scoreVector *pagerank.Vector) { + linkMatrix.Set(from, to, float64(weight1000)/float64(1000)) + *stochasticMatrix = pagerank.GetStochastixMatrix(*linkMatrix) + *scoreVector = pagerank.TransitionScore(*scoreVector, *stochasticMatrix) +} diff --git a/x/trust/internal/keeper/keeper_test.go b/old/x/trust/internal/keeper/keeper_test.go similarity index 100% rename from x/trust/internal/keeper/keeper_test.go rename to old/x/trust/internal/keeper/keeper_test.go diff --git a/old/x/trust/internal/keeper/querier.go b/old/x/trust/internal/keeper/querier.go new file mode 100644 index 0000000..e7d33d9 --- /dev/null +++ b/old/x/trust/internal/keeper/querier.go @@ -0,0 +1,40 @@ +package keeper + +import ( + "encoding/json" + "strings" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/lcnem/trust/x/trust/internal/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// NewQuerier is the module level router for state queries +func NewQuerier(keeper Keeper) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { + switch path[0] { + case types.QueryAccountScores: + return queryAccountScores(ctx, path[1:], req, keeper) + default: + return nil, sdk.ErrUnknownRequest("unknown trust query endpoint") + } + } +} + +func queryAccountScores(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { + var param types.QueryAccountScoresParam + codec.Cdc.MustUnmarshalJSON(req.Data, ¶m) + + address, err := sdk.AccAddressFromBech32(param.Address) + if err != nil { + return nil, sdk.ErrInvalidAddress(address.String()) + } + topicIDs := strings.Split(param.TopicIDs, ",") + + vector := keeper.GetAccountScores(ctx, topicIDs, address) + res, _ := json.Marshal(vector) + + return res, nil +} diff --git a/x/trust/internal/keeper/store.go b/old/x/trust/internal/keeper/store.go similarity index 100% rename from x/trust/internal/keeper/store.go rename to old/x/trust/internal/keeper/store.go diff --git a/old/x/trust/internal/types/codec.go b/old/x/trust/internal/types/codec.go new file mode 100644 index 0000000..fe9bcf9 --- /dev/null +++ b/old/x/trust/internal/types/codec.go @@ -0,0 +1,19 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +// ModuleCdc is the codec for the module +var ModuleCdc = codec.New() + +func init() { + RegisterCodec(ModuleCdc) +} + +// RegisterCodec registers concrete types on the Amino codec +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(MsgEvaluate{}, "trust/MsgEvaluate", nil) + cdc.RegisterConcrete(MsgDistributeTokenByScore{}, "trust/MsgDistributeTokenByScore", nil) + cdc.RegisterConcrete(MsgDistributeTokenByEvaluation{}, "trust/MsgDistributeTokenByEvaluation", nil) +} diff --git a/old/x/trust/internal/types/errors.go b/old/x/trust/internal/types/errors.go new file mode 100644 index 0000000..870bb27 --- /dev/null +++ b/old/x/trust/internal/types/errors.go @@ -0,0 +1,23 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// DefaultCodespace is the Module Name +const ( + DefaultCodespace sdk.CodespaceType = ModuleName + + CodeInvalidTopicID sdk.CodeType = 1 + CodeInvalidWeight sdk.CodeType = 2 +) + +// ErrInvalidTopicID is the error for invalid topic id +func ErrInvalidTopicID() sdk.Error { + return sdk.NewError(DefaultCodespace, CodeInvalidTopicID, "Topic ID must start with [a-z] and available characters are [a-z],[0-9],-") +} + +// ErrInvalidWeight is the error for invalid weight +func ErrInvalidWeight() sdk.Error { + return sdk.NewError(DefaultCodespace, CodeInvalidWeight, "1000times weight must be positive and less than or equal to 1000.") +} diff --git a/old/x/trust/internal/types/key.go b/old/x/trust/internal/types/key.go new file mode 100644 index 0000000..9e28f13 --- /dev/null +++ b/old/x/trust/internal/types/key.go @@ -0,0 +1,12 @@ +package types + +const ( + // ModuleName is the name of the module + ModuleName = "trust" + + // StoreKey to be used when creating the KVStore + StoreKey = ModuleName + + // QueryAccountScores QueryAccountScores + QueryAccountScores = "account-scores" +) diff --git a/x/trust/internal/types/msgs.go b/old/x/trust/internal/types/msgs.go similarity index 100% rename from x/trust/internal/types/msgs.go rename to old/x/trust/internal/types/msgs.go diff --git a/x/trust/internal/types/msgs_test.go b/old/x/trust/internal/types/msgs_test.go similarity index 100% rename from x/trust/internal/types/msgs_test.go rename to old/x/trust/internal/types/msgs_test.go diff --git a/old/x/trust/internal/types/querier.go b/old/x/trust/internal/types/querier.go new file mode 100644 index 0000000..19f8649 --- /dev/null +++ b/old/x/trust/internal/types/querier.go @@ -0,0 +1,12 @@ +package types + +// QueryAccountScoresParam QueryAccountScoresParam +type QueryAccountScoresParam struct { + Address string `json:"address"` + TopicIDs string `json:"topic_ids"` +} + +// QueryResAccountScores Queries Result Payload +type QueryResAccountScores struct { + Scores string `json:"scores" yaml:"scores"` +} diff --git a/old/x/trust/module.go b/old/x/trust/module.go new file mode 100644 index 0000000..aabf51e --- /dev/null +++ b/old/x/trust/module.go @@ -0,0 +1,130 @@ +package trust + +import ( + "encoding/json" + + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/lcnem/trust/x/trust/client/cli" + "github.com/lcnem/trust/x/trust/client/rest" + + "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// type check to ensure the interface is properly implemented +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// AppModuleBasic is an app module Basics object +type AppModuleBasic struct{} + +// Name returns module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// RegisterCodec returns RegisterCodec +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) +} + +// DefaultGenesis returns default genesis state +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +// ValidateGenesis checks the Genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := ModuleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + // Once json successfully marshalled, passes along to genesis.go + return ValidateGenesis(data) +} + +// RegisterRESTRoutes returns rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { + rest.RegisterRoutes(ctx, rtr, StoreKey) +} + +// GetQueryCmd returns the root query command of this module +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) +} + +// GetTxCmd returns the root tx command of this module +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(StoreKey, cdc) +} + +// AppModule struct +type AppModule struct { + AppModuleBasic + keeper Keeper +} + +// NewAppModule creates a new AppModule Object +func NewAppModule(k Keeper) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + keeper: k, + } +} + +// Name returns module name +func (AppModule) Name() string { + return ModuleName +} + +// RegisterInvariants is empty +func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {} + +// Route returns RouterKey +func (am AppModule) Route() string { + return RouterKey +} + +// NewHandler returns new Handler +func (am AppModule) NewHandler() sdk.Handler { + return NewHandler(am.keeper) +} + +// QuerierRoute returns module name +func (am AppModule) QuerierRoute() string { + return ModuleName +} + +// NewQuerierHandler returns new Querier +func (am AppModule) NewQuerierHandler() sdk.Querier { + return NewQuerier(am.keeper) +} + +// BeginBlock is a callback function +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} + +// EndBlock is a callback function +func (am AppModule) EndBlock(sdk.Context, abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// InitGenesis inits genesis +func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + ModuleCdc.MustUnmarshalJSON(data, &genesisState) + return InitGenesis(ctx, am.keeper, genesisState) +} + +// ExportGenesis exports genesis +func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, am.keeper) + return ModuleCdc.MustMarshalJSON(gs) +} diff --git a/x/trust/spec/01-concepts.md b/old/x/trust/spec/01-concepts.md similarity index 100% rename from x/trust/spec/01-concepts.md rename to old/x/trust/spec/01-concepts.md diff --git a/x/.gitkeep b/x/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/x/trust/README.md b/x/trust/README.md new file mode 100644 index 0000000..deff07c --- /dev/null +++ b/x/trust/README.md @@ -0,0 +1,7 @@ +# TODO + +The scaffolding tool creates a module with countless todos. These todos are placed in places in which you much delete them and fill them with what the module you are building needs. + +## APP + +Once you have created your module and you are ready to integrate it into your app then you can follow the readme that is generated in the scaffolding of the app. diff --git a/x/trust/abci.go b/x/trust/abci.go new file mode 100644 index 0000000..9019c34 --- /dev/null +++ b/x/trust/abci.go @@ -0,0 +1,18 @@ +package trust + +import ( + + abci "github.com/tendermint/tendermint/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// BeginBlocker check for infraction evidence or downtime of validators +// on every begin block +func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k Keeper) { +// TODO: fill out if your application requires beginblock, if not you can delete this function +} + +// EndBlocker called every block, process inflation, update validator set. +func EndBlocker(ctx sdk.Context, k Keeper) { +// TODO: fill out if your application requires endblock, if not you can delete this function +} \ No newline at end of file diff --git a/x/trust/alias.go b/x/trust/alias.go index b46c55a..56664f8 100644 --- a/x/trust/alias.go +++ b/x/trust/alias.go @@ -5,31 +5,42 @@ import ( "github.com/lcnem/trust/x/trust/internal/types" ) -// nolint const ( - ModuleName = types.ModuleName - RouterKey = types.RouterKey - StoreKey = types.StoreKey + // TODO: define constants that you would like exposed from the internal package + + ModuleName = types.ModuleName + RouterKey = types.RouterKey + StoreKey = types.StoreKey + DefaultParamspace = types.DefaultParamspace + QueryParams = types.QueryParams + QuerierRoute = types.QuerierRoute ) -// nolint var ( - NewKeeper = keeper.NewKeeper - NewQuerier = keeper.NewQuerier + // functions aliases + NewKeeper = keeper.NewKeeper + NewQuerier = keeper.NewQuerier + RegisterCodec = types.RegisterCodec + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + // TODO: Fill out function aliases NewMsgEvaluate = types.NewMsgEvaluate NewMsgDistributeTokenByScore = types.NewMsgDistributeTokenByScore NewMsgDistributeTokenByEvaluation = types.NewMsgDistributeTokenByEvaluation - ModuleCdc = types.ModuleCdc - RegisterCodec = types.RegisterCodec + + // variable aliases + ModuleCdc = types.ModuleCdc + // TODO: Fill out variable aliases ) type ( - // Keeper keeper.Keeper - Keeper = keeper.Keeper - // MsgEvaluate types.MsgEvaluate + Keeper = keeper.Keeper + GenesisState = types.GenesisState + Params = types.Params + + // TODO: Fill out module types MsgEvaluate = types.MsgEvaluate - // MsgDistributeTokenByScore types.MsgDistributeTokenByScore MsgDistributeTokenByScore = types.MsgDistributeTokenByScore - // MsgDistributeTokenByEvaluation types.MsgDistributeTokenByEvaluation MsgDistributeTokenByEvaluation = types.MsgDistributeTokenByEvaluation ) diff --git a/x/trust/client/cli/query.go b/x/trust/client/cli/query.go index a5ca533..6a08283 100644 --- a/x/trust/client/cli/query.go +++ b/x/trust/client/cli/query.go @@ -1,50 +1,39 @@ package cli import ( - "encoding/json" "fmt" + "strings" + + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/lcnem/trust/x/trust/internal/types" - "github.com/spf13/cobra" ) -// GetQueryCmd returns query commands -func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { - coinQueryCmd := &cobra.Command{ +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { + // Group trust queries under a subcommand + trustQueryCmd := &cobra.Command{ Use: types.ModuleName, - Short: "Querying commands for the trust module", + Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } - coinQueryCmd.AddCommand(client.GetCommands( - getCmdAccountScores(storeKey, cdc), - )...) - return coinQueryCmd -} -func getCmdAccountScores(queryRoute string, cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ - Use: "account-scores [address] [topic_ids[,]]", - Short: "get account scores", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - bz, _ := cdc.MarshalJSON(types.QueryAccountScoresParam{Address: args[0], TopicIDs: args[1]}) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryAccountScores), bz) - if err != nil { - fmt.Printf(err.Error()) - return nil - } - var scores map[string]float64 - json.Unmarshal(res, &scores) - - return cliCtx.PrintOutput(scores) - }, - } + trustQueryCmd.AddCommand( + flags.GetCommands( + // TODO: Add query Cmds + )..., + ) + + return trustQueryCmd + } + +// TODO: Add Query Commands diff --git a/x/trust/client/cli/tx.go b/x/trust/client/cli/tx.go index afe0e23..c597ae0 100644 --- a/x/trust/client/cli/tx.go +++ b/x/trust/client/cli/tx.go @@ -1,9 +1,13 @@ package cli import ( + "fmt" + "bufio" + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -12,113 +16,44 @@ import ( "github.com/lcnem/trust/x/trust/internal/types" ) -// GetTxCmd is GetTxCmd -func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { - coinTxCmd := &cobra.Command{ +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + trustTxCmd := &cobra.Command{ Use: types.ModuleName, - Short: "Trust transaction subcommands", + Short: fmt.Sprintf("%S transactions subcommands", types.ModuleName), DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } - coinTxCmd.AddCommand(client.PostCommands( - getCmdEvaluate(cdc), - getCmdDistributeTokenByScore(cdc), - getCmdDistributeTokenByEvaluation(cdc), + trustTxCmd.AddCommand(flags.PostCommands( + // TODO: Add tx based commands + // GetCmd(cdc) )...) - return coinTxCmd + return trustTxCmd } -func getCmdEvaluate(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ - Use: "evaluate [topic_id] [to_address] [weight1000]", - Short: "evaluate", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - - toAddress, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - weight1000, ok := sdk.NewIntFromString(args[2]) - if !ok { - return sdk.ErrUnknownRequest(args[2]) - } - - msg := types.NewMsgEvaluate(args[0], cliCtx.GetFromAddress(), toAddress, weight1000) - err = msg.ValidateBasic() - if err != nil { - return err - } - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } -} - -func getCmdDistributeTokenByScore(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ - Use: "distribute-by-score [topic_id] [amount]", - Short: "distribute your token by score", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - - fromAddress := cliCtx.GetFromAddress() - - coin, err := sdk.ParseCoin(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgDistributeTokenByScore(args[0], fromAddress, coin) - err = msg.ValidateBasic() - if err != nil { - return err - } - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } -} - -func getCmdDistributeTokenByEvaluation(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ - Use: "distribute-by-evaluation [topic_id] [address] [amount]", - Short: "distribute your token by evaluation", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - - address, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - fromAddress := cliCtx.GetFromAddress() - - coin, err := sdk.ParseCoin(args[2]) - if err != nil { - return err - } - - msg := types.NewMsgDistributeTokenByEvaluation(args[0], address, fromAddress, coin) - err = msg.ValidateBasic() - if err != nil { - return err - } - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } -} +// Example: +// +// GetCmd is the CLI command for doing +// func GetCmd(cdc *codec.Codec) *cobra.Command { +// return &cobra.Command{ +// Use: "/* Describe your action cmd */", +// Short: "/* Provide a short description on the cmd */", +// Args: cobra.ExactArgs(2), // Does your request require arguments +// RunE: func(cmd *cobra.Command, args []string) error { +// cliCtx := context.NewCLIContext().WithCodec(cdc) +// inBuf := bufio.NewReader(cmd.InOrStdin()) +// txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) + +// msg := types.NewMsg(/* Action params */) +// err = msg.ValidateBasic() +// if err != nil { +// return err +// } + +// return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) +// }, +// } +// } diff --git a/x/trust/client/rest/query.go b/x/trust/client/rest/query.go index 9417d8f..bda1a23 100644 --- a/x/trust/client/rest/query.go +++ b/x/trust/client/rest/query.go @@ -1,30 +1,40 @@ package rest import ( - "encoding/json" "fmt" "net/http" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/lcnem/trust/x/trust/internal/types" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/types/rest" - - "github.com/gorilla/mux" + "github.com/lcnem/trust/x/trust/internal/types" ) -func getAccountScoresHandler(cliCtx context.CLIContext, storeName string) http.HandlerFunc { +func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { + // TODO: Define your GET REST endpoints + r.HandleFunc( + "/trust/parameters", + queryParamsHandlerFn(cliCtx), + ).Methods("GET") +} + +func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - bz, _ := cliCtx.Codec.MarshalJSON(types.QueryAccountScoresParam{Address: mux.Vars(r)["address"], TopicIDs: mux.Vars(r)["topic-ids"]}) + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + route := fmt.Sprintf("custom/%s/parameters", types.QuerierRoute) - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", storeName, types.QueryAccountScores), bz) + res, height, err := cliCtx.QueryWithData(route, nil) if err != nil { - rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - var scores map[string]float64 - json.Unmarshal(res, &scores) - rest.PostProcessResponse(w, cliCtx, scores) + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, res) } } diff --git a/x/trust/client/rest/rest.go b/x/trust/client/rest/rest.go index 422a3c0..b575ccf 100644 --- a/x/trust/client/rest/rest.go +++ b/x/trust/client/rest/rest.go @@ -1,17 +1,13 @@ package rest import ( - "fmt" + "github.com/gorilla/mux" "github.com/cosmos/cosmos-sdk/client/context" - - "github.com/gorilla/mux" ) -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeName string) { - r.HandleFunc(fmt.Sprintf("/%s/scores/{address}", storeName), getAccountScoresHandler(cliCtx, storeName)).Queries("topic-ids", "{topic-ids}").Methods("GET") - r.HandleFunc(fmt.Sprintf("/%s/evaluate", storeName), evaluateHandler(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/%s/distribute-by-score", storeName), distributeByScoreHandler(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/%s/distribute-by-evaluation", storeName), distributeByEvaluationHandler(cliCtx)).Methods("POST") +// RegisterRoutes registers trust-related REST handlers to a router +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { + registerQueryRoutes(cliCtx, r) + registerTxRoutes(cliCtx, r) } diff --git a/x/trust/client/rest/tx.go b/x/trust/client/rest/tx.go index 2e0e3a0..699a287 100644 --- a/x/trust/client/rest/tx.go +++ b/x/trust/client/rest/tx.go @@ -1,141 +1,45 @@ package rest import ( + "bytes" "net/http" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/lcnem/trust/x/trust/internal/types" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/lcnem/trust/x/trust/internal/types" ) -type evaluateReq struct { - BaseReq rest.BaseReq `json:"base_req"` - TopicID string `json:"topic_id"` - FromAddress string `json:"from_address"` - ToAddress string `json:"to_address"` - Weight1000 sdk.Int `json:"weight1000"` -} - -func evaluateHandler(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req evaluateReq - - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") - return - } - - baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { - return - } - - toAddress, err := sdk.AccAddressFromBech32(req.ToAddress) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // create the message - msg := types.NewMsgEvaluate(req.TopicID, fromAddress, toAddress, req.Weight1000) - err = msg.ValidateBasic() - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) - } -} - -type distributeByScoreReq struct { - BaseReq rest.BaseReq `json:"base_req"` - TopicID string `json:"topic_id"` - FromAddress string `json:"from_address"` - Amount sdk.Coin `json:"amount"` +func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { + // r.HandleFunc( + // TODO: Define the Rest route , + // Call the function which should be executed for this route), + // ).Methods("POST") } -func distributeByScoreHandler(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req distributeByScoreReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") - return - } - - baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // create the message - msg := types.NewMsgDistributeTokenByScore(req.TopicID, fromAddress, req.Amount) - err = msg.ValidateBasic() - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) - } -} - -type distributeByEvaluationReq struct { - BaseReq rest.BaseReq `json:"base_req"` - TopicID string `json:"topic_id"` - Address string `json:"address"` - FromAddress string `json:"from_address"` - Amount sdk.Coin `json:"amount"` +/* +// Action TX body +type Req struct { + BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` + // TODO: Define more types if needed } -func distributeByEvaluationHandler(cliCtx context.CLIContext) http.HandlerFunc { +func RequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req distributeByEvaluationReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") - return - } + var req Req + vars := mux.Vars(r) baseReq := req.BaseReq.Sanitize() if !baseReq.ValidateBasic(w) { return } - fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - Address, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // create the message - msg := types.NewMsgDistributeTokenByEvaluation(req.TopicID, Address, fromAddress, req.Amount) - err = msg.ValidateBasic() - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } + // TODO: Define the module tx logic for this action - utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) + utils.WriteGenerateStdTxResponse(w, cliCtx, BaseReq, []sdk.Msg{msg}) } } +*/ \ No newline at end of file diff --git a/x/trust/genesis.go b/x/trust/genesis.go index c527c36..7212b84 100644 --- a/x/trust/genesis.go +++ b/x/trust/genesis.go @@ -2,34 +2,24 @@ package trust import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/lcnem/trust/x/trust/internal/types" abci "github.com/tendermint/tendermint/abci/types" ) -// GenesisState is genesis state -type GenesisState struct { -} - -// NewGenesisState is a constructor of GenesisState -func NewGenesisState(master string) GenesisState { - return GenesisState{} -} +// InitGenesis initialize default parameters +// and the keeper's address to pubkey map +func InitGenesis(ctx sdk.Context, k Keeper, data types.GenesisState) { -// ValidateGenesis checks the Genesis -func ValidateGenesis(data GenesisState) error { - return nil -} + // TODO: Define logic for when you would like to initalize a new genesis -// DefaultGenesisState returns default genesis state -func DefaultGenesisState() GenesisState { - return GenesisState{} -} - -// InitGenesis inits genesis -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } -// ExportGenesis exports genesis -func ExportGenesis(ctx sdk.Context, k Keeper) GenesisState { - return GenesisState{} +// ExportGenesis writes the current store values +// to a genesis file, which can be imported again +// with InitGenesis +func ExportGenesis(ctx sdk.Context, k Keeper) (data types.GenesisState) { + + // TODO: Define logic for exporting state + return types.NewGenesisState() } diff --git a/x/trust/handler.go b/x/trust/handler.go index 0f7c772..c69ac92 100644 --- a/x/trust/handler.go +++ b/x/trust/handler.go @@ -4,45 +4,42 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/lcnem/trust/x/trust/internal/types" ) -// NewHandler returns a handler for "coin" type messages. -func NewHandler(keeper Keeper) sdk.Handler { +// NewHandler creates an sdk.Handler for all the trust type messages +func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { - case MsgEvaluate: - return handleMsgEvaluate(ctx, keeper, msg) - case MsgDistributeTokenByScore: - return handleMsgDistributeTokenByScore(ctx, keeper, msg) - case MsgDistributeTokenByEvaluation: - return handleMsgDistributeTokenByEvaluation(ctx, keeper, msg) + // TODO: Define your msg cases + // + //Example: + // case MsgSet: + // return handleMsg(ctx, keeper, msg) default: - errMsg := fmt.Sprintf("Unrecognized coin Msg type: %v", msg.Type()) + errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) return sdk.ErrUnknownRequest(errMsg).Result() } } } -func handleMsgEvaluate(ctx sdk.Context, keeper Keeper, msg MsgEvaluate) sdk.Result { - keeper.SetEvaluation(ctx, msg.TopicID, msg.FromAddress, msg.ToAddress, msg.Weight1000) +// handde does x +func handleMsg(ctx sdk.Context, msg MsgType, k Keeper) sdk.Result { - return sdk.Result{} -} - -func handleMsgDistributeTokenByScore(ctx sdk.Context, keeper Keeper, msg MsgDistributeTokenByScore) sdk.Result { - err := keeper.DistributeTokenByScore(ctx, msg.TopicID, msg.FromAddress, msg.Amount) + err := k.(ctx, msg.ValidatorAddr) if err != nil { - return sdk.ResultFromError(err) + return err.Result() } - return sdk.Result{} -} - -func handleMsgDistributeTokenByEvaluation(ctx sdk.Context, keeper Keeper, msg MsgDistributeTokenByEvaluation) sdk.Result { - err := keeper.DistributeTokenByEvaluation(ctx, msg.TopicID, msg.Address, msg.FromAddress, msg.Amount) - if err != nil { - return sdk.ResultFromError(err) - } + // TODO: Define your msg events + ctx.EventManager().EmitEvent( + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeySender, msg.ValidatorAddr.String()), + ), + ) - return sdk.Result{} + return sdk.Result{Events: ctx.EventManager().Events()} } diff --git a/x/trust/internal/keeper/keeper.go b/x/trust/internal/keeper/keeper.go index a826707..6e9adea 100644 --- a/x/trust/internal/keeper/keeper.go +++ b/x/trust/internal/keeper/keeper.go @@ -1,62 +1,55 @@ package keeper import ( + "fmt" + + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/libs/log" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" - - "github.com/KimuraYu45z/pagerank-go" + "github.com/lcnem/trust/x/trust/internal/types" ) -// Keeper maintains the link to storage and exposes getter/setter methods for the various parts of the state machine +// Keeper of the trust store type Keeper struct { - cdc *codec.Codec // The wire codec for binary encoding/decoding. - - storeKey sdk.StoreKey // Unexposed key to access store from sdk.Context - - BankKeeper bank.Keeper + storeKey sdk.StoreKey + cdc *codec.Codec } -// NewKeeper creates new instances of the coin Keeper -func NewKeeper(cdc *codec.Codec, storeKey sdk.StoreKey, bankKeeper bank.Keeper) Keeper { - return Keeper{ +// NewKeeper creates a trust keeper +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey) Keeper { + keeper := Keeper{ + storeKey: key, cdc: cdc, - storeKey: storeKey, - BankKeeper: bankKeeper, } + return keeper } -// GetAccountScores returns the score -func (k Keeper) GetAccountScores(ctx sdk.Context, topicIDs []string, accAddress sdk.AccAddress) pagerank.Vector { - account := accAddress.String() - scoreVector := pagerank.Vector{} +// Logger returns a module-specific logger. +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} - for _, topicID := range topicIDs { - s := k.getScoreVectorUnmarshaled(ctx, topicID) - scoreVector[topicID] = s[account] +// Get returns the pubkey from the adddress-pubkey relation +func (k Keeper) Get(ctx sdk.Context, key string) (/* TODO: Fill out this type */, error) { + store := ctx.KVStore(k.storeKey) + var item /* TODO: Fill out this type */ + byteKey := []byte(key) + err := k.cdc.UnmarshalBinaryLengthPrefixed(store.Get(byteKey), &item) + if err != nil { + return nil, err } - - return scoreVector + return item, nil } -// SetEvaluation sets the evaluation -func (k Keeper) SetEvaluation(ctx sdk.Context, topicID string, fromAddress sdk.AccAddress, toAddress sdk.AccAddress, weight1000 sdk.Int) { - from := fromAddress.String() - to := toAddress.String() - - linkMatrix := k.getLinkMatrixUnmarshaled(ctx, topicID) - stochasticMatrix := pagerank.GetStochastixMatrix(linkMatrix) - scoreVector := k.getScoreVectorUnmarshaled(ctx, topicID) - - setEvaluationAndTransition(from, to, weight1000.Int64(), &linkMatrix, &stochasticMatrix, &scoreVector) - - k.setLinkMatrixMarshaled(ctx, topicID, linkMatrix) - k.setStochasticMatrixMarshaled(ctx, topicID, stochasticMatrix) - k.setScoreVectorMarshaled(ctx, topicID, scoreVector) +func (k Keeper) set(ctx sdk.Context, key string, value /* TODO: fill out this type */ ) { + store := ctx.KVStore(k.storeKey) + bz := k.cdc.MustMarshalBinaryLengthPrefixed(value) + store.Set([]byte(key), bz) } -func setEvaluationAndTransition(from string, to string, weight1000 int64, linkMatrix *pagerank.Matrix, stochasticMatrix *pagerank.Matrix, scoreVector *pagerank.Vector) { - linkMatrix.Set(from, to, float64(weight1000)/float64(1000)) - *stochasticMatrix = pagerank.GetStochastixMatrix(*linkMatrix) - *scoreVector = pagerank.TransitionScore(*scoreVector, *stochasticMatrix) +func (k Keeper) delete(ctx sdk.Context, key string) { + store := ctx.KVStore(k.storeKey) + store.Delete([]byte(key)) } diff --git a/x/trust/internal/keeper/params.go b/x/trust/internal/keeper/params.go new file mode 100644 index 0000000..1db30f4 --- /dev/null +++ b/x/trust/internal/keeper/params.go @@ -0,0 +1,22 @@ +package keeper +/* +// TODO: Define if your module needs Parameters, if not this can be deleted + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/lcnem/trust/x/trust/internal/types" +) + +// GetParams returns the total set of trust parameters. +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + k.paramspace.GetParamSet(ctx, ¶ms) + return params +} + +// SetParams sets the trust parameters to the param space. +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramspace.SetParamSet(ctx, ¶ms) +} +*/ \ No newline at end of file diff --git a/x/trust/internal/keeper/querier.go b/x/trust/internal/keeper/querier.go index e7d33d9..70082b2 100644 --- a/x/trust/internal/keeper/querier.go +++ b/x/trust/internal/keeper/querier.go @@ -1,40 +1,40 @@ package keeper import ( - "encoding/json" - "strings" + "fmt" - "github.com/cosmos/cosmos-sdk/codec" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/lcnem/trust/x/trust/internal/types" - abci "github.com/tendermint/tendermint/abci/types" ) -// NewQuerier is the module level router for state queries -func NewQuerier(keeper Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { +// NewQuerier creates a new querier for trust clients. +func NewQuerier(k Keeper) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { - case types.QueryAccountScores: - return queryAccountScores(ctx, path[1:], req, keeper) + case types.QueryParams: + return queryParams(ctx, k) + // TODO: Put the modules query routes default: - return nil, sdk.ErrUnknownRequest("unknown trust query endpoint") + return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown trust query endpoint") } } } -func queryAccountScores(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var param types.QueryAccountScoresParam - codec.Cdc.MustUnmarshalJSON(req.Data, ¶m) +func queryParams(ctx sdk.Context, k Keeper) ([]byte, error) { + params := k.GetParams(ctx) - address, err := sdk.AccAddressFromBech32(param.Address) + res, err := codec.MarshalJSONIndent(types.ModuleCdc, params) if err != nil { - return nil, sdk.ErrInvalidAddress(address.String()) + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) } - topicIDs := strings.Split(param.TopicIDs, ",") - - vector := keeper.GetAccountScores(ctx, topicIDs, address) - res, _ := json.Marshal(vector) return res, nil } + +// TODO: Add the modules query functions +// They will be similar to the above one: queryParams() diff --git a/x/trust/internal/types/codec.go b/x/trust/internal/types/codec.go index fe9bcf9..82f7e08 100644 --- a/x/trust/internal/types/codec.go +++ b/x/trust/internal/types/codec.go @@ -4,16 +4,17 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -// ModuleCdc is the codec for the module -var ModuleCdc = codec.New() +// RegisterCodec registers concrete types on codec +func RegisterCodec(cdc *codec.Codec) { + // TODO: Register the modules msgs +} + +// ModuleCdc defines the module codec +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() RegisterCodec(ModuleCdc) -} - -// RegisterCodec registers concrete types on the Amino codec -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgEvaluate{}, "trust/MsgEvaluate", nil) - cdc.RegisterConcrete(MsgDistributeTokenByScore{}, "trust/MsgDistributeTokenByScore", nil) - cdc.RegisterConcrete(MsgDistributeTokenByEvaluation{}, "trust/MsgDistributeTokenByEvaluation", nil) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/trust/internal/types/errors.go b/x/trust/internal/types/errors.go index 870bb27..1485819 100644 --- a/x/trust/internal/types/errors.go +++ b/x/trust/internal/types/errors.go @@ -1,23 +1,13 @@ package types import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DefaultCodespace is the Module Name -const ( - DefaultCodespace sdk.CodespaceType = ModuleName - CodeInvalidTopicID sdk.CodeType = 1 - CodeInvalidWeight sdk.CodeType = 2 + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// ErrInvalidTopicID is the error for invalid topic id -func ErrInvalidTopicID() sdk.Error { - return sdk.NewError(DefaultCodespace, CodeInvalidTopicID, "Topic ID must start with [a-z] and available characters are [a-z],[0-9],-") -} -// ErrInvalidWeight is the error for invalid weight -func ErrInvalidWeight() sdk.Error { - return sdk.NewError(DefaultCodespace, CodeInvalidWeight, "1000times weight must be positive and less than or equal to 1000.") -} +// TODO: Fill out some custom errors for the module +// You can see how they are constructed below: +// var ( +// ErrInvalid = sdkerrors.Register(ModuleName, 1, "custom error message") +// ) diff --git a/x/trust/internal/types/events.go b/x/trust/internal/types/events.go new file mode 100644 index 0000000..58c42dd --- /dev/null +++ b/x/trust/internal/types/events.go @@ -0,0 +1,15 @@ +package types + +// trust module event types +const ( + // TODO: Create your event types + // EventType = "action" + + // TODO: Create keys fo your events, the values will be derivided from the msg + // AttributeKeyAddress = "address" + + // TODO: Some events may not have values for that reason you want to emit that something happened. + // AttributeValueDoubleSign = "double_sign" + + AttributeValueCategory = ModuleName +) diff --git a/x/trust/internal/types/expected_keepers.go b/x/trust/internal/types/expected_keepers.go new file mode 100644 index 0000000..9bc1336 --- /dev/null +++ b/x/trust/internal/types/expected_keepers.go @@ -0,0 +1,24 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" +) + +// ParamSubspace defines the expected Subspace interfacace +type ParamSubspace interface { + WithKeyTable(table params.KeyTable) params.Subspace + Get(ctx sdk.Context, key []byte, ptr interface{}) + GetParamSet(ctx sdk.Context, ps params.ParamSet) + SetParamSet(ctx sdk.Context, ps params.ParamSet) +} + +/* +When a module wishes to interact with an otehr module it is good practice to define what it will use +as an interface so the module can not use things that are not permitted. +TODO: Create interfaces of what you expect the other keepers to have to be able to use this module. +type BankKeeper interface { + SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error) + SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error +} +*/ diff --git a/x/trust/internal/types/genesis.go b/x/trust/internal/types/genesis.go new file mode 100644 index 0000000..425dc6f --- /dev/null +++ b/x/trust/internal/types/genesis.go @@ -0,0 +1,29 @@ +package types + +// GenesisState - all trust state that must be provided at genesis +type GenesisState struct { + // TODO: Fill out what is needed by the module for genesis +} + +// NewGenesisState creates a new GenesisState object +func NewGenesisState( + /* TODO: Fill out with what is needed for genesis state*/ +) GenesisState { + + return GenesisState{ + // TODO: Fill out according to your genesis state + } +} + +// DefaultGenesisState - default GenesisState used by Cosmos Hub +func DefaultGenesisState() GenesisState { + return GenesisState{ + // TODO: Fill out according to your genesis state, these values will be initialized but empty + } +} + +// ValidateGenesis validates the trust genesis parameters +func ValidateGenesis(data GenesisState) error { + // TODO: Create a sanity check to make sure the state conforms to the modules needs + return nil +} diff --git a/x/trust/internal/types/key.go b/x/trust/internal/types/key.go index 9e28f13..2d62c8e 100644 --- a/x/trust/internal/types/key.go +++ b/x/trust/internal/types/key.go @@ -7,6 +7,8 @@ const ( // StoreKey to be used when creating the KVStore StoreKey = ModuleName - // QueryAccountScores QueryAccountScores - QueryAccountScores = "account-scores" -) + // RouterKey to be used for routing msgs + RouterKey = ModuleName + + QuerierRoute = ModuleName +) \ No newline at end of file diff --git a/x/trust/internal/types/msg.go b/x/trust/internal/types/msg.go new file mode 100644 index 0000000..86516c9 --- /dev/null +++ b/x/trust/internal/types/msg.go @@ -0,0 +1,47 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// TODO: Describe your actions, these will implment the interface of `sdk.Msg` +/* +verify interface at compile time +var _ sdk.Msg = &Msg{} + +Msg - struct for unjailing jailed validator +type Msg struct { + ValidatorAddr sdk.ValAddress `json:"address" yaml:"address"` // address of the validator operator +} + +NewMsg creates a new Msg instance +func NewMsg(validatorAddr sdk.ValAddress) Msg { + return Msg{ + ValidatorAddr: validatorAddr, + } +} + +const Const = "" + +// nolint +func (msg Msg) Route() string { return RouterKey } +func (msg Msg) Type() string { return Const } +func (msg Msg) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{sdk.AccAddress(msg.ValidatorAddr)} +} + +GetSignBytes gets the bytes for the message signer to sign on +func (msg Msg) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(msg) + return sdk.MustSortJSON(bz) +} + +ValidateBasic validity check for the AnteHandler +func (msg Msg) ValidateBasic() error { + if msg.ValidatorAddr.Empty() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing validator address" + } + return nil +} +*/ diff --git a/x/trust/internal/types/params.go b/x/trust/internal/types/params.go new file mode 100644 index 0000000..fdce42c --- /dev/null +++ b/x/trust/internal/types/params.go @@ -0,0 +1,60 @@ +package types + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/x/params" +) + +// Default parameter namespace +const ( + DefaultParamspace = ModuleName + // TODO: Define your default parameters +) + +// Parameter store keys +var ( + // TODO: Define your keys for the parameter store + // KeyParamName = []byte("ParamName") +) + +// ParamKeyTable for trust module +func ParamKeyTable() params.KeyTable { + return params.NewKeyTable().RegisterParamSet(&Params{}) +} + +// Params - used for initializing default parameter for trust at genesis +type Params struct { + // TODO: Add your Paramaters to the Paramter struct + // KeyParamName string `json:"key_param_name"` +} + +// NewParams creates a new Params object +func NewParams(/* TODO: Pass in the paramters*/) Params { + + return Params{ + // TODO: Create your Params Type + } +} + +// String implements the stringer interface for Params +func (p Params) String() string { + return fmt.Sprintf(` + // TODO: Return all the params as a string + `, ) +} + +// ParamSetPairs - Implements params.ParamSet +func (p *Params) ParamSetPairs() params.ParamSetPairs { + return params.ParamSetPairs{ + // TODO: Pair your key with the param + // params.NewParamSetPair(KeyParamName, &p.ParamName), + } +} + +// DefaultParams defines the parameters for this module +func DefaultParams() Params { + return NewParams( + // TODO: Pass in your default Params + ) +} diff --git a/x/trust/internal/types/querier.go b/x/trust/internal/types/querier.go index 19f8649..ef54f26 100644 --- a/x/trust/internal/types/querier.go +++ b/x/trust/internal/types/querier.go @@ -1,12 +1,22 @@ package types -// QueryAccountScoresParam QueryAccountScoresParam -type QueryAccountScoresParam struct { - Address string `json:"address"` - TopicIDs string `json:"topic_ids"` -} -// QueryResAccountScores Queries Result Payload -type QueryResAccountScores struct { - Scores string `json:"scores" yaml:"scores"` +// Query endpoints supported by the trust querier +const ( + //TODO: Describe query parameters, update with your query + // Query = "" +) + +/* +Below you will be able how to set your own queries: + + +// QueryResList Queries Result Payload for a query +type QueryResList []string + +// implement fmt.Stringer +func (n QueryResList) String() string { + return strings.Join(n[:], "\n") } + +*/ \ No newline at end of file diff --git a/x/trust/module.go b/x/trust/module.go index aabf51e..c85380c 100644 --- a/x/trust/module.go +++ b/x/trust/module.go @@ -6,125 +6,138 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/lcnem/trust/x/trust/client/cli" "github.com/lcnem/trust/x/trust/client/rest" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/lcnem/trust/x/trust/internal/types" ) -// type check to ensure the interface is properly implemented var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) -// AppModuleBasic is an app module Basics object +// AppModuleBasic defines the basic application module used by the trust module. type AppModuleBasic struct{} -// Name returns module name +var _ module.AppModuleBasic = AppModuleBasic{} + +// Name returns the trust module's name. func (AppModuleBasic) Name() string { - return ModuleName + return types.ModuleName } -// RegisterCodec returns RegisterCodec +// RegisterCodec registers the trust module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// DefaultGenesis returns default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the trust +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// ValidateGenesis checks the Genesis +// ValidateGenesis performs genesis state validation for the trust module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } - // Once json successfully marshalled, passes along to genesis.go return ValidateGenesis(data) } -// RegisterRESTRoutes returns rest routes +// RegisterRESTRoutes registers the REST routes for the trust module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr, StoreKey) + rest.RegisterRoutes(ctx, rtr) } -// GetQueryCmd returns the root query command of this module +// GetTxCmd returns the root tx command for the trust module. +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) +} + +// GetQueryCmd returns no root query command for the trust module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(StoreKey, cdc) } -// GetTxCmd returns the root tx command of this module -func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetTxCmd(StoreKey, cdc) -} +//____________________________________________________________________________ -// AppModule struct +// AppModule implements an application module for the trust module. type AppModule struct { AppModuleBasic - keeper Keeper + + keeper Keeper + // TODO: Add keepers that your application depends on } -// NewAppModule creates a new AppModule Object +// NewAppModule creates a new AppModule object func NewAppModule(k Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: k, + AppModuleBasic: AppModuleBasic{}, + keeper: k, + // TODO: Add keepers that your application depends on } } -// Name returns module name +// Name returns the trust module's name. func (AppModule) Name() string { return ModuleName } -// RegisterInvariants is empty -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {} +// RegisterInvariants registers the trust module invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Route returns RouterKey -func (am AppModule) Route() string { +// Route returns the message routing key for the trust module. +func (AppModule) Route() string { return RouterKey } -// NewHandler returns new Handler +// NewHandler returns an sdk.Handler for the trust module. func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } -// QuerierRoute returns module name -func (am AppModule) QuerierRoute() string { - return ModuleName +// QuerierRoute returns the trust module's querier route name. +func (AppModule) QuerierRoute() string { + return QuerierRoute } -// NewQuerierHandler returns new Querier +// NewQuerierHandler returns the trust module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.keeper) } -// BeginBlock is a callback function -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock is a callback function -func (am AppModule) EndBlock(sdk.Context, abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// InitGenesis inits genesis +// InitGenesis performs genesis initialization for the trust module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) - return InitGenesis(ctx, am.keeper, genesisState) + InitGenesis(ctx, am.keeper, genesisState) + return []abci.ValidatorUpdate{} } -// ExportGenesis exports genesis +// ExportGenesis returns the exported genesis state as raw bytes for the trust +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } + +// BeginBlock returns the begin blocker for the trust module. +func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { + BeginBlocker(ctx, req, am.keeper) +} + +// EndBlock returns the end blocker for the trust module. It returns no validator +// updates. +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} diff --git a/x/trust/spec/README.md b/x/trust/spec/README.md new file mode 100644 index 0000000..e71b092 --- /dev/null +++ b/x/trust/spec/README.md @@ -0,0 +1,17 @@ +# trust module specification + +## Abstract + + + +## Contents + +// TODO: Create the below files if they are needed. +1. **[Concepts](01_concepts.md)** +2. **[State](02_state.md)** +3. **[Messages](03_messages.md)** +4. **[Begin-Block](04_begin_block.md)** +5. **[End-Block](06_end_bloc.md)** +6. **[05_hooks](06_hooks.md)** +7. **[Events](07_events.md)** +8. **[Parameters](08_params.md)** From 64910448c86099a19daa1bb3c9c14ea2393d6c8d Mon Sep 17 00:00:00 2001 From: unknown <33382781+YuKimura45z@users.noreply.github.com> Date: Thu, 6 Feb 2020 22:09:46 +0900 Subject: [PATCH 2/3] [update]ci --- .github/workflows/go.yml | 45 +++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 24 deletions(-) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 195363c..ef83a00 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -1,34 +1,31 @@ name: Go -on: [push] +on: pull_request jobs: - build: name: Build runs-on: ubuntu-latest steps: + - name: Set up Go 1.13 + uses: actions/setup-go@v1 + with: + go-version: 1.13 + id: go + + - name: Check out code into the Go module directory + uses: actions/checkout@v2 - - name: Set up Go 1.13 - uses: actions/setup-go@v1 - with: - go-version: 1.13 - id: go + - uses: actions/cache@v1 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- - - name: Check out code into the Go module directory - uses: actions/checkout@v1 + - name: Get dependencies + run: go get -v -t -d ./... - - name: Get dependencies - run: | - go get -v -t -d ./... - if [ -f Gopkg.toml ]; then - curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - dep ensure - fi + - name: Build + run: go build -v . - - name: Build - run: | - go build -v ./cmd/trustcli - go build -v ./cmd/trustd - - - name: Test - run: | - go test ./app + - name: Test + run: go test -v . From b03d40459ec9deb7a3c3ca8ed99d0d85b7104624 Mon Sep 17 00:00:00 2001 From: unknown <33382781+YuKimura45z@users.noreply.github.com> Date: Fri, 7 Feb 2020 11:45:03 +0900 Subject: [PATCH 3/3] =?UTF-8?q?[update]=E9=80=94=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/settings.json | 3 + cmd/trustcli/main.go | 4 +- cmd/trustd/main.go | 2 +- go.mod | 1 + go.sum | 2 + old/x/trust/alias.go | 35 ---- old/x/trust/client/cli/query.go | 50 ----- old/x/trust/client/cli/tx.go | 124 ----------- old/x/trust/client/rest/query.go | 30 --- old/x/trust/client/rest/rest.go | 17 -- old/x/trust/client/rest/tx.go | 141 ------------- old/x/trust/genesis.go | 35 ---- old/x/trust/handler.go | 48 ----- old/x/trust/internal/keeper/distribute.go | 73 ------- old/x/trust/internal/keeper/keeper.go | 62 ------ old/x/trust/internal/keeper/querier.go | 40 ---- old/x/trust/internal/keeper/store.go | 66 ------ old/x/trust/internal/types/codec.go | 19 -- old/x/trust/internal/types/errors.go | 23 --- old/x/trust/internal/types/key.go | 12 -- old/x/trust/internal/types/msgs.go | 165 --------------- old/x/trust/internal/types/msgs_test.go | 15 -- old/x/trust/internal/types/querier.go | 12 -- old/x/trust/module.go | 130 ------------ old/x/trust/spec/01-concepts.md | 4 - x/trust/alias.go | 2 + x/trust/client/cli/query.go | 25 ++- x/trust/client/cli/tx.go | 96 ++++++++- x/trust/handler.go | 59 +++++- x/trust/internal/keeper/keeper.go | 193 +++++++++++++++--- .../trust/internal/keeper/keeper_test.go | 0 x/trust/internal/keeper/params.go | 22 -- x/trust/internal/keeper/querier.go | 17 +- x/trust/internal/types/errors.go | 7 +- x/trust/internal/types/events.go | 3 + x/trust/internal/types/expected_keepers.go | 24 --- x/trust/internal/types/msg.go | 164 ++++++++++++--- x/trust/internal/types/querier.go | 15 +- 38 files changed, 519 insertions(+), 1221 deletions(-) create mode 100644 .vscode/settings.json delete mode 100644 old/x/trust/alias.go delete mode 100644 old/x/trust/client/cli/query.go delete mode 100644 old/x/trust/client/cli/tx.go delete mode 100644 old/x/trust/client/rest/query.go delete mode 100644 old/x/trust/client/rest/rest.go delete mode 100644 old/x/trust/client/rest/tx.go delete mode 100644 old/x/trust/genesis.go delete mode 100644 old/x/trust/handler.go delete mode 100644 old/x/trust/internal/keeper/distribute.go delete mode 100644 old/x/trust/internal/keeper/keeper.go delete mode 100644 old/x/trust/internal/keeper/querier.go delete mode 100644 old/x/trust/internal/keeper/store.go delete mode 100644 old/x/trust/internal/types/codec.go delete mode 100644 old/x/trust/internal/types/errors.go delete mode 100644 old/x/trust/internal/types/key.go delete mode 100644 old/x/trust/internal/types/msgs.go delete mode 100644 old/x/trust/internal/types/msgs_test.go delete mode 100644 old/x/trust/internal/types/querier.go delete mode 100644 old/x/trust/module.go delete mode 100644 old/x/trust/spec/01-concepts.md rename {old/x => x}/trust/internal/keeper/keeper_test.go (100%) delete mode 100644 x/trust/internal/keeper/params.go delete mode 100644 x/trust/internal/types/expected_keepers.go diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..ad92582 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "editor.formatOnSave": true +} diff --git a/cmd/trustcli/main.go b/cmd/trustcli/main.go index dcd05d6..c998b0b 100644 --- a/cmd/trustcli/main.go +++ b/cmd/trustcli/main.go @@ -52,7 +52,7 @@ func main() { } // Add --chain-id to persistent flags and mark it required - rootCmd.PersistentFlags().String(flags.FlagChainID, "", "Chain ID of tendermint node") + rootCmd.PersistentFlags().String(flags.FlagChainID, "TRUST", "Chain ID of tendermint node") rootCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error { return initConfig(rootCmd) } @@ -73,7 +73,7 @@ func main() { ) // Add flags and prefix all env exposed with TR - executor := cli.PrepareMainCmd(rootCmd, "TR", app.DefaultCLIHome) + executor := cli.PrepareMainCmd(rootCmd, "TRUST", app.DefaultCLIHome) err := executor.Execute() if err != nil { diff --git a/cmd/trustd/main.go b/cmd/trustd/main.go index fccad89..f2e81f7 100644 --- a/cmd/trustd/main.go +++ b/cmd/trustd/main.go @@ -64,7 +64,7 @@ func main() { server.AddCommands(ctx, cdc, rootCmd, newApp, exportAppStateAndTMValidators) // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "TR", app.DefaultNodeHome) + executor := cli.PrepareBaseCmd(rootCmd, "TRUST", app.DefaultNodeHome) rootCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, 0, "Assert registered invariants every N blocks") err := executor.Execute() diff --git a/go.mod b/go.mod index 91ad518..8b659d3 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/lcnem/trust go 1.13 require ( + github.com/KimuraYu45z/pagerank-go v0.0.0-20200207000331-856677daa1b7 github.com/btcsuite/btcd v0.0.0-20190807005414-4063feeff79a // indirect github.com/cosmos/cosmos-sdk v0.38.0 github.com/golang/mock v1.3.1 // indirect diff --git a/go.sum b/go.sum index d9782a3..87efce6 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,8 @@ github.com/ChainSafe/go-schnorrkel v0.0.0-20200102211924-4bcbc698314f h1:4O1om+U github.com/ChainSafe/go-schnorrkel v0.0.0-20200102211924-4bcbc698314f/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= github.com/KimuraYu45z/pagerank-go v0.0.0-20190929124623-c0d3bdb5a499 h1:nl5FTCrmNSDvvKACSNjjnBMG1/aBagBPiwGX0WfQ7TE= github.com/KimuraYu45z/pagerank-go v0.0.0-20190929124623-c0d3bdb5a499/go.mod h1:p6iuwttTlVa82fJ75kcwh8qODW+s4bxjoBPPPRNw06M= +github.com/KimuraYu45z/pagerank-go v0.0.0-20200207000331-856677daa1b7 h1:cnDg9aD3DfticTGUFWe7USFwni5B7gnwDAM48BdTvBA= +github.com/KimuraYu45z/pagerank-go v0.0.0-20200207000331-856677daa1b7/go.mod h1:R4Gxizm9M1i8m8BiV9Pkoo+/3c2XhaUyazCkSWKAgnU= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= diff --git a/old/x/trust/alias.go b/old/x/trust/alias.go deleted file mode 100644 index b46c55a..0000000 --- a/old/x/trust/alias.go +++ /dev/null @@ -1,35 +0,0 @@ -package trust - -import ( - "github.com/lcnem/trust/x/trust/internal/keeper" - "github.com/lcnem/trust/x/trust/internal/types" -) - -// nolint -const ( - ModuleName = types.ModuleName - RouterKey = types.RouterKey - StoreKey = types.StoreKey -) - -// nolint -var ( - NewKeeper = keeper.NewKeeper - NewQuerier = keeper.NewQuerier - NewMsgEvaluate = types.NewMsgEvaluate - NewMsgDistributeTokenByScore = types.NewMsgDistributeTokenByScore - NewMsgDistributeTokenByEvaluation = types.NewMsgDistributeTokenByEvaluation - ModuleCdc = types.ModuleCdc - RegisterCodec = types.RegisterCodec -) - -type ( - // Keeper keeper.Keeper - Keeper = keeper.Keeper - // MsgEvaluate types.MsgEvaluate - MsgEvaluate = types.MsgEvaluate - // MsgDistributeTokenByScore types.MsgDistributeTokenByScore - MsgDistributeTokenByScore = types.MsgDistributeTokenByScore - // MsgDistributeTokenByEvaluation types.MsgDistributeTokenByEvaluation - MsgDistributeTokenByEvaluation = types.MsgDistributeTokenByEvaluation -) diff --git a/old/x/trust/client/cli/query.go b/old/x/trust/client/cli/query.go deleted file mode 100644 index a5ca533..0000000 --- a/old/x/trust/client/cli/query.go +++ /dev/null @@ -1,50 +0,0 @@ -package cli - -import ( - "encoding/json" - "fmt" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/lcnem/trust/x/trust/internal/types" - "github.com/spf13/cobra" -) - -// GetQueryCmd returns query commands -func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { - coinQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the trust module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - coinQueryCmd.AddCommand(client.GetCommands( - getCmdAccountScores(storeKey, cdc), - )...) - return coinQueryCmd -} - -func getCmdAccountScores(queryRoute string, cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ - Use: "account-scores [address] [topic_ids[,]]", - Short: "get account scores", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - bz, _ := cdc.MarshalJSON(types.QueryAccountScoresParam{Address: args[0], TopicIDs: args[1]}) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryAccountScores), bz) - if err != nil { - fmt.Printf(err.Error()) - return nil - } - var scores map[string]float64 - json.Unmarshal(res, &scores) - - return cliCtx.PrintOutput(scores) - }, - } -} diff --git a/old/x/trust/client/cli/tx.go b/old/x/trust/client/cli/tx.go deleted file mode 100644 index afe0e23..0000000 --- a/old/x/trust/client/cli/tx.go +++ /dev/null @@ -1,124 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/lcnem/trust/x/trust/internal/types" -) - -// GetTxCmd is GetTxCmd -func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { - coinTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Trust transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - coinTxCmd.AddCommand(client.PostCommands( - getCmdEvaluate(cdc), - getCmdDistributeTokenByScore(cdc), - getCmdDistributeTokenByEvaluation(cdc), - )...) - - return coinTxCmd -} - -func getCmdEvaluate(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ - Use: "evaluate [topic_id] [to_address] [weight1000]", - Short: "evaluate", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - - toAddress, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - weight1000, ok := sdk.NewIntFromString(args[2]) - if !ok { - return sdk.ErrUnknownRequest(args[2]) - } - - msg := types.NewMsgEvaluate(args[0], cliCtx.GetFromAddress(), toAddress, weight1000) - err = msg.ValidateBasic() - if err != nil { - return err - } - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } -} - -func getCmdDistributeTokenByScore(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ - Use: "distribute-by-score [topic_id] [amount]", - Short: "distribute your token by score", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - - fromAddress := cliCtx.GetFromAddress() - - coin, err := sdk.ParseCoin(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgDistributeTokenByScore(args[0], fromAddress, coin) - err = msg.ValidateBasic() - if err != nil { - return err - } - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } -} - -func getCmdDistributeTokenByEvaluation(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ - Use: "distribute-by-evaluation [topic_id] [address] [amount]", - Short: "distribute your token by evaluation", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - - address, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - fromAddress := cliCtx.GetFromAddress() - - coin, err := sdk.ParseCoin(args[2]) - if err != nil { - return err - } - - msg := types.NewMsgDistributeTokenByEvaluation(args[0], address, fromAddress, coin) - err = msg.ValidateBasic() - if err != nil { - return err - } - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } -} diff --git a/old/x/trust/client/rest/query.go b/old/x/trust/client/rest/query.go deleted file mode 100644 index 9417d8f..0000000 --- a/old/x/trust/client/rest/query.go +++ /dev/null @@ -1,30 +0,0 @@ -package rest - -import ( - "encoding/json" - "fmt" - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/lcnem/trust/x/trust/internal/types" - - "github.com/cosmos/cosmos-sdk/types/rest" - - "github.com/gorilla/mux" -) - -func getAccountScoresHandler(cliCtx context.CLIContext, storeName string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - bz, _ := cliCtx.Codec.MarshalJSON(types.QueryAccountScoresParam{Address: mux.Vars(r)["address"], TopicIDs: mux.Vars(r)["topic-ids"]}) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", storeName, types.QueryAccountScores), bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) - return - } - var scores map[string]float64 - json.Unmarshal(res, &scores) - - rest.PostProcessResponse(w, cliCtx, scores) - } -} diff --git a/old/x/trust/client/rest/rest.go b/old/x/trust/client/rest/rest.go deleted file mode 100644 index 422a3c0..0000000 --- a/old/x/trust/client/rest/rest.go +++ /dev/null @@ -1,17 +0,0 @@ -package rest - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - - "github.com/gorilla/mux" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeName string) { - r.HandleFunc(fmt.Sprintf("/%s/scores/{address}", storeName), getAccountScoresHandler(cliCtx, storeName)).Queries("topic-ids", "{topic-ids}").Methods("GET") - r.HandleFunc(fmt.Sprintf("/%s/evaluate", storeName), evaluateHandler(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/%s/distribute-by-score", storeName), distributeByScoreHandler(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/%s/distribute-by-evaluation", storeName), distributeByEvaluationHandler(cliCtx)).Methods("POST") -} diff --git a/old/x/trust/client/rest/tx.go b/old/x/trust/client/rest/tx.go deleted file mode 100644 index 2e0e3a0..0000000 --- a/old/x/trust/client/rest/tx.go +++ /dev/null @@ -1,141 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/lcnem/trust/x/trust/internal/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" -) - -type evaluateReq struct { - BaseReq rest.BaseReq `json:"base_req"` - TopicID string `json:"topic_id"` - FromAddress string `json:"from_address"` - ToAddress string `json:"to_address"` - Weight1000 sdk.Int `json:"weight1000"` -} - -func evaluateHandler(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req evaluateReq - - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") - return - } - - baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { - return - } - - toAddress, err := sdk.AccAddressFromBech32(req.ToAddress) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // create the message - msg := types.NewMsgEvaluate(req.TopicID, fromAddress, toAddress, req.Weight1000) - err = msg.ValidateBasic() - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) - } -} - -type distributeByScoreReq struct { - BaseReq rest.BaseReq `json:"base_req"` - TopicID string `json:"topic_id"` - FromAddress string `json:"from_address"` - Amount sdk.Coin `json:"amount"` -} - -func distributeByScoreHandler(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req distributeByScoreReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") - return - } - - baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // create the message - msg := types.NewMsgDistributeTokenByScore(req.TopicID, fromAddress, req.Amount) - err = msg.ValidateBasic() - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) - } -} - -type distributeByEvaluationReq struct { - BaseReq rest.BaseReq `json:"base_req"` - TopicID string `json:"topic_id"` - Address string `json:"address"` - FromAddress string `json:"from_address"` - Amount sdk.Coin `json:"amount"` -} - -func distributeByEvaluationHandler(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req distributeByEvaluationReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") - return - } - - baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.FromAddress) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - Address, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // create the message - msg := types.NewMsgDistributeTokenByEvaluation(req.TopicID, Address, fromAddress, req.Amount) - err = msg.ValidateBasic() - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) - } -} diff --git a/old/x/trust/genesis.go b/old/x/trust/genesis.go deleted file mode 100644 index c527c36..0000000 --- a/old/x/trust/genesis.go +++ /dev/null @@ -1,35 +0,0 @@ -package trust - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" -) - -// GenesisState is genesis state -type GenesisState struct { -} - -// NewGenesisState is a constructor of GenesisState -func NewGenesisState(master string) GenesisState { - return GenesisState{} -} - -// ValidateGenesis checks the Genesis -func ValidateGenesis(data GenesisState) error { - return nil -} - -// DefaultGenesisState returns default genesis state -func DefaultGenesisState() GenesisState { - return GenesisState{} -} - -// InitGenesis inits genesis -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ExportGenesis exports genesis -func ExportGenesis(ctx sdk.Context, k Keeper) GenesisState { - return GenesisState{} -} diff --git a/old/x/trust/handler.go b/old/x/trust/handler.go deleted file mode 100644 index 0f7c772..0000000 --- a/old/x/trust/handler.go +++ /dev/null @@ -1,48 +0,0 @@ -package trust - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewHandler returns a handler for "coin" type messages. -func NewHandler(keeper Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { - case MsgEvaluate: - return handleMsgEvaluate(ctx, keeper, msg) - case MsgDistributeTokenByScore: - return handleMsgDistributeTokenByScore(ctx, keeper, msg) - case MsgDistributeTokenByEvaluation: - return handleMsgDistributeTokenByEvaluation(ctx, keeper, msg) - default: - errMsg := fmt.Sprintf("Unrecognized coin Msg type: %v", msg.Type()) - return sdk.ErrUnknownRequest(errMsg).Result() - } - } -} - -func handleMsgEvaluate(ctx sdk.Context, keeper Keeper, msg MsgEvaluate) sdk.Result { - keeper.SetEvaluation(ctx, msg.TopicID, msg.FromAddress, msg.ToAddress, msg.Weight1000) - - return sdk.Result{} -} - -func handleMsgDistributeTokenByScore(ctx sdk.Context, keeper Keeper, msg MsgDistributeTokenByScore) sdk.Result { - err := keeper.DistributeTokenByScore(ctx, msg.TopicID, msg.FromAddress, msg.Amount) - if err != nil { - return sdk.ResultFromError(err) - } - - return sdk.Result{} -} - -func handleMsgDistributeTokenByEvaluation(ctx sdk.Context, keeper Keeper, msg MsgDistributeTokenByEvaluation) sdk.Result { - err := keeper.DistributeTokenByEvaluation(ctx, msg.TopicID, msg.Address, msg.FromAddress, msg.Amount) - if err != nil { - return sdk.ResultFromError(err) - } - - return sdk.Result{} -} diff --git a/old/x/trust/internal/keeper/distribute.go b/old/x/trust/internal/keeper/distribute.go deleted file mode 100644 index 2bda65f..0000000 --- a/old/x/trust/internal/keeper/distribute.go +++ /dev/null @@ -1,73 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/KimuraYu45z/pagerank-go" -) - -// DistributeTokenByScore distributes token by score -func (k Keeper) DistributeTokenByScore(ctx sdk.Context, topicID string, fromAddress sdk.AccAddress, amount sdk.Coin) error { - scoreVector := k.getScoreVectorUnmarshaled(ctx, topicID) - - amountVector, sum := getAmountVectorAndSumByScore(amount.Amount, scoreVector) - - distribute(k, ctx, fromAddress, amount.Denom, sum, amountVector) - - return nil -} - -func getAmountVectorAndSumByScore(amount sdk.Int, scoreVector pagerank.Vector) (map[string]sdk.Int, sdk.Int) { - amountVector := make(map[string]sdk.Int) - sum := sdk.NewInt(0) - for acc, s := range scoreVector { - val := sdk.NewInt(int64(s * float64(amount.Int64()))) - amountVector[acc] = val - sum = sum.Add(val) - } - - return amountVector, sum -} - -// DistributeTokenByEvaluation distributes token by evaluation -func (k Keeper) DistributeTokenByEvaluation(ctx sdk.Context, topicID string, address sdk.AccAddress, fromAddress sdk.AccAddress, amount sdk.Coin) error { - scoreVector := k.getScoreVectorUnmarshaled(ctx, topicID) - - stochasticMatrix := k.getStochasticMatrixUnmarshaled(ctx, topicID) - - amountVector, sum := getAmountVectorAndSumByEvaluation(address.String(), amount.Amount, scoreVector, stochasticMatrix) - - distribute(k, ctx, fromAddress, amount.Denom, sum, amountVector) - - return nil -} - -func getAmountVectorAndSumByEvaluation(address string, amount sdk.Int, scoreVector pagerank.Vector, stochasticMatrix pagerank.Matrix) (map[string]sdk.Int, sdk.Int) { - amountVector := map[string]sdk.Int{} - sum := sdk.NewInt(0) - for from, vec := range stochasticMatrix { - stochastic, ok := vec[address] - if !ok { - continue - } - val := sdk.NewInt(int64(stochastic * scoreVector[from] / scoreVector[address] * float64(amount.Int64()))) - amountVector[from] = val - sum = sum.Add(val) - } - - return amountVector, sum -} - -func distribute(k Keeper, ctx sdk.Context, fromAddress sdk.AccAddress, denom string, sum sdk.Int, amountVector map[string]sdk.Int) error { - _, err := k.BankKeeper.SubtractCoins(ctx, fromAddress, sdk.NewCoins(sdk.NewCoin(denom, sum))) - if err != nil { - return err - } - - for acc, val := range amountVector { - address, _ := sdk.AccAddressFromBech32(acc) - k.BankKeeper.AddCoins(ctx, address, sdk.NewCoins(sdk.NewCoin(denom, val))) - } - - return nil -} diff --git a/old/x/trust/internal/keeper/keeper.go b/old/x/trust/internal/keeper/keeper.go deleted file mode 100644 index a826707..0000000 --- a/old/x/trust/internal/keeper/keeper.go +++ /dev/null @@ -1,62 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" - - "github.com/KimuraYu45z/pagerank-go" -) - -// Keeper maintains the link to storage and exposes getter/setter methods for the various parts of the state machine -type Keeper struct { - cdc *codec.Codec // The wire codec for binary encoding/decoding. - - storeKey sdk.StoreKey // Unexposed key to access store from sdk.Context - - BankKeeper bank.Keeper -} - -// NewKeeper creates new instances of the coin Keeper -func NewKeeper(cdc *codec.Codec, storeKey sdk.StoreKey, bankKeeper bank.Keeper) Keeper { - return Keeper{ - cdc: cdc, - storeKey: storeKey, - BankKeeper: bankKeeper, - } -} - -// GetAccountScores returns the score -func (k Keeper) GetAccountScores(ctx sdk.Context, topicIDs []string, accAddress sdk.AccAddress) pagerank.Vector { - account := accAddress.String() - scoreVector := pagerank.Vector{} - - for _, topicID := range topicIDs { - s := k.getScoreVectorUnmarshaled(ctx, topicID) - scoreVector[topicID] = s[account] - } - - return scoreVector -} - -// SetEvaluation sets the evaluation -func (k Keeper) SetEvaluation(ctx sdk.Context, topicID string, fromAddress sdk.AccAddress, toAddress sdk.AccAddress, weight1000 sdk.Int) { - from := fromAddress.String() - to := toAddress.String() - - linkMatrix := k.getLinkMatrixUnmarshaled(ctx, topicID) - stochasticMatrix := pagerank.GetStochastixMatrix(linkMatrix) - scoreVector := k.getScoreVectorUnmarshaled(ctx, topicID) - - setEvaluationAndTransition(from, to, weight1000.Int64(), &linkMatrix, &stochasticMatrix, &scoreVector) - - k.setLinkMatrixMarshaled(ctx, topicID, linkMatrix) - k.setStochasticMatrixMarshaled(ctx, topicID, stochasticMatrix) - k.setScoreVectorMarshaled(ctx, topicID, scoreVector) -} - -func setEvaluationAndTransition(from string, to string, weight1000 int64, linkMatrix *pagerank.Matrix, stochasticMatrix *pagerank.Matrix, scoreVector *pagerank.Vector) { - linkMatrix.Set(from, to, float64(weight1000)/float64(1000)) - *stochasticMatrix = pagerank.GetStochastixMatrix(*linkMatrix) - *scoreVector = pagerank.TransitionScore(*scoreVector, *stochasticMatrix) -} diff --git a/old/x/trust/internal/keeper/querier.go b/old/x/trust/internal/keeper/querier.go deleted file mode 100644 index e7d33d9..0000000 --- a/old/x/trust/internal/keeper/querier.go +++ /dev/null @@ -1,40 +0,0 @@ -package keeper - -import ( - "encoding/json" - "strings" - - "github.com/cosmos/cosmos-sdk/codec" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/lcnem/trust/x/trust/internal/types" - abci "github.com/tendermint/tendermint/abci/types" -) - -// NewQuerier is the module level router for state queries -func NewQuerier(keeper Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { - switch path[0] { - case types.QueryAccountScores: - return queryAccountScores(ctx, path[1:], req, keeper) - default: - return nil, sdk.ErrUnknownRequest("unknown trust query endpoint") - } - } -} - -func queryAccountScores(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var param types.QueryAccountScoresParam - codec.Cdc.MustUnmarshalJSON(req.Data, ¶m) - - address, err := sdk.AccAddressFromBech32(param.Address) - if err != nil { - return nil, sdk.ErrInvalidAddress(address.String()) - } - topicIDs := strings.Split(param.TopicIDs, ",") - - vector := keeper.GetAccountScores(ctx, topicIDs, address) - res, _ := json.Marshal(vector) - - return res, nil -} diff --git a/old/x/trust/internal/keeper/store.go b/old/x/trust/internal/keeper/store.go deleted file mode 100644 index 3215ccb..0000000 --- a/old/x/trust/internal/keeper/store.go +++ /dev/null @@ -1,66 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/KimuraYu45z/pagerank-go" -) - -func (k Keeper) getScoreVectorUnmarshaled(ctx sdk.Context, topicID string) pagerank.Vector { - store := ctx.KVStore(k.storeKey) - key := fmt.Sprintf("%s/score-vector", topicID) - var vector pagerank.Vector - err := json.Unmarshal(store.Get([]byte(key)), &vector) - if err != nil { - vector = pagerank.Vector{} - } - - return vector -} - -func (k Keeper) setScoreVectorMarshaled(ctx sdk.Context, topicID string, v pagerank.Vector) { - store := ctx.KVStore(k.storeKey) - key := fmt.Sprintf("%s/score-vector", topicID) - bz, _ := json.Marshal(v) - store.Set([]byte(key), bz) -} - -func (k Keeper) getLinkMatrixUnmarshaled(ctx sdk.Context, topicID string) pagerank.Matrix { - store := ctx.KVStore(k.storeKey) - key := fmt.Sprintf("%s/link-matrix", topicID) - var matrix pagerank.Matrix - err := json.Unmarshal(store.Get([]byte(key)), &matrix) - if err != nil { - matrix = pagerank.Matrix{} - } - - return matrix -} - -func (k Keeper) setLinkMatrixMarshaled(ctx sdk.Context, topicID string, m pagerank.Matrix) { - store := ctx.KVStore(k.storeKey) - key := fmt.Sprintf("%s/link-matrix", topicID) - bz, _ := json.Marshal(m) - store.Set([]byte(key), bz) -} - -func (k Keeper) getStochasticMatrixUnmarshaled(ctx sdk.Context, topicID string) pagerank.Matrix { - store := ctx.KVStore(k.storeKey) - key := fmt.Sprintf("%s/stochastic-matrix", topicID) - var matrix pagerank.Matrix - err := json.Unmarshal(store.Get([]byte(key)), &matrix) - if err != nil { - matrix = pagerank.Matrix{} - } - - return matrix -} - -func (k Keeper) setStochasticMatrixMarshaled(ctx sdk.Context, topicID string, m pagerank.Matrix) { - store := ctx.KVStore(k.storeKey) - key := fmt.Sprintf("%s/stochastic-matrix", topicID) - bz, _ := json.Marshal(m) - store.Set([]byte(key), bz) -} diff --git a/old/x/trust/internal/types/codec.go b/old/x/trust/internal/types/codec.go deleted file mode 100644 index fe9bcf9..0000000 --- a/old/x/trust/internal/types/codec.go +++ /dev/null @@ -1,19 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" -) - -// ModuleCdc is the codec for the module -var ModuleCdc = codec.New() - -func init() { - RegisterCodec(ModuleCdc) -} - -// RegisterCodec registers concrete types on the Amino codec -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgEvaluate{}, "trust/MsgEvaluate", nil) - cdc.RegisterConcrete(MsgDistributeTokenByScore{}, "trust/MsgDistributeTokenByScore", nil) - cdc.RegisterConcrete(MsgDistributeTokenByEvaluation{}, "trust/MsgDistributeTokenByEvaluation", nil) -} diff --git a/old/x/trust/internal/types/errors.go b/old/x/trust/internal/types/errors.go deleted file mode 100644 index 870bb27..0000000 --- a/old/x/trust/internal/types/errors.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DefaultCodespace is the Module Name -const ( - DefaultCodespace sdk.CodespaceType = ModuleName - - CodeInvalidTopicID sdk.CodeType = 1 - CodeInvalidWeight sdk.CodeType = 2 -) - -// ErrInvalidTopicID is the error for invalid topic id -func ErrInvalidTopicID() sdk.Error { - return sdk.NewError(DefaultCodespace, CodeInvalidTopicID, "Topic ID must start with [a-z] and available characters are [a-z],[0-9],-") -} - -// ErrInvalidWeight is the error for invalid weight -func ErrInvalidWeight() sdk.Error { - return sdk.NewError(DefaultCodespace, CodeInvalidWeight, "1000times weight must be positive and less than or equal to 1000.") -} diff --git a/old/x/trust/internal/types/key.go b/old/x/trust/internal/types/key.go deleted file mode 100644 index 9e28f13..0000000 --- a/old/x/trust/internal/types/key.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -const ( - // ModuleName is the name of the module - ModuleName = "trust" - - // StoreKey to be used when creating the KVStore - StoreKey = ModuleName - - // QueryAccountScores QueryAccountScores - QueryAccountScores = "account-scores" -) diff --git a/old/x/trust/internal/types/msgs.go b/old/x/trust/internal/types/msgs.go deleted file mode 100644 index f69e561..0000000 --- a/old/x/trust/internal/types/msgs.go +++ /dev/null @@ -1,165 +0,0 @@ -package types - -import ( - "regexp" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// RouterKey is the module name router key -const RouterKey = ModuleName // this was defined in your key.go file - -// MsgEvaluate defines a Evaluate message -type MsgEvaluate struct { - TopicID string `json:"topic_id"` - FromAddress sdk.AccAddress `json:"from_address"` - ToAddress sdk.AccAddress `json:"to_address"` - Weight1000 sdk.Int `json:"weight1000"` -} - -// NewMsgEvaluate is a constructor function for MsgEvaluate -func NewMsgEvaluate(topicID string, fromAddress sdk.AccAddress, toAddress sdk.AccAddress, weight1000 sdk.Int) MsgEvaluate { - return MsgEvaluate{ - TopicID: topicID, - FromAddress: fromAddress, - ToAddress: toAddress, - Weight1000: weight1000, - } -} - -// Route should return the name of the module -func (msg MsgEvaluate) Route() string { return RouterKey } - -// Type should return the action -func (msg MsgEvaluate) Type() string { return "evaluate" } - -// ValidateBasic runs stateless checks on the message -func (msg MsgEvaluate) ValidateBasic() sdk.Error { - if !validateTopicID(msg.TopicID) { - return ErrInvalidTopicID() - } - if msg.FromAddress.Empty() { - return sdk.ErrInvalidAddress(msg.FromAddress.String()) - } - if msg.ToAddress.Empty() { - return sdk.ErrInvalidAddress(msg.ToAddress.String()) - } - if msg.Weight1000.IsNegative() || msg.Weight1000.GT(sdk.NewInt(1000)) { - return ErrInvalidWeight() - } - - return nil -} - -// GetSignBytes encodes the message for signing -func (msg MsgEvaluate) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -// GetSigners defines whose signature is required -func (msg MsgEvaluate) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.FromAddress} -} - -// MsgDistributeTokenByScore defines a DistributeTokenByScore message -type MsgDistributeTokenByScore struct { - TopicID string `json:"topic_id"` - FromAddress sdk.AccAddress `json:"from_address"` - Amount sdk.Coin `json:"amount"` -} - -// NewMsgDistributeTokenByScore is a constructor function for MsgMsgDistributeTokenByScore -func NewMsgDistributeTokenByScore(topicID string, fromAddress sdk.AccAddress, amount sdk.Coin) MsgDistributeTokenByScore { - return MsgDistributeTokenByScore{ - TopicID: topicID, - FromAddress: fromAddress, - Amount: amount, - } -} - -// Route should return the name of the module -func (msg MsgDistributeTokenByScore) Route() string { return RouterKey } - -// Type should return the action -func (msg MsgDistributeTokenByScore) Type() string { return "distribute_token_by_score" } - -// ValidateBasic runs stateless checks on the message -func (msg MsgDistributeTokenByScore) ValidateBasic() sdk.Error { - if !validateTopicID(msg.TopicID) { - return ErrInvalidTopicID() - } - if msg.FromAddress.Empty() { - return sdk.ErrInvalidAddress(msg.FromAddress.String()) - } - if msg.Amount.IsNegative() { - return sdk.ErrInvalidCoins(msg.Amount.String()) - } - - return nil -} - -// GetSignBytes encodes the message for signing -func (msg MsgDistributeTokenByScore) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -// GetSigners defines whose signature is required -func (msg MsgDistributeTokenByScore) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.FromAddress} -} - -// MsgDistributeTokenByEvaluation defines a DistributeTokenByEvaluation message -type MsgDistributeTokenByEvaluation struct { - TopicID string `json:"topic_id"` - Address sdk.AccAddress `json:"address"` - FromAddress sdk.AccAddress `json:"from_address"` - Amount sdk.Coin `json:"amount"` -} - -// NewMsgDistributeTokenByEvaluation is a constructor function for MsgMsgDistributeTokenByEvaluation -func NewMsgDistributeTokenByEvaluation(topicID string, address sdk.AccAddress, fromAddress sdk.AccAddress, amount sdk.Coin) MsgDistributeTokenByEvaluation { - return MsgDistributeTokenByEvaluation{ - TopicID: topicID, - Address: address, - FromAddress: fromAddress, - Amount: amount, - } -} - -// Route should return the name of the module -func (msg MsgDistributeTokenByEvaluation) Route() string { return RouterKey } - -// Type should return the action -func (msg MsgDistributeTokenByEvaluation) Type() string { return "distribute_token_by_evaluation" } - -// ValidateBasic runs stateless checks on the message -func (msg MsgDistributeTokenByEvaluation) ValidateBasic() sdk.Error { - if !validateTopicID(msg.TopicID) { - return ErrInvalidTopicID() - } - if msg.Address.Empty() { - return sdk.ErrInvalidAddress(msg.Address.String()) - } - if msg.FromAddress.Empty() { - return sdk.ErrInvalidAddress(msg.FromAddress.String()) - } - if msg.Amount.IsNegative() { - return sdk.ErrInvalidCoins(msg.Amount.String()) - } - - return nil -} - -// GetSignBytes encodes the message for signing -func (msg MsgDistributeTokenByEvaluation) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -// GetSigners defines whose signature is required -func (msg MsgDistributeTokenByEvaluation) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.FromAddress} -} - -func validateTopicID(topicID string) bool { - return regexp.MustCompile("^[a-z_][a-z_0-9]*$").Match([]byte(topicID)) -} diff --git a/old/x/trust/internal/types/msgs_test.go b/old/x/trust/internal/types/msgs_test.go deleted file mode 100644 index 4a6d200..0000000 --- a/old/x/trust/internal/types/msgs_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestValidateTopicID(t *testing.T) { - require.Equal(t, validateTopicID("a"), true) - require.Equal(t, validateTopicID("ab"), true) - require.Equal(t, validateTopicID("a-"), true) - require.Equal(t, validateTopicID("-a"), false) - require.Equal(t, validateTopicID("0"), false) -} diff --git a/old/x/trust/internal/types/querier.go b/old/x/trust/internal/types/querier.go deleted file mode 100644 index 19f8649..0000000 --- a/old/x/trust/internal/types/querier.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -// QueryAccountScoresParam QueryAccountScoresParam -type QueryAccountScoresParam struct { - Address string `json:"address"` - TopicIDs string `json:"topic_ids"` -} - -// QueryResAccountScores Queries Result Payload -type QueryResAccountScores struct { - Scores string `json:"scores" yaml:"scores"` -} diff --git a/old/x/trust/module.go b/old/x/trust/module.go deleted file mode 100644 index aabf51e..0000000 --- a/old/x/trust/module.go +++ /dev/null @@ -1,130 +0,0 @@ -package trust - -import ( - "encoding/json" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/lcnem/trust/x/trust/client/cli" - "github.com/lcnem/trust/x/trust/client/rest" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" -) - -// type check to ensure the interface is properly implemented -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic is an app module Basics object -type AppModuleBasic struct{} - -// Name returns module name -func (AppModuleBasic) Name() string { - return ModuleName -} - -// RegisterCodec returns RegisterCodec -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - -// DefaultGenesis returns default genesis state -func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) -} - -// ValidateGenesis checks the Genesis -func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := ModuleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - // Once json successfully marshalled, passes along to genesis.go - return ValidateGenesis(data) -} - -// RegisterRESTRoutes returns rest routes -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr, StoreKey) -} - -// GetQueryCmd returns the root query command of this module -func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetQueryCmd(StoreKey, cdc) -} - -// GetTxCmd returns the root tx command of this module -func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetTxCmd(StoreKey, cdc) -} - -// AppModule struct -type AppModule struct { - AppModuleBasic - keeper Keeper -} - -// NewAppModule creates a new AppModule Object -func NewAppModule(k Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: k, - } -} - -// Name returns module name -func (AppModule) Name() string { - return ModuleName -} - -// RegisterInvariants is empty -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {} - -// Route returns RouterKey -func (am AppModule) Route() string { - return RouterKey -} - -// NewHandler returns new Handler -func (am AppModule) NewHandler() sdk.Handler { - return NewHandler(am.keeper) -} - -// QuerierRoute returns module name -func (am AppModule) QuerierRoute() string { - return ModuleName -} - -// NewQuerierHandler returns new Querier -func (am AppModule) NewQuerierHandler() sdk.Querier { - return NewQuerier(am.keeper) -} - -// BeginBlock is a callback function -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock is a callback function -func (am AppModule) EndBlock(sdk.Context, abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// InitGenesis inits genesis -func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - var genesisState GenesisState - ModuleCdc.MustUnmarshalJSON(data, &genesisState) - return InitGenesis(ctx, am.keeper, genesisState) -} - -// ExportGenesis exports genesis -func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return ModuleCdc.MustMarshalJSON(gs) -} diff --git a/old/x/trust/spec/01-concepts.md b/old/x/trust/spec/01-concepts.md deleted file mode 100644 index 5035a51..0000000 --- a/old/x/trust/spec/01-concepts.md +++ /dev/null @@ -1,4 +0,0 @@ -# trust Concepts - -ページランクアルゴリズムによってアドレスをスコア付けする機能。 -トピックIDごとにスコアをつけられる。 \ No newline at end of file diff --git a/x/trust/alias.go b/x/trust/alias.go index 56664f8..bbf25b1 100644 --- a/x/trust/alias.go +++ b/x/trust/alias.go @@ -32,6 +32,8 @@ var ( // variable aliases ModuleCdc = types.ModuleCdc // TODO: Fill out variable aliases + ErrInvalidTopicID = types.ErrInvalidTopicID + ErrInvalidWeight = types.ErrInvalidWeight ) type ( diff --git a/x/trust/client/cli/query.go b/x/trust/client/cli/query.go index 6a08283..65da2c6 100644 --- a/x/trust/client/cli/query.go +++ b/x/trust/client/cli/query.go @@ -28,7 +28,7 @@ func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { trustQueryCmd.AddCommand( flags.GetCommands( - // TODO: Add query Cmds + getCmdAccountScores(queryRoute, cdc), )..., ) @@ -37,3 +37,26 @@ func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { } // TODO: Add Query Commands + +func getCmdAccountScores(queryRoute string, cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "account-scores [address] [topic_ids[,]]", + Short: "get account scores", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + + bz, _ := cdc.MarshalJSON(types.QueryAccountScoresParam{Address: args[0], TopicIDs: args[1]}) + + res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryAccountScores), bz) + if err != nil { + fmt.Printf(err.Error()) + return nil + } + var scores map[string]float64 + json.Unmarshal(res, &scores) + + return cliCtx.PrintOutput(scores) + }, + } +} diff --git a/x/trust/client/cli/tx.go b/x/trust/client/cli/tx.go index c597ae0..ae9b9ce 100644 --- a/x/trust/client/cli/tx.go +++ b/x/trust/client/cli/tx.go @@ -28,7 +28,9 @@ func GetTxCmd(cdc *codec.Codec) *cobra.Command { trustTxCmd.AddCommand(flags.PostCommands( // TODO: Add tx based commands - // GetCmd(cdc) + getCmdEvaluate(cdc), + getCmdDistributeByScore(cdc), + getCmdDistributeByEvaluation(cdc), )...) return trustTxCmd @@ -57,3 +59,95 @@ func GetTxCmd(cdc *codec.Codec) *cobra.Command { // }, // } // } + +func getCmdEvaluate(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "evaluate [topic_id] [to_address] [weight]", + Short: "evaluate", + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + + toAddress, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } + + weight1000, ok := sdk.NewIntFromString(args[2]) + if !ok { + return sdk.ErrUnknownRequest(args[2]) + } + + msg := types.NewMsgEvaluate(args[0], cliCtx.GetFromAddress(), toAddress, weight1000) + err = msg.ValidateBasic() + if err != nil { + return err + } + + return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + }, + } +} + +func getCmdDistributeByScore(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "distribute-by-score [topic_id] [amount]", + Short: "distribute your token by score", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + + fromAddress := cliCtx.GetFromAddress() + + coin, err := sdk.ParseCoin(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgDistributeByScore(args[0], fromAddress, coin) + err = msg.ValidateBasic() + if err != nil { + return err + } + + return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + }, + } +} + +func getCmdDistributeByEvaluation(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "distribute-by-evaluation [topic_id] [address] [amount]", + Short: "distribute your token by evaluation", + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + + address, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } + + fromAddress := cliCtx.GetFromAddress() + + coin, err := sdk.ParseCoin(args[2]) + if err != nil { + return err + } + + msg := types.NewMsgDistributeByEvaluation(args[0], address, fromAddress, coin) + err = msg.ValidateBasic() + if err != nil { + return err + } + + return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + }, + } +} diff --git a/x/trust/handler.go b/x/trust/handler.go index c69ac92..dcae012 100644 --- a/x/trust/handler.go +++ b/x/trust/handler.go @@ -12,11 +12,12 @@ func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { - // TODO: Define your msg cases - // - //Example: - // case MsgSet: - // return handleMsg(ctx, keeper, msg) + case MsgEvaluate: + return handleMsgEvaluate(ctx, k, msg) + case MsgDistributeTokenByScore: + return handleMsgDistributeByScore(ctx, k, msg) + case MsgDistributeTokenByEvaluation: + return handleMsgDistributeByEvaluation(ctx, k, msg) default: errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) return sdk.ErrUnknownRequest(errMsg).Result() @@ -24,10 +25,52 @@ func NewHandler(k Keeper) sdk.Handler { } } -// handde does x -func handleMsg(ctx sdk.Context, msg MsgType, k Keeper) sdk.Result { +// handdeEvaluate does x +func handleMsgEvaluate(ctx sdk.Context, msg MsgType, k Keeper) sdk.Result { - err := k.(ctx, msg.ValidatorAddr) + err := k.Evaluate(ctx, msg.ValidatorAddr) + if err != nil { + return err.Result() + } + + // TODO: Define your msg events + ctx.EventManager().EmitEvent( + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeySender, msg.ValidatorAddr.String()), + ), + ) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + + +// handdeDistributeByScore does x +func handleMsgDistributeByScore(ctx sdk.Context, msg MsgType, k Keeper) sdk.Result { + + err := k.DistributeByScore(ctx, msg.ValidatorAddr) + if err != nil { + return err.Result() + } + + // TODO: Define your msg events + ctx.EventManager().EmitEvent( + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeySender, msg.ValidatorAddr.String()), + ), + ) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + + +// handdeDistributeByEvaluation does x +func handleMsgDistributeByEvaluation(ctx sdk.Context, msg MsgType, k Keeper) sdk.Result { + + err := k.DistributeByEvaluation(ctx, msg.ValidatorAddr) if err != nil { return err.Result() } diff --git a/x/trust/internal/keeper/keeper.go b/x/trust/internal/keeper/keeper.go index 6e9adea..ac0174c 100644 --- a/x/trust/internal/keeper/keeper.go +++ b/x/trust/internal/keeper/keeper.go @@ -1,55 +1,192 @@ package keeper import ( - "fmt" - - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/libs/log" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/lcnem/trust/x/trust/internal/types" + "github.com/cosmos/cosmos-sdk/x/bank" + + "github.com/KimuraYu45z/pagerank-go" ) -// Keeper of the trust store +// Keeper maintains the link to storage and exposes getter/setter methods for the various parts of the state machine type Keeper struct { - storeKey sdk.StoreKey - cdc *codec.Codec + cdc *codec.Codec // The wire codec for binary encoding/decoding. + + storeKey sdk.StoreKey // Unexposed key to access store from sdk.Context + + BankKeeper bank.Keeper } -// NewKeeper creates a trust keeper -func NewKeeper(cdc *codec.Codec, key sdk.StoreKey) Keeper { - keeper := Keeper{ - storeKey: key, +// NewKeeper creates new instances of the coin Keeper +func NewKeeper(cdc *codec.Codec, storeKey sdk.StoreKey, bankKeeper bank.Keeper) Keeper { + return Keeper{ cdc: cdc, + storeKey: storeKey, + BankKeeper: bankKeeper, } - return keeper } -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +// GetAccountScores returns the score +func (k Keeper) GetAccountScores(ctx sdk.Context, topicIDs []string, accAddress sdk.AccAddress) pagerank.Vector { + account := accAddress.String() + scoreVector := pagerank.Vector{} + + for _, topicID := range topicIDs { + s := k.getScoreVectorUnmarshaled(ctx, topicID) + scoreVector[topicID] = s[account] + } + + return scoreVector +} + +// Evaluate sets the evaluation +func (k Keeper) Evalutate(ctx sdk.Context, topicID string, fromAddress sdk.AccAddress, toAddress sdk.AccAddress, weight1000 sdk.Int) { + from := fromAddress.String() + to := toAddress.String() + + linkMatrix := k.getLinkMatrixUnmarshaled(ctx, topicID) + stochasticMatrix := pagerank.GetStochastixMatrix(linkMatrix) + scoreVector := k.getScoreVectorUnmarshaled(ctx, topicID) + + setEvaluationAndTransition(from, to, weight1000.Int64(), &linkMatrix, &stochasticMatrix, &scoreVector) + + k.setLinkMatrixMarshaled(ctx, topicID, linkMatrix) + k.setStochasticMatrixMarshaled(ctx, topicID, stochasticMatrix) + k.setScoreVectorMarshaled(ctx, topicID, scoreVector) +} + +func setEvaluationAndTransition(from string, to string, weight1000 int64, linkMatrix *pagerank.Matrix, stochasticMatrix *pagerank.Matrix, scoreVector *pagerank.Vector) { + linkMatrix.Set(from, to, float64(weight1000)/float64(1000)) + *stochasticMatrix = pagerank.GetStochastixMatrix(*linkMatrix) + *scoreVector = pagerank.TransitionScore(*scoreVector, *stochasticMatrix) } -// Get returns the pubkey from the adddress-pubkey relation -func (k Keeper) Get(ctx sdk.Context, key string) (/* TODO: Fill out this type */, error) { + +// DistributeByScore distributes token by score +func (k Keeper) DistributeByScore(ctx sdk.Context, topicID string, fromAddress sdk.AccAddress, amount sdk.Coin) error { + scoreVector := k.getScoreVectorUnmarshaled(ctx, topicID) + + amountVector, sum := getAmountVectorAndSumByScore(amount.Amount, scoreVector) + + distribute(k, ctx, fromAddress, amount.Denom, sum, amountVector) + + return nil +} + +func getAmountVectorAndSumByScore(amount sdk.Int, scoreVector pagerank.Vector) (map[string]sdk.Int, sdk.Int) { + amountVector := make(map[string]sdk.Int) + sum := sdk.NewInt(0) + for acc, s := range scoreVector { + val := sdk.NewInt(int64(s * float64(amount.Int64()))) + amountVector[acc] = val + sum = sum.Add(val) + } + + return amountVector, sum +} + +// DistributeByEvaluation distributes token by evaluation +func (k Keeper) DistributeByEvaluation(ctx sdk.Context, topicID string, address sdk.AccAddress, fromAddress sdk.AccAddress, amount sdk.Coin) error { + scoreVector := k.getScoreVectorUnmarshaled(ctx, topicID) + + stochasticMatrix := k.getStochasticMatrixUnmarshaled(ctx, topicID) + + amountVector, sum := getAmountVectorAndSumByEvaluation(address.String(), amount.Amount, scoreVector, stochasticMatrix) + + distribute(k, ctx, fromAddress, amount.Denom, sum, amountVector) + + return nil +} + +func getAmountVectorAndSumByEvaluation(address string, amount sdk.Int, scoreVector pagerank.Vector, stochasticMatrix pagerank.Matrix) (map[string]sdk.Int, sdk.Int) { + amountVector := map[string]sdk.Int{} + sum := sdk.NewInt(0) + for from, vec := range stochasticMatrix { + stochastic, ok := vec[address] + if !ok { + continue + } + val := sdk.NewInt(int64(stochastic * scoreVector[from] / scoreVector[address] * float64(amount.Int64()))) + amountVector[from] = val + sum = sum.Add(val) + } + + return amountVector, sum +} + +func distribute(k Keeper, ctx sdk.Context, fromAddress sdk.AccAddress, denom string, sum sdk.Int, amountVector map[string]sdk.Int) error { + _, err := k.BankKeeper.SubtractCoins(ctx, fromAddress, sdk.NewCoins(sdk.NewCoin(denom, sum))) + if err != nil { + return err + } + + for acc, val := range amountVector { + address, _ := sdk.AccAddressFromBech32(acc) + k.BankKeeper.AddCoins(ctx, address, sdk.NewCoins(sdk.NewCoin(denom, val))) + } + + return nil +} + + +func (k Keeper) getScoreVectorUnmarshaled(ctx sdk.Context, topicID string) pagerank.Vector { + store := ctx.KVStore(k.storeKey) + key := fmt.Sprintf("%s/score-vector", topicID) + var vector pagerank.Vector + err := json.Unmarshal(store.Get([]byte(key)), &vector) + if err != nil { + vector = pagerank.Vector{} + } + + return vector +} + +func (k Keeper) setScoreVectorMarshaled(ctx sdk.Context, topicID string, v pagerank.Vector) { store := ctx.KVStore(k.storeKey) - var item /* TODO: Fill out this type */ - byteKey := []byte(key) - err := k.cdc.UnmarshalBinaryLengthPrefixed(store.Get(byteKey), &item) + key := fmt.Sprintf("%s/score-vector", topicID) + bz, _ := json.Marshal(v) + store.Set([]byte(key), bz) +} + +func (k Keeper) getLinkMatrixUnmarshaled(ctx sdk.Context, topicID string) pagerank.Matrix { + store := ctx.KVStore(k.storeKey) + key := fmt.Sprintf("%s/link-matrix", topicID) + var matrix pagerank.Matrix + err := json.Unmarshal(store.Get([]byte(key)), &matrix) if err != nil { - return nil, err + matrix = pagerank.Matrix{} } - return item, nil + + return matrix } -func (k Keeper) set(ctx sdk.Context, key string, value /* TODO: fill out this type */ ) { +func (k Keeper) setLinkMatrixMarshaled(ctx sdk.Context, topicID string, m pagerank.Matrix) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryLengthPrefixed(value) + key := fmt.Sprintf("%s/link-matrix", topicID) + bz, _ := json.Marshal(m) store.Set([]byte(key), bz) } -func (k Keeper) delete(ctx sdk.Context, key string) { +func (k Keeper) getStochasticMatrixUnmarshaled(ctx sdk.Context, topicID string) pagerank.Matrix { store := ctx.KVStore(k.storeKey) - store.Delete([]byte(key)) + key := fmt.Sprintf("%s/stochastic-matrix", topicID) + var matrix pagerank.Matrix + err := json.Unmarshal(store.Get([]byte(key)), &matrix) + if err != nil { + matrix = pagerank.Matrix{} + } + + return matrix +} + +func (k Keeper) setStochasticMatrixMarshaled(ctx sdk.Context, topicID string, m pagerank.Matrix) { + store := ctx.KVStore(k.storeKey) + key := fmt.Sprintf("%s/stochastic-matrix", topicID) + bz, _ := json.Marshal(m) + store.Set([]byte(key), bz) +} + +// Logger returns a module-specific logger. +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } diff --git a/old/x/trust/internal/keeper/keeper_test.go b/x/trust/internal/keeper/keeper_test.go similarity index 100% rename from old/x/trust/internal/keeper/keeper_test.go rename to x/trust/internal/keeper/keeper_test.go diff --git a/x/trust/internal/keeper/params.go b/x/trust/internal/keeper/params.go deleted file mode 100644 index 1db30f4..0000000 --- a/x/trust/internal/keeper/params.go +++ /dev/null @@ -1,22 +0,0 @@ -package keeper -/* -// TODO: Define if your module needs Parameters, if not this can be deleted - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/lcnem/trust/x/trust/internal/types" -) - -// GetParams returns the total set of trust parameters. -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramspace.GetParamSet(ctx, ¶ms) - return params -} - -// SetParams sets the trust parameters to the param space. -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramspace.SetParamSet(ctx, ¶ms) -} -*/ \ No newline at end of file diff --git a/x/trust/internal/keeper/querier.go b/x/trust/internal/keeper/querier.go index 70082b2..81be262 100644 --- a/x/trust/internal/keeper/querier.go +++ b/x/trust/internal/keeper/querier.go @@ -16,8 +16,8 @@ import ( func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { - case types.QueryParams: - return queryParams(ctx, k) + case types.QueryAccountScores: + return queryAccountScores(ctx, k, path[1:], req) // TODO: Put the modules query routes default: return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown trust query endpoint") @@ -25,13 +25,18 @@ func NewQuerier(k Keeper) sdk.Querier { } } -func queryParams(ctx sdk.Context, k Keeper) ([]byte, error) { - params := k.GetParams(ctx) +func queryAccountScores(ctx sdk.Context, k Keeper, path []string, req abci.RequestQuery) ([]byte, error) { + var param types.QueryAccountScoresParam + codec.Cdc.MustUnmarshalJSON(req.Data, ¶m) - res, err := codec.MarshalJSONIndent(types.ModuleCdc, params) + address, err := sdk.AccAddressFromBech32(param.Address) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) } + topicIDs := strings.Split(param.TopicIDs, ",") + + vector := keeper.GetAccountScores(ctx, topicIDs, address) + res, _ := json.Marshal(vector) return res, nil } diff --git a/x/trust/internal/types/errors.go b/x/trust/internal/types/errors.go index 1485819..7815ce3 100644 --- a/x/trust/internal/types/errors.go +++ b/x/trust/internal/types/errors.go @@ -8,6 +8,7 @@ import ( // TODO: Fill out some custom errors for the module // You can see how they are constructed below: -// var ( -// ErrInvalid = sdkerrors.Register(ModuleName, 1, "custom error message") -// ) +var ( + ErrInvalidTopicID = sdkerrors.Register(ModuleName, 1, "topic id must start with [a-z] and available characters are [a-z],[0-9],-") + ErrInvalidWeight = sdkerrors.Register(ModuleName, 2, "weight must be positive") +) diff --git a/x/trust/internal/types/events.go b/x/trust/internal/types/events.go index 58c42dd..0f2a168 100644 --- a/x/trust/internal/types/events.go +++ b/x/trust/internal/types/events.go @@ -4,6 +4,9 @@ package types const ( // TODO: Create your event types // EventType = "action" + EventTypeEvaluate = "evaluate" + EventTypeDistributeByScore = "distribute-by-score" + EventTypeDistributeByEvaluation = "distribute-by-evaluation" // TODO: Create keys fo your events, the values will be derivided from the msg // AttributeKeyAddress = "address" diff --git a/x/trust/internal/types/expected_keepers.go b/x/trust/internal/types/expected_keepers.go deleted file mode 100644 index 9bc1336..0000000 --- a/x/trust/internal/types/expected_keepers.go +++ /dev/null @@ -1,24 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" -) - -// ParamSubspace defines the expected Subspace interfacace -type ParamSubspace interface { - WithKeyTable(table params.KeyTable) params.Subspace - Get(ctx sdk.Context, key []byte, ptr interface{}) - GetParamSet(ctx sdk.Context, ps params.ParamSet) - SetParamSet(ctx sdk.Context, ps params.ParamSet) -} - -/* -When a module wishes to interact with an otehr module it is good practice to define what it will use -as an interface so the module can not use things that are not permitted. -TODO: Create interfaces of what you expect the other keepers to have to be able to use this module. -type BankKeeper interface { - SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error) - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error -} -*/ diff --git a/x/trust/internal/types/msg.go b/x/trust/internal/types/msg.go index 86516c9..255d334 100644 --- a/x/trust/internal/types/msg.go +++ b/x/trust/internal/types/msg.go @@ -1,47 +1,165 @@ package types import ( + "regexp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// TODO: Describe your actions, these will implment the interface of `sdk.Msg` -/* -verify interface at compile time -var _ sdk.Msg = &Msg{} +// verify interface at compile time +var _ sdk.Msg = &MsgEvaluate{} -Msg - struct for unjailing jailed validator -type Msg struct { - ValidatorAddr sdk.ValAddress `json:"address" yaml:"address"` // address of the validator operator +// MsgEvaluate - struct for unjailing jailed validator +type MsgEvaluate struct { + TopicID string `json:"topic_id"` + FromAddress sdk.AccAddress `json:"from_address"` + ToAddress sdk.AccAddress `json:"to_address"` + MilliWeight float32 `json:"milli_weight"` } -NewMsg creates a new Msg instance -func NewMsg(validatorAddr sdk.ValAddress) Msg { - return Msg{ - ValidatorAddr: validatorAddr, +// NewMsgEvaluate creates a new MsgEvaluate instance +func NewMsgEvaluate(topicID string, fromAddress sdk.AccAddress, toAddress sdk.AccAddress, milliWeight float32) MsgEvaluate { + return MsgEvaluate{ + TopicID: topicID, + FromAddress: fromAddress, + ToAddress: toAddress, + MilliWeight: milliWeight, } } -const Const = "" +const evaluateConst = "evaluate" // nolint -func (msg Msg) Route() string { return RouterKey } -func (msg Msg) Type() string { return Const } -func (msg Msg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(msg.ValidatorAddr)} +func (msg MsgEvaluate) Route() string { return RouterKey } +func (msg MsgEvaluate) Type() string { return evaluateConst } +func (msg MsgEvaluate) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.FromAddress} } -GetSignBytes gets the bytes for the message signer to sign on -func (msg Msg) GetSignBytes() []byte { +// GetSignBytes gets the bytes for the message signer to sign on +func (msg MsgEvaluate) GetSignBytes() []byte { bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } -ValidateBasic validity check for the AnteHandler -func (msg Msg) ValidateBasic() error { - if msg.ValidatorAddr.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing validator address" +// ValidateBasic validity check for the AnteHandler +func (msg MsgEvaluate) ValidateBasic() error { + if !validateTopicID(msg.TopicID) { + return ErrInvalidTopicID + } + if msg.FromAddress.Empty() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing from_address") + } + if msg.ToAddress.Empty() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing to_address") + } + if msg.MilliWeight <= 0 { + return ErrInvalidWeight + } + return nil +} + +// verify interface at compile time +var _ sdk.Msg = &MsgDistributeByScore{} + +// MsgDistributeByScore - struct for unjailing jailed validator +type MsgDistributeByScore struct { + TopicID string `json:"topic_id"` + FromAddress sdk.AccAddress `json:"from_address"` + Amount sdk.Coin `json:"amount"` +} + +// NewMsgDistributeByScore creates a new MsgDistributeByScore instance +func NewMsgDistributeByScore(topicID string, fromAddress sdk.AccAddress, amount sdk.Coin) MsgDistributeByScore { + return MsgDistributeByScore{ + TopicID: topicID, + FromAddress: fromAddress, + Amount: amount, + } +} + +const distributeByScoreConst = "distributeByScore" + +// nolint +func (msg MsgDistributeByScore) Route() string { return RouterKey } +func (msg MsgDistributeByScore) Type() string { return distributeByScoreConst } +func (msg MsgDistributeByScore) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.FromAddress} +} + +// GetSignBytes gets the bytes for the message signer to sign on +func (msg MsgDistributeByScore) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(msg) + return sdk.MustSortJSON(bz) +} + +// ValidateBasic validity check for the AnteHandler +func (msg MsgDistributeByScore) ValidateBasic() error { + if !validateTopicID(msg.TopicID) { + return ErrInvalidTopicID + } + if msg.FromAddress.Empty() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing from_address") + } + if !msg.Amount.IsPositive() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) } return nil } -*/ + +// verify interface at compile time +var _ sdk.Msg = &MsgDistributeByEvaluation{} + +// MsgDistributeByEvaluation - struct for unjailing jailed validator +type MsgDistributeByEvaluation struct { + TopicID string `json:"topic_id"` + FromAddress sdk.AccAddress `json:"from_address"` + EvaluatedAddress sdk.AccAddress `json:"evaluated_address"` + Amount sdk.Coin `json:"amount"` +} + +// NewMsgDistributeByEvaluation creates a new MsgDistributeByEvaluation instance +func NewMsgDistributeByEvaluation(topicID string, fromAddress sdk.AccAddress, evaluatedAddress sdk.AccAddress, amount sdk.Coin) MsgDistributeByEvaluation { + return MsgDistributeByEvaluation{ + TopicID: topicID, + FromAddress: fromAddress, + EvaluatedAddress: evaluatedAddress, + Amount: amount, + } +} + +const distributeByEvaluationConst = "distributeByEvaluation" + +// nolint +func (msg MsgDistributeByEvaluation) Route() string { return RouterKey } +func (msg MsgDistributeByEvaluation) Type() string { return distributeByEvaluationConst } +func (msg MsgDistributeByEvaluation) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.FromAddress} +} + +// GetSignBytes gets the bytes for the message signer to sign on +func (msg MsgDistributeByEvaluation) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(msg) + return sdk.MustSortJSON(bz) +} + +// ValidateBasic validity check for the AnteHandler +func (msg MsgDistributeByEvaluation) ValidateBasic() error { + if !validateTopicID(msg.TopicID) { + return ErrInvalidTopicID + } + if msg.FromAddress.Empty() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing from_address") + } + if msg.EvaluatedAddress.Empty() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing evaluated_address") + } + if !msg.Amount.IsPositive() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) + } + return nil +} + +func validateTopicID(topicID string) bool { + return regexp.MustCompile("^[a-z_][a-z_0-9]*$").Match([]byte(topicID)) +} diff --git a/x/trust/internal/types/querier.go b/x/trust/internal/types/querier.go index ef54f26..567ab38 100644 --- a/x/trust/internal/types/querier.go +++ b/x/trust/internal/types/querier.go @@ -5,6 +5,7 @@ package types const ( //TODO: Describe query parameters, update with your query // Query = "" + QueryAccountScores = "account-scores" ) /* @@ -19,4 +20,16 @@ func (n QueryResList) String() string { return strings.Join(n[:], "\n") } -*/ \ No newline at end of file +*/ + + +// QueryAccountScoresParam QueryAccountScoresParam +type QueryAccountScoresParam struct { + Address string `json:"address"` + TopicIDs string `json:"topic_ids"` +} + +// QueryResAccountScores Queries Result Payload +type QueryResAccountScores struct { + Scores string `json:"scores" yaml:"scores"` +}