-
Notifications
You must be signed in to change notification settings - Fork 22
/
assets.go
464 lines (409 loc) · 12.3 KB
/
assets.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// 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 assets
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"sync"
"time"
"code.vegaprotocol.io/vega/core/assets/builtin"
"code.vegaprotocol.io/vega/core/assets/erc20"
"code.vegaprotocol.io/vega/core/broker"
"code.vegaprotocol.io/vega/core/events"
nweth "code.vegaprotocol.io/vega/core/nodewallets/eth"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/logging"
)
var (
ErrAssetInvalid = errors.New("asset invalid")
ErrAssetDoesNotExist = errors.New("asset does not exist")
ErrUnknownAssetSource = errors.New("unknown asset source")
)
//go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/assets ERC20BridgeView,Notary
type ERC20BridgeView interface {
FindAsset(asset *types.AssetDetails) error
}
type Notary interface {
StartAggregate(resID string, kind types.NodeSignatureKind, signature []byte)
OfferSignatures(kind types.NodeSignatureKind, f func(id string) []byte)
}
type Service struct {
log *logging.Logger
cfg Config
broker broker.Interface
// id to asset
// these assets exists and have been save
amu sync.RWMutex
assets map[string]*Asset
// this is a list of pending asset which are currently going through
// proposal, they can later on be promoted to the asset lists once
// the proposal is accepted by both the nodes and the users
pamu sync.RWMutex
pendingAssets map[string]*Asset
pendingAssetUpdates map[string]*Asset
ethWallet nweth.EthereumWallet
ethClient erc20.ETHClient
notary Notary
ass *assetsSnapshotState
ethToVega map[string]string
isValidator bool
bridgeView ERC20BridgeView
}
func New(
log *logging.Logger,
cfg Config,
nw nweth.EthereumWallet,
ethClient erc20.ETHClient,
broker broker.Interface,
bridgeView ERC20BridgeView,
notary Notary,
isValidator bool,
) *Service {
log = log.Named(namedLogger)
log.SetLevel(cfg.Level.Get())
return &Service{
log: log,
cfg: cfg,
broker: broker,
assets: map[string]*Asset{},
pendingAssets: map[string]*Asset{},
pendingAssetUpdates: map[string]*Asset{},
ethWallet: nw,
ethClient: ethClient,
notary: notary,
ass: &assetsSnapshotState{},
isValidator: isValidator,
ethToVega: map[string]string{},
bridgeView: bridgeView,
}
}
// ReloadConf updates the internal configuration.
func (s *Service) ReloadConf(cfg Config) {
s.log.Info("reloading configuration")
if s.log.GetLevel() != cfg.Level.Get() {
s.log.Info("updating log level",
logging.String("old", s.log.GetLevel().String()),
logging.String("new", cfg.Level.String()),
)
s.log.SetLevel(cfg.Level.Get())
}
s.cfg = cfg
}
// Enable move the state of an from pending the list of valid and accepted assets.
func (s *Service) Enable(ctx context.Context, assetID string) error {
s.pamu.Lock()
defer s.pamu.Unlock()
asset, ok := s.pendingAssets[assetID]
if !ok {
return ErrAssetDoesNotExist
}
asset.SetEnabled()
s.amu.Lock()
defer s.amu.Unlock()
s.assets[assetID] = asset
if asset.IsERC20() {
eth, _ := asset.ERC20()
s.ethToVega[eth.ProtoAsset().GetDetails().GetErc20().GetContractAddress()] = assetID
}
delete(s.pendingAssets, assetID)
s.broker.Send(events.NewAssetEvent(ctx, *asset.Type()))
return nil
}
// EnactPendingAsset the given id for an asset has just been enacted by the governance engine so we
// now need to generate signatures so that the asset can be listed.
func (s *Service) EnactPendingAsset(id string) {
pa, _ := s.Get(id)
var err error
var signature []byte
if s.isValidator {
switch {
case pa.IsERC20():
asset, _ := pa.ERC20()
_, signature, err = asset.SignListAsset()
if err != nil {
s.log.Panic("couldn't to sign transaction to list asset, is the node properly configured as a validator?",
logging.Error(err))
}
default:
s.log.Panic("trying to generate signatures for an unknown asset type")
}
}
s.notary.StartAggregate(id, types.NodeSignatureKindAssetNew, signature)
}
func (s *Service) ExistsForEthereumAddress(address string) bool {
for _, a := range s.assets {
if source, ok := a.ERC20(); ok {
if strings.EqualFold(source.Address(), address) {
return true
}
}
}
for _, a := range s.pendingAssets {
if source, ok := a.ERC20(); ok {
if strings.EqualFold(source.Address(), address) {
return true
}
}
}
return false
}
// SetPendingListing update the state of an asset from proposed
// to pending listing on the bridge.
func (s *Service) SetPendingListing(ctx context.Context, assetID string) error {
s.pamu.Lock()
defer s.pamu.Unlock()
asset, ok := s.pendingAssets[assetID]
if !ok {
return ErrAssetDoesNotExist
}
asset.SetPendingListing()
s.broker.Send(events.NewAssetEvent(ctx, *asset.Type()))
return nil
}
// SetRejected update the state of an asset from proposed
// to pending listing on the bridge.
func (s *Service) SetRejected(ctx context.Context, assetID string) error {
s.pamu.Lock()
defer s.pamu.Unlock()
asset, ok := s.pendingAssets[assetID]
if !ok {
return ErrAssetDoesNotExist
}
asset.SetRejected()
s.broker.Send(events.NewAssetEvent(ctx, *asset.Type()))
delete(s.pendingAssets, assetID)
return nil
}
func (s *Service) GetVegaIDFromEthereumAddress(address string) string {
s.amu.Lock()
defer s.amu.Unlock()
return s.ethToVega[address]
}
func (s *Service) IsEnabled(assetID string) bool {
s.amu.RLock()
defer s.amu.RUnlock()
_, ok := s.assets[assetID]
return ok
}
func (s *Service) OnTick(ctx context.Context, _ time.Time) {
s.notary.OfferSignatures(types.NodeSignatureKindAssetNew, s.offerERC20NotarySignatures)
}
func (s *Service) offerERC20NotarySignatures(id string) []byte {
if !s.isValidator {
return nil
}
pa, err := s.Get(id)
if err != nil {
s.log.Panic("unable to find asset", logging.AssetID(id))
}
asset, _ := pa.ERC20()
_, signature, err := asset.SignListAsset()
if err != nil {
s.log.Panic("couldn't to sign transaction to list asset, is the node properly configured as a validator?",
logging.Error(err))
}
return signature
}
func (s *Service) assetFromDetails(assetID string, assetDetails *types.AssetDetails) (*Asset, error) {
switch assetDetails.Source.(type) {
case *types.AssetDetailsBuiltinAsset:
return &Asset{
builtin.New(assetID, assetDetails),
}, nil
case *types.AssetDetailsErc20:
// TODO(): fix once the ethereum wallet and client are not required
// anymore to construct assets
var (
asset *erc20.ERC20
err error
)
if s.isValidator {
asset, err = erc20.New(assetID, assetDetails, s.ethWallet, s.ethClient)
} else {
asset, err = erc20.New(assetID, assetDetails, nil, nil)
}
if err != nil {
return nil, err
}
return &Asset{asset}, nil
default:
return nil, ErrUnknownAssetSource
}
}
func (s *Service) buildAssetFromProto(asset *types.Asset) (*Asset, error) {
switch asset.Details.Source.(type) {
case *types.AssetDetailsBuiltinAsset:
return &Asset{
builtin.New(asset.ID, asset.Details),
}, nil
case *types.AssetDetailsErc20:
// TODO(): fix once the ethereum wallet and client are not required
// anymore to construct assets
var (
erc20Asset *erc20.ERC20
err error
)
if s.isValidator {
erc20Asset, err = erc20.New(asset.ID, asset.Details, s.ethWallet, s.ethClient)
} else {
erc20Asset, err = erc20.New(asset.ID, asset.Details, nil, nil)
}
if err != nil {
return nil, err
}
return &Asset{erc20Asset}, nil
default:
return nil, ErrUnknownAssetSource
}
}
// NewAsset add a new asset to the pending list of assets
// the ref is the reference of proposal which submitted the new asset
// returns the assetID and an error.
func (s *Service) NewAsset(ctx context.Context, proposalID string, assetDetails *types.AssetDetails) (string, error) {
s.pamu.Lock()
defer s.pamu.Unlock()
asset, err := s.assetFromDetails(proposalID, assetDetails)
if err != nil {
return "", err
}
s.pendingAssets[proposalID] = asset
s.broker.Send(events.NewAssetEvent(ctx, *asset.Type()))
return proposalID, err
}
func (s *Service) StageAssetUpdate(updatedAssetProto *types.Asset) error {
s.pamu.Lock()
defer s.pamu.Unlock()
if _, ok := s.assets[updatedAssetProto.ID]; !ok {
return ErrAssetDoesNotExist
}
updatedAsset, err := s.buildAssetFromProto(updatedAssetProto)
if err != nil {
return fmt.Errorf("couldn't update asset: %w", err)
}
s.pendingAssetUpdates[updatedAssetProto.ID] = updatedAsset
return nil
}
func (s *Service) ApplyAssetUpdate(ctx context.Context, assetID string) error {
s.pamu.Lock()
defer s.pamu.Unlock()
updatedAsset, ok := s.pendingAssetUpdates[assetID]
if !ok {
return ErrAssetDoesNotExist
}
s.amu.Lock()
defer s.amu.Unlock()
currentAsset, ok := s.assets[assetID]
if !ok {
return ErrAssetDoesNotExist
}
updatedAsset.SetEnabled()
if err := currentAsset.Update(updatedAsset); err != nil {
s.log.Panic("couldn't update the asset", logging.Error(err))
}
delete(s.pendingAssetUpdates, assetID)
s.broker.Send(events.NewAssetEvent(ctx, *updatedAsset.Type()))
return nil
}
func (s *Service) GetEnabledAssets() []*types.Asset {
s.amu.RLock()
defer s.amu.RUnlock()
ret := make([]*types.Asset, 0, len(s.assets))
for _, a := range s.assets {
ret = append(ret, a.ToAssetType())
}
sort.SliceStable(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID })
return ret
}
func (s *Service) getPendingAssets() []*types.Asset {
s.pamu.RLock()
defer s.pamu.RUnlock()
ret := make([]*types.Asset, 0, len(s.assets))
for _, a := range s.pendingAssets {
ret = append(ret, a.ToAssetType())
}
sort.SliceStable(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID })
return ret
}
func (s *Service) getPendingAssetUpdates() []*types.Asset {
s.pamu.RLock()
defer s.pamu.RUnlock()
ret := make([]*types.Asset, 0, len(s.assets))
for _, a := range s.pendingAssetUpdates {
ret = append(ret, a.ToAssetType())
}
sort.SliceStable(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID })
return ret
}
func (s *Service) Get(assetID string) (*Asset, error) {
s.amu.RLock()
defer s.amu.RUnlock()
asset, ok := s.assets[assetID]
if ok {
return asset, nil
}
s.pamu.RLock()
defer s.pamu.RUnlock()
asset, ok = s.pendingAssets[assetID]
if ok {
return asset, nil
}
return nil, ErrAssetDoesNotExist
}
// ValidateAssetNonValidator is only to be used by non-validators
// at startup when loading genesis file. We just assume assets are
// valid.
func (s *Service) ValidateAssetNonValidator(assetID string) error {
// get the asset to validate from the assets pool
asset, err := s.Get(assetID)
// if we get an error here, we'll never change the state of the proposal,
// so it will be dismissed later on by all the whole network
if err != nil || asset == nil {
s.log.Error("Validating asset, unable to get the asset",
logging.AssetID(assetID),
logging.Error(err),
)
return errors.New("invalid asset ID")
}
asset.SetValid()
return nil
}
func (s *Service) ValidateAsset(assetID string) error {
// get the asset to validate from the assets pool
asset, err := s.Get(assetID)
// if we get an error here, we'll never change the state of the proposal,
// so it will be dismissed later on by all the whole network
if err != nil || asset == nil {
s.log.Error("Validating asset, unable to get the asset",
logging.AssetID(assetID),
logging.Error(err),
)
return errors.New("invalid asset ID")
}
return s.validateAsset(asset)
}
func (s *Service) validateAsset(a *Asset) error {
var err error
if erc20, ok := a.ERC20(); ok {
err = s.bridgeView.FindAsset(erc20.Type().Details.DeepClone())
// no error, our asset exists on chain
if err == nil {
erc20.SetValid()
}
}
return err
}