Skip to content

Commit

Permalink
chore(types): add MustAccAddressFromBech32 util func (backport cosmos…
Browse files Browse the repository at this point in the history
  • Loading branch information
mergify[bot] authored and JeancarloBarrios committed Sep 28, 2024
1 parent 8b95d1c commit 6b35f53
Show file tree
Hide file tree
Showing 20 changed files with 329 additions and 372 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Improvements

* (types) [\#12201](https://github.com/cosmos/cosmos-sdk/pull/12201) Add `MustAccAddressFromBech32` util function
* [\#11693](https://github.com/cosmos/cosmos-sdk/pull/11693) Add validation for gentx cmd.
* [\#11686](https://github.com/cosmos/cosmos-sdk/pull/11686) Update the min required Golang version to `1.17`.
* (x/auth/vesting) [\#11652](https://github.com/cosmos/cosmos-sdk/pull/11652) Add util functions for `Period(s)`
Expand Down
22 changes: 4 additions & 18 deletions simapp/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,7 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []
panic(err)
}

delAddr, err := app.InterfaceRegistry().SigningContext().AddressCodec().StringToBytes(delegation.DelegatorAddress)
if err != nil {
panic(err)
}
delAddr := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress)

_, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr)
}
Expand Down Expand Up @@ -175,20 +172,9 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []
if err != nil {
panic(err)
}
delAddr, err := app.InterfaceRegistry().SigningContext().AddressCodec().StringToBytes(del.DelegatorAddress)
if err != nil {
panic(err)
}

if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil {
// never called as BeforeDelegationCreated always returns nil
panic(fmt.Errorf("error while incrementing period: %w", err))
}

if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil {
// never called as AfterDelegationModified always returns nil
panic(fmt.Errorf("error while creating a new delegation period record: %w", err))
}
delAddr := sdk.MustAccAddressFromBech32(del.DelegatorAddress)
app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr)
app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr)
}

// reset context height
Expand Down
10 changes: 10 additions & 0 deletions types/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,16 @@ func MustAccAddressFromBech32(address string) AccAddress {
return addr
}

// MustAccAddressFromBech32 calls AccAddressFromBech32 and panics on error.
func MustAccAddressFromBech32(address string) AccAddress {
addr, err := AccAddressFromBech32(address)
if err != nil {
panic(err)
}

return addr
}

// AccAddressFromBech32 creates an AccAddress from a Bech32 string.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func AccAddressFromBech32(address string) (addr AccAddress, err error) {
Expand Down
34 changes: 9 additions & 25 deletions types/tx/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,10 @@ func (t *Tx) GetSigners(cdc codec.Codec) ([][]byte, []protoreflect.Message, erro

// ensure any specified fee payer is included in the required signers (at the end)
feePayer := t.AuthInfo.Fee.Payer
var feePayerAddr []byte
if feePayer != "" {
var err error
feePayerAddr, err = cdc.InterfaceRegistry().SigningContext().AddressCodec().StringToBytes(feePayer)
if err != nil {
return nil, nil, err
}
}
if feePayerAddr != nil && !seen[string(feePayerAddr)] {
signers = append(signers, feePayerAddr)
seen[string(feePayerAddr)] = true
if feePayer != "" && !seen[feePayer] {
payerAddr := sdk.MustAccAddressFromBech32(feePayer)
signers = append(signers, payerAddr)
seen[feePayer] = true
}

return signers, reflectMsgs, nil
Expand All @@ -148,11 +141,7 @@ func (t *Tx) GetFee() sdk.Coins {
func (t *Tx) FeePayer(cdc codec.Codec) []byte {
feePayer := t.AuthInfo.Fee.Payer
if feePayer != "" {
feePayerAddr, err := cdc.InterfaceRegistry().SigningContext().AddressCodec().StringToBytes(feePayer)
if err != nil {
panic(err)
}
return feePayerAddr
return sdk.MustAccAddressFromBech32(feePayer)
}
// use first signer as default if no payer specified
signers, _, err := t.GetSigners(cdc)
Expand All @@ -163,15 +152,10 @@ func (t *Tx) FeePayer(cdc codec.Codec) []byte {
return signers[0]
}

func (t *Tx) FeeGranter(cdc codec.Codec) []byte {
feeGranter := t.AuthInfo.Fee.Granter
if feeGranter != "" {
feeGranterAddr, err := cdc.InterfaceRegistry().SigningContext().AddressCodec().StringToBytes(feeGranter)
if err != nil {
panic(err)
}

return feeGranterAddr
func (t *Tx) FeeGranter() sdk.AccAddress {
feePayer := t.AuthInfo.Fee.Granter
if feePayer != "" {
return sdk.MustAccAddressFromBech32(feePayer)
}
return nil
}
Expand Down
29 changes: 8 additions & 21 deletions x/auth/tx/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,29 +109,16 @@ var marshalOption = proto.MarshalOptions{
Deterministic: true,
}

func (w *builder) getTx() (*gogoTxWrapper, error) {
anyMsgs, err := msgsV1toAnyV2(w.msgs)
if err != nil {
return nil, err
}
body := &txv1beta1.TxBody{
Messages: anyMsgs,
Memo: w.memo,
TimeoutHeight: w.timeoutHeight,
TimeoutTimestamp: timestamppb.New(w.timeoutTimestamp),
Unordered: w.unordered,
ExtensionOptions: intoAnyV2(w.extensionOptions),
NonCriticalExtensionOptions: intoAnyV2(w.nonCriticalExtensionOptions),
func (w *wrapper) FeePayer() sdk.AccAddress {
feePayer := w.tx.AuthInfo.Fee.Payer
if feePayer != "" {
return sdk.MustAccAddressFromBech32(feePayer)
}

fee, err := w.getFee()
if err != nil {
return nil, fmt.Errorf("unable to parse fee: %w", err)
}
authInfo := &txv1beta1.AuthInfo{
SignerInfos: intoV2SignerInfo(w.signerInfos),
Fee: fee,
Tip: nil, // deprecated
func (w *wrapper) FeeGranter() sdk.AccAddress {
feePayer := w.tx.AuthInfo.Fee.Granter
if feePayer != "" {
return sdk.MustAccAddressFromBech32(feePayer)
}

bodyBytes, err := marshalOption.Marshal(body)
Expand Down
6 changes: 4 additions & 2 deletions x/authz/keeper/grpc_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ func (k Keeper) GranterGrants(c context.Context, req *authz.QueryGranterGrantsRe

var grants []*authz.GrantAuthorization
pageRes, err := query.FilteredPaginate(authzStore, req.Pagination, func(key []byte, value []byte,
accumulate bool) (bool, error) {
accumulate bool,
) (bool, error) {
auth, err := unmarshalAuthorization(k.cdc, value)
if err != nil {
return false, err
Expand Down Expand Up @@ -155,7 +156,8 @@ func (k Keeper) GranteeGrants(c context.Context, req *authz.QueryGranteeGrantsRe

var authorizations []*authz.GrantAuthorization
pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key []byte, value []byte,
accumulate bool) (bool, error) {
accumulate bool,
) (bool, error) {
auth, err := unmarshalAuthorization(k.cdc, value)
if err != nil {
return false, err
Expand Down
105 changes: 15 additions & 90 deletions x/authz/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,8 @@ func (k Keeper) updateGrant(ctx context.Context, grantee, granter sdk.AccAddress

// DispatchActions attempts to execute the provided messages via authorization
// grants from the message signer to the grantee.
func (k Keeper) DispatchActions(ctx context.Context, grantee sdk.AccAddress, msgs []sdk.Msg) ([][]byte, error) {
func (k Keeper) DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, msgs []sdk.Msg) ([][]byte, error) {
results := make([][]byte, len(msgs))
now := k.Environment.HeaderService.HeaderInfo(ctx).Time

for i, msg := range msgs {
signers, _, err := k.cdc.GetMsgSigners(msg)
if err != nil {
Expand Down Expand Up @@ -348,12 +346,11 @@ func (k Keeper) GetAuthorization(ctx context.Context, grantee, granter sdk.AccAd
// IterateGrants iterates over all authorization grants
// This function should be used with caution because it can involve significant IO operations.
// It should not be used in query or msg services without charging additional gas.
// The iteration stops when the handler function returns true or the iterator exhaust.
func (k Keeper) IterateGrants(ctx context.Context,
handler func(granterAddr, granteeAddr sdk.AccAddress, grant authz.Grant) (bool, error),
) error {
store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, GrantKey)
func (k Keeper) IterateGrants(ctx sdk.Context,
handler func(granterAddr sdk.AccAddress, granteeAddr sdk.AccAddress, grant authz.Grant) bool,
) {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, GrantKey)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var grant authz.Grant
Expand Down Expand Up @@ -411,89 +408,17 @@ func (k Keeper) getGrantQueueItem(ctx context.Context, expiration time.Time, gra
return &queueItems, nil
}

func (k Keeper) setGrantQueueItem(ctx context.Context, expiration time.Time,
granter, grantee sdk.AccAddress, queueItems *authz.GrantQueueItem,
) error {
store := k.KVStoreService.OpenKVStore(ctx)
bz, err := k.cdc.Marshal(queueItems)
if err != nil {
return err
}
return store.Set(GrantQueueKey(expiration, granter, grantee), bz)
}

// insertIntoGrantQueue inserts a grant key into the grant queue
func (k Keeper) insertIntoGrantQueue(ctx context.Context, granter, grantee sdk.AccAddress, msgType string, expiration time.Time) error {
queueItems, err := k.getGrantQueueItem(ctx, expiration, granter, grantee)
if err != nil {
return err
}

queueItems.MsgTypeUrls = append(queueItems.MsgTypeUrls, msgType)
return k.setGrantQueueItem(ctx, expiration, granter, grantee, queueItems)
}

// removeFromGrantQueue removes a grant key from the grant queue
func (k Keeper) removeFromGrantQueue(ctx context.Context, grantKey []byte, granter, grantee sdk.AccAddress, expiration time.Time) error {
store := k.KVStoreService.OpenKVStore(ctx)
key := GrantQueueKey(expiration, granter, grantee)
bz, err := store.Get(key)
if err != nil {
return err
}

if bz == nil {
return errorsmod.Wrap(authz.ErrNoGrantKeyFound, "can't remove grant from the expire queue, grant key not found")
}

var queueItem authz.GrantQueueItem
if err := k.cdc.Unmarshal(bz, &queueItem); err != nil {
return err
}

_, _, msgType := parseGrantStoreKey(grantKey)
queueItems := queueItem.MsgTypeUrls

for index, typeURL := range queueItems {
if err := k.GasService.GasMeter(ctx).Consume(gasCostPerIteration, "grant queue"); err != nil {
return err
}

if typeURL == msgType {
end := len(queueItem.MsgTypeUrls) - 1
queueItems[index] = queueItems[end]
queueItems = queueItems[:end]

if err := k.setGrantQueueItem(ctx, expiration, granter, grantee, &authz.GrantQueueItem{
MsgTypeUrls: queueItems,
}); err != nil {
return err
}
break
}
}

return nil
}

// DequeueAndDeleteExpiredGrants deletes expired grants from the state and grant queue.
func (k Keeper) DequeueAndDeleteExpiredGrants(ctx context.Context, limit int) error {
store := k.KVStoreService.OpenKVStore(ctx)

iterator, err := store.Iterator(GrantQueuePrefix, storetypes.InclusiveEndBytes(GrantQueueTimePrefix(k.HeaderService.HeaderInfo(ctx).Time)))
if err != nil {
return err
}
defer iterator.Close()

count := 0
for ; iterator.Valid(); iterator.Next() {
var queueItem authz.GrantQueueItem
if err := k.cdc.Unmarshal(iterator.Value(), &queueItem); err != nil {
return err
// InitGenesis new authz genesis
func (k Keeper) InitGenesis(ctx sdk.Context, data *authz.GenesisState) {
for _, entry := range data.Authorization {
grantee := sdk.MustAccAddressFromBech32(entry.Grantee)
granter := sdk.MustAccAddressFromBech32(entry.Granter)
a, ok := entry.Authorization.GetCachedValue().(authz.Authorization)
if !ok {
panic("expected authorization")
}

_, granter, grantee, err := parseGrantQueueKey(iterator.Key())
err := k.SaveGrant(ctx, grantee, granter, a, entry.Expiration)
if err != nil {
return err
}
Expand Down
4 changes: 0 additions & 4 deletions x/bank/keeper/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,6 @@ func (k BaseKeeper) InitGenesis(ctx context.Context, genState *types.GenesisStat

for _, balance := range genState.Balances {
addr := balance.GetAddress()
bz, err := k.ak.AddressCodec().StringToBytes(addr)
if err != nil {
return err
}

for _, coin := range balance.Coins {
err := k.Balances.Set(ctx, collections.Join(sdk.AccAddress(bz), coin.Denom), coin.Amount)
Expand Down
15 changes: 4 additions & 11 deletions x/bank/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,10 @@ func (k msgServer) MultiSend(ctx context.Context, msg *types.MsgMultiSend) (*typ
}

for _, out := range msg.Outputs {
if base, ok := k.Keeper.(BaseKeeper); ok {
accAddr, err := base.ak.AddressCodec().StringToBytes(out.Address)
if err != nil {
return nil, err
}

if k.BlockedAddr(accAddr) {
return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", out.Address)
}
} else {
return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid keeper type: %T", k.Keeper)
accAddr := sdk.MustAccAddressFromBech32(out.Address)

if k.BlockedAddr(accAddr) {
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive transactions", out.Address)
}
}

Expand Down
5 changes: 2 additions & 3 deletions x/bank/types/balance.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package types
import (
"bytes"
"encoding/json"
"fmt"
"sort"

"cosmossdk.io/core/address"
Expand All @@ -16,8 +15,8 @@ import (
var _ exported.GenesisBalance = (*Balance)(nil)

// GetAddress returns the account address of the Balance object.
func (b Balance) GetAddress() string {
return b.Address
func (b Balance) GetAddress() sdk.AccAddress {
return sdk.MustAccAddressFromBech32(b.Address)
}

// GetCoins returns the account coins of the Balance object.
Expand Down
28 changes: 11 additions & 17 deletions x/distribution/keeper/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ func (k Keeper) InitGenesis(ctx context.Context, data types.GenesisState) error
}

for _, dwi := range data.DelegatorWithdrawInfos {
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(dwi.DelegatorAddress)
if err != nil {
return err
}
withdrawAddress, err := k.authKeeper.AddressCodec().StringToBytes(dwi.WithdrawAddress)
if err != nil {
return err
}
err = k.DelegatorsWithdrawAddress.Set(ctx, delegatorAddress, withdrawAddress)
delegatorAddress := sdk.MustAccAddressFromBech32(dwi.DelegatorAddress)
withdrawAddress := sdk.MustAccAddressFromBech32(dwi.WithdrawAddress)
k.SetDelegatorWithdrawAddr(ctx, delegatorAddress, withdrawAddress)
}

var previousProposer sdk.ConsAddress
if data.PreviousProposer != "" {
var err error
previousProposer, err = sdk.ConsAddressFromBech32(data.PreviousProposer)
if err != nil {
return err
}
Expand Down Expand Up @@ -83,15 +83,9 @@ func (k Keeper) InitGenesis(ctx context.Context, data types.GenesisState) error
if err != nil {
return err
}
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(del.DelegatorAddress)
if err != nil {
return err
}
delegatorAddress := sdk.MustAccAddressFromBech32(del.DelegatorAddress)

err = k.DelegatorStartingInfo.Set(ctx, collections.Join(sdk.ValAddress(valAddr), sdk.AccAddress(delegatorAddress)), del.StartingInfo)
if err != nil {
return err
}
k.SetDelegatorStartingInfo(ctx, valAddr, delegatorAddress, del.StartingInfo)
}
for _, evt := range data.ValidatorSlashEvents {
valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(evt.ValidatorAddress)
Expand Down
Loading

0 comments on commit 6b35f53

Please sign in to comment.