diff --git a/config/config.go b/config/config.go index 78b663e4404..1a79bf4d3dc 100644 --- a/config/config.go +++ b/config/config.go @@ -1,5 +1,6 @@ package config +// NodeConfig stores Optimint node configuration. type NodeConfig struct { P2P P2PConfig } diff --git a/config/defaults.go b/config/defaults.go index a34bcac06da..be21d9d9bca 100644 --- a/config/defaults.go +++ b/config/defaults.go @@ -1,5 +1,6 @@ package config const ( + // DefaultListenAddress is a default listen address for P2P client. DefaultListenAddress = "/ip4/0.0.0.0/tcp/7676" ) diff --git a/config/p2p.go b/config/p2p.go index 5746db5a7ab..5a4e703988c 100644 --- a/config/p2p.go +++ b/config/p2p.go @@ -1,5 +1,6 @@ package config +// P2PConfig stores configuration related to peer-to-peer networking. type P2PConfig struct { ListenAddress string // Address to listen for incoming connections Seeds string // Comma separated list of seed nodes to connect to diff --git a/conv/abci/block.go b/conv/abci/block.go new file mode 100644 index 00000000000..5aef542504c --- /dev/null +++ b/conv/abci/block.go @@ -0,0 +1,44 @@ +package abci + +import ( + "time" + + tmproto "github.com/lazyledger/lazyledger-core/proto/tendermint/types" + tmversion "github.com/lazyledger/lazyledger-core/proto/tendermint/version" + + "github.com/lazyledger/optimint/hash" + "github.com/lazyledger/optimint/types" +) + +// ToABCIHeader converts Optimint header to Header format defined in ABCI. +func ToABCIHeader(header *types.Header) (tmproto.Header, error) { + h, err := hash.Hash(header) + if err != nil { + return tmproto.Header{}, err + } + return tmproto.Header{ + Version: tmversion.Consensus{ + Block: uint64(header.Version.Block), + App: uint64(header.Version.App), + }, + ChainID: "", // TODO(tzdybal) + Height: int64(header.Height), + Time: time.Unix(int64(header.Time), 0), + LastBlockId: tmproto.BlockID{ + Hash: h[:], + PartSetHeader: tmproto.PartSetHeader{ + Total: 0, + Hash: nil, + }, + }, + LastCommitHash: header.LastCommitHash[:], + DataHash: header.DataHash[:], + ValidatorsHash: nil, + NextValidatorsHash: nil, + ConsensusHash: header.ConsensusHash[:], + AppHash: header.AppHash[:], + LastResultsHash: header.LastResultsHash[:], + EvidenceHash: nil, + ProposerAddress: header.ProposerAddress, + }, nil +} diff --git a/conv/addr.go b/conv/addr.go index 26768979d64..2fd4399482d 100644 --- a/conv/addr.go +++ b/conv/addr.go @@ -7,6 +7,7 @@ import ( "github.com/multiformats/go-multiaddr" ) +// TranslateAddresses updates conf by changing Cosmos-style addresses to Multiaddr format. func TranslateAddresses(conf *config.NodeConfig) error { if conf.P2P.ListenAddress != "" { addr, err := GetMultiAddr(conf.P2P.ListenAddress) @@ -31,6 +32,8 @@ func TranslateAddresses(conf *config.NodeConfig) error { return nil } +// GetMultiAddr converts single Cosmos-style network address into Multiaddr. +// Input format: [protocol://][@]: func GetMultiAddr(addr string) (multiaddr.Multiaddr, error) { var err error var p2pID multiaddr.Multiaddr @@ -50,7 +53,7 @@ func GetMultiAddr(addr string) (multiaddr.Multiaddr, error) { } parts = strings.Split(addr, ":") if len(parts) != 2 { - return nil, ErrInvalidAddress + return nil, errInvalidAddress } maddr, err := multiaddr.NewMultiaddr("/ip4/" + parts[0] + "/" + proto + "/" + parts[1]) if err != nil { diff --git a/conv/addr_test.go b/conv/addr_test.go index 7cb5058ea46..3bcafdb151d 100644 --- a/conv/addr_test.go +++ b/conv/addr_test.go @@ -40,13 +40,13 @@ func TestTranslateAddresses(t *testing.T) { "invalid listen address", config.NodeConfig{P2P: config.P2PConfig{ListenAddress: invalidCosmos}}, config.NodeConfig{}, - ErrInvalidAddress.Error(), + errInvalidAddress.Error(), }, { "invalid seed address", config.NodeConfig{P2P: config.P2PConfig{Seeds: validCosmos + "," + invalidCosmos}}, config.NodeConfig{}, - ErrInvalidAddress.Error(), + errInvalidAddress.Error(), }, } @@ -79,9 +79,9 @@ func TestGetMultiaddr(t *testing.T) { expected multiaddr.Multiaddr expectedErr string }{ - {"empty", "", nil, ErrInvalidAddress.Error()}, + {"empty", "", nil, errInvalidAddress.Error()}, {"no port", "127.0.0.1:", nil, "failed to parse multiaddr"}, - {"ip only", "127.0.0.1", nil, ErrInvalidAddress.Error()}, + {"ip only", "127.0.0.1", nil, errInvalidAddress.Error()}, {"with invalid id", "deadbeef@127.0.0.1:1234", nil, "failed to parse multiaddr"}, {"valid", "127.0.0.1:1234", valid, ""}, {"valid with id", "k2k4r8oqamigqdo6o7hsbfwd45y70oyynp98usk7zmyfrzpqxh1pohl7@127.0.0.1:1234", withID, ""}, diff --git a/conv/crypto.go b/conv/crypto.go index f2130cc3607..0e4589d671d 100644 --- a/conv/crypto.go +++ b/conv/crypto.go @@ -8,12 +8,15 @@ import ( "github.com/libp2p/go-libp2p-core/crypto" ) -var ErrNilKey = errors.New("key can't be nil") -var ErrUnsupportedKeyType = errors.New("unsupported key type") +var ( + errNilKey = errors.New("key can't be nil") + errUnsupportedKeyType = errors.New("unsupported key type") +) +// GetNodeKey creates libp2p private key from Tendermints NodeKey. func GetNodeKey(nodeKey *p2p.NodeKey) (crypto.PrivKey, error) { if nodeKey == nil || nodeKey.PrivKey == nil { - return nil, ErrNilKey + return nil, errNilKey } switch nodeKey.PrivKey.Type() { case "ed25519": @@ -23,6 +26,6 @@ func GetNodeKey(nodeKey *p2p.NodeKey) (crypto.PrivKey, error) { } return privKey, nil default: - return nil, ErrUnsupportedKeyType + return nil, errUnsupportedKeyType } } diff --git a/conv/crypto_test.go b/conv/crypto_test.go index cf423a67b77..08c13f3301f 100644 --- a/conv/crypto_test.go +++ b/conv/crypto_test.go @@ -25,9 +25,9 @@ func TestGetNodeKey(t *testing.T) { expectedType pb.KeyType err error }{ - {"nil", nil, pb.KeyType(-1), ErrNilKey}, - {"empty", &p2p.NodeKey{}, pb.KeyType(-1), ErrNilKey}, - {"invalid", &invalid, pb.KeyType(-1), ErrUnsupportedKeyType}, + {"nil", nil, pb.KeyType(-1), errNilKey}, + {"empty", &p2p.NodeKey{}, pb.KeyType(-1), errNilKey}, + {"invalid", &invalid, pb.KeyType(-1), errUnsupportedKeyType}, {"valid", &valid, pb.KeyType_Ed25519, nil}, } diff --git a/conv/errors.go b/conv/errors.go index 66495bf408b..90468cbbb97 100644 --- a/conv/errors.go +++ b/conv/errors.go @@ -3,5 +3,5 @@ package conv import "errors" var ( - ErrInvalidAddress = errors.New("invalid address format, expected [protocol://][@]:") + errInvalidAddress = errors.New("invalid address format, expected [protocol://][@]:") ) diff --git a/da/da.go b/da/da.go index beeafc905f7..bd9f68bec72 100644 --- a/da/da.go +++ b/da/da.go @@ -5,11 +5,13 @@ import ( "github.com/lazyledger/optimint/types" ) -// TODO define an enum of different non-happy-path cases +// StatusCode is a type for DA layer return status. +// TODO: define an enum of different non-happy-path cases // that might need to be handled by Optimint independent of // the underlying DA chain. type StatusCode uint64 +// Data Availability return codes. const ( StatusUnknown StatusCode = iota StatusSuccess @@ -17,6 +19,7 @@ const ( StatusError ) +// ResultSubmitBlock contains information returned from DA layer after block submission. type ResultSubmitBlock struct { // Code is to determine if the action succeeded. Code StatusCode @@ -27,6 +30,8 @@ type ResultSubmitBlock struct { // Hash hash.Hash } +// DataAvailabilityLayerClient defines generic interface for DA layer block submission. +// It also contains life-cycle methods. type DataAvailabilityLayerClient interface { // Init is called once to allow DA client to read configuration and initialize resources. Init(config []byte, logger log.Logger) error diff --git a/da/lazyledger/lazyledger.go b/da/lazyledger/lazyledger.go index 9ac43790012..f6fc5ac23df 100644 --- a/da/lazyledger/lazyledger.go +++ b/da/lazyledger/lazyledger.go @@ -19,6 +19,7 @@ import ( "github.com/lazyledger/optimint/types" ) +// Config holds all configuration required by LazyLedger DA layer client. type Config struct { // PayForMessage related params NamespaceID []byte @@ -45,6 +46,8 @@ type Config struct { RootDir string } +// LazyLedger implements DataAvailabilityLayerClient interface. +// It use lazyledger-app via gRPC. type LazyLedger struct { config Config logger log.Logger @@ -70,11 +73,13 @@ func (ll *LazyLedger) Init(config []byte, logger log.Logger) error { return err } +// Start establishes gRPC connection to lazyledger app. func (ll *LazyLedger) Start() (err error) { ll.rpcClient, err = grpc.Dial(ll.config.RPCAddress, grpc.WithInsecure()) return } +// Stop closes gRPC connection. func (ll *LazyLedger) Stop() error { return ll.rpcClient.Close() } diff --git a/da/mock/mock.go b/da/mock/mock.go index e28da755e3b..52b883716fb 100644 --- a/da/mock/mock.go +++ b/da/mock/mock.go @@ -6,6 +6,8 @@ import ( "github.com/lazyledger/optimint/types" ) +// MockDataAvailabilityLayerClient is intended only for usage in tests. +// It does actually ensures DA - it stores data in-memory. type MockDataAvailabilityLayerClient struct { logger log.Logger @@ -18,11 +20,13 @@ func (m *MockDataAvailabilityLayerClient) Init(config []byte, logger log.Logger) return nil } +// Start implements DataAvailabilityLayerClient interface. func (m *MockDataAvailabilityLayerClient) Start() error { m.logger.Debug("Mock Data Availability Layer Client starting") return nil } +// Stop implements DataAvailabilityLayerClient interface. func (m *MockDataAvailabilityLayerClient) Stop() error { m.logger.Debug("Mock Data Availability Layer Client stopped") return nil diff --git a/hash/hashing.go b/hash/hashing.go index 3b3155c3b5a..4c2e88e2737 100644 --- a/hash/hashing.go +++ b/hash/hashing.go @@ -6,6 +6,7 @@ import ( "github.com/minio/sha256-simd" ) +// Hash creates a SHA-256 hash of object that can be serialized into binary form. func Hash(object encoding.BinaryMarshaler) ([32]byte, error) { blob, err := object.MarshalBinary() if err != nil { diff --git a/node/node.go b/node/node.go index 856b26c77b7..f72ae4b391b 100644 --- a/node/node.go +++ b/node/node.go @@ -20,6 +20,8 @@ import ( "github.com/lazyledger/optimint/store" ) +// Node represents a client node in Optimint network. +// It connects all the components and orchestrates their work. type Node struct { service.BaseService eventBus *types.EventBus @@ -42,6 +44,7 @@ type Node struct { ctx context.Context } +// NewNode creates new Optimint node. func NewNode(ctx context.Context, conf config.NodeConfig, nodeKey crypto.PrivKey, clientCreator proxy.ClientCreator, genesis *types.GenesisDoc, logger log.Logger) (*Node, error) { proxyApp := proxy.NewAppConns(clientCreator) proxyApp.SetLogger(logger.With("module", "proxy")) @@ -146,6 +149,7 @@ func (n *Node) mempoolPublishLoop(ctx context.Context) { } } +// OnStart is a part of Service interface. func (n *Node) OnStart() error { n.Logger.Info("starting P2P client") err := n.P2P.Start(n.ctx) @@ -161,26 +165,32 @@ func (n *Node) OnStart() error { return nil } +// OnStop is a part of Service interface. func (n *Node) OnStop() { n.P2P.Close() } +// OnReset is a part of Service interface. func (n *Node) OnReset() error { panic("OnReset - not implemented!") } +// SetLogger sets the logger used by node. func (n *Node) SetLogger(logger log.Logger) { n.Logger = logger } +// GetLogger returns logger. func (n *Node) GetLogger() log.Logger { return n.Logger } +// EventBus gives access to Node's event bus. func (n *Node) EventBus() *types.EventBus { return n.eventBus } +// ProxyApp returns ABCI proxy connections to comminicate with aplication. func (n *Node) ProxyApp() proxy.AppConns { return n.proxyApp } diff --git a/p2p/client.go b/p2p/client.go index 60b74553ec4..7964c3ff836 100644 --- a/p2p/client.go +++ b/p2p/client.go @@ -34,11 +34,13 @@ const ( txTopicSuffix = "-tx" ) -// TODO(tzdybal): refactor. This is only a stub. +// Tx represents transaction gossiped via P2P network. type Tx struct { Data []byte From peer.ID } + +// TxHandler is a callback function type. type TxHandler func(*Tx) // Client is a P2P client, implemented with libp2p. @@ -72,7 +74,7 @@ type Client struct { // TODO(tzdybal): consider passing entire config, not just P2P config, to reduce number of arguments func NewClient(conf config.P2PConfig, privKey crypto.PrivKey, chainID string, logger log.Logger) (*Client, error) { if privKey == nil { - return nil, ErrNoPrivKey + return nil, errNoPrivKey } if conf.ListenAddress == "" { conf.ListenAddress = config.DefaultListenAddress @@ -141,11 +143,13 @@ func (c *Client) Close() error { ) } +// GossipTx sends the transaction to the P2P network. func (c *Client) GossipTx(ctx context.Context, tx []byte) error { c.logger.Debug("Gossiping TX", "len", len(tx)) return c.txTopic.Publish(ctx, tx) } +// SetTxHandler sets the callback function, that will be invoked after transaction is received from P2P network. func (c *Client) SetTxHandler(handler TxHandler) { c.txHandler = handler } diff --git a/p2p/errors.go b/p2p/errors.go index 5505c51cf97..69c8e98ed38 100644 --- a/p2p/errors.go +++ b/p2p/errors.go @@ -3,5 +3,5 @@ package p2p import "errors" var ( - ErrNoPrivKey = errors.New("private key not provided") + errNoPrivKey = errors.New("private key not provided") ) diff --git a/proto/optimint.proto b/proto/optimint.proto index 2fd8bcc0653..fe9adc43fc1 100644 --- a/proto/optimint.proto +++ b/proto/optimint.proto @@ -9,8 +9,8 @@ import "tendermint/abci/types.proto"; // state transition machine. // This is equivalent to the tmversion.Consensus type in Tendermint. message Version { - uint32 block = 1; - uint32 app = 2; + uint64 block = 1; + uint64 app = 2; } message Header { diff --git a/rpcclient/local.go b/rpcclient/local.go index 1ace599d30e..74998dc32e3 100644 --- a/rpcclient/local.go +++ b/rpcclient/local.go @@ -23,7 +23,7 @@ import ( const ( // TODO(tzdybal): make this configurable - SubscribeTimeout = 5 * time.Second + subscribeTimeout = 5 * time.Second ) var _ rpcclient.Client = &Local{} @@ -86,7 +86,7 @@ func (l *Local) BroadcastTxCommit(ctx context.Context, tx types.Tx) (*ctypes.Res } // Subscribe to tx being committed in block. - subCtx, cancel := context.WithTimeout(ctx, SubscribeTimeout) + subCtx, cancel := context.WithTimeout(ctx, subscribeTimeout) defer cancel() q := types.EventQueryTxFor(tx) deliverTxSub, err := l.EventBus.Subscribe(subCtx, subscriber, q) diff --git a/state/executor.go b/state/executor.go new file mode 100644 index 00000000000..b867430d515 --- /dev/null +++ b/state/executor.go @@ -0,0 +1,254 @@ +package state + +import ( + "bytes" + "context" + "errors" + "time" + + abci "github.com/lazyledger/lazyledger-core/abci/types" + tmstate "github.com/lazyledger/lazyledger-core/proto/tendermint/state" + "github.com/lazyledger/lazyledger-core/proxy" + lltypes "github.com/lazyledger/lazyledger-core/types" + + abciconv "github.com/lazyledger/optimint/conv/abci" + "github.com/lazyledger/optimint/hash" + "github.com/lazyledger/optimint/log" + "github.com/lazyledger/optimint/mempool" + "github.com/lazyledger/optimint/types" +) + +// BlockExecutor creates and applies blocks and maintain state. +type BlockExecutor struct { + proposerAddress []byte + namespaceID [8]byte + proxyApp proxy.AppConnConsensus + mempool mempool.Mempool + + logger log.Logger +} + +// NewBlockExecutor creates new instance of BlockExecutor. +// Proposer address and namespace ID will be used in all newly created blocks. +func NewBlockExecutor(proposerAddress []byte, namespaceID [8]byte, mempool mempool.Mempool, proxyApp proxy.AppConnConsensus, logger log.Logger) *BlockExecutor { + return &BlockExecutor{ + proposerAddress: proposerAddress, + namespaceID: namespaceID, + proxyApp: proxyApp, + mempool: mempool, + logger: logger, + } +} + +// CreateBlock reaps transactions from mempool and builds a block. +func (e *BlockExecutor) CreateBlock(height uint64, commit *types.Commit, state State) *types.Block { + maxBytes := state.ConsensusParams.Block.MaxBytes + maxGas := state.ConsensusParams.Block.MaxGas + + mempoolTxs := e.mempool.ReapMaxBytesMaxGas(maxBytes, maxGas) + + block := &types.Block{ + Header: types.Header{ + Version: types.Version{ + Block: state.Version.Consensus.Block, + App: state.Version.Consensus.App, + }, + NamespaceID: e.namespaceID, + Height: height, + Time: uint64(time.Now().Unix()), // TODO(tzdybal): how to get TAI64? + LastHeaderHash: [32]byte{}, + LastCommitHash: [32]byte{}, + DataHash: [32]byte{}, + ConsensusHash: [32]byte{}, + AppHash: state.AppHash, + LastResultsHash: state.LastResultsHash, + ProposerAddress: e.proposerAddress, + }, + Data: types.Data{ + Txs: toOptimintTxs(mempoolTxs), + IntermediateStateRoots: types.IntermediateStateRoots{RawRootsList: nil}, + Evidence: types.EvidenceData{Evidence: nil}, + }, + } + + return block +} + +// ApplyBlock validates, executes and commits the block. +func (e *BlockExecutor) ApplyBlock(ctx context.Context, state State, block *types.Block) (State, uint64, error) { + err := e.validate(state, block) + if err != nil { + return State{}, 0, err + } + + resp, err := e.execute(ctx, state, block) + if err != nil { + return State{}, 0, err + } + + state, err = e.updateState(state, block, resp) + if err != nil { + return State{}, 0, err + } + + appHash, retainHeight, err := e.commit(ctx, state, block, resp.DeliverTxs) + if err != nil { + return State{}, 0, err + } + + copy(state.AppHash[:], appHash[:]) + + return state, retainHeight, nil +} + +func (e *BlockExecutor) updateState(state State, block *types.Block, abciResponses *tmstate.ABCIResponses) (State, error) { + h, err := hash.Hash(&block.Header) + if err != nil { + return State{}, err + } + s := State{ + Version: state.Version, + ChainID: state.ChainID, + InitialHeight: state.InitialHeight, + LastBlockHeight: int64(block.Header.Height), + LastBlockTime: time.Unix(int64(block.Header.Time), 0), + LastBlockID: lltypes.BlockID{ + Hash: h[:], + // for now, we don't care about part set headers + }, + // skipped all "Validators" fields + ConsensusParams: state.ConsensusParams, + LastHeightConsensusParamsChanged: state.LastHeightConsensusParamsChanged, + } + copy(s.LastResultsHash[:], lltypes.NewResults(abciResponses.DeliverTxs).Hash()) + + return s, nil +} + +func (e *BlockExecutor) commit(ctx context.Context, state State, block *types.Block, deliverTxs []*abci.ResponseDeliverTx) ([]byte, uint64, error) { + e.mempool.Lock() + defer e.mempool.Unlock() + + err := e.mempool.FlushAppConn() + if err != nil { + return nil, 0, err + } + + resp, err := e.proxyApp.CommitSync(ctx) + if err != nil { + return nil, 0, err + } + + maxBytes := state.ConsensusParams.Block.MaxBytes + maxGas := state.ConsensusParams.Block.MaxGas + err = e.mempool.Update(int64(block.Header.Height), fromOptimintTxs(block.Data.Txs), deliverTxs, mempool.PreCheckMaxBytes(maxBytes), mempool.PostCheckMaxGas(maxGas)) + if err != nil { + return nil, 0, err + } + + return resp.Data, uint64(resp.RetainHeight), err +} + +func (e *BlockExecutor) validate(state State, block *types.Block) error { + err := block.ValidateBasic() + if err != nil { + return err + } + if block.Header.Version.App != state.Version.Consensus.App || + block.Header.Version.Block != state.Version.Consensus.Block { + return errors.New("block version mismatch") + } + if state.LastBlockHeight <= 0 && block.Header.Height != uint64(state.InitialHeight) { + return errors.New("initial block height mismatch") + } + if state.LastBlockHeight > 0 && block.Header.Height != uint64(state.LastBlockHeight)+1 { + return errors.New("block height mismatch") + } + if !bytes.Equal(block.Header.AppHash[:], state.AppHash[:]) { + return errors.New("AppHash mismatch") + } + + if !bytes.Equal(block.Header.LastResultsHash[:], state.LastResultsHash[:]) { + return errors.New("LastResultsHash mismatch") + } + + return nil +} + +func (e *BlockExecutor) execute(ctx context.Context, state State, block *types.Block) (*tmstate.ABCIResponses, error) { + abciResponses := new(tmstate.ABCIResponses) + abciResponses.DeliverTxs = make([]*abci.ResponseDeliverTx, len(block.Data.Txs)) + + txIdx := 0 + validTxs := 0 + invalidTxs := 0 + + var err error + + e.proxyApp.SetResponseCallback(func(req *abci.Request, res *abci.Response) { + if r, ok := res.Value.(*abci.Response_DeliverTx); ok { + txRes := r.DeliverTx + if txRes.Code == abci.CodeTypeOK { + validTxs++ + } else { + e.logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log) + invalidTxs++ + } + abciResponses.DeliverTxs[txIdx] = txRes + txIdx++ + } + }) + + hash, err := hash.Hash(block) + if err != nil { + return nil, err + } + abciHeader, err := abciconv.ToABCIHeader(&block.Header) + if err != nil { + return nil, err + } + abciResponses.BeginBlock, err = e.proxyApp.BeginBlockSync( + ctx, + abci.RequestBeginBlock{ + Hash: hash[:], + Header: abciHeader, + LastCommitInfo: abci.LastCommitInfo{ + Round: 0, + Votes: nil, + }, + ByzantineValidators: nil, + }) + if err != nil { + return nil, err + } + + for _, tx := range block.Data.Txs { + _, err = e.proxyApp.DeliverTxAsync(ctx, abci.RequestDeliverTx{Tx: tx}) + if err != nil { + return nil, err + } + } + + abciResponses.EndBlock, err = e.proxyApp.EndBlockSync(ctx, abci.RequestEndBlock{Height: int64(block.Header.Height)}) + if err != nil { + return nil, err + } + + return abciResponses, nil +} + +func toOptimintTxs(txs lltypes.Txs) types.Txs { + optiTxs := make(types.Txs, len(txs)) + for i := range txs { + optiTxs[i] = []byte(txs[i]) + } + return optiTxs +} + +func fromOptimintTxs(optiTxs types.Txs) lltypes.Txs { + txs := make(lltypes.Txs, len(optiTxs)) + for i := range optiTxs { + txs[i] = []byte(optiTxs[i]) + } + return txs +} diff --git a/state/executor_test.go b/state/executor_test.go new file mode 100644 index 00000000000..97a88db6f7d --- /dev/null +++ b/state/executor_test.go @@ -0,0 +1,127 @@ +package state + +import ( + "context" + "crypto/rand" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + abci "github.com/lazyledger/lazyledger-core/abci/types" + cfg "github.com/lazyledger/lazyledger-core/config" + "github.com/lazyledger/lazyledger-core/libs/log" + "github.com/lazyledger/lazyledger-core/proxy" + + "github.com/lazyledger/optimint/mempool" + "github.com/lazyledger/optimint/mocks" + "github.com/lazyledger/optimint/types" +) + +func TestCreateBlock(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + + logger := log.TestingLogger() + + app := &mocks.Application{} + app.On("CheckTx", mock.Anything).Return(abci.ResponseCheckTx{}) + + client, err := proxy.NewLocalClientCreator(app).NewABCIClient() + require.NoError(err) + require.NotNil(client) + + nsID := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} + + mpool := mempool.NewCListMempool(cfg.DefaultMempoolConfig(), proxy.NewAppConnMempool(client), 0) + executor := NewBlockExecutor([]byte("test address"), nsID, mpool, proxy.NewAppConnConsensus(client), logger) + + state := State{} + state.ConsensusParams.Block.MaxBytes = 100 + state.ConsensusParams.Block.MaxGas = 100000 + + // empty block + block := executor.CreateBlock(1, &types.Commit{}, state) + require.NotNil(block) + assert.Empty(block.Data.Txs) + assert.Equal(uint64(1), block.Header.Height) + + // one small Tx + err = mpool.CheckTx([]byte{1, 2, 3, 4}, func(r *abci.Response) {}, mempool.TxInfo{}) + require.NoError(err) + block = executor.CreateBlock(2, &types.Commit{}, state) + require.NotNil(block) + assert.Equal(uint64(2), block.Header.Height) + assert.Len(block.Data.Txs, 1) + + // now there are 3 Txs, and only two can fit into single block + err = mpool.CheckTx([]byte{4, 5, 6, 7}, func(r *abci.Response) {}, mempool.TxInfo{}) + require.NoError(err) + err = mpool.CheckTx(make([]byte, 100), func(r *abci.Response) {}, mempool.TxInfo{}) + require.NoError(err) + block = executor.CreateBlock(3, &types.Commit{}, state) + require.NotNil(block) + assert.Len(block.Data.Txs, 2) +} + +func TestApplyBlock(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + + logger := log.TestingLogger() + + app := &mocks.Application{} + app.On("CheckTx", mock.Anything).Return(abci.ResponseCheckTx{}) + app.On("BeginBlock", mock.Anything).Return(abci.ResponseBeginBlock{}) + app.On("DeliverTx", mock.Anything).Return(abci.ResponseDeliverTx{}) + app.On("EndBlock", mock.Anything).Return(abci.ResponseEndBlock{}) + var mockAppHash [32]byte + _, err := rand.Read(mockAppHash[:]) + require.NoError(err) + app.On("Commit", mock.Anything).Return(abci.ResponseCommit{ + Data: mockAppHash[:], + }) + + client, err := proxy.NewLocalClientCreator(app).NewABCIClient() + require.NoError(err) + require.NotNil(client) + + nsID := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} + + mpool := mempool.NewCListMempool(cfg.DefaultMempoolConfig(), proxy.NewAppConnMempool(client), 0) + executor := NewBlockExecutor([]byte("test address"), nsID, mpool, proxy.NewAppConnConsensus(client), logger) + + state := State{} + state.InitialHeight = 1 + state.LastBlockHeight = 0 + state.ConsensusParams.Block.MaxBytes = 100 + state.ConsensusParams.Block.MaxGas = 100000 + + _ = mpool.CheckTx([]byte{1, 2, 3, 4}, func(r *abci.Response) {}, mempool.TxInfo{}) + require.NoError(err) + block := executor.CreateBlock(1, &types.Commit{}, state) + require.NotNil(block) + assert.Equal(uint64(1), block.Header.Height) + assert.Len(block.Data.Txs, 1) + + newState, _, err := executor.ApplyBlock(context.TODO(), state, block) + require.NoError(err) + require.NotNil(newState) + assert.Equal(int64(1), newState.LastBlockHeight) + assert.Equal(mockAppHash, newState.AppHash) + + require.NoError(mpool.CheckTx([]byte{0, 1, 2, 3, 4}, func(r *abci.Response) {}, mempool.TxInfo{})) + require.NoError(mpool.CheckTx([]byte{5, 6, 7, 8, 9}, func(r *abci.Response) {}, mempool.TxInfo{})) + require.NoError(mpool.CheckTx([]byte{1, 2, 3, 4, 5}, func(r *abci.Response) {}, mempool.TxInfo{})) + require.NoError(mpool.CheckTx(make([]byte, 90), func(r *abci.Response) {}, mempool.TxInfo{})) + block = executor.CreateBlock(2, &types.Commit{}, newState) + require.NotNil(block) + assert.Equal(uint64(2), block.Header.Height) + assert.Len(block.Data.Txs, 3) + + newState, _, err = executor.ApplyBlock(context.TODO(), newState, block) + require.NoError(err) + require.NotNil(newState) + assert.Equal(int64(2), newState.LastBlockHeight) +} diff --git a/state/state.go b/state/state.go new file mode 100644 index 00000000000..64263e029f4 --- /dev/null +++ b/state/state.go @@ -0,0 +1,98 @@ +package state + +import ( + "fmt" + "time" + + // TODO(tzdybal): copy to local project? + tmstate "github.com/lazyledger/lazyledger-core/proto/tendermint/state" + tmproto "github.com/lazyledger/lazyledger-core/proto/tendermint/types" + tmversion "github.com/lazyledger/lazyledger-core/proto/tendermint/version" + "github.com/lazyledger/lazyledger-core/types" + "github.com/lazyledger/lazyledger-core/version" +) + +// InitStateVersion sets the Consensus.Block and Software versions, +// but leaves the Consensus.App version blank. +// The Consensus.App version will be set during the Handshake, once +// we hear from the app what protocol version it is running. +var InitStateVersion = tmstate.Version{ + Consensus: tmversion.Consensus{ + Block: version.BlockProtocol, + App: 0, + }, + Software: version.TMCoreSemVer, +} + +// State contains information about current state of the blockchain. +type State struct { + Version tmstate.Version + + // immutable + ChainID string + InitialHeight int64 // should be 1, not 0, when starting from height 1 + + // LastBlockHeight=0 at genesis (ie. block(H=0) does not exist) + LastBlockHeight int64 + LastBlockID types.BlockID + LastBlockTime time.Time + + // In the MVP implementation, there will be only one Validator + NextValidators *types.ValidatorSet + Validators *types.ValidatorSet + LastValidators *types.ValidatorSet + LastHeightValidatorsChanged int64 + + // Consensus parameters used for validating blocks. + // Changes returned by EndBlock and updated after Commit. + ConsensusParams tmproto.ConsensusParams + LastHeightConsensusParamsChanged int64 + + // Merkle root of the results from executing prev block + LastResultsHash [32]byte + + // the latest AppHash we've received from calling abci.Commit() + AppHash [32]byte +} + +// NewFromGenesisDoc reads blockchain State from genesis. +func NewFromGenesisDoc(genDoc *types.GenesisDoc) (State, error) { + err := genDoc.ValidateAndComplete() + if err != nil { + return State{}, fmt.Errorf("error in genesis doc: %w", err) + } + + var validatorSet, nextValidatorSet *types.ValidatorSet + if genDoc.Validators == nil { + validatorSet = types.NewValidatorSet(nil) + nextValidatorSet = types.NewValidatorSet(nil) + } else { + validators := make([]*types.Validator, len(genDoc.Validators)) + for i, val := range genDoc.Validators { + validators[i] = types.NewValidator(val.PubKey, val.Power) + } + validatorSet = types.NewValidatorSet(validators) + nextValidatorSet = types.NewValidatorSet(validators).CopyIncrementProposerPriority(1) + } + + s := State{ + Version: InitStateVersion, + ChainID: genDoc.ChainID, + InitialHeight: genDoc.InitialHeight, + + LastBlockHeight: 0, + LastBlockID: types.BlockID{}, + LastBlockTime: genDoc.GenesisTime, + + NextValidators: nextValidatorSet, + Validators: validatorSet, + LastValidators: types.NewValidatorSet(nil), + LastHeightValidatorsChanged: genDoc.InitialHeight, + + ConsensusParams: *genDoc.ConsensusParams, + LastHeightConsensusParamsChanged: genDoc.InitialHeight, + } + copy(s.AppHash[:], genDoc.AppHash) + + return s, nil +} diff --git a/store/badger.go b/store/badger.go index e748b11a2c2..3213975ee23 100644 --- a/store/badger.go +++ b/store/badger.go @@ -4,10 +4,12 @@ import "github.com/dgraph-io/badger/v3" var _ KVStore = &BadgerKV{} +// BadgerKV is a implementation of KVStore using Badger v3. type BadgerKV struct { db *badger.DB } +// Get returns value for given key, or error. func (b *BadgerKV) Get(key []byte) ([]byte, error) { txn := b.db.NewTransaction(false) defer txn.Discard() @@ -18,6 +20,7 @@ func (b *BadgerKV) Get(key []byte) ([]byte, error) { return item.ValueCopy(nil) } +// Set saves key-value mapping in store. func (b *BadgerKV) Set(key []byte, value []byte) error { txn := b.db.NewTransaction(true) err := txn.Set(key, value) @@ -28,6 +31,7 @@ func (b *BadgerKV) Set(key []byte, value []byte) error { return txn.Commit() } +// Delete removes key and corresponding value from store. func (b *BadgerKV) Delete(key []byte) error { txn := b.db.NewTransaction(true) err := txn.Delete(key) diff --git a/store/kv.go b/store/kv.go index f9a1c44fb23..3caeb2df5e5 100644 --- a/store/kv.go +++ b/store/kv.go @@ -11,6 +11,7 @@ type KVStore interface { Delete(key []byte) error // Delete deletes a key. } +// NewInMemoryKVStore builds KVStore that works in-memory (without accessing disk). func NewInMemoryKVStore() KVStore { db, err := badger.Open(badger.DefaultOptions("").WithInMemory(true)) if err != nil { diff --git a/store/store.go b/store/store.go index b905d7603b8..18e86af307e 100644 --- a/store/store.go +++ b/store/store.go @@ -17,6 +17,7 @@ var ( commitPrefix = [1]byte{3} ) +// DefaultStore is a default store implmementation. type DefaultStore struct { db KVStore @@ -28,16 +29,20 @@ type DefaultStore struct { var _ Store = &DefaultStore{} +// New returns new, default store. func New() Store { return &DefaultStore{db: NewInMemoryKVStore()} } +// Height returns height of the highest block saved in the Store. func (s *DefaultStore) Height() uint64 { s.mtx.RLock() defer s.mtx.RUnlock() return s.height } +// SaveBlock adds block to the store along with corresponding commit. +// Stored height is updated if block height is greater than stored value. func (s *DefaultStore) SaveBlock(block *types.Block, commit *types.Commit) error { hash, err := hash.Hash(&block.Header) if err != nil { @@ -71,6 +76,7 @@ func (s *DefaultStore) SaveBlock(block *types.Block, commit *types.Commit) error return nil } +// LoadBlock returns block at given height, or error if it's not found in Store. // TODO(tzdybal): what is more common access pattern? by height or by hash? // currently, we're indexing height->hash, and store blocks by hash, but we might as well store by height // and index hash->height @@ -82,6 +88,7 @@ func (s *DefaultStore) LoadBlock(height uint64) (*types.Block, error) { return s.LoadBlockByHash(h) } +// LoadBlockByHash returns block with given block header hash, or error if it's not found in Store. func (s *DefaultStore) LoadBlockByHash(hash [32]byte) (*types.Block, error) { blockData, err := s.db.Get(getBlockKey(hash)) @@ -95,6 +102,7 @@ func (s *DefaultStore) LoadBlockByHash(hash [32]byte) (*types.Block, error) { return block, err } +// LoadCommit returns commit for a block at given height, or error if it's not found in Store. func (s *DefaultStore) LoadCommit(height uint64) (*types.Commit, error) { hash, err := s.loadHashFromIndex(height) if err != nil { @@ -103,6 +111,7 @@ func (s *DefaultStore) LoadCommit(height uint64) (*types.Commit, error) { return s.LoadCommitByHash(hash) } +// LoadCommitByHash returns commit for a block with given block header hash, or error if it's not found in Store. func (s *DefaultStore) LoadCommitByHash(hash [32]byte) (*types.Commit, error) { commitData, err := s.db.Get(getCommitKey(hash)) if err != nil { diff --git a/store/types.go b/store/types.go index 655a4704496..8895122b14c 100644 --- a/store/types.go +++ b/store/types.go @@ -17,6 +17,6 @@ type Store interface { // LoadCommit returns commit for a block at given height, or error if it's not found in Store. LoadCommit(height uint64) (*types.Commit, error) - // LoadCommit returns commit for a block with given block header hash, or error if it's not found in Store. + // LoadCommitByHash returns commit for a block with given block header hash, or error if it's not found in Store. LoadCommitByHash(hash [32]byte) (*types.Commit, error) } diff --git a/types/block.go b/types/block.go index a1037ba271f..4879efd2620 100644 --- a/types/block.go +++ b/types/block.go @@ -1,5 +1,6 @@ package types +// Header defines the structure of Optimint block header. type Header struct { // Block and App version Version Version @@ -37,34 +38,41 @@ type Header struct { // state transition machine. // This is equivalent to the tmversion.Consensus type in Tendermint. type Version struct { - Block uint32 - App uint32 + Block uint64 + App uint64 } +// Block defines the structure of Optimint block. type Block struct { Header Header Data Data LastCommit Commit } +// Data defines Optimint block data. type Data struct { Txs Txs IntermediateStateRoots IntermediateStateRoots Evidence EvidenceData } +// EvidenceData defines how evidence is stored in block. type EvidenceData struct { Evidence []Evidence } +// Commit cointains evidence of block creation. type Commit struct { Height uint64 HeaderHash [32]byte Signatures []Signature // most of the time this is a single signature } +// Signature represents signature of block creator. type Signature []byte +// IntermediateStateRoots describes the state between transactions. +// They are required for fraud proofs. type IntermediateStateRoots struct { RawRootsList [][]byte } diff --git a/types/pb/optimint/optimint.pb.go b/types/pb/optimint/optimint.pb.go index 3590eb34aec..0af2c2da46e 100644 --- a/types/pb/optimint/optimint.pb.go +++ b/types/pb/optimint/optimint.pb.go @@ -39,8 +39,8 @@ const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // state transition machine. // This is equivalent to the tmversion.Consensus type in Tendermint. type Version struct { - Block uint32 `protobuf:"varint,1,opt,name=block,proto3" json:"block,omitempty"` - App uint32 `protobuf:"varint,2,opt,name=app,proto3" json:"app,omitempty"` + Block uint64 `protobuf:"varint,1,opt,name=block,proto3" json:"block,omitempty"` + App uint64 `protobuf:"varint,2,opt,name=app,proto3" json:"app,omitempty"` } func (m *Version) Reset() { *m = Version{} } @@ -48,14 +48,14 @@ func (m *Version) String() string { return proto.CompactTextString(m) func (*Version) ProtoMessage() {} func (*Version) Descriptor() ([]byte, []int) { return fileDescriptorOptimint, []int{0} } -func (m *Version) GetBlock() uint32 { +func (m *Version) GetBlock() uint64 { if m != nil { return m.Block } return 0 } -func (m *Version) GetApp() uint32 { +func (m *Version) GetApp() uint64 { if m != nil { return m.App } @@ -728,7 +728,7 @@ func (m *Version) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.Block |= (uint32(b) & 0x7F) << shift + m.Block |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } @@ -747,7 +747,7 @@ func (m *Version) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.App |= (uint32(b) & 0x7F) << shift + m.App |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } @@ -1667,38 +1667,37 @@ var ( func init() { proto.RegisterFile("optimint.proto", fileDescriptorOptimint) } var fileDescriptorOptimint = []byte{ - // 514 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x54, 0x93, 0xc1, 0x6e, 0x13, 0x31, - 0x10, 0x86, 0xd9, 0x26, 0x4d, 0xd2, 0xd9, 0x36, 0xa4, 0x16, 0xaa, 0x5c, 0x2a, 0x85, 0xb0, 0x12, - 0x52, 0x00, 0x29, 0x55, 0x83, 0x90, 0xb8, 0x52, 0x40, 0x2a, 0x57, 0x23, 0x71, 0x8d, 0x9c, 0xdd, - 0x51, 0xd7, 0x22, 0xbb, 0xb6, 0x6c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 0x59, 0x9d, 0x85, 0xac, 0xce, 0x3e, 0x34, 0x80, 0xd8, 0xa1, 0xd9, 0xf7, 0x04, 0x0e, - 0xaf, 0x29, 0x9b, 0xd3, 0x30, 0x6e, 0x98, 0xa1, 0x49, 0xdf, 0xa8, 0x4d, 0x5f, 0x7c, 0xfd, 0xa2, - 0xf1, 0x59, 0x06, 0xdd, 0xf0, 0x1e, 0x69, 0xf2, 0x74, 0x3e, 0x6c, 0xb9, 0x30, 0x94, 0x20, 0x8f, - 0x5d, 0x41, 0xba, 0x17, 0x13, 0x4a, 0xe0, 0xbd, 0x92, 0x71, 0xc7, 0x02, 0xda, 0xcc, 0x5c, 0x8f, - 0x7e, 0x6f, 0xc6, 0xc9, 0x9f, 0xcd, 0x38, 0xf9, 0xbb, 0x19, 0x27, 0xbf, 0xfe, 0x8d, 0x1f, 0x2c, - 0x7b, 0xf4, 0x59, 0xbd, 0xfa, 0x1f, 0x00, 0x00, 0xff, 0xff, 0x4c, 0xa3, 0x71, 0x3b, 0x8f, 0x03, - 0x00, 0x00, + // 511 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x54, 0x93, 0xcf, 0x6e, 0xd3, 0x40, + 0x10, 0xc6, 0x71, 0xf3, 0xb7, 0xe3, 0x12, 0xd2, 0x15, 0xaa, 0xb6, 0x54, 0x0a, 0xc5, 0x12, 0x52, + 0x00, 0x29, 0x55, 0x83, 0x90, 0xb8, 0x52, 0x40, 0x2a, 0x57, 0x23, 0x71, 0xb5, 0x36, 0xf6, 0xa8, + 0x5e, 0x11, 0x7b, 0x57, 0xbb, 0x9b, 0x0a, 0xde, 0x00, 0x2e, 0x9c, 0x79, 0x24, 0x8e, 0x3c, 0x02, + 0x0a, 0x2f, 0x52, 0xed, 0xac, 0x63, 0xa7, 0x97, 0x68, 0xf7, 0xfb, 0x7e, 0x1e, 0xcf, 0x8c, 0xbf, + 0xc0, 0x44, 0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4b, 0xa0, + 0xef, 0xbf, 0x23, 0x4d, 0x1e, 0x2f, 0x27, 0x1d, 0xe7, 0x87, 0x4a, 0xc9, 0x63, 0x97, 0x10, 0xef, + 0xc5, 0x84, 0x12, 0x78, 0xaf, 0x64, 0xd8, 0x71, 0x0a, 0x5d, 0x66, 0xae, 0xa6, 0x7f, 0xb6, 0xb3, + 0xe8, 0xef, 0x76, 0x16, 0xfd, 0xdb, 0xce, 0xa2, 0xdf, 0xff, 0x67, 0x0f, 0x56, 0x43, 0xfa, 0x5b, + 0xbd, 0xbe, 0x0b, 0x00, 0x00, 0xff, 0xff, 0xff, 0x7c, 0xd6, 0xd0, 0x8f, 0x03, 0x00, 0x00, } diff --git a/types/serialization.go b/types/serialization.go index e2975f40c4a..0bfc46b1834 100644 --- a/types/serialization.go +++ b/types/serialization.go @@ -7,18 +7,22 @@ import ( pb "github.com/lazyledger/optimint/types/pb/optimint" ) +// MarshalBinary encodes Block into binary form and returns it. func (b *Block) MarshalBinary() ([]byte, error) { return b.ToProto().Marshal() } +// MarshalBinary encodes Header into binary form and returns it. func (h *Header) MarshalBinary() ([]byte, error) { return h.ToProto().Marshal() } +// MarshalBinary encodes Data into binary form and returns it. func (d *Data) MarshalBinary() ([]byte, error) { return d.ToProto().Marshal() } +// UnmarshalBinary decodes binary form of Block into object. func (b *Block) UnmarshalBinary(data []byte) error { var pBlock pb.Block err := pBlock.Unmarshal(data) @@ -29,10 +33,12 @@ func (b *Block) UnmarshalBinary(data []byte) error { return err } +// MarshalBinary encodes Commit into binary form and returns it. func (c *Commit) MarshalBinary() ([]byte, error) { return c.ToProto().Marshal() } +// UnmarshalBinary decodes binary form of Commit into object. func (c *Commit) UnmarshalBinary(data []byte) error { var pCommit pb.Commit err := pCommit.Unmarshal(data) @@ -43,6 +49,7 @@ func (c *Commit) UnmarshalBinary(data []byte) error { return err } +// ToProto converts Header into protobuf representation and returns it. func (h *Header) ToProto() *pb.Header { return &pb.Header{ Version: &pb.Version{ @@ -62,6 +69,7 @@ func (h *Header) ToProto() *pb.Header { } } +// FromProto fills Header with data from its protobuf representation. func (h *Header) FromProto(other *pb.Header) error { h.Version.Block = other.Version.Block h.Version.App = other.Version.App @@ -106,6 +114,7 @@ func safeCopy(dst, src []byte) bool { return true } +// ToProto converts Block into protobuf representation and returns it. func (b *Block) ToProto() *pb.Block { return &pb.Block{ Header: b.Header.ToProto(), @@ -114,6 +123,7 @@ func (b *Block) ToProto() *pb.Block { } } +// ToProto converts Data into protobuf representation and returns it. func (d *Data) ToProto() *pb.Data { return &pb.Data{ Txs: txsToByteSlices(d.Txs), @@ -122,6 +132,7 @@ func (d *Data) ToProto() *pb.Data { } } +// FromProto fills Block with data from its protobuf representation. func (b *Block) FromProto(other *pb.Block) error { err := b.Header.FromProto(other.Header) if err != nil { @@ -140,6 +151,7 @@ func (b *Block) FromProto(other *pb.Block) error { return nil } +// ToProto converts Commit into protobuf representation and returns it. func (c *Commit) ToProto() *pb.Commit { return &pb.Commit{ Height: c.Height, @@ -148,6 +160,7 @@ func (c *Commit) ToProto() *pb.Commit { } } +// FromProto fills Commit with data from its protobuf representation. func (c *Commit) FromProto(other *pb.Commit) error { c.Height = other.Height if !safeCopy(c.HeaderHash[:], other.HeaderHash) { diff --git a/types/tx.go b/types/tx.go index b9a84dff020..2ede78da288 100644 --- a/types/tx.go +++ b/types/tx.go @@ -1,5 +1,7 @@ package types +// Tx represents transactoin. type Tx []byte +// Txs represents a slice of transactions. type Txs []Tx diff --git a/types/validation.go b/types/validation.go new file mode 100644 index 00000000000..b55abfd83c6 --- /dev/null +++ b/types/validation.go @@ -0,0 +1,48 @@ +package types + +import "errors" + +// ValidateBasic performs basic validation of a block. +func (b *Block) ValidateBasic() error { + err := b.Header.ValidateBasic() + if err != nil { + return err + } + + err = b.Data.ValidateBasic() + if err != nil { + return err + } + + err = b.LastCommit.ValidateBasic() + if err != nil { + return err + } + + return nil +} + +// ValidateBasic performs basic validation of a header. +func (h *Header) ValidateBasic() error { + if len(h.ProposerAddress) == 0 { + return errors.New("no proposer address") + } + + return nil +} + +// ValidateBasic performs basic validation of block data. +// Actually it's a placeholder, because nothing is checked. +func (d *Data) ValidateBasic() error { + return nil +} + +// ValidateBasic performs basic validation of a commit. +func (c *Commit) ValidateBasic() error { + if c.Height > 0 { + if len(c.Signatures) == 0 { + return errors.New("no signatures") + } + } + return nil +}