prysm-pulse/sharding/proposer/service.go
Terence Tsao 75015adc8a sharding: use shardConfig across shard codebase
Former-commit-id: a1a8597ff0d5249056feed2f1f888d46b35eccda [formerly 4da30c5de1366f140374410ff700043a778e9f97]
Former-commit-id: 9125d61ab20e9a6cedc3f63f69b6bdd152687190
2018-06-12 16:03:20 -07:00

83 lines
2.5 KiB
Go

// Package proposer defines all relevant functionality for a Proposer actor
// within the minimal sharding protocol.
package proposer
import (
"context"
"crypto/rand"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/sharding"
"github.com/ethereum/go-ethereum/sharding/mainchain"
"github.com/ethereum/go-ethereum/sharding/params"
)
// Proposer holds functionality required to run a collation proposer
// in a sharded system. Must satisfy the Service interface defined in
// sharding/service.go.
type Proposer struct {
config *params.ShardConfig
client *mainchain.SMCClient
shardp2p sharding.ShardP2P
txpool sharding.TXPool
shardChainDb ethdb.Database
shardID int
}
// NewProposer creates a struct instance of a proposer service.
// It will have access to a mainchain client, a shardp2p network,
// and a shard transaction pool.
func NewProposer(config *params.ShardConfig, client *mainchain.SMCClient, shardp2p sharding.ShardP2P, txpool sharding.TXPool, shardChainDb ethdb.Database, shardID int) (*Proposer, error) {
// Initializes a directory persistent db.
return &Proposer{config, client, shardp2p, txpool, shardChainDb, shardID}, nil
}
// Start the main loop for proposing collations.
func (p *Proposer) Start() error {
log.Info(fmt.Sprintf("Starting proposer service in shard %d", p.shardID))
// TODO: Receive TXs from shard TX generator or TXpool (Github Issues 153 and 161)
var txs []*types.Transaction
for i := 0; i < 10; i++ {
data := make([]byte, 1024)
rand.Read(data)
txs = append(txs, types.NewTransaction(0, common.HexToAddress("0x0"),
nil, 0, nil, data))
}
// Get current block number.
blockNumber, err := p.client.ChainReader().BlockByNumber(context.Background(), nil)
if err != nil {
return err
}
period := new(big.Int).Div(blockNumber.Number(), big.NewInt(p.config.PeriodLength))
// Create collation.
collation, err := createCollation(p.client, big.NewInt(int64(p.shardID)), period, txs)
if err != nil {
return err
}
// Check SMC if we can submit header before addHeader
canAdd, err := checkHeaderAdded(p.client, big.NewInt(int64(p.shardID)), period)
if err != nil {
return err
}
if canAdd {
addHeader(p.client, collation)
}
return nil
}
// Stop the main loop for proposing collations.
func (p *Proposer) Stop() error {
log.Info(fmt.Sprintf("Stopping proposer service in shard %d", p.shardID))
return nil
}