/
addressbook_connector.go
222 lines (193 loc) · 7.23 KB
/
addressbook_connector.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
// Copyright 2019 The klaytn Authors
// This file is part of the klaytn library.
//
// The klaytn 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 klaytn 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 klaytn library. If not, see <http://www.gnu.org/licenses/>.
package reward
import (
"errors"
"fmt"
"math/big"
"strings"
"github.com/klaytn/klaytn/accounts/abi"
"github.com/klaytn/klaytn/blockchain"
"github.com/klaytn/klaytn/blockchain/types"
"github.com/klaytn/klaytn/blockchain/vm"
"github.com/klaytn/klaytn/common"
"github.com/klaytn/klaytn/contracts/reward/contract"
"github.com/klaytn/klaytn/params"
)
// addressType defined in AddressBook
const (
addressTypeNodeID = iota
addressTypeStakingAddr
addressTypeRewardAddr
addressTypePoCAddr
addressTypeKIRAddr
)
var errAddressBookIncomplete = errors.New("incomplete node information from AddressBook")
var addressBookContractAddress = contract.AddressBookContractAddress
type addressBookConnector struct {
bc blockChain
gh governanceHelper
abi string
contractAddress common.Address
}
// create and return addressBookConnector
func newAddressBookConnector(bc blockChain, gh governanceHelper) *addressBookConnector {
return &addressBookConnector{
bc: bc,
gh: gh,
abi: contract.AddressBookABI,
contractAddress: common.HexToAddress(addressBookContractAddress),
}
}
// make a message to the addressBook contract for executing getAllAddress function of the addressBook contract
func (ac *addressBookConnector) makeMsgToAddressBook(r params.Rules) (*types.Transaction, error) {
abiInstance, err := abi.JSON(strings.NewReader(ac.abi))
if err != nil {
return nil, err
}
data, err := abiInstance.Pack("getAllAddress")
if err != nil {
return nil, err
}
intrinsicGas, err := types.IntrinsicGas(data, nil, false, r)
if err != nil {
return nil, err
}
// Create new call message
// TODO-Klaytn-Issue1166 Decide who will be sender(i.e. from)
var (
from = common.Address{}
to = &ac.contractAddress
nonce = uint64(0)
amount = big.NewInt(0)
gasLimit = uint64(10000000)
gasPrice = big.NewInt(0)
checkNonce = false
)
msg := types.NewMessage(from, to, nonce, amount, gasLimit, gasPrice,
data, checkNonce, intrinsicGas)
return msg, nil
}
// It parses the result bytes of calling addressBook to addresses.
func (ac *addressBookConnector) parseAllAddresses(result []byte) (nodeIds []common.Address, stakingAddrs []common.Address, rewardAddrs []common.Address, pocAddr common.Address, kirAddr common.Address, err error) {
nodeIds = []common.Address{}
stakingAddrs = []common.Address{}
rewardAddrs = []common.Address{}
pocAddr = common.Address{}
kirAddr = common.Address{}
if result == nil {
err = errAddressBookIncomplete
return
}
abiInstance, err := abi.JSON(strings.NewReader(ac.abi))
if err != nil {
return
}
var (
allTypeList = new([]uint8)
allAddressList = new([]common.Address)
)
out := &[]interface{}{
allTypeList,
allAddressList,
}
err = abiInstance.Unpack(out, "getAllAddress", result)
if err != nil {
logger.Trace("abiInstance.Unpack failed for getAllAddress in AddressBook")
return
}
if len(*allTypeList) != len(*allAddressList) {
err = errors.New(fmt.Sprintf("length of type list and address list differ. len(type)=%d, len(addrs)=%d", len(*allTypeList), len(*allAddressList)))
return
}
// Parse and construct node information
for i, addrType := range *allTypeList {
switch addrType {
case addressTypeNodeID:
nodeIds = append(nodeIds, (*allAddressList)[i])
case addressTypeStakingAddr:
stakingAddrs = append(stakingAddrs, (*allAddressList)[i])
case addressTypeRewardAddr:
rewardAddrs = append(rewardAddrs, (*allAddressList)[i])
case addressTypePoCAddr:
pocAddr = (*allAddressList)[i]
case addressTypeKIRAddr:
kirAddr = (*allAddressList)[i]
default:
err = errors.New(fmt.Sprintf("invalid type from AddressBook: %d", addrType))
return
}
}
// validate parsed node information
if len(nodeIds) != len(stakingAddrs) ||
len(nodeIds) != len(rewardAddrs) ||
common.EmptyAddress(pocAddr) ||
common.EmptyAddress(kirAddr) {
err = errAddressBookIncomplete
return
}
return
}
// getStakingInfoFromAddressBook returns stakingInfo when calling AddressBook succeeded.
// If addressBook is not activated, emptyStakingInfo is returned.
// After addressBook is activated, it returns stakingInfo with addresses and stakingAmount.
// Otherwise, it returns an error.
func (ac *addressBookConnector) getStakingInfoFromAddressBook(blockNum uint64) (*StakingInfo, error) {
if !params.IsStakingUpdateInterval(blockNum) {
return nil, errors.New(fmt.Sprintf("not staking block number. blockNum: %d", blockNum))
}
// Prepare a message
msg, err := ac.makeMsgToAddressBook(ac.bc.Config().Rules(new(big.Int).SetUint64(blockNum)))
if err != nil {
return nil, errors.New(fmt.Sprintf("failed to make message for AddressBook. root err: %s", err))
}
intervalBlock := ac.bc.GetBlockByNumber(blockNum)
if intervalBlock == nil {
return nil, errors.New("stateDB is not ready for staking info")
}
statedb, err := ac.bc.StateAt(intervalBlock.Root())
if err != nil {
return nil, errors.New(fmt.Sprintf("failed to make a state for interval block. blockNum: %d, root err: %s", blockNum, err))
}
// Create a new context to be used in the EVM environment
context := blockchain.NewEVMContext(msg, intervalBlock.Header(), ac.bc, nil)
// EVM demands the sender to have enough KLAY balance (gasPrice * gasLimit) in buyGas()
// After KIP-71, gasPrice is baseFee (=nonzero), regardless of the msg.gasPrice (=zero)
// But our sender (0x0) won't have enough balance. Instead we override gasPrice = 0 here
context.GasPrice = big.NewInt(0)
evm := vm.NewEVM(context, statedb, ac.bc.Config(), &vm.Config{})
res, gas, kerr := blockchain.ApplyMessage(evm, msg)
logger.Trace("Call AddressBook contract", "used gas", gas, "kerr", kerr)
err = kerr.ErrTxInvalid
if err != nil {
return nil, errors.New(fmt.Sprintf("failed to call AddressBook contract. root err: %s", err))
}
nodeAddrs, stakingAddrs, rewardAddrs, PoCAddr, KIRAddr, err := ac.parseAllAddresses(res)
if err != nil {
if err == errAddressBookIncomplete {
// This is an expected behavior when the addressBook contract is not activated yet.
logger.Info("The addressBook is not yet activated. Use empty stakingInfo", "reason", err)
} else {
logger.Error("Fail while parsing a result from the addressBook. Use empty staking info", "err", err)
}
return newEmptyStakingInfo(blockNum), nil
}
return newStakingInfo(ac.bc, ac.gh, blockNum, nodeAddrs, stakingAddrs, rewardAddrs, KIRAddr, PoCAddr)
}
// Only for testing purpose.
func SetTestAddressBookAddress(addr common.Address) {
addressBookContractAddress = addr.Hex()
}