-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathsigverify.go
350 lines (288 loc) · 10.9 KB
/
sigverify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package ante
import (
"bytes"
"encoding/hex"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
errs "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/auth/exported"
"github.com/cosmos/cosmos-sdk/x/auth/keeper"
"github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/crypto/multisig"
"github.com/tendermint/tendermint/crypto/secp256k1"
)
var (
// simulation signature values used to estimate gas consumption
simSecp256k1Pubkey secp256k1.PubKeySecp256k1
simSecp256k1Sig [64]byte
)
func init() {
// This decodes a valid hex string into a sepc256k1Pubkey for use in transaction simulation
bz, _ := hex.DecodeString("035AD6810A47F073553FF30D2FCC7E0D3B1C0B74B61A1AAA2582344037151E143A")
copy(simSecp256k1Pubkey[:], bz)
}
// SignatureVerificationGasConsumer is the type of function that is used to both consume gas when verifying signatures
// and also to accept or reject different types of PubKey's. This is where apps can define their own PubKey
type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params) error
// Consume parameter-defined amount of gas for each signature according to the passed-in SignatureVerificationGasConsumer function
// before calling the next AnteHandler
type SigGasConsumeDecorator struct {
ak keeper.AccountKeeper
sigGasConsumer SignatureVerificationGasConsumer
}
func NewSigGasConsumeDecorator(ak keeper.AccountKeeper, sigGasConsumer SignatureVerificationGasConsumer) SigGasConsumeDecorator {
return SigGasConsumeDecorator{
ak: ak,
sigGasConsumer: sigGasConsumer,
}
}
func (sgcd SigGasConsumeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
stdTx, ok := tx.(types.StdTx)
if !ok {
return ctx, errs.Wrap(errs.ErrTxDecode, "Tx must be a StdTx")
}
params := sgcd.ak.GetParams(ctx)
stdSigs := stdTx.GetSignatures()
// stdSigs contains the sequence number, account number, and signatures.
// When simulating, this would just be a 0-length slice.
signerAddrs := stdTx.GetSigners()
for i, sig := range stdSigs {
pubKey := sig.PubKey
if pubKey == nil {
signerAcc, err := GetSignerAcc(ctx, sgcd.ak, signerAddrs[i])
if err != nil {
return ctx, err
}
pubKey = signerAcc.GetPubKey()
}
if simulate {
// Simulated txs should not contain a signature and are not required to
// contain a pubkey, so we must account for tx size of including a
// StdSignature (Amino encoding) and simulate gas consumption
// (assuming a SECP256k1 simulation key).
consumeSimSigGas(ctx.GasMeter(), pubKey, sig, params)
}
err = sgcd.sigGasConsumer(ctx.GasMeter(), sig.Signature, pubKey, params)
if err != nil {
return ctx, err
}
}
return next(ctx, tx, simulate)
}
// Verify all signatures for tx and return error if any are invalid
// increment sequence of each signer and set updated account back in store
// Call next AnteHandler
type SigVerificationDecorator struct {
ak keeper.AccountKeeper
}
func NewSigVerificationDecorator(ak keeper.AccountKeeper) SigVerificationDecorator {
return SigVerificationDecorator{
ak: ak,
}
}
func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
stdTx, ok := tx.(types.StdTx)
if !ok {
return ctx, errs.Wrap(errs.ErrTxDecode, "Tx must be a StdTx")
}
isGenesis := ctx.BlockHeight() == 0
// stdSigs contains the sequence number, account number, and signatures.
// When simulating, this would just be a 0-length slice.
stdSigs := stdTx.GetSignatures()
// stdSigs contains the sequence number, account number, and signatures.
// When simulating, this would just be a 0-length slice.
signerAddrs := stdTx.GetSigners()
signerAccs := make([]exported.Account, len(signerAddrs))
for i := 0; i < len(stdSigs); i++ {
signerAccs[i], err = GetSignerAcc(ctx, svd.ak, signerAddrs[i])
if err != nil {
return ctx, err
}
// check signature, return account with incremented nonce
signBytes := GetSignBytes(ctx.ChainID(), stdTx, signerAccs[i], isGenesis)
signerAccs[i], err = processSig(ctx, signerAccs[i], stdSigs[i], signBytes, simulate)
if err != nil {
return ctx, err
}
svd.ak.SetAccount(ctx, signerAccs[i])
}
return next(ctx, tx, simulate)
}
// ValidateSigCountDecorator takes in Params and returns errors if there are too many signatures in the tx for the given params
// otherwise it calls next AnteHandler
type ValidateSigCountDecorator struct {
ak keeper.AccountKeeper
}
func NewValidateSigCountDecorator(ak keeper.AccountKeeper) ValidateSigCountDecorator {
return ValidateSigCountDecorator{
ak: ak,
}
}
func (vscd ValidateSigCountDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
stdTx, ok := tx.(types.StdTx)
if !ok {
return ctx, errs.Wrap(errs.ErrTxDecode, "Tx must be a StdTx")
}
params := vscd.ak.GetParams(ctx)
stdSigs := stdTx.GetSignatures()
sigCount := 0
for i := 0; i < len(stdSigs); i++ {
sigCount += types.CountSubKeys(stdSigs[i].PubKey)
if uint64(sigCount) > params.TxSigLimit {
return ctx, errs.Wrapf(errs.ErrTooManySignatures,
"signatures: %d, limit: %d", sigCount, params.TxSigLimit)
}
}
return next(ctx, tx, simulate)
}
type SetPubKeyDecorator struct {
ak keeper.AccountKeeper
}
func NewSetPubKeyDecorator(ak keeper.AccountKeeper) SetPubKeyDecorator {
return SetPubKeyDecorator{
ak: ak,
}
}
func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
if simulate {
return next(ctx, tx, simulate)
}
stdTx, ok := tx.(types.StdTx)
if !ok {
return ctx, errs.Wrap(errs.ErrTxDecode, "Tx must be a StdTx")
}
stdSigs := stdTx.GetSignatures()
signers := stdTx.GetSigners()
for i, sig := range stdSigs {
if sig.PubKey != nil {
if !bytes.Equal(sig.PubKey.Address(), signers[i]) {
return ctx, errs.Wrapf(errs.ErrInvalidPubKey,
"PubKey does not match Signer address %s with signer index: %d", signers[i], i)
}
acc, err := GetSignerAcc(ctx, spkd.ak, signers[i])
if err != nil {
return ctx, err
}
err = acc.SetPubKey(sig.PubKey)
if err != nil {
return ctx, errs.Wrap(errs.ErrInvalidPubKey, err.Error())
}
spkd.ak.SetAccount(ctx, acc)
}
}
return next(ctx, tx, simulate)
}
// DefaultSigVerificationGasConsumer is the default implementation of SignatureVerificationGasConsumer. It consumes gas
// for signature verification based upon the public key type. The cost is fetched from the given params and is matched
// by the concrete type.
func DefaultSigVerificationGasConsumer(
meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params,
) error {
switch pubkey := pubkey.(type) {
case ed25519.PubKeyEd25519:
meter.ConsumeGas(params.SigVerifyCostED25519, "ante verify: ed25519")
return errs.Wrap(errs.ErrInvalidPubKey, "ED25519 public keys are unsupported")
case secp256k1.PubKeySecp256k1:
meter.ConsumeGas(params.SigVerifyCostSecp256k1, "ante verify: secp256k1")
return nil
case multisig.PubKeyMultisigThreshold:
var multisignature multisig.Multisignature
codec.Cdc.MustUnmarshalBinaryBare(sig, &multisignature)
consumeMultisignatureVerificationGas(meter, multisignature, pubkey, params)
return nil
default:
return errs.Wrapf(errs.ErrInvalidPubKey, "unrecognized public key type: %T", pubkey)
}
}
func consumeMultisignatureVerificationGas(meter sdk.GasMeter,
sig multisig.Multisignature, pubkey multisig.PubKeyMultisigThreshold,
params types.Params) {
size := sig.BitArray.Size()
sigIndex := 0
for i := 0; i < size; i++ {
if sig.BitArray.GetIndex(i) {
DefaultSigVerificationGasConsumer(meter, sig.Sigs[sigIndex], pubkey.PubKeys[i], params)
sigIndex++
}
}
}
func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig types.StdSignature, params types.Params) {
simSig := types.StdSignature{PubKey: pubkey}
if len(sig.Signature) == 0 {
simSig.Signature = simSecp256k1Sig[:]
}
sigBz := types.ModuleCdc.MustMarshalBinaryLengthPrefixed(simSig)
cost := sdk.Gas(len(sigBz) + 6)
// If the pubkey is a multi-signature pubkey, then we estimate for the maximum
// number of signers.
if _, ok := pubkey.(multisig.PubKeyMultisigThreshold); ok {
cost *= params.TxSigLimit
}
gasmeter.ConsumeGas(params.TxSizeCostPerByte*cost, "txSize")
}
// ProcessPubKey verifies that the given account address matches that of the
// StdSignature. In addition, it will set the public key of the account if it
// has not been set.
func ProcessPubKey(acc exported.Account, sig types.StdSignature, simulate bool) (crypto.PubKey, error) {
// If pubkey is not known for account, set it from the types.StdSignature.
pubKey := acc.GetPubKey()
if simulate {
// In simulate mode the transaction comes with no signatures, thus if the
// account's pubkey is nil, both signature verification and gasKVStore.Set()
// shall consume the largest amount, i.e. it takes more gas to verify
// secp256k1 keys than ed25519 ones.
if pubKey == nil {
return simSecp256k1Pubkey, nil
}
return pubKey, nil
}
if pubKey == nil {
pubKey = sig.PubKey
if pubKey == nil {
return nil, errs.Wrap(errs.ErrInvalidPubKey, "PubKey not found")
}
if !bytes.Equal(pubKey.Address(), acc.GetAddress()) {
return nil, errs.Wrapf(errs.ErrUnauthorized,
"PubKey does not match Signer address %s", acc.GetAddress())
}
}
return pubKey, nil
}
// verify the signature and increment the sequence. If the account doesn't have
// a pubkey, set it.
func processSig(
ctx sdk.Context, acc exported.Account, sig types.StdSignature, signBytes []byte, simulate bool,
) (updatedAcc exported.Account, err error) {
pubKey := acc.GetPubKey()
if !simulate && pubKey == nil {
return nil, errs.Wrap(errs.ErrInvalidPubKey, "pubkey on account is not set")
}
if !simulate && !pubKey.VerifyBytes(signBytes, sig.Signature) {
return nil, errs.Wrap(errs.ErrUnauthorized, "signature verification failed; verify correct account sequence and chain-id")
}
if err = acc.SetSequence(acc.GetSequence() + 1); err != nil {
panic(err)
}
return acc, nil
}
// GetSignerAcc returns an account for a given address that is expected to sign
// a transaction.
func GetSignerAcc(ctx sdk.Context, ak keeper.AccountKeeper, addr sdk.AccAddress) (exported.Account, error) {
if acc := ak.GetAccount(ctx, addr); acc != nil {
return acc, nil
}
return nil, errs.Wrapf(errs.ErrUnknownAddress, "account %s does not exist", addr)
}
// GetSignBytes returns a slice of bytes to sign over for a given transaction
// and an account.
func GetSignBytes(chainID string, stdTx types.StdTx, acc exported.Account, genesis bool) []byte {
var accNum uint64
if !genesis {
accNum = acc.GetAccountNumber()
}
return types.StdSignBytes(
chainID, accNum, acc.GetSequence(), stdTx.Fee, stdTx.Msgs, stdTx.Memo,
)
}