-
Notifications
You must be signed in to change notification settings - Fork 22
/
accounting_snapshot.go
202 lines (175 loc) · 5.94 KB
/
accounting_snapshot.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
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package staking
import (
"context"
"fmt"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/proto"
"code.vegaprotocol.io/vega/logging"
)
var accountsKey = (&types.PayloadStakingAccounts{}).Key()
type accountingSnapshotState struct {
serialised []byte
isRestoring bool
}
func (a *Accounting) serialiseStakingAccounts() ([]byte, error) {
accounts := make([]*types.StakingAccount, 0, len(a.hashableAccounts))
a.log.Debug("serialsing staking accounts", logging.Int("n", len(a.hashableAccounts)))
for _, acc := range a.hashableAccounts {
// dedup transactions with the same eth hash from different block heights and recalc the balance
acc.Events = a.dedupHack(acc.Events)
acc.computeOngoingBalance()
accounts = append(accounts,
&types.StakingAccount{
Party: acc.Party,
Balance: acc.Balance,
Events: acc.Events,
})
}
var psts *types.StakeTotalSupply
if a.pendingStakeTotalSupply != nil {
psts = a.pendingStakeTotalSupply.sts
}
pl := types.Payload{
Data: &types.PayloadStakingAccounts{
PendingStakeTotalSupply: psts,
StakingAccounts: &types.StakingAccounts{
Accounts: accounts,
StakingAssetTotalSupply: a.stakingAssetTotalSupply.Clone(),
},
},
}
return proto.Marshal(pl.IntoProto())
}
// get the serialised form and hash of the given key.
func (a *Accounting) serialise(k string) ([]byte, error) {
if k != accountsKey {
return nil, types.ErrSnapshotKeyDoesNotExist
}
data, err := a.serialiseStakingAccounts()
if err != nil {
return nil, err
}
a.accState.serialised = data
return data, nil
}
func (a *Accounting) OnStateLoaded(_ context.Context) error {
a.accState.isRestoring = false
return nil
}
func (a *Accounting) OnStateLoadStarts(_ context.Context) error {
a.accState.isRestoring = true
return nil
}
func (a *Accounting) Namespace() types.SnapshotNamespace {
return types.StakingSnapshot
}
func (a *Accounting) Keys() []string {
return []string{accountsKey}
}
func (a *Accounting) Stopped() bool {
return false
}
func (a *Accounting) GetState(k string) ([]byte, []types.StateProvider, error) {
data, err := a.serialise(k)
return data, nil, err
}
func (a *Accounting) LoadState(ctx context.Context, payload *types.Payload) ([]types.StateProvider, error) {
if a.Namespace() != payload.Data.Namespace() {
return nil, types.ErrInvalidSnapshotNamespace
}
switch pl := payload.Data.(type) {
case *types.PayloadStakingAccounts:
return nil, a.restoreStakingAccounts(ctx, pl.StakingAccounts, pl.PendingStakeTotalSupply, payload)
default:
return nil, types.ErrUnknownSnapshotType
}
}
// dedupHack takes care of events with the same ethereum tx hash originating from
// reorg - the result is that duplicates are removed and the branch with the latest block height is kept
// after calling this function, the balance should be recalculated.
func (a *Accounting) dedupHack(evts []*types.StakeLinking) []*types.StakeLinking {
hashToEvt := map[string]*types.StakeLinking{}
for _, sl := range evts {
evt, ok := hashToEvt[sl.TxHash]
if !ok {
hashToEvt[sl.TxHash] = sl
} else {
if sl.BlockHeight > evt.BlockHeight {
a.log.Warn("duplicate events with identical transaction hash found", logging.String("tx-hash", sl.TxHash), logging.Uint64("block-height1", sl.BlockHeight), logging.Uint64("block-height2", evt.BlockHeight))
hashToEvt[sl.TxHash] = sl
}
}
}
newEvts := make([]*types.StakeLinking, 0, len(hashToEvt))
for _, sl := range evts {
evt := hashToEvt[sl.TxHash]
if evt.BlockHeight == sl.BlockHeight {
newEvts = append(newEvts, sl)
}
}
return newEvts
}
func (a *Accounting) restoreStakingAccounts(ctx context.Context, accounts *types.StakingAccounts, pendingSupply *types.StakeTotalSupply, p *types.Payload) error {
a.hashableAccounts = make([]*Account, 0, len(accounts.Accounts))
a.log.Debug("restoring staking accounts",
logging.Int("n", len(accounts.Accounts)),
)
evts := []events.Event{}
pevts := []events.Event{}
for _, acc := range accounts.Accounts {
stakingAcc := &Account{
Party: acc.Party,
Balance: acc.Balance,
Events: a.dedupHack(acc.Events),
}
stakingAcc.computeOngoingBalance()
a.hashableAccounts = append(a.hashableAccounts, stakingAcc)
a.accounts[acc.Party] = stakingAcc
pevts = append(pevts, events.NewPartyEvent(ctx, types.Party{Id: acc.Party}))
for _, e := range acc.Events {
evts = append(evts, events.NewStakeLinking(ctx, *e))
}
}
if pendingSupply != nil {
expectedSupply := pendingSupply.TotalSupply.Clone()
a.pendingStakeTotalSupply = &pendingStakeTotalSupply{
sts: pendingSupply,
chainID: a.chainID,
check: func() error {
totalSupply, err := a.getStakeAssetTotalSupply(a.stakingBridgeAddress)
if err != nil {
return err
}
if totalSupply.NEQ(expectedSupply) {
return fmt.Errorf(
"invalid stake asset total supply, expected %s got %s",
expectedSupply.String(), totalSupply.String(),
)
}
return nil
},
}
a.witness.RestoreResource(a.pendingStakeTotalSupply, a.onStakeTotalSupplyVerified)
}
a.stakingAssetTotalSupply = accounts.StakingAssetTotalSupply.Clone()
var err error
a.accState.serialised, err = proto.Marshal(p.IntoProto())
a.broker.SendBatch(evts)
a.broker.SendBatch(pevts)
return err
}