Skip to content

Commit 5467103

Browse files
authored
Remove PK from config and producing a block (iotexproject#627)
1 parent 1f73da5 commit 5467103

File tree

19 files changed

+57
-174
lines changed

19 files changed

+57
-174
lines changed

blockchain/block/block.go

-3
Original file line numberDiff line numberDiff line change
@@ -165,13 +165,10 @@ func (b *Block) ProducerAddress() string {
165165

166166
// RunnableActions abstructs RunnableActions from a Block.
167167
func (b *Block) RunnableActions() RunnableActions {
168-
pkHash := keypair.HashPubKey(b.Header.pubkey)
169-
addr, _ := address.FromBytes(pkHash[:])
170168
return RunnableActions{
171169
blockHeight: b.Header.height,
172170
blockTimeStamp: b.Header.timestamp,
173171
blockProducerPubKey: b.Header.pubkey,
174-
blockProducerAddr: addr.String(),
175172
actions: b.Actions,
176173
txHash: b.txRoot,
177174
}

blockchain/block/builder.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ func NewBuilder(ra RunnableActions) *Builder {
2828
height: ra.blockHeight,
2929
timestamp: ra.blockTimeStamp,
3030
txRoot: ra.txHash,
31+
pubkey: ra.blockProducerPubKey,
3132
},
3233
Actions: ra.actions,
3334
},
@@ -65,12 +66,15 @@ func (b *Builder) SetReceiptRoot(h hash.Hash256) *Builder {
6566
}
6667

6768
// SignAndBuild signs and then builds a block.
68-
func (b *Builder) SignAndBuild(signerPubKey keypair.PublicKey, signerPriKey keypair.PrivateKey) (Block, error) {
69-
b.blk.Header.pubkey = signerPubKey
69+
func (b *Builder) SignAndBuild(signerPriKey keypair.PrivateKey) (Block, error) {
70+
if keypair.EncodePublicKey(b.blk.Header.pubkey) != keypair.EncodePublicKey(&signerPriKey.PublicKey) {
71+
return Block{}, errors.New("public key from the signer doesn't match that from runnable actions")
72+
}
73+
7074
h := b.blk.Header.HashHeaderCore()
7175
sig, err := crypto.Sign(h[:], signerPriKey)
7276
if err != nil {
73-
return Block{}, errors.New("Failed to sign block")
77+
return Block{}, errors.New("failed to sign block")
7478
}
7579
b.blk.Header.blockSig = sig
7680
return b.blk, nil

blockchain/block/builder_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,11 @@ func TestBuilder(t *testing.T) {
2020
ra := NewRunnableActionsBuilder().
2121
SetHeight(1).
2222
SetTimeStamp(testutil.TimestampNow()).
23-
Build(ta.Addrinfo["bravo"].String(), ta.Keyinfo["bravo"].PubKey)
23+
Build(ta.Keyinfo["bravo"].PubKey)
2424

2525
nblk, err := NewBuilder(ra).
2626
SetPrevBlockHash(hash.ZeroHash256).
27-
SignAndBuild(ta.Keyinfo["bravo"].PubKey, ta.Keyinfo["bravo"].PriKey)
27+
SignAndBuild(ta.Keyinfo["bravo"].PriKey)
2828
require.NoError(t, err)
2929

3030
require.True(t, nblk.VerifySignature())

blockchain/block/runnable.go

+1-8
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ type RunnableActions struct {
1717
blockHeight uint64
1818
blockTimeStamp int64
1919
blockProducerPubKey keypair.PublicKey
20-
blockProducerAddr string
2120
txHash hash.Hash256
2221
actions []action.SealedEnvelope
2322
}
@@ -37,11 +36,6 @@ func (ra RunnableActions) BlockProducerPubKey() keypair.PublicKey {
3736
return ra.blockProducerPubKey
3837
}
3938

40-
// BlockProducerAddr returns BlockProducerAddr.
41-
func (ra RunnableActions) BlockProducerAddr() string {
42-
return ra.blockProducerAddr
43-
}
44-
4539
// TxHash returns TxHash.
4640
func (ra RunnableActions) TxHash() hash.Hash256 { return ra.txHash }
4741

@@ -78,8 +72,7 @@ func (b *RunnableActionsBuilder) AddActions(acts ...action.SealedEnvelope) *Runn
7872
}
7973

8074
// Build signs and then builds a block.
81-
func (b *RunnableActionsBuilder) Build(producerAddr string, producerPubKey keypair.PublicKey) RunnableActions {
82-
b.ra.blockProducerAddr = producerAddr
75+
func (b *RunnableActionsBuilder) Build(producerPubKey keypair.PublicKey) RunnableActions {
8376
b.ra.blockProducerPubKey = producerPubKey
8477
b.ra.txHash = calculateTxRoot(b.ra.actions)
8578
return b.ra

blockchain/blockchain.go

+14-32
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ func NewBlockchain(cfg config.Config, opts ...Option) Blockchain {
304304
if err != nil {
305305
log.L().Panic("Failed to get block producer address.", zap.Error(err))
306306
}
307-
chain.validator = &validator{sf: chain.sf, validatorAddr: producerAddress(cfg).String()}
307+
chain.validator = &validator{sf: chain.sf, validatorAddr: cfg.ProducerAddress().String()}
308308

309309
if chain.dao != nil {
310310
chain.lifecycle.Add(chain.dao)
@@ -727,14 +727,14 @@ func (bc *blockchain) MintNewBlock(
727727
SetHeight(newblockHeight).
728728
SetTimeStamp(timestamp).
729729
AddActions(actions...).
730-
Build(producerAddr, producerPubKey)
730+
Build(producerPubKey)
731731

732732
blk, err := block.NewBuilder(ra).
733733
SetPrevBlockHash(bc.tipHash).
734734
SetDeltaStateDigest(ws.Digest()).
735735
SetReceipts(rc).
736736
SetReceiptRoot(calculateReceiptRoot(rc)).
737-
SignAndBuild(producerPubKey, producerPriKey)
737+
SignAndBuild(producerPriKey)
738738
if err != nil {
739739
return nil, errors.Wrapf(err, "failed to create block")
740740
}
@@ -951,7 +951,7 @@ func (bc *blockchain) startEmptyBlockchain() error {
951951
ws factory.WorkingSet
952952
err error
953953
)
954-
pk, sk, addr, err := bc.genesisProducer()
954+
pk, sk, _, err := bc.genesisProducer()
955955
if err != nil {
956956
return errors.Wrap(err, "failed to get the key and address of producer")
957957
}
@@ -973,7 +973,7 @@ func (bc *blockchain) startEmptyBlockchain() error {
973973
SetHeight(0).
974974
SetTimeStamp(Gen.Timestamp).
975975
AddActions(acts...).
976-
Build(addr, pk)
976+
Build(pk)
977977
// run execution and update state trie root hash
978978
receipts, err := bc.runActions(racts, ws)
979979
if err != nil {
@@ -985,18 +985,18 @@ func (bc *blockchain) startEmptyBlockchain() error {
985985
SetDeltaStateDigest(ws.Digest()).
986986
SetReceipts(receipts).
987987
SetReceiptRoot(calculateReceiptRoot(receipts)).
988-
SignAndBuild(pk, sk)
988+
SignAndBuild(sk)
989989
if err != nil {
990990
return errors.Wrapf(err, "Failed to create block")
991991
}
992992
} else {
993993
racts := block.NewRunnableActionsBuilder().
994994
SetHeight(0).
995995
SetTimeStamp(Gen.Timestamp).
996-
Build(addr, pk)
996+
Build(pk)
997997
genesis, err = block.NewBuilder(racts).
998998
SetPrevBlockHash(hash.ZeroHash256).
999-
SignAndBuild(pk, sk)
999+
SignAndBuild(sk)
10001000
if err != nil {
10011001
return errors.Wrapf(err, "Failed to create block")
10021002
}
@@ -1139,7 +1139,8 @@ func (bc *blockchain) runActions(
11391139
}
11401140
gasLimit := bc.config.Genesis.BlockGasLimit
11411141
// update state factory
1142-
producer, err := address.FromString(acts.BlockProducerAddr())
1142+
pkHash := keypair.HashPubKey(acts.BlockProducerPubKey())
1143+
producer, err := address.FromBytes(pkHash[:])
11431144
if err != nil {
11441145
return nil, err
11451146
}
@@ -1321,10 +1322,7 @@ func (bc *blockchain) createPutPollResultAction(height uint64) (skip bool, se ac
13211322
default:
13221323
return
13231324
}
1324-
_, sk, err := bc.config.KeyPair()
1325-
if err != nil {
1326-
log.L().Panic("Failed to get block producer private key.", zap.Error(err))
1327-
}
1325+
sk := bc.config.ProducerPrivateKey()
13281326
nonce := uint64(0)
13291327
pollAction := action.NewPutPollResult(nonce, nextEpochHeight, l)
13301328
builder := action.EnvelopeBuilder{}
@@ -1402,7 +1400,7 @@ func (bc *blockchain) refreshStateDB() error {
14021400
}
14031401

14041402
func (bc *blockchain) buildStateInGenesis() error {
1405-
pk, _, addr, err := bc.genesisProducer()
1403+
pk, _, _, err := bc.genesisProducer()
14061404
if err != nil {
14071405
return errors.Wrap(err, "failed to get the key and address of producer")
14081406
}
@@ -1415,7 +1413,7 @@ func (bc *blockchain) buildStateInGenesis() error {
14151413
SetHeight(0).
14161414
SetTimeStamp(Gen.Timestamp).
14171415
AddActions(acts...).
1418-
Build(addr, pk)
1416+
Build(pk)
14191417
// run execution and update state trie root hash
14201418
if _, err := bc.runActions(racts, ws); err != nil {
14211419
return errors.Wrap(err, "failed to update state changes in Genesis block")
@@ -1439,10 +1437,7 @@ func (bc *blockchain) createGrantRewardAction(rewardType int) (action.SealedEnve
14391437
SetGasLimit(grant.GasLimit()).
14401438
SetAction(&grant).
14411439
Build()
1442-
_, sk, err := bc.config.KeyPair()
1443-
if err != nil {
1444-
log.L().Panic("Failed to get block producer private key.", zap.Error(err))
1445-
}
1440+
sk := bc.config.ProducerPrivateKey()
14461441
return action.Sign(envelope, sk)
14471442
}
14481443

@@ -1550,16 +1545,3 @@ func calculateReceiptRoot(receipts []*action.Receipt) hash.Hash256 {
15501545
res := crypto.NewMerkleTree(h).HashTree()
15511546
return res
15521547
}
1553-
1554-
func producerAddress(cfg config.Config) address.Address {
1555-
pubKey, _, err := cfg.KeyPair()
1556-
if err != nil {
1557-
log.L().Panic("Failed to get block producer public key.", zap.Error(err))
1558-
}
1559-
pkHash := keypair.HashPubKey(pubKey)
1560-
address, err := address.FromBytes(pkHash[:])
1561-
if err != nil {
1562-
log.L().Panic("Failed to get block producer address.", zap.Error(err))
1563-
}
1564-
return address
1565-
}

blockchain/genesis_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,11 @@ func TestGenesis(t *testing.T) {
3535
SetHeight(0).
3636
SetTimeStamp(Gen.Timestamp).
3737
AddActions(acts...).
38-
Build(testaddress.Addrinfo["producer"].String(), testaddress.Keyinfo["producer"].PubKey)
38+
Build(testaddress.Keyinfo["producer"].PubKey)
3939

4040
genesisBlk, err := block.NewBuilder(racts).
4141
SetPrevBlockHash(Gen.ParentHash).
42-
SignAndBuild(testaddress.Keyinfo["producer"].PubKey, testaddress.Keyinfo["producer"].PriKey)
42+
SignAndBuild(testaddress.Keyinfo["producer"].PriKey)
4343
assert.NoError(err)
4444

4545
t.Log("The Genesis Block has the following header:")

cli/ioctl/cmd/account/accountcreate.go

+2-4
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func init() {
3737
AccountCmd.AddCommand(accountCreateCmd)
3838
}
3939

40-
func accountCreate(args []string) string {
40+
func accountCreate(_ []string) string {
4141
items := make([]string, numAccounts)
4242
for i := 0; i < numAccounts; i++ {
4343
private, err := crypto.GenerateKey()
@@ -46,12 +46,10 @@ func accountCreate(args []string) string {
4646
}
4747
pkHash := keypair.HashPubKey(&private.PublicKey)
4848
addr, _ := address.FromBytes(pkHash[:])
49-
pubKeyBytes := keypair.PublicKeyToBytes(&private.PublicKey)
5049
priKeyBytes := keypair.PrivateKeyToBytes(private)
5150
items[i] = fmt.Sprintf(
52-
"{\"Address\": \"%s\", \"PublicKey\": \"%x\", \"PrivateKey\": \"%x\"}\n",
51+
"{\"Address\": \"%s\", \"PrivateKey\": \"%x\"}\n",
5352
addr.String(),
54-
pubKeyBytes,
5553
priKeyBytes,
5654
)
5755
}

config/config.go

+20-42
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,19 @@
77
package config
88

99
import (
10-
"encoding/hex"
1110
"flag"
1211
"os"
1312
"time"
1413

14+
"go.uber.org/zap"
15+
1516
"github.com/ethereum/go-ethereum/crypto"
1617
"github.com/pkg/errors"
1718
uconfig "go.uber.org/config"
1819

1920
"github.com/iotexproject/iotex-core/address"
2021
"github.com/iotexproject/iotex-core/blockchain/genesis"
2122
"github.com/iotexproject/iotex-core/consensus/consensusfsm"
22-
"github.com/iotexproject/iotex-core/pkg/hash"
2323
"github.com/iotexproject/iotex-core/pkg/keypair"
2424
"github.com/iotexproject/iotex-core/pkg/log"
2525
)
@@ -76,7 +76,6 @@ var (
7676
TrieDBPath: "/tmp/trie.db",
7777
ID: 1,
7878
Address: "",
79-
ProducerPubKey: keypair.EncodePublicKey(&PrivateKey.PublicKey),
8079
ProducerPrivKey: keypair.EncodePrivateKey(PrivateKey),
8180
GenesisActionsPath: "",
8281
EmptyGenesis: false,
@@ -171,7 +170,6 @@ var (
171170

172171
// Validates is the collection config validation functions
173172
Validates = []Validate{
174-
ValidateKeyPair,
175173
ValidateRollDPoS,
176174
ValidateDispatcher,
177175
ValidateExplorer,
@@ -201,7 +199,6 @@ type (
201199
TrieDBPath string `yaml:"trieDBPath"`
202200
ID uint32 `yaml:"id"`
203201
Address string `yaml:"address"`
204-
ProducerPubKey string `yaml:"producerPubKey"`
205202
ProducerPrivKey string `yaml:"producerPrivKey"`
206203
GenesisActionsPath string `yaml:"genesisActionsPath"`
207204
EmptyGenesis bool `yaml:"emptyGenesis"`
@@ -440,50 +437,31 @@ func NewSub(validates ...Validate) (Config, error) {
440437
return cfg, nil
441438
}
442439

443-
// BlockchainAddress returns the address derived from the configured chain ID and public key
444-
func (cfg Config) BlockchainAddress() (address.Address, error) {
445-
pk, err := keypair.DecodePublicKey(cfg.Chain.ProducerPubKey)
440+
// ProducerAddress returns the configured producer address derived from key
441+
func (cfg Config) ProducerAddress() address.Address {
442+
sk := cfg.ProducerPrivateKey()
443+
pkHash := keypair.HashPubKey(&sk.PublicKey)
444+
addr, err := address.FromBytes(pkHash[:])
446445
if err != nil {
447-
return nil, errors.Wrapf(err, "error when decoding public key %s", cfg.Chain.ProducerPubKey)
446+
log.L().Panic(
447+
"Error when constructing producer address",
448+
zap.Error(err),
449+
)
448450
}
449-
pkHash := keypair.HashPubKey(pk)
450-
return address.FromBytes(pkHash[:])
451+
return addr
451452
}
452453

453-
// KeyPair returns the decoded public and private key pair
454-
func (cfg Config) KeyPair() (keypair.PublicKey, keypair.PrivateKey, error) {
455-
pk, err := keypair.DecodePublicKey(cfg.Chain.ProducerPubKey)
456-
if err != nil {
457-
return nil, nil, errors.Wrapf(err, "error when decoding public key %s", cfg.Chain.ProducerPubKey)
458-
}
454+
// ProducerPrivateKey returns the configured private key
455+
func (cfg Config) ProducerPrivateKey() keypair.PrivateKey {
459456
sk, err := keypair.DecodePrivateKey(cfg.Chain.ProducerPrivKey)
460457
if err != nil {
461-
return nil, nil, errors.Wrapf(err, "error when decoding private key %s", cfg.Chain.ProducerPrivKey)
462-
}
463-
return pk, sk, nil
464-
}
465-
466-
// ValidateKeyPair validates the block producer address
467-
func ValidateKeyPair(cfg Config) error {
468-
pkBytes, err := hex.DecodeString(cfg.Chain.ProducerPubKey)
469-
if err != nil {
470-
return err
471-
}
472-
priKey, err := keypair.DecodePrivateKey(cfg.Chain.ProducerPrivKey)
473-
if err != nil {
474-
return err
475-
}
476-
// Validate producer pubkey and prikey by signing a dummy message and verify it
477-
validationMsg := "connecting the physical world block by block"
478-
msgHash := hash.Hash256b([]byte(validationMsg))
479-
sig, err := crypto.Sign(msgHash[:], priKey)
480-
if err != nil {
481-
return err
482-
}
483-
if !crypto.VerifySignature(pkBytes, msgHash[:], sig[:64]) {
484-
return errors.Wrap(ErrInvalidCfg, "block producer has unmatched pubkey and prikey")
458+
log.L().Panic(
459+
"Error when decoding private key",
460+
zap.String("key", cfg.Chain.ProducerPrivKey),
461+
zap.Error(err),
462+
)
485463
}
486-
return nil
464+
return sk
487465
}
488466

489467
// ValidateChain validates the chain configure

0 commit comments

Comments
 (0)