Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial version PoE module #52

Merged
merged 5 commits into from
Jun 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ version: 2.1
executors:
golang:
docker:
- image: circleci/golang:1.15
- image: circleci/golang:1.16
# user: root # for local testing: https://github.com/CircleCI-Public/circleci-cli/issues/291
working_directory: /go/src/github.com/confio/tgrade

Expand Down
36 changes: 20 additions & 16 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"github.com/CosmWasm/wasmd/x/wasm"
wasmclient "github.com/CosmWasm/wasmd/x/wasm/client"
"github.com/confio/tgrade/x/globalfee"
"github.com/confio/tgrade/x/poe"
poekeeper "github.com/confio/tgrade/x/poe/keeper"
"github.com/confio/tgrade/x/twasm"
twasmkeeper "github.com/confio/tgrade/x/twasm/keeper"
"github.com/cosmos/cosmos-sdk/baseapp"
Expand Down Expand Up @@ -43,8 +45,6 @@ import (
"github.com/cosmos/cosmos-sdk/x/evidence"
evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper"
evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/gov"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
Expand Down Expand Up @@ -126,7 +126,7 @@ var (
// and genesis verification.
ModuleBasics = module.NewBasicManager(
auth.AppModuleBasic{},
genutil.AppModuleBasic{},
poe.AppModuleBasic{},
bank.AppModuleBasic{},
capability.AppModuleBasic{},
staking.AppModuleBasic{},
Expand Down Expand Up @@ -202,6 +202,7 @@ type TgradeApp struct {
evidenceKeeper evidencekeeper.Keeper
transferKeeper ibctransferkeeper.Keeper
twasmKeeper twasmkeeper.Keeper
poeKeeper poekeeper.Keeper

scopedIBCKeeper capabilitykeeper.ScopedKeeper
scopedTransferKeeper capabilitykeeper.ScopedKeeper
Expand Down Expand Up @@ -231,7 +232,7 @@ func NewTgradeApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest
minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey,
evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey,
wasm.StoreKey,
wasm.StoreKey, poe.StoreKey,
)
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
Expand Down Expand Up @@ -333,14 +334,16 @@ func NewTgradeApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest
// The last arguments can contain custom message handlers, and custom query handlers,
// if we want to allow any custom callbacks
supportedFeatures := "staking,stargate"

stakingAdapter := poekeeper.NewStakingAdapter(&app.poeKeeper, app.twasmKeeper.GetContractKeeper())
app.twasmKeeper = twasmkeeper.NewKeeper(
appCodec,
keys[twasm.StoreKey],
app.getSubspace(twasm.ModuleName),
app.accountKeeper,
app.bankKeeper,
app.stakingKeeper,
app.distrKeeper,
stakingAdapter,
stakingAdapter,
app.ibcKeeper.ChannelKeeper,
&app.ibcKeeper.PortKeeper,
scopedWasmKeeper,
Expand Down Expand Up @@ -369,6 +372,8 @@ func NewTgradeApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest
&stakingKeeper,
govRouter,
)

app.poeKeeper = poekeeper.NewKeeper(appCodec, keys[poe.StoreKey])
/**** Module Options ****/

// NOTE: we may consider parsing `appOpts` inside module constructors. For the moment
Expand All @@ -378,10 +383,7 @@ func NewTgradeApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest
// 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,
encodingConfig.TxConfig,
),
poe.NewAppModule(app.poeKeeper, &app.twasmKeeper, app.BaseApp.DeliverTx, encodingConfig.TxConfig, app.twasmKeeper.GetContractKeeper()),
auth.NewAppModule(appCodec, app.accountKeeper, authsims.RandomGenesisAccounts),
vesting.NewAppModule(app.accountKeeper, app.bankKeeper),
bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper),
Expand All @@ -406,13 +408,13 @@ func NewTgradeApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest
// CanWithdrawInvariant invariant.
// NOTE: staking module is required if HistoricalEntries param > 0
app.mm.SetOrderBeginBlockers(
upgradetypes.ModuleName, minttypes.ModuleName, distrtypes.ModuleName, slashingtypes.ModuleName,
evidencetypes.ModuleName, stakingtypes.ModuleName, ibchost.ModuleName,
upgradetypes.ModuleName,
evidencetypes.ModuleName, ibchost.ModuleName,
twasm.ModuleName,
)
app.mm.SetOrderEndBlockers(crisistypes.ModuleName, govtypes.ModuleName, stakingtypes.ModuleName, twasm.ModuleName)
app.mm.SetOrderEndBlockers(crisistypes.ModuleName, govtypes.ModuleName, twasm.ModuleName, poe.ModuleName)

// NOTE: The genutils module must occur after staking so that pools are
// NOTE: The poe module must occur after staking so that pools are
// properly initialized with tokens from genesis accounts.
// NOTE: Capability module must occur first so that it can initialize any capabilities
// so that other modules that want to create or claim capabilities afterwards in InitChain
Expand All @@ -422,9 +424,11 @@ func NewTgradeApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest
app.mm.SetOrderInitGenesis(
capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName,
slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName,
ibchost.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, ibctransfertypes.ModuleName,
ibchost.ModuleName, evidencetypes.ModuleName, ibctransfertypes.ModuleName,
// wasm after ibc transfer
twasm.ModuleName, globalfee.ModuleName,
twasm.ModuleName,
// poe after wasm contract instantiation
poe.ModuleName, globalfee.ModuleName,
)

app.mm.RegisterInvariants(&app.crisisKeeper)
Expand Down
45 changes: 44 additions & 1 deletion app/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@ package app

import (
"encoding/json"
poetypes "github.com/confio/tgrade/x/poe/types"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/tendermint/tendermint/libs/rand"
"os"
"testing"
"time"

"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"
Expand All @@ -18,14 +24,17 @@ var emptyWasmOpts []wasm.Option = nil
func TestTgradeExport(t *testing.T) {
db := db.NewMemDB()
gapp := NewTgradeApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, EmptyBaseAppOptions{}, emptyWasmOpts)

genesisState := NewDefaultGenesisState()

setupWithSingleValidatorGenTX(t, genesisState)

stateBytes, err := json.MarshalIndent(genesisState, "", " ")
require.NoError(t, err)

// Initialize the chain
gapp.InitChain(
abci.RequestInitChain{
Time: time.Now().UTC(),
Validators: []abci.ValidatorUpdate{},
AppStateBytes: stateBytes,
},
Expand All @@ -38,6 +47,40 @@ func TestTgradeExport(t *testing.T) {
require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
}

func setupWithSingleValidatorGenTX(t *testing.T, genesisState GenesisState) {
// a validator needs:
// - signed genTX
// - account object
// - enough funds on the bank
// - membership in engagement group
marshaler := MakeEncodingConfig().Marshaler

myGenTx, myAddr, _ := poetypes.RandomGenTX(t, 100)

var authGenState authtypes.GenesisState
marshaler.MustUnmarshalJSON(genesisState[authtypes.ModuleName], &authGenState)
genAccounts := []authtypes.GenesisAccount{authtypes.NewBaseAccount(myAddr, nil, 0, 0)}
accounts, err := authtypes.PackAccounts(genAccounts)
require.NoError(t, err)
authGenState.Accounts = accounts
genesisState[authtypes.ModuleName] = marshaler.MustMarshalJSON(&authGenState)

var bankGenState banktypes.GenesisState
marshaler.MustUnmarshalJSON(genesisState[banktypes.ModuleName], &bankGenState)

coins := sdk.Coins{sdk.NewCoin(poetypes.DefaultBondDenom, sdk.NewInt(1000000000))}
bankGenState.Balances = append(bankGenState.Balances, banktypes.Balance{Address: myAddr.String(), Coins: coins.Sort()})
genesisState[banktypes.ModuleName] = marshaler.MustMarshalJSON(&bankGenState)

// add system admin to not fail poe on validation
poeGS := poetypes.GetGenesisStateFromAppState(marshaler, genesisState)
poeGS.BondDenom = poetypes.DefaultBondDenom
poeGS.SystemAdminAddress = sdk.AccAddress(rand.Bytes(sdk.AddrLen)).String()
poeGS.GenTxs = []json.RawMessage{myGenTx}
poeGS.Engagement = []poetypes.TG4Member{{Address: myAddr.String(), Weight: 10}}
genesisState = poetypes.SetGenesisStateInAppState(marshaler, genesisState, poeGS)
}

// ensure that blocked addresses are properly set in bank keeper
func TestBlockedAddrs(t *testing.T) {
db := db.NewMemDB()
Expand Down
5 changes: 3 additions & 2 deletions cmd/tgrade/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"errors"
"github.com/confio/tgrade/x/poe/client/cli"
"io"
"os"
"path/filepath"
Expand Down Expand Up @@ -80,9 +81,9 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) {

rootCmd.AddCommand(
genutilcli.InitCmd(app.ModuleBasics, app.DefaultNodeHome),
genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
cli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
genutilcli.MigrateGenesisCmd(),
genutilcli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
cli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
genutilcli.ValidateGenesisCmd(app.ModuleBasics),
AddGenesisAccountCmd(app.DefaultNodeHome),
AddGenesisWasmMsgCmd(app.DefaultNodeHome),
Expand Down
84 changes: 55 additions & 29 deletions cmd/tgrade/testnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,8 @@ import (
"bufio"
"encoding/json"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"

"github.com/spf13/cobra"
tmconfig "github.com/tendermint/tendermint/config"
tmos "github.com/tendermint/tendermint/libs/os"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"

poeclient "github.com/confio/tgrade/x/poe/client"
poetypes "github.com/confio/tgrade/x/poe/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
Expand All @@ -34,6 +23,17 @@ import (
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/spf13/cobra"
tmconfig "github.com/tendermint/tendermint/config"
tmos "github.com/tendermint/tendermint/libs/os"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
"net"
"os"
"path/filepath"
"strings"
"time"
)

const stakingToken = "utgd"
Expand Down Expand Up @@ -154,6 +154,7 @@ func InitTestnet(
p2pPortStart := 26656

inBuf := bufio.NewReader(cmd.InOrStdin())
var adminAddr sdk.AccAddress
// generate private keys, node IDs, and initial transactions
for i := 0; i < numValidators; i++ {
var portOffset int
Expand Down Expand Up @@ -211,6 +212,16 @@ func InitTestnet(
_ = os.RemoveAll(outputDir)
return err
}
if i == 0 { // generate new key for system admin in node0 keychain. This keychain is used by system tests
adminAddr, _, err = server.GenerateSaveCoinKey(kb, "systemadmin", true, algo)
if err != nil {
_ = os.RemoveAll(outputDir)
return err
}
coins := sdk.Coins{sdk.NewCoin(stakingToken, sdk.NewInt(1000000))}
genBalances = append(genBalances, banktypes.Balance{Address: adminAddr.String(), Coins: coins.Sort()})
genAccounts = append(genAccounts, authtypes.NewBaseAccount(adminAddr, nil, 0, 0))
}

info := map[string]string{"secret": secret}

Expand All @@ -235,13 +246,11 @@ func InitTestnet(
genAccounts = append(genAccounts, authtypes.NewBaseAccount(addr, nil, 0, 0))

valTokens := sdk.TokensFromConsensusPower(100)
createValMsg, err := stakingtypes.NewMsgCreateValidator(
sdk.ValAddress(addr),
createValMsg, err := poetypes.NewMsgCreateValidator(
addr,
valPubKeys[i],
sdk.NewCoin(stakingToken, valTokens),
stakingtypes.NewDescription(nodeDirName, "", "", "", ""),
stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()),
sdk.OneInt(),
)
if err != nil {
return err
Expand Down Expand Up @@ -276,8 +285,7 @@ func InitTestnet(

srvconfig.WriteConfigFile(filepath.Join(nodeDir, "config/app.toml"), appConfig)
}

if err := initGenFiles(clientCtx, mbm, chainID, genAccounts, genBalances, genFiles, numValidators); err != nil {
if err := initGenFiles(clientCtx, mbm, chainID, genAccounts, genBalances, genFiles, numValidators, adminAddr); err != nil {
return err
}

Expand All @@ -295,11 +303,15 @@ func InitTestnet(
}

func initGenFiles(
clientCtx client.Context, mbm module.BasicManager, chainID string,
genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance,
genFiles []string, numValidators int,
clientCtx client.Context,
mbm module.BasicManager,
chainID string,
genAccounts []authtypes.GenesisAccount,
genBalances []banktypes.Balance,
genFiles []string,
numValidators int,
admin sdk.AccAddress,
) error {

appGenState := mbm.DefaultGenesis(clientCtx.JSONMarshaler)

// set the accounts in the genesis state
Expand All @@ -320,6 +332,15 @@ func initGenFiles(

bankGenState.Balances = genBalances
appGenState[banktypes.ModuleName] = clientCtx.JSONMarshaler.MustMarshalJSON(&bankGenState)
poeGenesisState := poetypes.GetGenesisStateFromAppState(clientCtx.JSONMarshaler, appGenState)
for i, addr := range genAccounts {
poeGenesisState.Engagement = append(poeGenesisState.Engagement, poetypes.TG4Member{
Address: addr.GetAddress().String(),
Weight: uint64(len(genAccounts) - i), // unique weight
})
}
poeGenesisState.SystemAdminAddress = admin.String()
poetypes.SetGenesisStateInAppState(clientCtx.JSONMarshaler, appGenState, poeGenesisState)

appGenStateJSON, err := json.MarshalIndent(appGenState, "", " ")
if err != nil {
Expand All @@ -344,15 +365,20 @@ func initGenFiles(
}

func collectGenFiles(
clientCtx client.Context, nodeConfig *tmconfig.Config, chainID string,
nodeIDs []string, valPubKeys []cryptotypes.PubKey, numValidators int,
outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator,
rpcPortStart, p2pPortStart int, singleMachine bool,
clientCtx client.Context,
nodeConfig *tmconfig.Config,
chainID string,
nodeIDs []string,
valPubKeys []cryptotypes.PubKey,
numValidators int,
outputDir, nodeDirPrefix, nodeDaemonHome string,
genBalIterator banktypes.GenesisBalancesIterator,
rpcPortStart, p2pPortStart int,
singleMachine bool,
) error {

var appState json.RawMessage
genTime := tmtime.Now()

for i := 0; i < numValidators; i++ {
var portOffset int
if singleMachine {
Expand All @@ -375,7 +401,7 @@ func collectGenFiles(
return err
}

nodeAppState, err := genutil.GenAppStateFromConfig(clientCtx.JSONMarshaler, clientCtx.TxConfig, nodeConfig, initCfg, *genDoc, genBalIterator)
nodeAppState, err := poeclient.AddGenTxsToGenesisFile(clientCtx.JSONMarshaler, clientCtx.TxConfig, nodeConfig, initCfg, *genDoc, genBalIterator)
if err != nil {
return err
}
Expand Down
Loading