Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

txsource: delegation workload #2752

Merged
merged 2 commits into from
Mar 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changelog/2752.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
txsource: delegation workload
2 changes: 0 additions & 2 deletions go/consensus/tendermint/apps/staking/state/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,6 @@ func (s *ImmutableState) DelegationsFor(delegatorID signature.PublicKey) (map[si
if !delegationKeyFmt.Decode(key, &escrowID, &decDelegatorID) {
return true
}
// TODO: add unit test for DelegationsFor.
if !decDelegatorID.Equal(delegatorID) {
return false
}
Expand Down Expand Up @@ -310,7 +309,6 @@ func (s *ImmutableState) DebondingDelegationsFor(delegatorID signature.PublicKey
if !debondingDelegationKeyFmt.Decode(key, &decDelegatorID, &escrowID) {
return true
}
// TODO: add unit test for DebondingDelegationsFor.
if !decDelegatorID.Equal(delegatorID) {
return false
}
Expand Down
229 changes: 168 additions & 61 deletions go/consensus/tendermint/apps/staking/state/state_test.go

Large diffs are not rendered by default.

283 changes: 283 additions & 0 deletions go/oasis-node/cmd/debug/txsource/workload/delegation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,283 @@
package workload

import (
"context"
"fmt"
"math/rand"
"time"

"google.golang.org/grpc"

"github.com/oasislabs/oasis-core/go/common/crypto/signature"
memorySigner "github.com/oasislabs/oasis-core/go/common/crypto/signature/signers/memory"
"github.com/oasislabs/oasis-core/go/common/logging"
consensus "github.com/oasislabs/oasis-core/go/consensus/api"
"github.com/oasislabs/oasis-core/go/consensus/api/transaction"
runtimeClient "github.com/oasislabs/oasis-core/go/runtime/client/api"
staking "github.com/oasislabs/oasis-core/go/staking/api"
)

const (
// NameDelegation is the name of the delegation workload.
NameDelegation = "delegation"

delegationNumAccounts = 10
delegateAmount = 100
)

type delegation struct {
logger *logging.Logger

accounts []struct {
signer signature.Signer
reckonedNonce uint64
delegatedTo signature.PublicKey
debondEndTime uint64
}
fundingAccount signature.Signer
}

func (d *delegation) doEscrowTx(ctx context.Context, rng *rand.Rand, cnsc consensus.ClientBackend) error {
d.logger.Debug("escrow tx flow")

// Get current epoch.
epoch, err := cnsc.GetEpoch(ctx, consensus.HeightLatest)
if err != nil {
return fmt.Errorf("GetEpoch: %w", err)
}

// Select an account that has no active delegations nor debonding funds.
perm := rng.Perm(delegationNumAccounts)
fromPermIdx := -1
var empty signature.PublicKey
for i := range d.accounts {
if d.accounts[perm[i]].delegatedTo == empty && d.accounts[perm[i]].debondEndTime < uint64(epoch) {
fromPermIdx = i
break
}
}
if fromPermIdx == -1 {
d.logger.Debug("all accounts already delegating or debonding, skipping delegation")
return nil
}

// Select an account to delegate to.
toPermIdx := rng.Intn(delegationNumAccounts)

// Remember index.
selectedIdx := perm[fromPermIdx]

// Update local state.
d.accounts[selectedIdx].delegatedTo = d.accounts[perm[toPermIdx]].signer.Public()

// Create escrow tx.
escrow := &staking.Escrow{
Account: d.accounts[selectedIdx].delegatedTo,
}
if err = escrow.Tokens.FromInt64(delegateAmount); err != nil {
return fmt.Errorf("escrow amount error: %w", err)
}

tx := staking.NewAddEscrowTx(d.accounts[selectedIdx].reckonedNonce, &transaction.Fee{}, escrow)
d.accounts[selectedIdx].reckonedNonce++

// Estimate gas.
gas, err := cnsc.EstimateGas(ctx, &consensus.EstimateGasRequest{
Caller: d.accounts[selectedIdx].signer.Public(),
Transaction: tx,
})
if err != nil {
return fmt.Errorf("failed to estimate gas: %w", err)
}
tx.Fee.Gas = gas
feeAmount := int64(gas) * gasPrice
if err = tx.Fee.Amount.FromInt64(feeAmount); err != nil {
return fmt.Errorf("fee amount from int64: %w", err)
}

// Fund account to cover Escrow fees.
// We only do one escrow per account at a time, so `delegateAmount`
// funds (that are Escrowed) should already be in the balance.
fundAmount := int64(gas) * gasPrice // transaction costs
if err = transferFunds(ctx, d.logger, cnsc, d.fundingAccount, d.accounts[selectedIdx].signer.Public(), fundAmount); err != nil {
return fmt.Errorf("account funding failure: %w", err)
}

// Sign transaction.
signedTx, err := transaction.Sign(d.accounts[selectedIdx].signer, tx)
if err != nil {
return fmt.Errorf("transaction.Sign: %w", err)
}
d.logger.Debug("submitting escrow transaction",
"from", d.accounts[selectedIdx].signer.Public(),
"to", d.accounts[selectedIdx].delegatedTo,
)

// Submit transaction.
if err = cnsc.SubmitTx(ctx, signedTx); err != nil {
return fmt.Errorf("cnsc.SubmitTx: %w", err)
}

return nil
}

func (d *delegation) doReclaimEscrowTx(ctx context.Context, rng *rand.Rand, cnsc consensus.ClientBackend, stakingClient staking.Backend) error {
d.logger.Debug("reclaim escrow tx")

// Select an account that has active delegation.
perm := rng.Perm(delegationNumAccounts)
fromPermIdx := -1
var empty signature.PublicKey
for i := range d.accounts {
if d.accounts[perm[i]].delegatedTo != empty {
fromPermIdx = i
break
}
}
if fromPermIdx == -1 {
d.logger.Debug("no accounts delegating, skipping reclaim")
return nil
}
selectedIdx := perm[fromPermIdx]

// Query amount of delegated shares for the account.
delegations, err := stakingClient.Delegations(ctx, &staking.OwnerQuery{
Height: consensus.HeightLatest,
Owner: d.accounts[selectedIdx].signer.Public(),
})
if err != nil {
return fmt.Errorf("stakingClient.Delegations %s: %w", d.accounts[selectedIdx].signer.Public(), err)
}
delegation := delegations[d.accounts[selectedIdx].delegatedTo]
if delegation == nil {
d.logger.Error("missing expected delegation",
"delegator", d.accounts[selectedIdx].signer.Public(),
"account", d.accounts[selectedIdx].delegatedTo,
"delegations", delegations,
)
return fmt.Errorf("missing expected delegation by account: %s in account: %s",
d.accounts[selectedIdx].signer.Public(), d.accounts[selectedIdx].delegatedTo)
}

// Create ReclaimEscrow tx.
reclaim := &staking.ReclaimEscrow{
Account: d.accounts[selectedIdx].delegatedTo,
Shares: delegation.Shares,
}
tx := staking.NewReclaimEscrowTx(d.accounts[selectedIdx].reckonedNonce, &transaction.Fee{}, reclaim)
d.accounts[selectedIdx].reckonedNonce++

// Estimate gas.
gas, err := cnsc.EstimateGas(ctx, &consensus.EstimateGasRequest{
Caller: d.accounts[selectedIdx].signer.Public(),
Transaction: tx,
})
if err != nil {
return fmt.Errorf("failed to estimate gas: %w", err)
}
tx.Fee.Gas = gas
feeAmount := int64(gas) * gasPrice
if err = tx.Fee.Amount.FromInt64(feeAmount); err != nil {
return fmt.Errorf("fee amount from int64: %w", err)
}

// Fund account to cover reclaim escrow fees.
fundAmount := int64(gas) * gasPrice // transaction costs
if err = transferFunds(ctx, d.logger, cnsc, d.fundingAccount, d.accounts[selectedIdx].signer.Public(), fundAmount); err != nil {
return fmt.Errorf("account funding failure: %w", err)
}

signedTx, err := transaction.Sign(d.accounts[selectedIdx].signer, tx)
if err != nil {
return fmt.Errorf("transaction.Sign: %w", err)
}

d.logger.Debug("submitting reclaim escrow transaction",
"reclaim_from", d.accounts[selectedIdx].delegatedTo,
"account", d.accounts[selectedIdx].signer.Public(),
)

// Submit transaction.
if err = cnsc.SubmitTx(ctx, signedTx); err != nil {
return fmt.Errorf("cnsc.SubmitTx: %w", err)
}

// Query debonding end epoch for the account.
var debondingDelegations map[signature.PublicKey][]*staking.DebondingDelegation
debondingDelegations, err = stakingClient.DebondingDelegations(ctx, &staking.OwnerQuery{
Height: consensus.HeightLatest,
Owner: d.accounts[selectedIdx].signer.Public(),
})
if err != nil {
return fmt.Errorf("stakingClient.Delegations %s: %w", d.accounts[selectedIdx].signer.Public(), err)
}
debondingDelegation := debondingDelegations[d.accounts[selectedIdx].delegatedTo]
if len(debondingDelegation) == 0 {
d.logger.Error("missing expected debonding delegation",
"delegator", d.accounts[selectedIdx].signer.Public(),
"account", d.accounts[selectedIdx].delegatedTo,
"debonding_delegations", debondingDelegation,
)
return fmt.Errorf("missing expected debonding delegation by account: %s in account: %s",
d.accounts[selectedIdx].signer.Public(), d.accounts[selectedIdx].delegatedTo)
}

// Update local state.
d.accounts[selectedIdx].delegatedTo = empty
d.accounts[selectedIdx].debondEndTime = uint64(debondingDelegation[0].DebondEndTime)

return nil
}

func (d *delegation) Run(gracefulExit context.Context, rng *rand.Rand, conn *grpc.ClientConn, cnsc consensus.ClientBackend, rtc runtimeClient.RuntimeClient, fundingAccount signature.Signer) error {
var err error
ctx := context.Background()

d.logger = logging.GetLogger("cmd/txsource/workload/delegation")
d.fundingAccount = fundingAccount

fac := memorySigner.NewFactory()
d.accounts = make([]struct {
signer signature.Signer
reckonedNonce uint64
delegatedTo signature.PublicKey
debondEndTime uint64
}, delegationNumAccounts)

for i := range d.accounts {
d.accounts[i].signer, err = fac.Generate(signature.SignerEntity, rng)
if err != nil {
return fmt.Errorf("memory signer factory Generate account %d: %w", i, err)
}

// Fund the account with delegation amount.
// Funds for fee's will be transferred before making transactions.
if err = transferFunds(ctx, d.logger, cnsc, fundingAccount, d.accounts[i].signer.Public(), delegateAmount); err != nil {
return fmt.Errorf("account funding failure: %w", err)
}
}

stakingClient := staking.NewStakingClient(conn)

for {
switch rng.Intn(2) {
case 0:
if err = d.doEscrowTx(ctx, rng, cnsc); err != nil {
return err
}
case 1:
if err = d.doReclaimEscrowTx(ctx, rng, cnsc, stakingClient); err != nil {
return err
}
default:
return fmt.Errorf("unimplemented")
}

select {
case <-time.After(1 * time.Second):
case <-gracefulExit.Done():
d.logger.Debug("time's up")
return nil
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -357,10 +357,10 @@ func (r *registration) Run(gracefulExit context.Context, rng *rand.Rand, conn *g
)

select {
case <-time.After(1 * time.Second):
case <-gracefulExit.Done():
registryLogger.Debug("time's up")
return nil
default:
}
}
}
1 change: 1 addition & 0 deletions go/oasis-node/cmd/debug/txsource/workload/workload.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,5 @@ var ByName = map[string]Workload{
NameOversized: oversized{},
NameRegistration: &registration{},
NameParallel: parallel{},
NameDelegation: &delegation{},
}
2 changes: 2 additions & 0 deletions go/oasis-test-runner/scenario/e2e/txsource.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ var TxSourceMultiShort scenario.Scenario = &txSourceImpl{
workload.NameOversized,
workload.NameRegistration,
workload.NameParallel,
workload.NameDelegation,
},
timeLimit: timeLimitShort,
livenessCheckInterval: livenessCheckInterval,
Expand All @@ -52,6 +53,7 @@ var TxSourceMulti scenario.Scenario = &txSourceImpl{
workload.NameOversized,
workload.NameRegistration,
workload.NameParallel,
workload.NameDelegation,
},
timeLimit: timeLimitLong,
nodeRestartInterval: nodeRestartIntervalLong,
Expand Down
1 change: 1 addition & 0 deletions tests/fixture-data/txsource/staking-genesis.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"params": {
"debonding_interval": 2,
"gas_costs": {
"transfer": 10,
"burn": 10,
Expand Down