-
Notifications
You must be signed in to change notification settings - Fork 42
/
collapse.go
393 lines (311 loc) · 9.85 KB
/
collapse.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// Copyright (c) 2019 Perlin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package wavelet
import (
"encoding/hex"
"github.com/perlin-network/wavelet/avl"
"github.com/perlin-network/wavelet/log"
"github.com/perlin-network/wavelet/sys"
"github.com/pkg/errors"
)
func collapseTransactions(
height uint64, txs []*Transaction, block *Block, accounts *Accounts,
) (*collapseResults, error) {
snapshot := accounts.Snapshot()
snapshot.SetViewID(height)
res := &collapseResults{
snapshot: snapshot,
ctx: NewCollapseContext(snapshot),
applied: make([]*Transaction, 0, len(txs)),
rejected: make([]*Transaction, 0, len(txs)),
rejectedErrors: make([]error, 0, len(txs)),
}
var (
totalStake uint64
totalFee uint64
)
stakes := make(map[AccountID]uint64)
// Apply transactions in reverse order from the end of the round
// all the way down to the beginning of the round.
for _, tx := range txs {
if hex.EncodeToString(tx.Sender[:]) != sys.FaucetAddress {
fee := tx.Fee()
senderBalance, _ := res.ctx.ReadAccountBalance(tx.Sender)
if senderBalance < fee {
res.rejected = append(res.rejected, tx)
res.rejectedErrors = append(
res.rejectedErrors,
errors.Errorf(
"stake: sender %x does not have enough PERLs to pay transaction fees (comprised of %d PERLs)",
tx.Sender, fee,
),
)
res.rejectedCount += tx.LogicalUnits()
continue
}
res.ctx.WriteAccountBalance(tx.Sender, senderBalance-fee)
totalFee += fee
stake, _ := res.ctx.ReadAccountStake(tx.Sender)
if stake >= sys.MinimumStake {
if _, ok := stakes[tx.Sender]; !ok {
stakes[tx.Sender] = stake
} else {
stakes[tx.Sender] += stake
}
totalStake += stake
}
}
if err := res.ctx.ApplyTransaction(block, tx); err != nil {
res.rejected = append(res.rejected, tx)
res.rejectedErrors = append(res.rejectedErrors, err)
res.rejectedCount += tx.LogicalUnits()
logger := log.Node()
logger.Error().Err(err).Msg("error applying transaction")
continue
}
// Update statistics.
res.applied = append(res.applied, tx)
res.appliedCount += tx.LogicalUnits()
}
if totalStake > 0 {
for sender, stake := range stakes {
rewardeeBalance, _ := res.ctx.ReadAccountReward(sender)
reward := float64(totalFee) * (float64(stake) / float64(totalStake))
res.ctx.WriteAccountReward(sender, rewardeeBalance+uint64(reward))
}
}
res.ctx.processRewardWithdrawals(block.Index)
if err := res.ctx.Flush(); err != nil {
return res, err
}
//res.ctx.processFinalizedTransactions(block.Index, txs)
return res, nil
}
// WARNING: While using this, the tree must not be modified.
type CollapseContext struct {
tree *avl.Tree
checksum [16]byte
accountLen uint64
// To preserve order of state insertions of accounts
accountIDs []AccountID
accounts map[AccountID]struct{}
balances map[AccountID]uint64
stakes map[AccountID]uint64
rewards map[AccountID]uint64
contracts map[TransactionID][]byte
contractGasBalances map[TransactionID]uint64
contractVMs map[AccountID]*VMState
rewardWithdrawalRequests []RewardWithdrawalRequest
VMCache *VMLRU
}
func NewCollapseContext(tree *avl.Tree) *CollapseContext {
ctx := &CollapseContext{
tree: tree,
}
ctx.init()
return ctx
}
func (c *CollapseContext) init() {
c.checksum = c.tree.Checksum()
c.accountLen = ReadAccountsLen(c.tree)
c.accounts = make(map[AccountID]struct{})
c.balances = make(map[AccountID]uint64)
c.stakes = make(map[AccountID]uint64)
c.rewards = make(map[AccountID]uint64)
c.contracts = make(map[TransactionID][]byte)
c.contractGasBalances = make(map[TransactionID]uint64)
c.contractVMs = make(map[AccountID]*VMState)
c.VMCache = NewVMLRU(4)
}
func (c *CollapseContext) ReadAccountsLen() uint64 {
return c.accountLen
}
func (c *CollapseContext) WriteAccountsLen(size uint64) {
c.accountLen = size
}
func (c *CollapseContext) ReadAccountBalance(id AccountID) (uint64, bool) {
if balance, ok := c.balances[id]; ok {
return balance, true
}
balance, exists := ReadAccountBalance(c.tree, id)
if exists {
c.balances[id] = balance
}
return balance, exists
}
func (c *CollapseContext) ReadAccountStake(id AccountID) (uint64, bool) {
if stake, ok := c.stakes[id]; ok {
return stake, true
}
stake, exists := ReadAccountStake(c.tree, id)
if exists {
c.stakes[id] = stake
}
return stake, exists
}
func (c *CollapseContext) ReadAccountReward(id AccountID) (uint64, bool) {
if reward, ok := c.rewards[id]; ok {
return reward, true
}
reward, exists := ReadAccountReward(c.tree, id)
if exists {
c.rewards[id] = reward
}
return reward, exists
}
func (c *CollapseContext) ReadAccountContractGasBalance(id TransactionID) (uint64, bool) {
if gasBalance, ok := c.contractGasBalances[id]; ok {
return gasBalance, true
}
gasBalance, exists := ReadAccountContractGasBalance(c.tree, id)
if exists {
c.contractGasBalances[id] = gasBalance
}
return gasBalance, exists
}
func (c *CollapseContext) ReadAccountContractCode(id TransactionID) ([]byte, bool) {
if code, ok := c.contracts[id]; ok {
return code, true
}
code, exists := ReadAccountContractCode(c.tree, id)
if exists {
c.contracts[id] = code
}
return code, exists
}
func (c *CollapseContext) GetContractState(id AccountID) (*VMState, bool) {
vm, exists := c.contractVMs[id]
return vm, exists
}
func (c *CollapseContext) addAccount(id AccountID) {
if _, ok := c.accounts[id]; ok {
return
}
c.accounts[id] = struct{}{}
c.accountIDs = append(c.accountIDs, id)
}
func (c *CollapseContext) WriteAccountBalance(id AccountID, balance uint64) {
c.addAccount(id)
c.balances[id] = balance
}
func (c *CollapseContext) WriteAccountStake(id AccountID, stake uint64) {
c.addAccount(id)
c.stakes[id] = stake
}
func (c *CollapseContext) WriteAccountReward(id AccountID, reward uint64) {
c.addAccount(id)
c.rewards[id] = reward
}
func (c *CollapseContext) WriteAccountContractGasBalance(id TransactionID, gasBalance uint64) {
c.addAccount(id)
c.contractGasBalances[id] = gasBalance
}
func (c *CollapseContext) WriteAccountContractCode(id TransactionID, code []byte) {
c.addAccount(id)
c.contracts[id] = code
}
func (c *CollapseContext) SetContractState(id AccountID, state *VMState) {
c.addAccount(id)
c.contractVMs[id] = state
}
func (c *CollapseContext) StoreRewardWithdrawalRequest(rw RewardWithdrawalRequest) {
c.rewardWithdrawalRequests = append(c.rewardWithdrawalRequests, rw)
}
func (c *CollapseContext) processRewardWithdrawals(blockIndex uint64) {
if blockIndex < uint64(sys.RewardWithdrawalsBlockLimit) {
return
}
blockLimit := blockIndex - uint64(sys.RewardWithdrawalsBlockLimit)
var leftovers []RewardWithdrawalRequest
for i, rw := range c.rewardWithdrawalRequests {
if c.rewardWithdrawalRequests[i].blockIndex > blockLimit {
leftovers = append(leftovers, rw)
continue
}
balance, _ := c.ReadAccountBalance(rw.account)
c.WriteAccountBalance(rw.account, balance+rw.amount)
}
c.rewardWithdrawalRequests = leftovers
}
//func (c *CollapseContext) processFinalizedTransactions(height uint64, finalized []*Transaction) {
// pruningLimit := uint64(conf.GetPruningLimit())
//
// if height < pruningLimit {
// return
// }
//
// heightLimit := height - pruningLimit
//
// cb := func(k, v []byte) bool {
// height := binary.BigEndian.Uint64(k[:8])
//
// if height <= heightLimit {
// c.tree.Delete(append(keyTransactionFinalized[:], k...))
// return true
// }
//
// return false
// }
//
// c.tree.IteratePrefix(keyTransactionFinalized[:], cb)
//
// StoreFinalizedTransactionIDs(c.tree, height, finalized)
//}
// Write the changes into the tree.
func (c *CollapseContext) Flush() error {
if c.checksum != c.tree.Checksum() {
return errors.Errorf(
"stale state, the state has been modified. got merkle %x but expected %x.",
c.tree.Checksum(), c.checksum,
)
}
WriteAccountsLen(c.tree, c.accountLen)
for _, id := range c.accountIDs {
if bal, ok := c.balances[id]; ok {
WriteAccountBalance(c.tree, id, bal)
}
if stake, ok := c.stakes[id]; ok {
WriteAccountStake(c.tree, id, stake)
}
if reward, ok := c.rewards[id]; ok {
WriteAccountReward(c.tree, id, reward)
}
if gasBal, ok := c.contractGasBalances[id]; ok {
WriteAccountContractGasBalance(c.tree, id, gasBal)
}
if code, ok := c.contracts[id]; ok {
WriteAccountContractCode(c.tree, id, code)
}
if vm, ok := c.contractVMs[id]; ok {
SaveContractMemorySnapshot(c.tree, id, vm.Memory)
SaveContractGlobals(c.tree, id, vm.Globals)
}
}
return nil
}
// Apply a transaction by writing the states into memory.
// After you've finished, you MUST call CollapseContext.Flush() to actually write the states into the tree.
func (c *CollapseContext) ApplyTransaction(block *Block, tx *Transaction) error {
if err := applyTransaction(block, c, tx, &contractExecutorState{
GasPayer: tx.Sender,
}); err != nil {
return err
}
return nil
}