From 6ed11b8f79a597a2c201a841602e762c2cf1e60d Mon Sep 17 00:00:00 2001
From: bruce-wayne2 <97930236+bruce-wayne2@users.noreply.github.com>
Date: Wed, 17 Aug 2022 22:12:45 +0800
Subject: [PATCH] feat: deterministic map iteration (#12781)

## Description

We should ensure that events emitted are in a deterministic order on any node.


Sorry, the previous [PR-12693](https://github.com/cosmos/cosmos-sdk/pull/12693) was closed due to wrong operation.

Close: #12693



---

### Author Checklist

*All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.*

I have...

- [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [x] added `!` to the type prefix if API or client breaking change
- [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#pr-targeting))
- [x] provided a link to the relevant issue or specification
- [x] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules)
- [x] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing)
- [x] added a changelog entry to `CHANGELOG.md`
- [x] included comments for [documenting Go code](https://blog.golang.org/godoc)
- [x] updated the relevant documentation or specification
- [x] reviewed "Files changed" and left comments if necessary
- [x] confirmed all CI checks have passed

### Reviewers Checklist

*All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.*

I have...

- [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] confirmed `!` in the type prefix if API or client breaking change
- [ ] confirmed all author checklist items have been addressed
- [ ] reviewed state machine logic
- [ ] reviewed API design and naming
- [ ] reviewed documentation is accurate
- [ ] reviewed tests and test coverage
- [ ] manually tested (if applicable)
---
 CHANGELOG.md         |  1 +
 types/events.go      |  9 ++++++++-
 types/events_test.go | 15 +++++++++++++++
 3 files changed, 24 insertions(+), 1 deletion(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 005ddeaaf5..b35c1791a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -58,6 +58,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
 * [#12634](https://github.com/cosmos/cosmos-sdk/pull/12634) Move `sdk.Dec` to math package.
 * [#12596](https://github.com/cosmos/cosmos-sdk/pull/12596) Remove all imports of the non-existent gogo/protobuf v1.3.3 to ease downstream use and go workspaces. 
 * [#12187](https://github.com/cosmos/cosmos-sdk/pull/12187) Add batch operation for x/nft module.
+* [#12693](https://github.com/cosmos/cosmos-sdk/pull/12693) Make sure the order of each node is consistent when emitting proto events.
 * [#12455](https://github.com/cosmos/cosmos-sdk/pull/12455) Show attempts count in error for signing. 
 
 ### State Machine Breaking
diff --git a/types/events.go b/types/events.go
index 322123b432..57a7db3d3b 100644
--- a/types/events.go
+++ b/types/events.go
@@ -3,6 +3,8 @@ package types
 import (
 	"encoding/json"
 	"fmt"
+	"golang.org/x/exp/maps"
+	"golang.org/x/exp/slices"
 	"reflect"
 	"sort"
 	"strings"
@@ -87,8 +89,13 @@ func TypedEventToEvent(tev proto.Message) (Event, error) {
 		return Event{}, err
 	}
 
+	// sort the keys to ensure the order is always the same
+	keys := maps.Keys(attrMap)
+	slices.Sort(keys)
+
 	attrs := make([]abci.EventAttribute, 0, len(attrMap))
-	for k, v := range attrMap {
+	for _, k := range keys {
+		v := attrMap[k]
 		attrs = append(attrs, abci.EventAttribute{
 			Key:   k,
 			Value: string(v),
diff --git a/types/events_test.go b/types/events_test.go
index a395f8c738..a9aad20839 100644
--- a/types/events_test.go
+++ b/types/events_test.go
@@ -67,6 +67,21 @@ func (s *eventsTestSuite) TestEventManager() {
 	s.Require().Equal(em.Events(), events.AppendEvent(event))
 }
 
+func (s *eventsTestSuite) TestEmitTypedEvent() {
+	s.Run("deterministic key-value order", func() {
+		for i := 0; i < 10; i++ {
+			em := sdk.NewEventManager()
+			coin := sdk.NewCoin("fakedenom", sdk.NewInt(1999999))
+			s.Require().NoError(em.EmitTypedEvent(&coin))
+			s.Require().Len(em.Events(), 1)
+			attrs := em.Events()[0].Attributes
+			s.Require().Len(attrs, 2)
+			s.Require().Equal(attrs[0].Key, "amount")
+			s.Require().Equal(attrs[1].Key, "denom")
+		}
+	})
+}
+
 func (s *eventsTestSuite) TestEventManagerTypedEvents() {
 	em := sdk.NewEventManager()