Skip to content

Commit 3282834

Browse files
authored
Change keypair.PrivateKey/PublicKey to interface (iotexproject#654)
1. Replace keypair utility func to interface method
1 parent 0da7ac8 commit 3282834

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+388
-335
lines changed

action/actctx.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ func (act *AbstractAction) Hash() hash.Hash256 { return act.hash }
5151
func (act *AbstractAction) BasicActionSize() uint32 {
5252
// VersionSizeInBytes + NonceSizeInBytes + GasSizeInBytes
5353
size := 4 + 8 + 8
54-
size += len(keypair.PublicKeyToBytes(act.srcPubkey))
54+
if act.srcPubkey != nil {
55+
size += len(act.srcPubkey.Bytes())
56+
}
5557
if act.gasPrice != nil && len(act.gasPrice.Bytes()) > 0 {
5658
size += len(act.gasPrice.Bytes())
5759
}

action/action.go

+7-6
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ package action
99
import (
1010
"math/big"
1111

12-
"github.com/ethereum/go-ethereum/crypto"
1312
"github.com/golang/protobuf/proto"
1413
"github.com/pkg/errors"
1514

@@ -279,7 +278,7 @@ func (sealed *SealedEnvelope) Signature() []byte {
279278
func (sealed SealedEnvelope) Proto() *iotextypes.Action {
280279
return &iotextypes.Action{
281280
Core: sealed.Envelope.Proto(),
282-
SenderPubKey: keypair.PublicKeyToBytes(sealed.srcPubkey),
281+
SenderPubKey: sealed.srcPubkey.Bytes(),
283282
Signature: sealed.signature,
284283
}
285284
}
@@ -313,10 +312,10 @@ func (sealed *SealedEnvelope) LoadProto(pbAct *iotextypes.Action) error {
313312
func Sign(act Envelope, sk keypair.PrivateKey) (SealedEnvelope, error) {
314313
sealed := SealedEnvelope{Envelope: act}
315314

316-
sealed.srcPubkey = &sk.PublicKey
315+
sealed.srcPubkey = sk.PublicKey()
317316

318317
hash := act.Hash()
319-
sig, err := crypto.Sign(hash[:], sk)
318+
sig, err := sk.Sign(hash[:])
320319
if err != nil {
321320
return sealed, errors.Wrapf(ErrAction, "failed to sign action hash = %x", hash)
322321
}
@@ -354,8 +353,10 @@ func Verify(sealed SealedEnvelope) error {
354353
if len(sealed.Signature()) != SignatureLength {
355354
return errors.New("incorrect length of signature")
356355
}
357-
if success := crypto.VerifySignature(keypair.PublicKeyToBytes(sealed.SrcPubkey()), hash[:],
358-
sealed.Signature()[:SignatureLength-1]); success {
356+
if sealed.SrcPubkey() == nil {
357+
return errors.New("empty public key")
358+
}
359+
if sealed.SrcPubkey().Verify(hash[:], sealed.Signature()) {
359360
return nil
360361
}
361362
return errors.Wrapf(

action/protocol/execution/protocol_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ func TestProtocol_Handle(t *testing.T) {
505505
require.Equal(0, balance.Cmp(big.NewInt(500000000)))
506506

507507
log.S().Info("Roll Dice")
508-
h := keypair.HashPubKey(testaddress.Keyinfo["alfa"].PubKey)
508+
h := testaddress.Keyinfo["alfa"].PubKey.Hash()
509509
data, _ = hex.DecodeString(fmt.Sprintf("797d9fbd000000000000000000000000%x", h))
510510
execution, err = action.NewExecution(contractAddr, 3, big.NewInt(0), uint64(120000), big.NewInt(0), data)
511511
require.NoError(err)

action/protocol/multichain/mainchain/datamodel.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ func (bs SubChain) Serialize() ([]byte, error) {
3838
StartHeight: bs.StartHeight,
3939
StopHeight: bs.StopHeight,
4040
ParentHeightOffset: bs.ParentHeightOffset,
41-
OwnerPublicKey: keypair.PublicKeyToBytes(bs.OwnerPublicKey),
41+
OwnerPublicKey: bs.OwnerPublicKey.Bytes(),
4242
CurrentHeight: bs.CurrentHeight,
4343
DepositCount: bs.DepositCount,
4444
}
@@ -107,7 +107,7 @@ func (bp BlockProof) Serialize() ([]byte, error) {
107107
SubChainAddress: bp.SubChainAddress,
108108
Height: bp.Height,
109109
Roots: r,
110-
ProducerPublicKey: keypair.PublicKeyToBytes(bp.ProducerPublicKey),
110+
ProducerPublicKey: bp.ProducerPublicKey.Bytes(),
111111
ProducerAddress: bp.ProducerAddress,
112112
}
113113
return proto.Marshal(gen)

action/protocol/multichain/mainchain/stopsubchain.go

+2-4
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@ import (
1616
"github.com/iotexproject/iotex-core/action/protocol"
1717
accountutil "github.com/iotexproject/iotex-core/action/protocol/account/util"
1818
"github.com/iotexproject/iotex-core/address"
19-
"github.com/iotexproject/iotex-core/pkg/hash"
20-
"github.com/iotexproject/iotex-core/pkg/keypair"
2119
"github.com/iotexproject/iotex-core/pkg/log"
2220
"github.com/iotexproject/iotex-core/state"
2321
)
@@ -31,7 +29,7 @@ func (p *Protocol) subChainToStop(subChainAddr string) (*SubChain, error) {
3129
}
3230

3331
func (p *Protocol) validateSubChainOwnership(
34-
ownerPKHash hash.Hash160,
32+
ownerPKHash []byte,
3533
sender string,
3634
sm protocol.StateManager,
3735
) (*state.Account, error) {
@@ -73,7 +71,7 @@ func (p *Protocol) handleStopSubChain(ctx context.Context, stop *action.StopSubC
7371
return err
7472
}
7573
acct, err := p.validateSubChainOwnership(
76-
keypair.HashPubKey(subChain.OwnerPublicKey),
74+
subChain.OwnerPublicKey.Hash(),
7775
raCtx.Caller.String(),
7876
sm,
7977
)

action/protocol/vote/protocol.go

+1-4
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import (
1818
"github.com/iotexproject/iotex-core/action/protocol/rewarding"
1919
"github.com/iotexproject/iotex-core/action/protocol/vote/candidatesutil"
2020
"github.com/iotexproject/iotex-core/address"
21-
"github.com/iotexproject/iotex-core/pkg/keypair"
2221
"github.com/iotexproject/iotex-core/pkg/log"
2322
"github.com/iotexproject/iotex-core/state"
2423
)
@@ -110,9 +109,7 @@ func (p *Protocol) Handle(ctx context.Context, act action.Action, sm protocol.St
110109
} else if raCtx.Caller.String() == vote.Votee() {
111110
// Vote to self: self-nomination
112111
voteFrom.IsCandidate = true
113-
votePubkey := vote.VoterPublicKey()
114-
callerPKHash := keypair.HashPubKey(votePubkey)
115-
addr, err := address.FromBytes(callerPKHash[:])
112+
addr, err := address.FromBytes(vote.VoterPublicKey().Hash())
116113
if err != nil {
117114
return nil, err
118115
}

action/putpollresult_test.go

+1-3
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,14 @@ import (
1313
"github.com/stretchr/testify/assert"
1414

1515
"github.com/iotexproject/iotex-core/address"
16-
"github.com/iotexproject/iotex-core/pkg/keypair"
1716
"github.com/iotexproject/iotex-core/state"
1817
"github.com/iotexproject/iotex-core/test/testaddress"
1918
)
2019

2120
func TestPutPollResult(t *testing.T) {
2221
candidates := state.CandidateList{}
2322
pk := testaddress.Keyinfo["echo"].PubKey
24-
pkHash := keypair.HashPubKey(pk)
25-
addr, err := address.FromBytes(pkHash[:])
23+
addr, err := address.FromBytes(pk.Hash())
2624
assert.NoError(t, err)
2725
candidates = append(candidates, &state.Candidate{
2826
Address: addr.String(),

actpool/actioniterator/actioniterator.go

+1-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"container/heap"
1111

1212
"github.com/iotexproject/iotex-core/address"
13-
"github.com/iotexproject/iotex-core/pkg/keypair"
1413

1514
"github.com/iotexproject/iotex-core/action"
1615
)
@@ -74,8 +73,7 @@ func NewActionIterator(accountActs map[string][]action.SealedEnvelope) ActionIte
7473
// LoadNext load next action of account of top action
7574
func (ai *actionIterator) loadNextActionForTopAccount() {
7675
sender := ai.heads[0].SrcPubkey()
77-
callerPKHash := keypair.HashPubKey(sender)
78-
callerAddr, _ := address.FromBytes(callerPKHash[:])
76+
callerAddr, _ := address.FromBytes(sender.Hash())
7977
callerAddrStr := callerAddr.String()
8078
if actions, ok := ai.accountActs[callerAddrStr]; ok && len(actions) > 0 {
8179
ai.heads[0], ai.accountActs[callerAddrStr] = actions[0], actions[1:]

actpool/actpool.go

+2-5
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,12 @@ import (
1010
"context"
1111
"sync"
1212

13-
"github.com/iotexproject/iotex-core/address"
14-
"github.com/iotexproject/iotex-core/pkg/keypair"
15-
1613
"github.com/pkg/errors"
1714
"go.uber.org/zap"
1815

1916
"github.com/iotexproject/iotex-core/action"
2017
"github.com/iotexproject/iotex-core/action/protocol"
18+
"github.com/iotexproject/iotex-core/address"
2119
"github.com/iotexproject/iotex-core/blockchain"
2220
"github.com/iotexproject/iotex-core/config"
2321
"github.com/iotexproject/iotex-core/pkg/hash"
@@ -165,8 +163,7 @@ func (ap *actPool) Add(act action.SealedEnvelope) error {
165163
return errors.Errorf("reject existed action: %x", hash)
166164
}
167165

168-
callerPKHash := keypair.HashPubKey(act.SrcPubkey())
169-
caller, err := address.FromBytes(callerPKHash[:])
166+
caller, err := address.FromBytes(act.SrcPubkey().Hash())
170167
if err != nil {
171168
return err
172169
}

address/address_v1_test.go

+6-9
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import (
1111
"strings"
1212
"testing"
1313

14-
"github.com/ethereum/go-ethereum/crypto"
1514
"github.com/stretchr/testify/assert"
1615
"github.com/stretchr/testify/require"
1716

@@ -20,14 +19,13 @@ import (
2019

2120
func TestAddress(t *testing.T) {
2221
runTest := func(t *testing.T) {
23-
sk, err := crypto.GenerateKey()
22+
sk, err := keypair.GenerateKey()
2423
require.NoError(t, err)
2524

26-
pkHash := keypair.HashPubKey(&sk.PublicKey)
27-
28-
addr1, err := _v1.FromBytes(pkHash[:])
25+
pkHash := sk.PublicKey().Hash()
26+
addr1, err := _v1.FromBytes(pkHash)
2927
require.NoError(t, err)
30-
assert.Equal(t, pkHash[:], addr1.Bytes())
28+
assert.Equal(t, pkHash, addr1.Bytes())
3129

3230
encodedAddr := addr1.String()
3331
if isTestNet {
@@ -58,11 +56,10 @@ func TestAddress(t *testing.T) {
5856
func TestAddressError(t *testing.T) {
5957
t.Parallel()
6058

61-
sk, err := crypto.GenerateKey()
59+
sk, err := keypair.GenerateKey()
6260
require.NoError(t, err)
6361

64-
pkHash := keypair.HashPubKey(&sk.PublicKey)
65-
addr1, err := _v1.FromBytes(pkHash[:])
62+
addr1, err := _v1.FromBytes(sk.PublicKey().Hash())
6663
require.NoError(t, err)
6764

6865
encodedAddr := addr1.String()

api/api.go

+1-3
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ import (
3232
"github.com/iotexproject/iotex-core/gasstation"
3333
"github.com/iotexproject/iotex-core/indexservice"
3434
"github.com/iotexproject/iotex-core/pkg/hash"
35-
"github.com/iotexproject/iotex-core/pkg/keypair"
3635
"github.com/iotexproject/iotex-core/pkg/log"
3736
"github.com/iotexproject/iotex-core/protogen/iotexapi"
3837
"github.com/iotexproject/iotex-core/protogen/iotextypes"
@@ -277,8 +276,7 @@ func (api *Server) ReadContract(ctx context.Context, in *iotexapi.ReadContractRe
277276
return nil, errors.New("not execution")
278277
}
279278

280-
callerPKHash := keypair.HashPubKey(selp.SrcPubkey())
281-
callerAddr, err := address.FromBytes(callerPKHash[:])
279+
callerAddr, err := address.FromBytes(selp.SrcPubkey().Hash())
282280
if err != nil {
283281
return nil, err
284282
}

api/api_test.go

+4-5
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ import (
3636
"github.com/iotexproject/iotex-core/blockchain/genesis"
3737
"github.com/iotexproject/iotex-core/config"
3838
"github.com/iotexproject/iotex-core/gasstation"
39-
"github.com/iotexproject/iotex-core/pkg/keypair"
4039
"github.com/iotexproject/iotex-core/pkg/unit"
4140
"github.com/iotexproject/iotex-core/pkg/util/byteutil"
4241
"github.com/iotexproject/iotex-core/protogen/iotexapi"
@@ -151,19 +150,19 @@ var (
151150
false,
152151
hex.EncodeToString(transferHash1[:]),
153152
1,
154-
keypair.EncodePublicKey(testTransfer1.SrcPubkey()),
153+
testTransfer1.SrcPubkey().HexString(),
155154
},
156155
{
157156
false,
158157
hex.EncodeToString(voteHash1[:]),
159158
5,
160-
keypair.EncodePublicKey(testVote1.SrcPubkey()),
159+
testVote1.SrcPubkey().HexString(),
161160
},
162161
{
163162
true,
164163
hex.EncodeToString(executionHash1[:]),
165164
5,
166-
keypair.EncodePublicKey(testExecution1.SrcPubkey()),
165+
testExecution1.SrcPubkey().HexString(),
167166
},
168167
}
169168

@@ -1139,7 +1138,7 @@ func addActsToActPool(ap actpool.ActPool) error {
11391138
}
11401139

11411140
func setupChain(cfg config.Config) (blockchain.Blockchain, *protocol.Registry, error) {
1142-
cfg.Chain.ProducerPrivKey = hex.EncodeToString(keypair.PrivateKeyToBytes(identityset.PrivateKey(0)))
1141+
cfg.Chain.ProducerPrivKey = hex.EncodeToString(identityset.PrivateKey(0).Bytes())
11431142
sf, err := factory.NewFactory(cfg, factory.InMemTrieOption())
11441143
if err != nil {
11451144
return nil, nil, err

blockchain/block/block.go

+3-6
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"bytes"
1111
"time"
1212

13-
"github.com/ethereum/go-ethereum/crypto"
1413
"github.com/golang/protobuf/proto"
1514
"github.com/pkg/errors"
1615
"go.uber.org/zap"
@@ -141,11 +140,10 @@ func (b *Block) VerifyDeltaStateDigest(digest hash.Hash256) error {
141140
func (b *Block) VerifySignature() bool {
142141
h := b.Header.HashHeaderCore()
143142

144-
if len(b.Header.blockSig) != action.SignatureLength {
143+
if b.Header.pubkey == nil || len(b.Header.blockSig) != action.SignatureLength {
145144
return false
146145
}
147-
return crypto.VerifySignature(keypair.PublicKeyToBytes(b.Header.pubkey), h[:],
148-
b.Header.blockSig[:action.SignatureLength-1])
146+
return b.Header.pubkey.Verify(h[:], b.Header.blockSig)
149147
}
150148

151149
// VerifyReceiptRoot verifies the receipt root in header
@@ -158,8 +156,7 @@ func (b *Block) VerifyReceiptRoot(root hash.Hash256) error {
158156

159157
// ProducerAddress returns the address of producer
160158
func (b *Block) ProducerAddress() string {
161-
pkHash := keypair.HashPubKey(b.Header.pubkey)
162-
addr, _ := address.FromBytes(pkHash[:])
159+
addr, _ := address.FromBytes(b.Header.pubkey.Hash())
163160
return addr.String()
164161
}
165162

blockchain/block/block_test.go

+5-6
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import (
1515

1616
"github.com/iotexproject/iotex-core/action"
1717
"github.com/iotexproject/iotex-core/pkg/hash"
18-
"github.com/iotexproject/iotex-core/pkg/keypair"
1918
"github.com/iotexproject/iotex-core/pkg/version"
2019
"github.com/iotexproject/iotex-core/protogen/iotextypes"
2120
ta "github.com/iotexproject/iotex-core/test/testaddress"
@@ -69,7 +68,7 @@ func TestConvertFromBlockPb(t *testing.T) {
6968
Version: version.ProtocolVersion,
7069
Height: 123456789,
7170
},
72-
ProducerPubkey: keypair.PublicKeyToBytes(senderPubKey),
71+
ProducerPubkey: senderPubKey.Bytes(),
7372
},
7473
Actions: []*iotextypes.Action{
7574
{
@@ -80,7 +79,7 @@ func TestConvertFromBlockPb(t *testing.T) {
8079
Version: version.ProtocolVersion,
8180
Nonce: 101,
8281
},
83-
SenderPubKey: keypair.PublicKeyToBytes(senderPubKey),
82+
SenderPubKey: senderPubKey.Bytes(),
8483
},
8584
{
8685
Core: &iotextypes.ActionCore{
@@ -90,7 +89,7 @@ func TestConvertFromBlockPb(t *testing.T) {
9089
Version: version.ProtocolVersion,
9190
Nonce: 102,
9291
},
93-
SenderPubKey: keypair.PublicKeyToBytes(senderPubKey),
92+
SenderPubKey: senderPubKey.Bytes(),
9493
},
9594
{
9695
Core: &iotextypes.ActionCore{
@@ -100,7 +99,7 @@ func TestConvertFromBlockPb(t *testing.T) {
10099
Version: version.ProtocolVersion,
101100
Nonce: 103,
102101
},
103-
SenderPubKey: keypair.PublicKeyToBytes(senderPubKey),
102+
SenderPubKey: senderPubKey.Bytes(),
104103
},
105104
{
106105
Core: &iotextypes.ActionCore{
@@ -110,7 +109,7 @@ func TestConvertFromBlockPb(t *testing.T) {
110109
Version: version.ProtocolVersion,
111110
Nonce: 104,
112111
},
113-
SenderPubKey: keypair.PublicKeyToBytes(senderPubKey),
112+
SenderPubKey: senderPubKey.Bytes(),
114113
},
115114
},
116115
}))

blockchain/block/builder.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
package block
88

99
import (
10-
"github.com/ethereum/go-ethereum/crypto"
10+
"bytes"
11+
1112
"github.com/pkg/errors"
1213

1314
"github.com/iotexproject/iotex-core/action"
@@ -66,13 +67,13 @@ func (b *Builder) SetReceiptRoot(h hash.Hash256) *Builder {
6667
}
6768

6869
// SignAndBuild signs and then builds a block.
69-
func (b *Builder) SignAndBuild(signerPriKey keypair.PrivateKey) (Block, error) {
70-
if keypair.EncodePublicKey(b.blk.Header.pubkey) != keypair.EncodePublicKey(&signerPriKey.PublicKey) {
70+
func (b *Builder) SignAndBuild(signerPrvKey keypair.PrivateKey) (Block, error) {
71+
if !bytes.Equal(b.blk.Header.pubkey.Bytes(), signerPrvKey.PublicKey().Bytes()) {
7172
return Block{}, errors.New("public key from the signer doesn't match that from runnable actions")
7273
}
7374

7475
h := b.blk.Header.HashHeaderCore()
75-
sig, err := crypto.Sign(h[:], signerPriKey)
76+
sig, err := signerPrvKey.Sign(h[:])
7677
if err != nil {
7778
return Block{}, errors.New("failed to sign block")
7879
}

0 commit comments

Comments
 (0)