Skip to content

Commit

Permalink
feat: add derived keys mapping to parties engine
Browse files Browse the repository at this point in the history
  • Loading branch information
karlem committed May 16, 2024
1 parent d5504b8 commit 1e76ead
Show file tree
Hide file tree
Showing 22 changed files with 168 additions and 64 deletions.
10 changes: 8 additions & 2 deletions core/banking/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import (
"golang.org/x/exp/maps"
)

//go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/banking Assets,Notary,Collateral,Witness,TimeService,EpochService,Topology,MarketActivityTracker,ERC20BridgeView,EthereumEventSource
//go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/banking Assets,Notary,Collateral,Witness,TimeService,EpochService,Topology,MarketActivityTracker,ERC20BridgeView,EthereumEventSource,Parties

var (
ErrWrongAssetTypeUsedInBuiltinAssetChainEvent = errors.New("non builtin asset used for builtin asset chain event")
Expand Down Expand Up @@ -83,7 +83,6 @@ type Collateral interface {
GovernanceTransferFunds(ctx context.Context, transfers []*types.Transfer, accountTypes []types.AccountType, references []string) ([]*types.LedgerMovement, error)
PropagateAssetUpdate(ctx context.Context, asset types.Asset) error
GetSystemAccountBalance(asset, market string, accountType types.AccountType) (*num.Uint, error)
IsAMMKeyOwner(owner, ammKey string) (bool, error)
}

// Witness provide foreign chain resources validations.
Expand Down Expand Up @@ -121,6 +120,10 @@ type EthereumEventSource interface {
UpdateCollateralStartingBlock(uint64)
}

type Parties interface {
CheckDerivedKeyOwnership(party types.PartyID, derivedKey string) (bool, error)
}

const (
pendingState uint32 = iota
okState
Expand All @@ -144,6 +147,7 @@ type Engine struct {
notary Notary
assets Assets
top Topology
parties Parties

// assetActions tracks all the asset actions the engine must process on network
// tick.
Expand Down Expand Up @@ -235,6 +239,7 @@ func New(log *logging.Logger,
secondaryBridgeView ERC20BridgeView,
primaryEthEventSource EthereumEventSource,
secondaryEthEventSource EthereumEventSource,
parties Parties,
) (e *Engine) {
log = log.Named(namedLogger)
log.SetLevel(cfg.Level.Get())
Expand All @@ -251,6 +256,7 @@ func New(log *logging.Logger,
top: top,
primaryEthEventSource: primaryEthEventSource,
secondaryEthEventSource: secondaryEthEventSource,
parties: parties,
assetActions: map[string]*assetAction{},
seenAssetActions: treeset.NewWithStringComparator(),
withdrawals: map[string]withdrawalRef{},
Expand Down
5 changes: 4 additions & 1 deletion core/banking/engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ type testEngine struct {
marketActivityTracker *mocks.MockMarketActivityTracker
ethSource *mocks.MockEthereumEventSource
secondaryBridgeView *mocks.MockERC20BridgeView
parties *mocks.MockParties
}

func getTestEngine(t *testing.T) *testEngine {
Expand All @@ -79,7 +80,8 @@ func getTestEngine(t *testing.T) *testEngine {

notary.EXPECT().OfferSignatures(gomock.Any(), gomock.Any()).AnyTimes()
epoch.EXPECT().NotifyOnEpoch(gomock.Any(), gomock.Any()).AnyTimes()
eng := banking.New(logging.NewTestLogger(), banking.NewDefaultConfig(), col, witness, tsvc, assets, notary, broker, top, marketActivityTracker, primaryBridgeView, secondaryBridgeView, ethSource, nil)
parties := mocks.NewMockParties(ctrl)
eng := banking.New(logging.NewTestLogger(), banking.NewDefaultConfig(), col, witness, tsvc, assets, notary, broker, top, marketActivityTracker, primaryBridgeView, secondaryBridgeView, ethSource, nil, parties)

require.NoError(t, eng.OnMaxQuantumAmountUpdate(context.Background(), num.DecimalOne()))
eng.OnPrimaryEthChainIDUpdated("1")
Expand All @@ -98,6 +100,7 @@ func getTestEngine(t *testing.T) *testEngine {
secondaryBridgeView: secondaryBridgeView,
marketActivityTracker: marketActivityTracker,
ethSource: ethSource,
parties: parties,
}
}

Expand Down
55 changes: 39 additions & 16 deletions core/banking/mocks/mocks.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion core/banking/oneoff_transfers.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func (e *Engine) oneOffTransfer(
}

if transfer.FromDerivedKey != nil {
if _, err := e.col.IsAMMKeyOwner(transfer.From, *transfer.FromDerivedKey); err != nil {
if _, err := e.parties.CheckDerivedKeyOwnership(types.PartyID(transfer.From), *transfer.FromDerivedKey); err != nil {
transfer.Status = types.TransferStatusRejected
return err
}
Expand Down
4 changes: 2 additions & 2 deletions core/banking/oneoff_transfers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ func testValidOneOffTransferWithFromDerivedKey(t *testing.T) {
}

e.col.EXPECT().GetPartyVestedRewardAccount(derivedKey, assetNameETH).Return(&vestedAccount, nil).Times(1)
e.col.EXPECT().IsAMMKeyOwner(partyKey, derivedKey).Return(true, nil).Times(1)
e.parties.EXPECT().CheckDerivedKeyOwnership(types.PartyID(partyKey), derivedKey).Return(true, nil).Times(1)

// assert the calculation of fees and transfer request are correct
e.col.EXPECT().TransferFunds(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(1).DoAndReturn(
Expand Down Expand Up @@ -652,7 +652,7 @@ func testOneOffTransferInvalidOwnerTransfersWithFromDerivedKey(t *testing.T) {
e.assets.EXPECT().Get(gomock.Any()).Times(1).Return(
assets.NewAsset(&mockAsset{name: assetNameETH, quantum: num.DecimalFromFloat(100)}), nil)

e.col.EXPECT().IsAMMKeyOwner(partyKey, derivedKey).Return(false, fmt.Errorf("not and amm owner")).Times(1)
e.parties.EXPECT().CheckDerivedKeyOwnership(types.PartyID(partyKey), derivedKey).Return(false, fmt.Errorf("not and amm owner")).Times(1)

e.broker.EXPECT().Send(gomock.Any()).Times(1)
assert.Error(t, e.TransferFunds(ctx, transfer), "not and amm owner")
Expand Down
19 changes: 0 additions & 19 deletions core/collateral/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,6 @@ type Engine struct {
// we'll use it only once after an upgrade
// to make sure asset are being created
ensuredAssetAccounts bool

// amm key` to party ID
ammKeyToParty map[string]string
}

// New instantiates a new collateral engine.
Expand All @@ -147,7 +144,6 @@ func New(log *logging.Logger, conf Config, ts TimeService, broker Broker) *Engin
vesting: map[string]map[string]*num.Uint{},
partiesAccsBalanceCache: map[string]*num.Uint{},
nextBalancesSnapshot: time.Time{},
ammKeyToParty: map[string]string{},
}
}

Expand Down Expand Up @@ -3578,19 +3574,6 @@ func (e *Engine) CreatePartyMarginAccount(ctx context.Context, partyID, marketID
return marginID, nil
}

func (e *Engine) IsAMMKeyOwner(owner, ammKey string) (bool, error) {
party, ok := e.ammKeyToParty[ammKey]
if !ok {
return false, fmt.Errorf("amm key %s does not exists", ammKey)
}

if party != owner {
return false, fmt.Errorf("party %s does not own %s", owner, ammKey)
}

return true, nil
}

// CreatePartyAMMSubAccounts ...
func (e *Engine) CreatePartyAMMsSubAccounts(
ctx context.Context,
Expand All @@ -3611,8 +3594,6 @@ func (e *Engine) CreatePartyAMMsSubAccounts(
return nil, nil, err
}

e.ammKeyToParty[ammKey] = party

return e.accs[generalID].Clone(), e.accs[marginID].Clone(), nil
}

Expand Down
10 changes: 7 additions & 3 deletions core/execution/amm/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,12 @@ func (s *Sqrter) sqrt(u *num.Uint) num.Decimal {
type Engine struct {
log *logging.Logger

broker Broker
// TODO karel - use interface for market activity tracker
broker Broker
marketActivityTracker *common.MarketActivityTracker

collateral Collateral
position Position
parties common.Parties

marketID string
assetID string
Expand Down Expand Up @@ -155,6 +155,7 @@ func New(
priceFactor num.Decimal,
positionFactor num.Decimal,
marketActivityTracker *common.MarketActivityTracker,
parties common.Parties,
) *Engine {
return &Engine{
log: log,
Expand All @@ -171,6 +172,7 @@ func New(
rooter: &Sqrter{cache: map[string]num.Decimal{}},
priceFactor: priceFactor,
positionFactor: positionFactor,
parties: parties,
}
}

Expand All @@ -185,8 +187,9 @@ func NewFromProto(
priceFactor num.Decimal,
positionFactor num.Decimal,
marketActivityTracker *common.MarketActivityTracker,
parties common.Parties,
) (*Engine, error) {
e := New(log, broker, collateral, marketID, assetID, position, priceFactor, positionFactor, marketActivityTracker)
e := New(log, broker, collateral, marketID, assetID, position, priceFactor, positionFactor, marketActivityTracker, parties)

for _, v := range state.AmmPartyIds {
e.ammParties[v.Key] = v.Value
Expand Down Expand Up @@ -683,6 +686,7 @@ func (e *Engine) Confirm(
pool.status = types.AMMPoolStatusActive
e.add(pool)
e.sendUpdate(ctx, pool)
e.parties.AssignDeriveKey(types.PartyID(pool.owner), pool.AMMParty)
return nil
}

Expand Down
17 changes: 11 additions & 6 deletions core/execution/amm/engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -622,11 +622,12 @@ func getCancelSubmission(t *testing.T, party, market string, method types.AMMCan
}

type tstEngine struct {
engine *Engine
broker *bmocks.MockBroker
col *mocks.MockCollateral
pos *mocks.MockPosition
ctrl *gomock.Controller
engine *Engine
broker *bmocks.MockBroker
col *mocks.MockCollateral
pos *mocks.MockPosition
parties *cmocks.MockParties
ctrl *gomock.Controller

marketID string
assetID string
Expand All @@ -650,7 +651,10 @@ func getTestEngine(t *testing.T) *tstEngine {

mat := common.NewMarketActivityTracker(logging.NewTestLogger(), teams, balanceChecker, broker)

eng := New(logging.NewTestLogger(), broker, col, marketID, assetID, pos, num.DecimalOne(), num.DecimalOne(), mat)
parties := cmocks.NewMockParties(ctrl)
parties.EXPECT().AssignDeriveKey(gomock.Any(), gomock.Any()).AnyTimes()

eng := New(logging.NewTestLogger(), broker, col, marketID, assetID, pos, num.DecimalOne(), num.DecimalOne(), mat, parties)

// do an ontick to initialise the idgen
ctx := vgcontext.WithTraceID(context.Background(), vgcrypto.RandomHash())
Expand All @@ -662,6 +666,7 @@ func getTestEngine(t *testing.T) *tstEngine {
col: col,
pos: pos,
ctrl: ctrl,
parties: parties,
marketID: marketID,
assetID: assetID,
}
Expand Down
6 changes: 5 additions & 1 deletion core/execution/common/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import (

var One = num.UintOne()

//go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/execution/common TimeService,Assets,StateVarEngine,Collateral,OracleEngine,EpochEngine,AuctionState,LiquidityEngine,EquityLikeShares,MarketLiquidityEngine,Teams,AccountBalanceChecker,Banking
//go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/execution/common TimeService,Assets,StateVarEngine,Collateral,OracleEngine,EpochEngine,AuctionState,LiquidityEngine,EquityLikeShares,MarketLiquidityEngine,Teams,AccountBalanceChecker,Banking,Parties

//go:generate go run github.com/golang/mock/mockgen -destination mocks_amm/mocks.go -package mocks_amm code.vegaprotocol.io/vega/core/execution/common AMMPool,AMM

Expand Down Expand Up @@ -238,6 +238,10 @@ type Banking interface {
RegisterTradingFees(ctx context.Context, asset string, feesPerParty map[string]*num.Uint)
}

type Parties interface {
AssignDeriveKey(party types.PartyID, derivedKey string)
}

type LiquidityEngine interface {
GetLegacyOrders() []string
OnEpochRestore(ep types.Epoch)
Expand Down
37 changes: 36 additions & 1 deletion core/execution/common/mocks/mocks.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 1e76ead

Please sign in to comment.