From c94fd4afc5317bf92385bab35af0f823d1e6cb53 Mon Sep 17 00:00:00 2001 From: Amaury Martiny Date: Fri, 11 Sep 2020 16:22:18 +0200 Subject: [PATCH] Return app_hash in InitChain (#7208) * Return app_hash in InitChain * Hash empty string --- baseapp/abci.go | 19 ++++++++++++++++++- baseapp/baseapp_test.go | 11 ++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/baseapp/abci.go b/baseapp/abci.go index 4a5b633502..5e8f6f760e 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -1,6 +1,7 @@ package baseapp import ( + "crypto/sha256" "errors" "fmt" "os" @@ -81,9 +82,25 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC } } + // In the case of a new chain, AppHash will be the hash of an empty string. + // During an upgrade, it'll be the hash of the last committed block. + var appHash []byte + if !app.LastCommitID().IsZero() { + appHash = app.LastCommitID().Hash + } else { + // $ echo -n '' | sha256sum + // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 + emptyHash := sha256.Sum256([]byte{}) + appHash = emptyHash[:] + } + // NOTE: We don't commit, but BeginBlock for block `initial_height` starts from this // deliverState. - return res + return abci.ResponseInitChain{ + ConsensusParams: res.ConsensusParams, + Validators: res.Validators, + AppHash: appHash, + } } // Info implements the ABCI interface. diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index efe2b1528b..089277ccac 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -564,7 +564,16 @@ func TestInitChainer(t *testing.T) { require.Nil(t, err) require.Equal(t, int64(0), app.LastBlockHeight()) - app.InitChain(abci.RequestInitChain{AppStateBytes: []byte("{}"), ChainId: "test-chain-id"}) // must have valid JSON genesis file, even if empty + initChainRes := app.InitChain(abci.RequestInitChain{AppStateBytes: []byte("{}"), ChainId: "test-chain-id"}) // must have valid JSON genesis file, even if empty + + // The AppHash returned by a new chain is the sha256 hash of "". + // $ echo -n '' | sha256sum + // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 + require.Equal( + t, + []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}, + initChainRes.AppHash, + ) // assert that chainID is set correctly in InitChain chainID := app.deliverState.ctx.ChainID()