forked from PlatONnetwork/PlatON-Go
/
validator_inner_contract.go
241 lines (206 loc) · 7.3 KB
/
validator_inner_contract.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
// Copyright 2021 The PlatON Network Authors
// This file is part of the PlatON-Go library.
//
// The PlatON-Go library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The PlatON-Go library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the PlatON-Go library. If not, see <http://www.gnu.org/licenses/>.
package vm
import (
"errors"
"fmt"
"bytes"
"encoding/json"
"encoding/binary"
"github.com/hashkey-chain/hashkey-chain/common"
"github.com/hashkey-chain/hashkey-chain/crypto"
"github.com/hashkey-chain/hashkey-chain/crypto/bls"
"github.com/hashkey-chain/hashkey-chain/log"
"github.com/hashkey-chain/hashkey-chain/p2p/discover"
"github.com/hashkey-chain/hashkey-chain/params"
"github.com/hashkey-chain/hashkey-chain/rlp"
)
const (
CurrentValidatorKey = "current_validator"
NextValidatorKey = "next_validator"
txTypeUpdate = 2000
txTypeCurrent = 2001
txTypeNext = 2002
txTypeSwitch = 2003
)
type ValidateNode struct {
Index uint `json:"index"`
NodeID discover.NodeID `json:"nodeID"`
Address common.NodeAddress `json:"-"`
BlsPubKey bls.PublicKey `json:"blsPubKey"`
}
type NodeList []*ValidateNode
func (nl *NodeList) String() string {
s := ""
for _, v := range *nl {
s = s + fmt.Sprintf("{Index: %d NodeID: %s Address: %s blsPubKey: %s},", v.Index, v.NodeID, v.Address.String(), fmt.Sprintf("%x", v.BlsPubKey.Serialize()))
}
return s
}
type Validators struct {
ValidateNodes NodeList `json:"validateNodes"`
ValidBlockNumber uint64 `json:"-"`
}
func (vds *Validators) String() string {
return fmt.Sprintf("{validateNodes: [%s] validBlockNumber: %d}", vds.ValidateNodes.String(), vds.ValidBlockNumber)
}
type ValidatorInnerContractBase interface {
UpdateValidators(validators *Validators) error
CurrentValidators() (*Validators, error)
NextValidators() (*Validators, error)
SwitchValidators(validBlockNumber uint64) error
}
type validatorInnerContract struct {
ValidatorInnerContractBase
Contract *Contract
Evm *EVM
}
func (vic *validatorInnerContract) RequiredGas(input []byte) uint64 {
return params.EcrecoverGas
}
func (vic *validatorInnerContract) Run(input []byte) ([]byte, error) {
var cmd = map[string]interface{}{
"UpdateValidators": vic.UpdateValidators,
"CurrentValidatros": vic.CurrentValidators,
"NextValidators": vic.NextValidators,
"SwitchValidators": vic.SwitchValidators,
}
return vic.execute(input, cmd)
}
func (vic *validatorInnerContract) UpdateValidators(validators *Validators) error {
if len(validators.ValidateNodes) <= 0 {
log.Error("Empty validator nodes")
return errors.New("Empty validator nodes")
}
var newVds Validators
for _, node := range validators.ValidateNodes {
pubkey, err := node.NodeID.Pubkey()
if err != nil {
log.Error("Get pubkey from nodeID fail", "error", err)
return err
}
node.Address = crypto.PubkeyToNodeAddress(*pubkey)
newVds.ValidateNodes = append(newVds.ValidateNodes, node)
}
log.Debug("Update validators", "validators", newVds.String(), "address", vic.Contract.Address())
vs, err := rlp.EncodeToBytes(newVds)
if err != nil {
log.Error("RLP encode error", "validators", newVds.String(), "error", err)
return err
}
vic.Evm.StateDB.SetState(vic.Contract.Address(), []byte(NextValidatorKey), vs)
return nil
}
func (vic *validatorInnerContract) CurrentValidators() (*Validators, error) {
state := vic.Evm.StateDB
b := state.GetState(vic.Contract.Address(), []byte(CurrentValidatorKey))
var vds Validators
err := rlp.DecodeBytes(b, &vds)
return &vds, err
}
func (vic *validatorInnerContract) NextValidators() (*Validators, error) {
state := vic.Evm.StateDB
b := state.GetState(vic.Contract.Address(), []byte(NextValidatorKey))
var vds Validators
err := rlp.DecodeBytes(b, &vds)
return &vds, err
}
func (vic *validatorInnerContract) SwitchValidators(validBlockNumber uint64) error {
state := vic.Evm.StateDB
b := state.GetState(vic.Contract.Address(), []byte(NextValidatorKey))
var nvs Validators
err := rlp.DecodeBytes(b, &nvs)
if err == nil {
nvs.ValidBlockNumber = validBlockNumber
b, _ = rlp.EncodeToBytes(nvs)
state.SetState(vic.Contract.Address(), []byte(CurrentValidatorKey), b)
log.Debug("Switch validators success", "number", vic.Evm.Context.BlockNumber, "validators", nvs.String())
return nil
}
log.Warn("Get next validators fail, try to get current validators", "error", err, "validBlockNumber", validBlockNumber)
// Try to get current validators.
b = state.GetState(vic.Contract.Address(), []byte(CurrentValidatorKey))
err = rlp.DecodeBytes(b, &nvs)
if err != nil {
log.Error("RLP decode current Validators fail", "validBlockNumber", validBlockNumber, "error", err)
return err
}
// There not next validators, so update ValidBlockNumber and setting current as next.
nvs.ValidBlockNumber = validBlockNumber
b, _ = rlp.EncodeToBytes(nvs)
state.SetState(vic.Contract.Address(), []byte(CurrentValidatorKey), b)
log.Debug("Switch validators success", "number", vic.Evm.Context.BlockNumber, "validators", nvs.String())
return nil
}
func (vic *validatorInnerContract) execute(input []byte, cmd map[string]interface{}) (ret []byte, err error) {
defer func() {
if er := recover(); er != nil {
ret, err = nil, fmt.Errorf("Validator inner contract execute fail: %v", er)
log.Error("Validator inner contract execute fail", "error", err)
}
}()
var source [][]byte
if err = rlp.Decode(bytes.NewReader(input), &source); err != nil {
log.Error("Validator inner contract execute fail", "error", err)
return nil, errors.New("RLP decode fail")
}
if len(source) < 2 {
log.Error("Params base length not match")
return nil, errors.New("Params base length not match")
}
funcName := string(source[1])
if _, ok := cmd[funcName]; !ok {
log.Error("Function undefined", "function", funcName)
return nil, errors.New("Function undefined")
}
txType := common.BytesToInt64(source[0])
switch txType {
case txTypeUpdate:
var vds Validators
err = json.Unmarshal(source[2], &vds)
if err != nil {
log.Error("Parse params fail", "params", string(source[2]), "error", err)
return nil, err
}
err = vic.UpdateValidators(&vds)
return nil, err
case txTypeCurrent:
var vds *Validators = nil
vds, err = vic.CurrentValidators()
if err != nil {
log.Error("Get current validators fail", "error", err)
return nil, err
}
b, _ := json.Marshal(&vds)
return b, nil
case txTypeNext:
var vds *Validators = nil
vds, err = vic.NextValidators()
if err != nil {
log.Error("Get next validators fail", "error", err)
return nil, err
}
b, _ := json.Marshal(&vds)
return b, nil
case txTypeSwitch:
log.Debug("Switch validators", "source", len(source))
validBlockNumber := binary.BigEndian.Uint64(source[2])
return nil, vic.SwitchValidators(validBlockNumber)
default:
log.Error("Unexpected transaction type", "txType", txType)
return nil, errors.New("unexpected transaction type")
}
}