Move (core/)types.Header and friends into block

pull/1498/head
Eugene Kim 5 years ago
parent abdf1c4aa9
commit a48123e749
  1. 3
      api/proto/node/node.go
  2. 11
      api/proto/node/node_test.go
  3. 5
      api/service/explorer/storage_test.go
  4. 4
      api/service/explorer/structs_test.go
  5. 2
      block/gen_header_json.go
  6. 3
      block/header.go
  7. 3
      consensus/consensus_service.go
  8. 10
      consensus/consensus_v2.go
  9. 23
      consensus/engine/consensus_engine.go
  10. 29
      core/blockchain.go
  11. 8
      core/chain_indexer.go
  12. 23
      core/chain_makers.go
  13. 15
      core/core_test.go
  14. 8
      core/evm.go
  15. 3
      core/genesis.go
  16. 27
      core/headerchain.go
  17. 9
      core/rawdb/accessors_chain.go
  18. 20
      core/rawdb/accessors_chain_test.go
  19. 4
      core/rawdb/accessors_indexes_test.go
  20. 8
      core/state_processor.go
  21. 5
      core/tx_pool.go
  22. 4
      core/tx_pool_test.go
  23. 33
      core/types/block.go
  24. 4
      core/types/block_test.go
  25. 8
      core/types/crosslink.go
  26. 4
      drand/drand_test.go
  27. 10
      hmy/api_backend.go
  28. 4
      hmy/bloombits.go
  29. 8
      hmyclient/hmyclient.go
  30. 19
      internal/chain/engine.go
  31. 4
      internal/chain/reward.go
  32. 8
      internal/hmyapi/backend.go
  33. 8
      internal/hmyapi/filters/api.go
  34. 10
      internal/hmyapi/filters/filter.go
  35. 26
      internal/hmyapi/filters/filter_system.go
  36. 3
      node/node.go
  37. 10
      node/node_cross_shard.go
  38. 3
      node/node_handler.go
  39. 9
      node/worker/worker.go

@ -11,6 +11,7 @@ import (
peer "github.com/libp2p/go-libp2p-peer" peer "github.com/libp2p/go-libp2p-peer"
"github.com/harmony-one/harmony/api/proto" "github.com/harmony-one/harmony/api/proto"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/utils" "github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard" "github.com/harmony-one/harmony/shard"
@ -148,7 +149,7 @@ func ConstructBlocksSyncMessage(blocks []*types.Block) []byte {
} }
// ConstructCrossLinkHeadersMessage constructs cross link header message to send to beacon chain // ConstructCrossLinkHeadersMessage constructs cross link header message to send to beacon chain
func ConstructCrossLinkHeadersMessage(headers []*types.Header) []byte { func ConstructCrossLinkHeadersMessage(headers []*block.Header) []byte {
byteBuffer := bytes.NewBuffer([]byte{byte(proto.Node)}) byteBuffer := bytes.NewBuffer([]byte{byte(proto.Node)})
byteBuffer.WriteByte(byte(Block)) byteBuffer.WriteByte(byte(Block))
byteBuffer.WriteByte(byte(Header)) byteBuffer.WriteByte(byte(Header))

@ -1,18 +1,19 @@
package node package node
import ( import (
"math/big"
"reflect"
"strings" "strings"
"testing"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/params" "github.com/harmony-one/harmony/internal/params"
"math/big"
"reflect"
"testing"
) )
var ( var (
@ -59,7 +60,7 @@ func TestConstructBlocksSyncMessage(t *testing.T) {
statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))
root := statedb.IntermediateRoot(false) root := statedb.IntermediateRoot(false)
head := &types.Header{ head := &block.Header{
Number: new(big.Int).SetUint64(uint64(10000)), Number: new(big.Int).SetUint64(uint64(10000)),
Epoch: big.NewInt(0), Epoch: big.NewInt(0),
ShardID: 0, ShardID: 0,

@ -10,6 +10,7 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/bls/ffi/go/bls" "github.com/harmony-one/bls/ffi/go/bls"
block2 "github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/shard" "github.com/harmony-one/harmony/shard"
@ -57,7 +58,7 @@ func TestDump(t *testing.T) {
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33}) tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3} txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, nil, nil) block := types.NewBlock(&block2.Header{Number: big.NewInt(314)}, txs, nil, nil, nil)
ins := GetStorageInstance("1.1.1.1", "3333", true) ins := GetStorageInstance("1.1.1.1", "3333", true)
ins.Dump(block, uint64(1)) ins.Dump(block, uint64(1))
db := ins.GetDB() db := ins.GetDB()
@ -115,7 +116,7 @@ func TestUpdateAddressStorage(t *testing.T) {
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33}) tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3} txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, nil, nil) block := types.NewBlock(&block2.Header{Number: big.NewInt(314)}, txs, nil, nil, nil)
ins := GetStorageInstance("1.1.1.1", "3333", true) ins := GetStorageInstance("1.1.1.1", "3333", true)
ins.Dump(block, uint64(1)) ins.Dump(block, uint64(1))
db := ins.GetDB() db := ins.GetDB()

@ -8,6 +8,8 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
block2 "github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
) )
@ -18,7 +20,7 @@ func TestGetTransaction(t *testing.T) {
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33}) tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3} txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, nil, nil) block := types.NewBlock(&block2.Header{Number: big.NewInt(314)}, txs, nil, nil, nil)
tx := GetTransaction(tx1, block) tx := GetTransaction(tx1, block)
assert.Equal(t, tx.ID, tx1.Hash().Hex(), "should be equal tx1.Hash()") assert.Equal(t, tx.ID, tx1.Hash().Hex(), "should be equal tx1.Hash()")

@ -1,6 +1,6 @@
// Code generated by github.com/fjl/gencodec. DO NOT EDIT. // Code generated by github.com/fjl/gencodec. DO NOT EDIT.
package types package block
import ( import (
"encoding/json" "encoding/json"

@ -1,4 +1,4 @@
package types package block
import ( import (
"math/big" "math/big"
@ -88,4 +88,3 @@ func (h *Header) GetShardState() (shard.ShardState, error) {
} }
return shardState, nil return shardState, nil
} }

@ -9,6 +9,7 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/crypto/hash" "github.com/harmony-one/harmony/crypto/hash"
@ -456,7 +457,7 @@ func (consensus *Consensus) getLogger() *zerolog.Logger {
} }
// retrieve corresponding blsPublicKey from Coinbase Address // retrieve corresponding blsPublicKey from Coinbase Address
func (consensus *Consensus) getLeaderPubKeyFromCoinbase(header *types.Header) (*bls.PublicKey, error) { func (consensus *Consensus) getLeaderPubKeyFromCoinbase(header *block.Header) (*bls.PublicKey, error) {
shardState, err := consensus.ChainReader.ReadShardState(header.Epoch) shardState, err := consensus.ChainReader.ReadShardState(header.Epoch)
if err != nil { if err != nil {
return nil, ctxerror.New("cannot read shard state", return nil, ctxerror.New("cannot read shard state",

@ -10,8 +10,11 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
protobuf "github.com/golang/protobuf/proto" protobuf "github.com/golang/protobuf/proto"
"github.com/harmony-one/bls/ffi/go/bls" "github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/vdf/src/vdf_go"
"github.com/harmony-one/harmony/api/proto" "github.com/harmony-one/harmony/api/proto"
msg_pb "github.com/harmony-one/harmony/api/proto/message" msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
vrf_bls "github.com/harmony-one/harmony/crypto/vrf/bls" vrf_bls "github.com/harmony-one/harmony/crypto/vrf/bls"
@ -20,7 +23,6 @@ import (
"github.com/harmony-one/harmony/internal/utils" "github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/p2p" "github.com/harmony-one/harmony/p2p"
"github.com/harmony-one/harmony/p2p/host" "github.com/harmony-one/harmony/p2p/host"
"github.com/harmony-one/vdf/src/vdf_go"
) )
// handleMessageUpdate will update the consensus state according to received message // handleMessageUpdate will update the consensus state according to received message
@ -182,7 +184,7 @@ func (consensus *Consensus) onAnnounce(msg *msg_pb.Message) {
// verify validity of block header object // verify validity of block header object
blockHeader := recvMsg.Payload blockHeader := recvMsg.Payload
var headerObj types.Header var headerObj block.Header
err = rlp.DecodeBytes(blockHeader, &headerObj) err = rlp.DecodeBytes(blockHeader, &headerObj)
if err != nil { if err != nil {
consensus.getLogger().Warn(). consensus.getLogger().Warn().
@ -1203,7 +1205,7 @@ func (consensus *Consensus) GenerateVrfAndProof(newBlock *types.Block, vrfBlockN
} }
// ValidateVrfAndProof validates a VRF/Proof from hash of previous block // ValidateVrfAndProof validates a VRF/Proof from hash of previous block
func (consensus *Consensus) ValidateVrfAndProof(headerObj types.Header) bool { func (consensus *Consensus) ValidateVrfAndProof(headerObj block.Header) bool {
vrfPk := vrf_bls.NewVRFVerifier(consensus.LeaderPubKey) vrfPk := vrf_bls.NewVRFVerifier(consensus.LeaderPubKey)
var blockHash [32]byte var blockHash [32]byte
@ -1275,7 +1277,7 @@ func (consensus *Consensus) GenerateVdfAndProof(newBlock *types.Block, vrfBlockN
} }
// ValidateVdfAndProof validates the VDF/proof in the current epoch // ValidateVdfAndProof validates the VDF/proof in the current epoch
func (consensus *Consensus) ValidateVdfAndProof(headerObj types.Header) bool { func (consensus *Consensus) ValidateVdfAndProof(headerObj block.Header) bool {
vrfBlockNumbers, err := consensus.ChainReader.ReadEpochVrfBlockNums(headerObj.Epoch) vrfBlockNumbers, err := consensus.ChainReader.ReadEpochVrfBlockNums(headerObj.Epoch)
if err != nil { if err != nil {
consensus.getLogger().Error().Err(err). consensus.getLogger().Error().Err(err).

@ -6,6 +6,7 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/internal/params" "github.com/harmony-one/harmony/internal/params"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/shard" "github.com/harmony-one/harmony/shard"
@ -19,16 +20,16 @@ type ChainReader interface {
Config() *params.ChainConfig Config() *params.ChainConfig
// CurrentHeader retrieves the current header from the local chain. // CurrentHeader retrieves the current header from the local chain.
CurrentHeader() *types.Header CurrentHeader() *block.Header
// GetHeader retrieves a block header from the database by hash and number. // GetHeader retrieves a block header from the database by hash and number.
GetHeader(hash common.Hash, number uint64) *types.Header GetHeader(hash common.Hash, number uint64) *block.Header
// GetHeaderByNumber retrieves a block header from the database by number. // GetHeaderByNumber retrieves a block header from the database by number.
GetHeaderByNumber(number uint64) *types.Header GetHeaderByNumber(number uint64) *block.Header
// GetHeaderByHash retrieves a block header from the database by its hash. // GetHeaderByHash retrieves a block header from the database by its hash.
GetHeaderByHash(hash common.Hash) *types.Header GetHeaderByHash(hash common.Hash) *block.Header
// GetBlock retrieves a block from the database by hash and number. // GetBlock retrieves a block from the database by hash and number.
GetBlock(hash common.Hash, number uint64) *types.Block GetBlock(hash common.Hash, number uint64) *types.Block
@ -42,32 +43,32 @@ type ChainReader interface {
type Engine interface { type Engine interface {
// Author retrieves the Harmony address of the account that validated the given // Author retrieves the Harmony address of the account that validated the given
// block. // block.
Author(header *types.Header) (common.Address, error) Author(header *block.Header) (common.Address, error)
// VerifyHeader checks whether a header conforms to the consensus rules of a // VerifyHeader checks whether a header conforms to the consensus rules of a
// given engine. Verifying the seal may be done optionally here, or explicitly // given engine. Verifying the seal may be done optionally here, or explicitly
// via the VerifySeal method. // via the VerifySeal method.
VerifyHeader(chain ChainReader, header *types.Header, seal bool) error VerifyHeader(chain ChainReader, header *block.Header, seal bool) error
// VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
// concurrently. The method returns a quit channel to abort the operations and // concurrently. The method returns a quit channel to abort the operations and
// a results channel to retrieve the async verifications (the order is that of // a results channel to retrieve the async verifications (the order is that of
// the input slice). // the input slice).
VerifyHeaders(chain ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) VerifyHeaders(chain ChainReader, headers []*block.Header, seals []bool) (chan<- struct{}, <-chan error)
// VerifySeal checks whether the crypto seal on a header is valid according to // VerifySeal checks whether the crypto seal on a header is valid according to
// the consensus rules of the given engine. // the consensus rules of the given engine.
VerifySeal(chain ChainReader, header *types.Header) error VerifySeal(chain ChainReader, header *block.Header) error
// Prepare initializes the consensus fields of a block header according to the // Prepare initializes the consensus fields of a block header according to the
// rules of a particular engine. The changes are executed inline. // rules of a particular engine. The changes are executed inline.
Prepare(chain ChainReader, header *types.Header) error Prepare(chain ChainReader, header *block.Header) error
// Finalize runs any post-transaction state modifications (e.g. block rewards) // Finalize runs any post-transaction state modifications (e.g. block rewards)
// and assembles the final block. // and assembles the final block.
// Note: The block header and state database might be updated to reflect any // Note: The block header and state database might be updated to reflect any
// consensus rules that happen at finalization (e.g. block rewards). // consensus rules that happen at finalization (e.g. block rewards).
Finalize(chain ChainReader, header *types.Header, state *state.DB, txs []*types.Transaction, Finalize(chain ChainReader, header *block.Header, state *state.DB, txs []*types.Transaction,
receipts []*types.Receipt, outcxs []*types.CXReceipt, incxs []*types.CXReceiptsProof) (*types.Block, error) receipts []*types.Receipt, outcxs []*types.CXReceipt, incxs []*types.CXReceiptsProof) (*types.Block, error)
// Seal generates a new sealing request for the given input block and pushes // Seal generates a new sealing request for the given input block and pushes
@ -78,5 +79,5 @@ type Engine interface {
Seal(chain ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error Seal(chain ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error
// SealHash returns the hash of a block prior to it being sealed. // SealHash returns the hash of a block prior to it being sealed.
SealHash(header *types.Header) common.Hash SealHash(header *block.Header) common.Hash
} }

@ -38,6 +38,7 @@ import (
"github.com/harmony-one/harmony/internal/params" "github.com/harmony-one/harmony/internal/params"
lru "github.com/hashicorp/golang-lru" lru "github.com/hashicorp/golang-lru"
"github.com/harmony-one/harmony/block"
consensus_engine "github.com/harmony-one/harmony/consensus/engine" consensus_engine "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/contracts/structs" "github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core/rawdb" "github.com/harmony-one/harmony/core/rawdb"
@ -249,7 +250,7 @@ func IsEpochLastBlock(block *types.Block) bool {
// IsEpochLastBlockByHeader returns whether this block is the last block of an epoch // IsEpochLastBlockByHeader returns whether this block is the last block of an epoch
// given block header // given block header
func IsEpochLastBlockByHeader(header *types.Header) bool { func IsEpochLastBlockByHeader(header *block.Header) bool {
return ShardingSchedule.IsLastBlock(header.Number.Uint64()) return ShardingSchedule.IsLastBlock(header.Number.Uint64())
} }
@ -726,11 +727,11 @@ func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*type
// GetUnclesInChain retrieves all the uncles from a given block backwards until // GetUnclesInChain retrieves all the uncles from a given block backwards until
// a specific distance is reached. // a specific distance is reached.
func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header { func (bc *BlockChain) GetUnclesInChain(b *types.Block, length int) []*block.Header {
uncles := []*types.Header{} uncles := []*block.Header{}
for i := 0; block != nil && i < length; i++ { for i := 0; b != nil && i < length; i++ {
uncles = append(uncles, block.Uncles()...) uncles = append(uncles, b.Uncles()...)
block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1) b = bc.GetBlock(b.ParentHash(), b.NumberU64()-1)
} }
return uncles return uncles
} }
@ -1208,7 +1209,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*ty
coalescedLogs []*types.Log coalescedLogs []*types.Log
) )
// Start the parallel header verifier // Start the parallel header verifier
headers := make([]*types.Header, len(chain)) headers := make([]*block.Header, len(chain))
seals := make([]bool, len(chain)) seals := make([]bool, len(chain))
for i, block := range chain { for i, block := range chain {
@ -1670,7 +1671,7 @@ Error: %v
// should be done or not. The reason behind the optional check is because some // should be done or not. The reason behind the optional check is because some
// of the header retrieval mechanisms already need to verify nonces, as well as // of the header retrieval mechanisms already need to verify nonces, as well as
// because nonces can be verified sparsely, not needing to check each. // because nonces can be verified sparsely, not needing to check each.
func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) { func (bc *BlockChain) InsertHeaderChain(chain []*block.Header, checkFreq int) (int, error) {
start := time.Now() start := time.Now()
if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil { if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
return i, err return i, err
@ -1683,7 +1684,7 @@ func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (i
bc.wg.Add(1) bc.wg.Add(1)
defer bc.wg.Done() defer bc.wg.Done()
whFunc := func(header *types.Header) error { whFunc := func(header *block.Header) error {
bc.mu.Lock() bc.mu.Lock()
defer bc.mu.Unlock() defer bc.mu.Unlock()
@ -1703,7 +1704,7 @@ func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (i
// without the real blocks. Hence, writing headers directly should only be done // without the real blocks. Hence, writing headers directly should only be done
// in two scenarios: pure-header mode of operation (light clients), or properly // in two scenarios: pure-header mode of operation (light clients), or properly
// separated header/block phases (non-archive clients). // separated header/block phases (non-archive clients).
func (bc *BlockChain) writeHeader(header *types.Header) error { func (bc *BlockChain) writeHeader(header *block.Header) error {
bc.wg.Add(1) bc.wg.Add(1)
defer bc.wg.Done() defer bc.wg.Done()
@ -1716,7 +1717,7 @@ func (bc *BlockChain) writeHeader(header *types.Header) error {
// CurrentHeader retrieves the current head header of the canonical chain. The // CurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the HeaderChain's internal cache. // header is retrieved from the HeaderChain's internal cache.
func (bc *BlockChain) CurrentHeader() *types.Header { func (bc *BlockChain) CurrentHeader() *block.Header {
return bc.hc.CurrentHeader() return bc.hc.CurrentHeader()
} }
@ -1734,13 +1735,13 @@ func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
// GetHeader retrieves a block header from the database by hash and number, // GetHeader retrieves a block header from the database by hash and number,
// caching it if found. // caching it if found.
func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header { func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *block.Header {
return bc.hc.GetHeader(hash, number) return bc.hc.GetHeader(hash, number)
} }
// GetHeaderByHash retrieves a block header from the database by hash, caching it if // GetHeaderByHash retrieves a block header from the database by hash, caching it if
// found. // found.
func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header { func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *block.Header {
return bc.hc.GetHeaderByHash(hash) return bc.hc.GetHeaderByHash(hash)
} }
@ -1770,7 +1771,7 @@ func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, max
// GetHeaderByNumber retrieves a block header from the database by number, // GetHeaderByNumber retrieves a block header from the database by number,
// caching it (associated with its hash) if found. // caching it (associated with its hash) if found.
func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header { func (bc *BlockChain) GetHeaderByNumber(number uint64) *block.Header {
return bc.hc.GetHeaderByNumber(number) return bc.hc.GetHeaderByNumber(number)
} }

@ -29,8 +29,8 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/rawdb" "github.com/harmony-one/harmony/core/rawdb"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/utils" "github.com/harmony-one/harmony/internal/utils"
) )
@ -44,7 +44,7 @@ type ChainIndexerBackend interface {
// Process crunches through the next header in the chain segment. The caller // Process crunches through the next header in the chain segment. The caller
// will ensure a sequential order of headers. // will ensure a sequential order of headers.
Process(ctx context.Context, header *types.Header) error Process(ctx context.Context, header *block.Header) error
// Commit finalizes the section metadata and stores it into the database. // Commit finalizes the section metadata and stores it into the database.
Commit() error Commit() error
@ -53,7 +53,7 @@ type ChainIndexerBackend interface {
// ChainIndexerChain interface is used for connecting the indexer to a blockchain // ChainIndexerChain interface is used for connecting the indexer to a blockchain
type ChainIndexerChain interface { type ChainIndexerChain interface {
// CurrentHeader retrieves the latest locally known header. // CurrentHeader retrieves the latest locally known header.
CurrentHeader() *types.Header CurrentHeader() *block.Header
// SubscribeChainHeadEvent subscribes to new head header notifications. // SubscribeChainHeadEvent subscribes to new head header notifications.
SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
@ -193,7 +193,7 @@ func (c *ChainIndexer) Close() error {
// eventLoop is a secondary - optional - event loop of the indexer which is only // eventLoop is a secondary - optional - event loop of the indexer which is only
// started for the outermost indexer to push chain head events into a processing // started for the outermost indexer to push chain head events into a processing
// queue. // queue.
func (c *ChainIndexer) eventLoop(currentHeader *types.Header, events chan ChainHeadEvent, sub event.Subscription) { func (c *ChainIndexer) eventLoop(currentHeader *block.Header, events chan ChainHeadEvent, sub event.Subscription) {
// Mark the chain indexer as active, requiring an additional teardown // Mark the chain indexer as active, requiring an additional teardown
atomic.StoreUint32(&c.active, 1) atomic.StoreUint32(&c.active, 1)

@ -24,6 +24,7 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/harmony-one/harmony/internal/params" "github.com/harmony-one/harmony/internal/params"
"github.com/harmony-one/harmony/block"
consensus_engine "github.com/harmony-one/harmony/consensus/engine" consensus_engine "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -37,13 +38,13 @@ type BlockGen struct {
i int i int
parent *types.Block parent *types.Block
chain []*types.Block chain []*types.Block
header *types.Header header *block.Header
statedb *state.DB statedb *state.DB
gasPool *GasPool gasPool *GasPool
txs []*types.Transaction txs []*types.Transaction
receipts []*types.Receipt receipts []*types.Receipt
uncles []*types.Header uncles []*block.Header
config *params.ChainConfig config *params.ChainConfig
engine consensus_engine.Engine engine consensus_engine.Engine
@ -129,7 +130,7 @@ func (b *BlockGen) TxNonce(addr common.Address) uint64 {
} }
// AddUncle adds an uncle header to the generated block. // AddUncle adds an uncle header to the generated block.
func (b *BlockGen) AddUncle(h *types.Header) { func (b *BlockGen) AddUncle(h *block.Header) {
b.uncles = append(b.uncles, h) b.uncles = append(b.uncles, h)
} }
@ -207,7 +208,7 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse
return blocks, receipts return blocks, receipts
} }
func makeHeader(chain consensus_engine.ChainReader, parent *types.Block, state *state.DB, engine consensus_engine.Engine) *types.Header { func makeHeader(chain consensus_engine.ChainReader, parent *types.Block, state *state.DB, engine consensus_engine.Engine) *block.Header {
var time *big.Int var time *big.Int
if parent.Time() == nil { if parent.Time() == nil {
time = big.NewInt(10) time = big.NewInt(10)
@ -215,7 +216,7 @@ func makeHeader(chain consensus_engine.ChainReader, parent *types.Block, state *
time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
} }
return &types.Header{ return &block.Header{
Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())), Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
ParentHash: parent.Hash(), ParentHash: parent.Hash(),
Coinbase: parent.Coinbase(), Coinbase: parent.Coinbase(),
@ -232,9 +233,9 @@ func makeHeader(chain consensus_engine.ChainReader, parent *types.Block, state *
} }
// makeHeaderChain creates a deterministic chain of headers rooted at parent. // makeHeaderChain creates a deterministic chain of headers rooted at parent.
func makeHeaderChain(parent *types.Header, n int, engine consensus_engine.Engine, db ethdb.Database, seed int) []*types.Header { func makeHeaderChain(parent *block.Header, n int, engine consensus_engine.Engine, db ethdb.Database, seed int) []*block.Header {
blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed) blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
headers := make([]*types.Header, len(blocks)) headers := make([]*block.Header, len(blocks))
for i, block := range blocks { for i, block := range blocks {
headers[i] = block.Header() headers[i] = block.Header()
} }
@ -259,9 +260,9 @@ func (cr *fakeChainReader) Config() *params.ChainConfig {
return cr.config return cr.config
} }
func (cr *fakeChainReader) CurrentHeader() *types.Header { return nil } func (cr *fakeChainReader) CurrentHeader() *block.Header { return nil }
func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header { return nil } func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *block.Header { return nil }
func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header { return nil } func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *block.Header { return nil }
func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil } func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *block.Header { return nil }
func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil } func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil }
func (cr *fakeChainReader) ReadShardState(epoch *big.Int) (shard.ShardState, error) { return nil, nil } func (cr *fakeChainReader) ReadShardState(epoch *big.Int) (shard.ShardState, error) { return nil, nil }

@ -4,18 +4,19 @@ import (
"math/big" "math/big"
"testing" "testing"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
shardingconfig "github.com/harmony-one/harmony/internal/configs/sharding" shardingconfig "github.com/harmony-one/harmony/internal/configs/sharding"
) )
func TestIsEpochBlock(t *testing.T) { func TestIsEpochBlock(t *testing.T) {
block1 := types.NewBlock(&types.Header{Number: big.NewInt(10)}, nil, nil, nil, nil) block1 := types.NewBlock(&block.Header{Number: big.NewInt(10)}, nil, nil, nil, nil)
block2 := types.NewBlock(&types.Header{Number: big.NewInt(0)}, nil, nil, nil, nil) block2 := types.NewBlock(&block.Header{Number: big.NewInt(0)}, nil, nil, nil, nil)
block3 := types.NewBlock(&types.Header{Number: big.NewInt(344064)}, nil, nil, nil, nil) block3 := types.NewBlock(&block.Header{Number: big.NewInt(344064)}, nil, nil, nil, nil)
block4 := types.NewBlock(&types.Header{Number: big.NewInt(77)}, nil, nil, nil, nil) block4 := types.NewBlock(&block.Header{Number: big.NewInt(77)}, nil, nil, nil, nil)
block5 := types.NewBlock(&types.Header{Number: big.NewInt(78)}, nil, nil, nil, nil) block5 := types.NewBlock(&block.Header{Number: big.NewInt(78)}, nil, nil, nil, nil)
block6 := types.NewBlock(&types.Header{Number: big.NewInt(188)}, nil, nil, nil, nil) block6 := types.NewBlock(&block.Header{Number: big.NewInt(188)}, nil, nil, nil, nil)
block7 := types.NewBlock(&types.Header{Number: big.NewInt(189)}, nil, nil, nil, nil) block7 := types.NewBlock(&block.Header{Number: big.NewInt(189)}, nil, nil, nil, nil)
tests := []struct { tests := []struct {
schedule shardingconfig.Schedule schedule shardingconfig.Schedule
block *types.Block block *types.Block

@ -20,6 +20,8 @@ import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/block"
consensus_engine "github.com/harmony-one/harmony/consensus/engine" consensus_engine "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/core/vm" "github.com/harmony-one/harmony/core/vm"
@ -32,11 +34,11 @@ type ChainContext interface {
Engine() consensus_engine.Engine Engine() consensus_engine.Engine
// GetHeader returns the hash corresponding to their hash. // GetHeader returns the hash corresponding to their hash.
GetHeader(common.Hash, uint64) *types.Header GetHeader(common.Hash, uint64) *block.Header
} }
// NewEVMContext creates a new context for use in the EVM. // NewEVMContext creates a new context for use in the EVM.
func NewEVMContext(msg Message, header *types.Header, chain ChainContext, author *common.Address) vm.Context { func NewEVMContext(msg Message, header *block.Header, chain ChainContext, author *common.Address) vm.Context {
// If we don't have an explicit author (i.e. not mining), extract from the header // If we don't have an explicit author (i.e. not mining), extract from the header
var beneficiary common.Address var beneficiary common.Address
if author == nil { if author == nil {
@ -59,7 +61,7 @@ func NewEVMContext(msg Message, header *types.Header, chain ChainContext, author
} }
// GetHashFn returns a GetHashFunc which retrieves header hashes by number // GetHashFn returns a GetHashFunc which retrieves header hashes by number
func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash { func GetHashFn(ref *block.Header, chain ChainContext) func(n uint64) common.Hash {
var cache map[uint64]common.Hash var cache map[uint64]common.Hash
return func(n uint64) common.Hash { return func(n uint64) common.Hash {

@ -32,6 +32,7 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/harmony/internal/params" "github.com/harmony-one/harmony/internal/params"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/rawdb" "github.com/harmony-one/harmony/core/rawdb"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -244,7 +245,7 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
utils.Logger().Error().Msg("failed to rlp-serialize genesis shard state") utils.Logger().Error().Msg("failed to rlp-serialize genesis shard state")
os.Exit(1) os.Exit(1)
} }
head := &types.Header{ head := &block.Header{
Number: new(big.Int).SetUint64(g.Number), Number: new(big.Int).SetUint64(g.Number),
Epoch: big.NewInt(0), Epoch: big.NewInt(0),
ShardID: g.ShardID, ShardID: g.ShardID,

@ -31,6 +31,7 @@ import (
"github.com/harmony-one/harmony/internal/params" "github.com/harmony-one/harmony/internal/params"
lru "github.com/hashicorp/golang-lru" lru "github.com/hashicorp/golang-lru"
"github.com/harmony-one/harmony/block"
consensus_engine "github.com/harmony-one/harmony/consensus/engine" consensus_engine "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/core/rawdb" "github.com/harmony-one/harmony/core/rawdb"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -52,7 +53,7 @@ type HeaderChain struct {
config *params.ChainConfig config *params.ChainConfig
chainDb ethdb.Database chainDb ethdb.Database
genesisHeader *types.Header genesisHeader *block.Header
currentHeader atomic.Value // Current head of the header chain (may be above the block chain!) currentHeader atomic.Value // Current head of the header chain (may be above the block chain!)
currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time) currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time)
@ -132,7 +133,7 @@ func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64 {
// without the real blocks. Hence, writing headers directly should only be done // without the real blocks. Hence, writing headers directly should only be done
// in two scenarios: pure-header mode of operation (light clients), or properly // in two scenarios: pure-header mode of operation (light clients), or properly
// separated header/block phases (non-archive clients). // separated header/block phases (non-archive clients).
func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) { func (hc *HeaderChain) WriteHeader(header *block.Header) (status WriteStatus, err error) {
// Cache some values to prevent constant recalculation // Cache some values to prevent constant recalculation
var ( var (
hash = header.Hash() hash = header.Hash()
@ -199,10 +200,10 @@ func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, er
// processed and light chain events sent, while in a BlockChain this is not // processed and light chain events sent, while in a BlockChain this is not
// necessary since chain events are sent after inserting blocks. Second, the // necessary since chain events are sent after inserting blocks. Second, the
// header writes should be protected by the parent chain mutex individually. // header writes should be protected by the parent chain mutex individually.
type WhCallback func(*types.Header) error type WhCallback func(*block.Header) error
// ValidateHeaderChain validates header chain. // ValidateHeaderChain validates header chain.
func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) { func (hc *HeaderChain) ValidateHeaderChain(chain []*block.Header, checkFreq int) (int, error) {
// Do a sanity check that the provided chain is actually ordered and linked // Do a sanity check that the provided chain is actually ordered and linked
for i := 1; i < len(chain); i++ { for i := 1; i < len(chain); i++ {
if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() { if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
@ -259,7 +260,7 @@ func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int)
// should be done or not. The reason behind the optional check is because some // should be done or not. The reason behind the optional check is because some
// of the header retrieval mechanisms already need to verfy nonces, as well as // of the header retrieval mechanisms already need to verfy nonces, as well as
// because nonces can be verified sparsely, not needing to check each. // because nonces can be verified sparsely, not needing to check each.
func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) { func (hc *HeaderChain) InsertHeaderChain(chain []*block.Header, writeHeader WhCallback, start time.Time) (int, error) {
// Collect some import statistics to report on // Collect some import statistics to report on
stats := struct{ processed, ignored int }{} stats := struct{ processed, ignored int }{}
// All headers passed verification, import them into the database // All headers passed verification, import them into the database
@ -395,10 +396,10 @@ func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) err
// GetHeader retrieves a block header from the database by hash and number, // GetHeader retrieves a block header from the database by hash and number,
// caching it if found. // caching it if found.
func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header { func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *block.Header {
// Short circuit if the header's already in the cache, retrieve otherwise // Short circuit if the header's already in the cache, retrieve otherwise
if header, ok := hc.headerCache.Get(hash); ok { if header, ok := hc.headerCache.Get(hash); ok {
return header.(*types.Header) return header.(*block.Header)
} }
header := rawdb.ReadHeader(hc.chainDb, hash, number) header := rawdb.ReadHeader(hc.chainDb, hash, number)
if header == nil { if header == nil {
@ -411,7 +412,7 @@ func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header
// GetHeaderByHash retrieves a block header from the database by hash, caching it if // GetHeaderByHash retrieves a block header from the database by hash, caching it if
// found. // found.
func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header { func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *block.Header {
number := hc.GetBlockNumber(hash) number := hc.GetBlockNumber(hash)
if number == nil { if number == nil {
return nil return nil
@ -429,7 +430,7 @@ func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
// GetHeaderByNumber retrieves a block header from the database by number, // GetHeaderByNumber retrieves a block header from the database by number,
// caching it (associated with its hash) if found. // caching it (associated with its hash) if found.
func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header { func (hc *HeaderChain) GetHeaderByNumber(number uint64) *block.Header {
hash := rawdb.ReadCanonicalHash(hc.chainDb, number) hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
if hash == (common.Hash{}) { if hash == (common.Hash{}) {
return nil return nil
@ -439,12 +440,12 @@ func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
// CurrentHeader retrieves the current head header of the canonical chain. The // CurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the HeaderChain's internal cache. // header is retrieved from the HeaderChain's internal cache.
func (hc *HeaderChain) CurrentHeader() *types.Header { func (hc *HeaderChain) CurrentHeader() *block.Header {
return hc.currentHeader.Load().(*types.Header) return hc.currentHeader.Load().(*block.Header)
} }
// SetCurrentHeader sets the current head header of the canonical chain. // SetCurrentHeader sets the current head header of the canonical chain.
func (hc *HeaderChain) SetCurrentHeader(head *types.Header) { func (hc *HeaderChain) SetCurrentHeader(head *block.Header) {
rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash()) rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash())
hc.currentHeader.Store(head) hc.currentHeader.Store(head)
@ -495,7 +496,7 @@ func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
} }
// SetGenesis sets a new genesis block header for the chain // SetGenesis sets a new genesis block header for the chain
func (hc *HeaderChain) SetGenesis(head *types.Header) { func (hc *HeaderChain) SetGenesis(head *block.Header) {
hc.genesisHeader = head hc.genesisHeader = head
} }

@ -24,6 +24,7 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/ctxerror" "github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils" "github.com/harmony-one/harmony/internal/utils"
@ -151,12 +152,12 @@ func HasHeader(db DatabaseReader, hash common.Hash, number uint64) bool {
} }
// ReadHeader retrieves the block header corresponding to the hash. // ReadHeader retrieves the block header corresponding to the hash.
func ReadHeader(db DatabaseReader, hash common.Hash, number uint64) *types.Header { func ReadHeader(db DatabaseReader, hash common.Hash, number uint64) *block.Header {
data := ReadHeaderRLP(db, hash, number) data := ReadHeaderRLP(db, hash, number)
if len(data) == 0 { if len(data) == 0 {
return nil return nil
} }
header := new(types.Header) header := new(block.Header)
if err := rlp.Decode(bytes.NewReader(data), header); err != nil { if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
utils.Logger().Error().Err(err).Str("hash", hash.Hex()).Msg("Invalid block header RLP") utils.Logger().Error().Err(err).Str("hash", hash.Hex()).Msg("Invalid block header RLP")
return nil return nil
@ -166,7 +167,7 @@ func ReadHeader(db DatabaseReader, hash common.Hash, number uint64) *types.Heade
// WriteHeader stores a block header into the database and also stores the hash- // WriteHeader stores a block header into the database and also stores the hash-
// to-number mapping. // to-number mapping.
func WriteHeader(db DatabaseWriter, header *types.Header) { func WriteHeader(db DatabaseWriter, header *block.Header) {
// Write the hash -> number mapping // Write the hash -> number mapping
var ( var (
hash = header.Hash() hash = header.Hash()
@ -384,7 +385,7 @@ func DeleteBlock(db DatabaseDeleter, hash common.Hash, number uint64) {
} }
// FindCommonAncestor returns the last common ancestor of two block headers // FindCommonAncestor returns the last common ancestor of two block headers
func FindCommonAncestor(db DatabaseReader, a, b *types.Header) *types.Header { func FindCommonAncestor(db DatabaseReader, a, b *block.Header) *block.Header {
for bn := b.Number.Uint64(); a.Number.Uint64() > bn; { for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1) a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
if a == nil { if a == nil {

@ -27,10 +27,12 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
mock "github.com/harmony-one/harmony/core/rawdb/mock"
"github.com/harmony-one/harmony/core/types"
"github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb"
"golang.org/x/crypto/sha3" "golang.org/x/crypto/sha3"
"github.com/harmony-one/harmony/block"
mock "github.com/harmony-one/harmony/core/rawdb/mock"
"github.com/harmony-one/harmony/core/types"
) )
// Tests block header storage and retrieval operations. // Tests block header storage and retrieval operations.
@ -38,7 +40,7 @@ func TestHeaderStorage(t *testing.T) {
db := ethdb.NewMemDatabase() db := ethdb.NewMemDatabase()
// Create a test header to move around the database and make sure it's really new // Create a test header to move around the database and make sure it's really new
header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")} header := &block.Header{Number: big.NewInt(42), Extra: []byte("test header")}
if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil { if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
t.Fatalf("Non existent header returned: %v", entry) t.Fatalf("Non existent header returned: %v", entry)
} }
@ -71,7 +73,7 @@ func TestBodyStorage(t *testing.T) {
db := ethdb.NewMemDatabase() db := ethdb.NewMemDatabase()
// Create a test body to move around the database and make sure it's really new // Create a test body to move around the database and make sure it's really new
body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}} body := &types.Body{Uncles: []*block.Header{{Extra: []byte("test header")}}}
hasher := sha3.NewLegacyKeccak256() hasher := sha3.NewLegacyKeccak256()
rlp.Encode(hasher, body) rlp.Encode(hasher, body)
@ -109,7 +111,7 @@ func TestBlockStorage(t *testing.T) {
db := ethdb.NewMemDatabase() db := ethdb.NewMemDatabase()
// Create a test block to move around the database and make sure it's really new // Create a test block to move around the database and make sure it's really new
block := types.NewBlockWithHeader(&types.Header{ block := types.NewBlockWithHeader(&block.Header{
Extra: []byte("test block"), Extra: []byte("test block"),
TxHash: types.EmptyRootHash, TxHash: types.EmptyRootHash,
ReceiptHash: types.EmptyRootHash, ReceiptHash: types.EmptyRootHash,
@ -169,7 +171,7 @@ func TestBlockStorage(t *testing.T) {
// Tests that partial block contents don't get reassembled into full blocks. // Tests that partial block contents don't get reassembled into full blocks.
func TestPartialBlockStorage(t *testing.T) { func TestPartialBlockStorage(t *testing.T) {
db := ethdb.NewMemDatabase() db := ethdb.NewMemDatabase()
block := types.NewBlockWithHeader(&types.Header{ block := types.NewBlockWithHeader(&block.Header{
Extra: []byte("test block"), Extra: []byte("test block"),
TxHash: types.EmptyRootHash, TxHash: types.EmptyRootHash,
ReceiptHash: types.EmptyRootHash, ReceiptHash: types.EmptyRootHash,
@ -249,9 +251,9 @@ func TestCanonicalMappingStorage(t *testing.T) {
func TestHeadStorage(t *testing.T) { func TestHeadStorage(t *testing.T) {
db := ethdb.NewMemDatabase() db := ethdb.NewMemDatabase()
blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")}) blockHead := types.NewBlockWithHeader(&block.Header{Extra: []byte("test block header")})
blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")}) blockFull := types.NewBlockWithHeader(&block.Header{Extra: []byte("test block full")})
blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")}) blockFast := types.NewBlockWithHeader(&block.Header{Extra: []byte("test block fast")})
// Check that no head entries are in a pristine database // Check that no head entries are in a pristine database
if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) { if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {

@ -22,6 +22,8 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
block2 "github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
) )
@ -34,7 +36,7 @@ func TestLookupStorage(t *testing.T) {
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33}) tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3} txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, nil, nil) block := types.NewBlock(&block2.Header{Number: big.NewInt(314)}, txs, nil, nil, nil)
// Check that no transactions entries are in a pristine database // Check that no transactions entries are in a pristine database
for i, tx := range txs { for i, tx := range txs {

@ -21,6 +21,8 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/harmony-one/harmony/block"
consensus_engine "github.com/harmony-one/harmony/consensus/engine" consensus_engine "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -101,7 +103,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.DB, cfg vm.C
} }
// return true if it is valid // return true if it is valid
func getTransactionType(header *types.Header, tx *types.Transaction) types.TransactionType { func getTransactionType(header *block.Header, tx *types.Transaction) types.TransactionType {
if tx.ShardID() == tx.ToShardID() && header.ShardID == tx.ShardID() { if tx.ShardID() == tx.ToShardID() && header.ShardID == tx.ShardID() {
return types.SameShardTx return types.SameShardTx
} }
@ -117,7 +119,7 @@ func getTransactionType(header *types.Header, tx *types.Transaction) types.Trans
// and uses the input parameters for its environment. It returns the receipt // and uses the input parameters for its environment. It returns the receipt
// for the transaction, gas used and an error if the transaction failed, // for the transaction, gas used and an error if the transaction failed,
// indicating the block was invalid. // indicating the block was invalid.
func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.DB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, *types.CXReceipt, uint64, error) { func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.DB, header *block.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, *types.CXReceipt, uint64, error) {
txType := getTransactionType(header, tx) txType := getTransactionType(header, tx)
if txType == types.InvalidTx { if txType == types.InvalidTx {
return nil, nil, 0, fmt.Errorf("Invalid Transaction Type") return nil, nil, 0, fmt.Errorf("Invalid Transaction Type")
@ -172,7 +174,7 @@ func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *commo
} }
// ApplyIncomingReceipt will add amount into ToAddress in the receipt // ApplyIncomingReceipt will add amount into ToAddress in the receipt
func ApplyIncomingReceipt(config *params.ChainConfig, db *state.DB, header *types.Header, cxp *types.CXReceiptsProof) error { func ApplyIncomingReceipt(config *params.ChainConfig, db *state.DB, header *block.Header, cxp *types.CXReceiptsProof) error {
if cxp == nil { if cxp == nil {
return nil return nil
} }

@ -32,6 +32,7 @@ import (
"github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/metrics"
"github.com/harmony-one/harmony/internal/params" "github.com/harmony-one/harmony/internal/params"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/utils" "github.com/harmony-one/harmony/internal/utils"
@ -360,7 +361,7 @@ func (pool *TxPool) loop() {
// lockedReset is a wrapper around reset to allow calling it in a thread safe // lockedReset is a wrapper around reset to allow calling it in a thread safe
// manner. This method is only ever used in the tester! // manner. This method is only ever used in the tester!
func (pool *TxPool) lockedReset(oldHead, newHead *types.Header) { func (pool *TxPool) lockedReset(oldHead, newHead *block.Header) {
pool.mu.Lock() pool.mu.Lock()
defer pool.mu.Unlock() defer pool.mu.Unlock()
@ -369,7 +370,7 @@ func (pool *TxPool) lockedReset(oldHead, newHead *types.Header) {
// reset retrieves the current state of the blockchain and ensures the content // reset retrieves the current state of the blockchain and ensures the content
// of the transaction pool is valid with regard to the chain state. // of the transaction pool is valid with regard to the chain state.
func (pool *TxPool) reset(oldHead, newHead *types.Header) { func (pool *TxPool) reset(oldHead, newHead *block.Header) {
// If we're reorging an old state, reinject all dropped transactions // If we're reorging an old state, reinject all dropped transactions
var reinject types.Transactions var reinject types.Transactions

@ -30,6 +30,8 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/common/denominations" "github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -52,7 +54,7 @@ type testBlockChain struct {
} }
func (bc *testBlockChain) CurrentBlock() *types.Block { func (bc *testBlockChain) CurrentBlock() *types.Block {
return types.NewBlock(&types.Header{ return types.NewBlock(&block.Header{
GasLimit: bc.gasLimit, GasLimit: bc.gasLimit,
}, nil, nil, nil, nil) }, nil, nil, nil, nil)
} }

@ -31,6 +31,7 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/crypto/hash" "github.com/harmony-one/harmony/crypto/hash"
"github.com/harmony-one/harmony/internal/utils" "github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard" "github.com/harmony-one/harmony/shard"
@ -73,14 +74,14 @@ func (n *BlockNonce) UnmarshalText(input []byte) error {
// a block's data contents (transactions and uncles) together. // a block's data contents (transactions and uncles) together.
type Body struct { type Body struct {
Transactions []*Transaction Transactions []*Transaction
Uncles []*Header Uncles []*block.Header
IncomingReceipts CXReceiptsProofs IncomingReceipts CXReceiptsProofs
} }
// Block represents an entire block in the Ethereum blockchain. // Block represents an entire block in the Ethereum blockchain.
type Block struct { type Block struct {
header *Header header *block.Header
uncles []*Header uncles []*block.Header
transactions Transactions transactions Transactions
incomingReceipts CXReceiptsProofs incomingReceipts CXReceiptsProofs
@ -126,18 +127,18 @@ type StorageBlock Block
// "external" block encoding. used for eth protocol, etc. // "external" block encoding. used for eth protocol, etc.
type extblock struct { type extblock struct {
Header *Header Header *block.Header
Txs []*Transaction Txs []*Transaction
Uncles []*Header Uncles []*block.Header
IncomingReceipts CXReceiptsProofs IncomingReceipts CXReceiptsProofs
} }
// [deprecated by eth/63] // [deprecated by eth/63]
// "storage" block encoding. used for database. // "storage" block encoding. used for database.
type storageblock struct { type storageblock struct {
Header *Header Header *block.Header
Txs []*Transaction Txs []*Transaction
Uncles []*Header Uncles []*block.Header
TD *big.Int TD *big.Int
} }
@ -148,7 +149,7 @@ type storageblock struct {
// The values of TxHash, UncleHash, ReceiptHash and Bloom in header // The values of TxHash, UncleHash, ReceiptHash and Bloom in header
// are ignored and set to values derived from the given txs, // are ignored and set to values derived from the given txs,
// and receipts. // and receipts.
func NewBlock(header *Header, txs []*Transaction, receipts []*Receipt, outcxs []*CXReceipt, incxs []*CXReceiptsProof) *Block { func NewBlock(header *block.Header, txs []*Transaction, receipts []*Receipt, outcxs []*CXReceipt, incxs []*CXReceiptsProof) *Block {
b := &Block{header: CopyHeader(header)} b := &Block{header: CopyHeader(header)}
// TODO: panic if len(txs) != len(receipts) // TODO: panic if len(txs) != len(receipts)
@ -183,13 +184,13 @@ func NewBlock(header *Header, txs []*Transaction, receipts []*Receipt, outcxs []
// NewBlockWithHeader creates a block with the given header data. The // NewBlockWithHeader creates a block with the given header data. The
// header data is copied, changes to header and to the field values // header data is copied, changes to header and to the field values
// will not affect the block. // will not affect the block.
func NewBlockWithHeader(header *Header) *Block { func NewBlockWithHeader(header *block.Header) *Block {
return &Block{header: CopyHeader(header)} return &Block{header: CopyHeader(header)}
} }
// CopyHeader creates a deep copy of a block header to prevent side effects from // CopyHeader creates a deep copy of a block header to prevent side effects from
// modifying a header variable. // modifying a header variable.
func CopyHeader(h *Header) *Header { func CopyHeader(h *block.Header) *block.Header {
// TODO: update with new fields // TODO: update with new fields
cpy := *h cpy := *h
if cpy.Time = new(big.Int); h.Time != nil { if cpy.Time = new(big.Int); h.Time != nil {
@ -265,7 +266,7 @@ func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error {
} }
// Uncles return uncles. // Uncles return uncles.
func (b *Block) Uncles() []*Header { func (b *Block) Uncles() []*block.Header {
return b.uncles return b.uncles
} }
@ -338,7 +339,7 @@ func (b *Block) OutgoingReceiptHash() common.Hash { return b.header.OutgoingRece
func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) } func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) }
// Header returns a copy of Header. // Header returns a copy of Header.
func (b *Block) Header() *Header { return CopyHeader(b.header) } func (b *Block) Header() *block.Header { return CopyHeader(b.header) }
// Body returns the non-header content of the block. // Body returns the non-header content of the block.
func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles, b.incomingReceipts} } func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles, b.incomingReceipts} }
@ -369,13 +370,13 @@ func (c *writeCounter) Write(b []byte) (int, error) {
} }
// CalcUncleHash returns rlp hash of uncles. // CalcUncleHash returns rlp hash of uncles.
func CalcUncleHash(uncles []*Header) common.Hash { func CalcUncleHash(uncles []*block.Header) common.Hash {
return hash.FromRLP(uncles) return hash.FromRLP(uncles)
} }
// WithSeal returns a new block with the data from b but the header replaced with // WithSeal returns a new block with the data from b but the header replaced with
// the sealed one. // the sealed one.
func (b *Block) WithSeal(header *Header) *Block { func (b *Block) WithSeal(header *block.Header) *Block {
cpy := *header cpy := *header
return &Block{ return &Block{
@ -386,11 +387,11 @@ func (b *Block) WithSeal(header *Header) *Block {
} }
// WithBody returns a new block with the given transaction and uncle contents. // WithBody returns a new block with the given transaction and uncle contents.
func (b *Block) WithBody(transactions []*Transaction, uncles []*Header, incomingReceipts CXReceiptsProofs) *Block { func (b *Block) WithBody(transactions []*Transaction, uncles []*block.Header, incomingReceipts CXReceiptsProofs) *Block {
block := &Block{ block := &Block{
header: CopyHeader(b.header), header: CopyHeader(b.header),
transactions: make([]*Transaction, len(transactions)), transactions: make([]*Transaction, len(transactions)),
uncles: make([]*Header, len(uncles)), uncles: make([]*block.Header, len(uncles)),
incomingReceipts: make([]*CXReceiptsProof, len(incomingReceipts)), incomingReceipts: make([]*CXReceiptsProof, len(incomingReceipts)),
} }
copy(block.transactions, transactions) copy(block.transactions, transactions)

@ -20,6 +20,8 @@ package types
import ( import (
"bytes" "bytes"
"testing" "testing"
"github.com/harmony-one/harmony/block"
) )
var ( var (
@ -94,7 +96,7 @@ func TestBlock_SetLastCommitSig(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
b := &Block{header: &Header{}} b := &Block{header: &block.Header{}}
b.SetLastCommitSig(tt.sig, tt.signers) b.SetLastCommitSig(tt.sig, tt.signers)
if !bytes.Equal(tt.sig, b.header.LastCommitSignature[:]) { if !bytes.Equal(tt.sig, b.header.LastCommitSignature[:]) {
t.Errorf("signature mismatch: expected %+v, actual %+v", t.Errorf("signature mismatch: expected %+v, actual %+v",

@ -7,20 +7,22 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/block"
) )
// CrossLink is only used on beacon chain to store the hash links from other shards // CrossLink is only used on beacon chain to store the hash links from other shards
type CrossLink struct { type CrossLink struct {
ChainHeader *Header ChainHeader *block.Header
} }
// NewCrossLink returns a new cross link object // NewCrossLink returns a new cross link object
func NewCrossLink(header *Header) CrossLink { func NewCrossLink(header *block.Header) CrossLink {
return CrossLink{header} return CrossLink{header}
} }
// Header returns header // Header returns header
func (cl CrossLink) Header() *Header { func (cl CrossLink) Header() *block.Header {
return cl.ChainHeader return cl.ChainHeader
} }

@ -7,6 +7,8 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/bls/ffi/go/bls" "github.com/harmony-one/bls/ffi/go/bls"
block2 "github.com/harmony-one/harmony/block"
bls2 "github.com/harmony-one/harmony/crypto/bls" bls2 "github.com/harmony-one/harmony/crypto/bls"
msg_pb "github.com/harmony-one/harmony/api/proto/message" msg_pb "github.com/harmony-one/harmony/api/proto/message"
@ -126,7 +128,7 @@ func TestVrf(test *testing.T) {
tx1 := types.NewTransaction(1, common.BytesToAddress([]byte{0x11}), 0, big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11}) tx1 := types.NewTransaction(1, common.BytesToAddress([]byte{0x11}), 0, big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
txs := []*types.Transaction{tx1} txs := []*types.Transaction{tx1}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, nil, nil) block := types.NewBlock(&block2.Header{Number: big.NewInt(314)}, txs, nil, nil, nil)
blockHash := block.Hash() blockHash := block.Hash()
dRand.vrf(blockHash) dRand.vrf(blockHash)

@ -12,8 +12,10 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/harmony-one/harmony/accounts" "github.com/harmony-one/harmony/accounts"
"github.com/harmony-one/harmony/api/proto" "github.com/harmony-one/harmony/api/proto"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -55,7 +57,7 @@ func (b *APIBackend) BlockByNumber(ctx context.Context, blockNr rpc.BlockNumber)
} }
// StateAndHeaderByNumber ... // StateAndHeaderByNumber ...
func (b *APIBackend) StateAndHeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*state.DB, *types.Header, error) { func (b *APIBackend) StateAndHeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*state.DB, *block.Header, error) {
// Pending state is only known by the miner // Pending state is only known by the miner
if blockNr == rpc.PendingBlockNumber { if blockNr == rpc.PendingBlockNumber {
return nil, nil, errors.New("not implemented") return nil, nil, errors.New("not implemented")
@ -70,7 +72,7 @@ func (b *APIBackend) StateAndHeaderByNumber(ctx context.Context, blockNr rpc.Blo
} }
// HeaderByNumber ... // HeaderByNumber ...
func (b *APIBackend) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) { func (b *APIBackend) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*block.Header, error) {
// Pending block is only known by the miner // Pending block is only known by the miner
if blockNr == rpc.PendingBlockNumber { if blockNr == rpc.PendingBlockNumber {
return nil, errors.New("not implemented") return nil, errors.New("not implemented")
@ -139,7 +141,7 @@ func (b *APIBackend) GetLogs(ctx context.Context, blockHash common.Hash) ([][]*t
} }
// HeaderByHash ... // HeaderByHash ...
func (b *APIBackend) HeaderByHash(ctx context.Context, blockHash common.Hash) (*types.Header, error) { func (b *APIBackend) HeaderByHash(ctx context.Context, blockHash common.Hash) (*block.Header, error) {
// TODO(ricl): implement // TODO(ricl): implement
return nil, nil return nil, nil
} }
@ -211,7 +213,7 @@ func (b *APIBackend) NetVersion() uint64 {
} }
// GetEVM returns a new EVM entity // GetEVM returns a new EVM entity
func (b *APIBackend) GetEVM(ctx context.Context, msg core.Message, state *state.DB, header *types.Header) (*vm.EVM, func() error, error) { func (b *APIBackend) GetEVM(ctx context.Context, msg core.Message, state *state.DB, header *block.Header) (*vm.EVM, func() error, error) {
// TODO(ricl): The code is borrowed from [go-ethereum](https://github.com/ethereum/go-ethereum/blob/40cdcf8c47ff094775aca08fd5d94051f9cf1dbb/les/api_backend.go#L114) // TODO(ricl): The code is borrowed from [go-ethereum](https://github.com/ethereum/go-ethereum/blob/40cdcf8c47ff094775aca08fd5d94051f9cf1dbb/les/api_backend.go#L114)
// [question](https://ethereum.stackexchange.com/q/72977/54923) // [question](https://ethereum.stackexchange.com/q/72977/54923)
// Might need to reconsider the SetBalance behavior // Might need to reconsider the SetBalance behavior

@ -25,6 +25,8 @@ import (
"github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/bloombits"
"github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
) )
@ -117,7 +119,7 @@ func (b *BloomIndexer) Reset(ctx context.Context, section uint64, lastSectionHea
// Process implements core.ChainIndexerBackend, adding a new header's bloom into // Process implements core.ChainIndexerBackend, adding a new header's bloom into
// the index. // the index.
func (b *BloomIndexer) Process(ctx context.Context, header *types.Header) error { func (b *BloomIndexer) Process(ctx context.Context, header *block.Header) error {
b.gen.AddBloom(uint(header.Number.Uint64()-b.section*b.size), header.Bloom) b.gen.AddBloom(uint(header.Number.Uint64()-b.section*b.size), header.Bloom)
b.head = header.Hash() b.head = header.Hash()
return nil return nil

@ -6,10 +6,12 @@ import (
"fmt" "fmt"
"math/big" "math/big"
ethereum "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
) )
@ -96,7 +98,7 @@ func (c *Client) getBlock(ctx context.Context, method string, args ...interface{
return nil, ethereum.NotFound return nil, ethereum.NotFound
} }
// Decode header and transactions. // Decode header and transactions.
var head *types.Header var head *block.Header
var body rpcBlock var body rpcBlock
if err := json.Unmarshal(raw, &head); err != nil { if err := json.Unmarshal(raw, &head); err != nil {
return nil, err return nil, err
@ -119,7 +121,7 @@ func (c *Client) getBlock(ctx context.Context, method string, args ...interface{
} }
txs[i] = tx.tx txs[i] = tx.tx
} }
return types.NewBlockWithHeader(head).WithBody(txs, []*types.Header{}, nil), nil return types.NewBlockWithHeader(head).WithBody(txs, []*block.Header{}, nil), nil
} }
func toBlockNumArg(number *big.Int) string { func toBlockNumArg(number *big.Int) string {

@ -9,6 +9,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/crypto/sha3" "golang.org/x/crypto/sha3"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/consensus/engine" "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -22,7 +23,7 @@ type engineImpl struct{}
var Engine = &engineImpl{} var Engine = &engineImpl{}
// SealHash returns the hash of a block prior to it being sealed. // SealHash returns the hash of a block prior to it being sealed.
func (e *engineImpl) SealHash(header *types.Header) (hash common.Hash) { func (e *engineImpl) SealHash(header *block.Header) (hash common.Hash) {
hasher := sha3.NewLegacyKeccak256() hasher := sha3.NewLegacyKeccak256()
// TODO: update with new fields // TODO: update with new fields
if err := rlp.Encode(hasher, []interface{}{ if err := rlp.Encode(hasher, []interface{}{
@ -51,20 +52,20 @@ func (e *engineImpl) Seal(chain engine.ChainReader, block *types.Block, results
} }
// Author returns the author of the block header. // Author returns the author of the block header.
func (e *engineImpl) Author(header *types.Header) (common.Address, error) { func (e *engineImpl) Author(header *block.Header) (common.Address, error) {
// TODO: implement this // TODO: implement this
return common.Address{}, nil return common.Address{}, nil
} }
// Prepare is to prepare ... // Prepare is to prepare ...
// TODO(RJ): fix it. // TODO(RJ): fix it.
func (e *engineImpl) Prepare(chain engine.ChainReader, header *types.Header) error { func (e *engineImpl) Prepare(chain engine.ChainReader, header *block.Header) error {
// TODO: implement prepare method // TODO: implement prepare method
return nil return nil
} }
// VerifyHeader checks whether a header conforms to the consensus rules of the bft engine. // VerifyHeader checks whether a header conforms to the consensus rules of the bft engine.
func (e *engineImpl) VerifyHeader(chain engine.ChainReader, header *types.Header, seal bool) error { func (e *engineImpl) VerifyHeader(chain engine.ChainReader, header *block.Header, seal bool) error {
parentHeader := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1) parentHeader := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
if parentHeader == nil { if parentHeader == nil {
return engine.ErrUnknownAncestor return engine.ErrUnknownAncestor
@ -80,7 +81,7 @@ func (e *engineImpl) VerifyHeader(chain engine.ChainReader, header *types.Header
// VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
// concurrently. The method returns a quit channel to abort the operations and // concurrently. The method returns a quit channel to abort the operations and
// a results channel to retrieve the async verifications. // a results channel to retrieve the async verifications.
func (e *engineImpl) VerifyHeaders(chain engine.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) { func (e *engineImpl) VerifyHeaders(chain engine.ChainReader, headers []*block.Header, seals []bool) (chan<- struct{}, <-chan error) {
abort, results := make(chan struct{}), make(chan error, len(headers)) abort, results := make(chan struct{}), make(chan error, len(headers))
for i := 0; i < len(headers); i++ { for i := 0; i < len(headers); i++ {
results <- nil results <- nil
@ -89,7 +90,7 @@ func (e *engineImpl) VerifyHeaders(chain engine.ChainReader, headers []*types.He
} }
// retrievePublicKeysFromLastBlock finds the public keys of last block's committee // retrievePublicKeysFromLastBlock finds the public keys of last block's committee
func retrievePublicKeysFromLastBlock(bc engine.ChainReader, header *types.Header) ([]*bls.PublicKey, error) { func retrievePublicKeysFromLastBlock(bc engine.ChainReader, header *block.Header) ([]*bls.PublicKey, error) {
parentHeader := bc.GetHeaderByHash(header.ParentHash) parentHeader := bc.GetHeaderByHash(header.ParentHash)
if parentHeader == nil { if parentHeader == nil {
return nil, ctxerror.New("cannot find parent block header in DB", return nil, ctxerror.New("cannot find parent block header in DB",
@ -123,7 +124,7 @@ func retrievePublicKeysFromLastBlock(bc engine.ChainReader, header *types.Header
// VerifySeal implements Engine, checking whether the given block satisfies // VerifySeal implements Engine, checking whether the given block satisfies
// the PoS difficulty requirements, i.e. >= 2f+1 valid signatures from the committee // the PoS difficulty requirements, i.e. >= 2f+1 valid signatures from the committee
func (e *engineImpl) VerifySeal(chain engine.ChainReader, header *types.Header) error { func (e *engineImpl) VerifySeal(chain engine.ChainReader, header *block.Header) error {
if chain.CurrentHeader().Number.Uint64() <= uint64(1) { if chain.CurrentHeader().Number.Uint64() <= uint64(1) {
return nil return nil
} }
@ -159,7 +160,7 @@ func (e *engineImpl) VerifySeal(chain engine.ChainReader, header *types.Header)
// Finalize implements Engine, accumulating the block rewards, // Finalize implements Engine, accumulating the block rewards,
// setting the final state and assembling the block. // setting the final state and assembling the block.
func (e *engineImpl) Finalize(chain engine.ChainReader, header *types.Header, state *state.DB, txs []*types.Transaction, receipts []*types.Receipt, outcxs []*types.CXReceipt, incxs []*types.CXReceiptsProof) (*types.Block, error) { func (e *engineImpl) Finalize(chain engine.ChainReader, header *block.Header, state *state.DB, txs []*types.Transaction, receipts []*types.Receipt, outcxs []*types.CXReceipt, incxs []*types.CXReceiptsProof) (*types.Block, error) {
// Accumulate any block and uncle rewards and commit the final state root // Accumulate any block and uncle rewards and commit the final state root
// Header seems complete, assemble into a block and return // Header seems complete, assemble into a block and return
if err := AccumulateRewards(chain, state, header); err != nil { if err := AccumulateRewards(chain, state, header); err != nil {
@ -171,7 +172,7 @@ func (e *engineImpl) Finalize(chain engine.ChainReader, header *types.Header, st
// QuorumForBlock returns the quorum for the given block header. // QuorumForBlock returns the quorum for the given block header.
func QuorumForBlock( func QuorumForBlock(
chain engine.ChainReader, h *types.Header, chain engine.ChainReader, h *block.Header,
) (quorum int, err error) { ) (quorum int, err error) {
ss, err := chain.ReadShardState(h.Epoch) ss, err := chain.ReadShardState(h.Epoch)
if err != nil { if err != nil {

@ -6,10 +6,10 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/bls/ffi/go/bls" "github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/common/denominations" "github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/consensus/engine" "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
bls2 "github.com/harmony-one/harmony/crypto/bls" bls2 "github.com/harmony-one/harmony/crypto/bls"
common2 "github.com/harmony-one/harmony/internal/common" common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/ctxerror" "github.com/harmony-one/harmony/internal/ctxerror"
@ -23,7 +23,7 @@ var BlockReward = new(big.Int).Mul(big.NewInt(24), big.NewInt(denominations.One)
// reward. The total reward consists of the static block reward and rewards for // reward. The total reward consists of the static block reward and rewards for
// included uncles. The coinbase of each uncle block is also rewarded. // included uncles. The coinbase of each uncle block is also rewarded.
func AccumulateRewards( func AccumulateRewards(
bc engine.ChainReader, state *state.DB, header *types.Header, bc engine.ChainReader, state *state.DB, header *block.Header,
) error { ) error {
blockNum := header.Number.Uint64() blockNum := header.Number.Uint64()
if blockNum == 0 { if blockNum == 0 {

@ -9,7 +9,9 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/harmony-one/harmony/accounts" "github.com/harmony-one/harmony/accounts"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -36,13 +38,13 @@ type Backend interface {
// BlockChain API // BlockChain API
// SetHead(number uint64) // SetHead(number uint64)
HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*block.Header, error)
BlockByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Block, error) BlockByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Block, error)
StateAndHeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*state.DB, *types.Header, error) StateAndHeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*state.DB, *block.Header, error)
GetBlock(ctx context.Context, blockHash common.Hash) (*types.Block, error) GetBlock(ctx context.Context, blockHash common.Hash) (*types.Block, error)
GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error) GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error)
// GetTd(blockHash common.Hash) *big.Int // GetTd(blockHash common.Hash) *big.Int
GetEVM(ctx context.Context, msg core.Message, state *state.DB, header *types.Header) (*vm.EVM, func() error, error) GetEVM(ctx context.Context, msg core.Message, state *state.DB, header *block.Header) (*vm.EVM, func() error, error)
SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription
SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription

@ -6,11 +6,13 @@ import (
"sync" "sync"
"time" "time"
ethereum "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
) )
@ -154,7 +156,7 @@ func (api *PublicFilterAPI) NewPendingTransactions(ctx context.Context) (*rpc.Su
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newblockfilter // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newblockfilter
func (api *PublicFilterAPI) NewBlockFilter() rpc.ID { func (api *PublicFilterAPI) NewBlockFilter() rpc.ID {
var ( var (
headers = make(chan *types.Header) headers = make(chan *block.Header)
headerSub = api.events.SubscribeNewHeads(headers) headerSub = api.events.SubscribeNewHeads(headers)
) )
@ -193,7 +195,7 @@ func (api *PublicFilterAPI) NewHeads(ctx context.Context) (*rpc.Subscription, er
rpcSub := notifier.CreateSubscription() rpcSub := notifier.CreateSubscription()
go func() { go func() {
headers := make(chan *types.Header) headers := make(chan *block.Header)
headersSub := api.events.SubscribeNewHeads(headers) headersSub := api.events.SubscribeNewHeads(headers)
for { for {

@ -27,6 +27,8 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
) )
@ -35,8 +37,8 @@ import (
type Backend interface { type Backend interface {
ChainDb() ethdb.Database ChainDb() ethdb.Database
EventMux() *event.TypeMux EventMux() *event.TypeMux
HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*block.Header, error)
HeaderByHash(ctx context.Context, blockHash common.Hash) (*types.Header, error) HeaderByHash(ctx context.Context, blockHash common.Hash) (*block.Header, error)
GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error) GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error)
GetLogs(ctx context.Context, blockHash common.Hash) ([][]*types.Log, error) GetLogs(ctx context.Context, blockHash common.Hash) ([][]*types.Log, error)
@ -232,7 +234,7 @@ func (f *Filter) unindexedLogs(ctx context.Context, end uint64) ([]*types.Log, e
} }
// blockLogs returns the logs matching the filter criteria within a single block. // blockLogs returns the logs matching the filter criteria within a single block.
func (f *Filter) blockLogs(ctx context.Context, header *types.Header) (logs []*types.Log, err error) { func (f *Filter) blockLogs(ctx context.Context, header *block.Header) (logs []*types.Log, err error) {
if bloomFilter(header.Bloom, f.addresses, f.topics) { if bloomFilter(header.Bloom, f.addresses, f.topics) {
found, err := f.checkMatches(ctx, header) found, err := f.checkMatches(ctx, header)
if err != nil { if err != nil {
@ -245,7 +247,7 @@ func (f *Filter) blockLogs(ctx context.Context, header *types.Header) (logs []*t
// checkMatches checks if the receipts belonging to the given header contain any log events that // checkMatches checks if the receipts belonging to the given header contain any log events that
// match the filter criteria. This function is called when the bloom filter signals a potential match. // match the filter criteria. This function is called when the bloom filter signals a potential match.
func (f *Filter) checkMatches(ctx context.Context, header *types.Header) (logs []*types.Log, err error) { func (f *Filter) checkMatches(ctx context.Context, header *block.Header) (logs []*types.Log, err error) {
// Get the logs of the block // Get the logs of the block
logsList, err := f.backend.GetLogs(ctx, header.Hash()) logsList, err := f.backend.GetLogs(ctx, header.Hash())
if err != nil { if err != nil {

@ -24,11 +24,13 @@ import (
"sync" "sync"
"time" "time"
ethereum "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/rawdb" "github.com/harmony-one/harmony/core/rawdb"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -76,7 +78,7 @@ type subscription struct {
logsCrit ethereum.FilterQuery logsCrit ethereum.FilterQuery
logs chan []*types.Log logs chan []*types.Log
hashes chan []common.Hash hashes chan []common.Hash
headers chan *types.Header headers chan *block.Header
installed chan struct{} // closed when the filter is installed installed chan struct{} // closed when the filter is installed
err chan error // closed when the filter is uninstalled err chan error // closed when the filter is uninstalled
} }
@ -87,7 +89,7 @@ type EventSystem struct {
mux *event.TypeMux mux *event.TypeMux
backend Backend backend Backend
lightMode bool lightMode bool
lastHead *types.Header lastHead *block.Header
// Subscriptions // Subscriptions
txsSub event.Subscription // Subscription for new transaction event txsSub event.Subscription // Subscription for new transaction event
@ -236,7 +238,7 @@ func (es *EventSystem) subscribeMinedPendingLogs(crit ethereum.FilterQuery, logs
created: time.Now(), created: time.Now(),
logs: logs, logs: logs,
hashes: make(chan []common.Hash), hashes: make(chan []common.Hash),
headers: make(chan *types.Header), headers: make(chan *block.Header),
installed: make(chan struct{}), installed: make(chan struct{}),
err: make(chan error), err: make(chan error),
} }
@ -253,7 +255,7 @@ func (es *EventSystem) subscribeLogs(crit ethereum.FilterQuery, logs chan []*typ
created: time.Now(), created: time.Now(),
logs: logs, logs: logs,
hashes: make(chan []common.Hash), hashes: make(chan []common.Hash),
headers: make(chan *types.Header), headers: make(chan *block.Header),
installed: make(chan struct{}), installed: make(chan struct{}),
err: make(chan error), err: make(chan error),
} }
@ -270,7 +272,7 @@ func (es *EventSystem) subscribePendingLogs(crit ethereum.FilterQuery, logs chan
created: time.Now(), created: time.Now(),
logs: logs, logs: logs,
hashes: make(chan []common.Hash), hashes: make(chan []common.Hash),
headers: make(chan *types.Header), headers: make(chan *block.Header),
installed: make(chan struct{}), installed: make(chan struct{}),
err: make(chan error), err: make(chan error),
} }
@ -279,7 +281,7 @@ func (es *EventSystem) subscribePendingLogs(crit ethereum.FilterQuery, logs chan
// SubscribeNewHeads creates a subscription that writes the header of a block that is // SubscribeNewHeads creates a subscription that writes the header of a block that is
// imported in the chain. // imported in the chain.
func (es *EventSystem) SubscribeNewHeads(headers chan *types.Header) *Subscription { func (es *EventSystem) SubscribeNewHeads(headers chan *block.Header) *Subscription {
sub := &subscription{ sub := &subscription{
id: rpc.NewID(), id: rpc.NewID(),
typ: BlocksSubscription, typ: BlocksSubscription,
@ -302,7 +304,7 @@ func (es *EventSystem) SubscribePendingTxs(hashes chan []common.Hash) *Subscript
created: time.Now(), created: time.Now(),
logs: make(chan []*types.Log), logs: make(chan []*types.Log),
hashes: hashes, hashes: hashes,
headers: make(chan *types.Header), headers: make(chan *block.Header),
installed: make(chan struct{}), installed: make(chan struct{}),
err: make(chan error), err: make(chan error),
} }
@ -355,7 +357,7 @@ func (es *EventSystem) broadcast(filters filterIndex, ev interface{}) {
f.headers <- e.Block.Header() f.headers <- e.Block.Header()
} }
if es.lightMode && len(filters[LogsSubscription]) > 0 { if es.lightMode && len(filters[LogsSubscription]) > 0 {
es.lightFilterNewHead(e.Block.Header(), func(header *types.Header, remove bool) { es.lightFilterNewHead(e.Block.Header(), func(header *block.Header, remove bool) {
for _, f := range filters[LogsSubscription] { for _, f := range filters[LogsSubscription] {
if matchedLogs := es.lightFilterLogs(header, f.logsCrit.Addresses, f.logsCrit.Topics, remove); len(matchedLogs) > 0 { if matchedLogs := es.lightFilterLogs(header, f.logsCrit.Addresses, f.logsCrit.Topics, remove); len(matchedLogs) > 0 {
f.logs <- matchedLogs f.logs <- matchedLogs
@ -366,7 +368,7 @@ func (es *EventSystem) broadcast(filters filterIndex, ev interface{}) {
} }
} }
func (es *EventSystem) lightFilterNewHead(newHeader *types.Header, callBack func(*types.Header, bool)) { func (es *EventSystem) lightFilterNewHead(newHeader *block.Header, callBack func(*block.Header, bool)) {
oldh := es.lastHead oldh := es.lastHead
es.lastHead = newHeader es.lastHead = newHeader
if oldh == nil { if oldh == nil {
@ -374,7 +376,7 @@ func (es *EventSystem) lightFilterNewHead(newHeader *types.Header, callBack func
} }
newh := newHeader newh := newHeader
// find common ancestor, create list of rolled back and new block hashes // find common ancestor, create list of rolled back and new block hashes
var oldHeaders, newHeaders []*types.Header var oldHeaders, newHeaders []*block.Header
for oldh.Hash() != newh.Hash() { for oldh.Hash() != newh.Hash() {
if oldh.Number.Uint64() >= newh.Number.Uint64() { if oldh.Number.Uint64() >= newh.Number.Uint64() {
oldHeaders = append(oldHeaders, oldh) oldHeaders = append(oldHeaders, oldh)
@ -400,7 +402,7 @@ func (es *EventSystem) lightFilterNewHead(newHeader *types.Header, callBack func
} }
// filter logs of a single header in light client mode // filter logs of a single header in light client mode
func (es *EventSystem) lightFilterLogs(header *types.Header, addresses []common.Address, topics [][]common.Hash, remove bool) []*types.Log { func (es *EventSystem) lightFilterLogs(header *block.Header, addresses []common.Address, topics [][]common.Hash, remove bool) []*types.Log {
if bloomFilter(header.Bloom, addresses, topics) { if bloomFilter(header.Bloom, addresses, topics) {
// Get the logs of the block // Get the logs of the block
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)

@ -18,6 +18,7 @@ import (
"github.com/harmony-one/harmony/api/service" "github.com/harmony-one/harmony/api/service"
"github.com/harmony-one/harmony/api/service/syncing" "github.com/harmony-one/harmony/api/service/syncing"
"github.com/harmony-one/harmony/api/service/syncing/downloader" "github.com/harmony-one/harmony/api/service/syncing/downloader"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/consensus" "github.com/harmony-one/harmony/consensus"
"github.com/harmony-one/harmony/contracts" "github.com/harmony-one/harmony/contracts"
"github.com/harmony-one/harmony/contracts/structs" "github.com/harmony-one/harmony/contracts/structs"
@ -96,7 +97,7 @@ type Node struct {
ConfirmedBlockChannel chan *types.Block // The channel to send confirmed blocks ConfirmedBlockChannel chan *types.Block // The channel to send confirmed blocks
BeaconBlockChannel chan *types.Block // The channel to send beacon blocks for non-beaconchain nodes BeaconBlockChannel chan *types.Block // The channel to send beacon blocks for non-beaconchain nodes
DRand *drand.DRand // The instance for distributed randomness protocol DRand *drand.DRand // The instance for distributed randomness protocol
pendingCrossLinks []*types.Header pendingCrossLinks []*block.Header
pendingClMutex sync.Mutex pendingClMutex sync.Mutex
pendingCXReceipts []*types.CXReceiptsProof // All the receipts received but not yet processed for Consensus pendingCXReceipts []*types.CXReceiptsProof // All the receipts received but not yet processed for Consensus

@ -9,6 +9,8 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/bls/ffi/go/bls" "github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
bls_cosi "github.com/harmony-one/harmony/crypto/bls" bls_cosi "github.com/harmony-one/harmony/crypto/bls"
@ -20,7 +22,7 @@ import (
func (node *Node) ProcessHeaderMessage(msgPayload []byte) { func (node *Node) ProcessHeaderMessage(msgPayload []byte) {
if node.NodeConfig.ShardID == 0 { if node.NodeConfig.ShardID == 0 {
var headers []*types.Header var headers []*block.Header
err := rlp.DecodeBytes(msgPayload, &headers) err := rlp.DecodeBytes(msgPayload, &headers)
if err != nil { if err != nil {
utils.Logger().Error(). utils.Logger().Error().
@ -32,7 +34,7 @@ func (node *Node) ProcessHeaderMessage(msgPayload []byte) {
// Try to reprocess all the pending cross links // Try to reprocess all the pending cross links
node.pendingClMutex.Lock() node.pendingClMutex.Lock()
crossLinkHeadersToProcess := node.pendingCrossLinks crossLinkHeadersToProcess := node.pendingCrossLinks
node.pendingCrossLinks = []*types.Header{} node.pendingCrossLinks = []*block.Header{}
node.pendingClMutex.Unlock() node.pendingClMutex.Unlock()
firstCrossLinkBlock := core.ShardingSchedule.FirstCrossLinkBlock() firstCrossLinkBlock := core.ShardingSchedule.FirstCrossLinkBlock()
@ -46,7 +48,7 @@ func (node *Node) ProcessHeaderMessage(msgPayload []byte) {
utils.Logger().Debug(). utils.Logger().Debug().
Msgf("[ProcessingHeader] number of crosslink headers to propose %d, firstCrossLinkBlock %d", len(crossLinkHeadersToProcess), firstCrossLinkBlock) Msgf("[ProcessingHeader] number of crosslink headers to propose %d, firstCrossLinkBlock %d", len(crossLinkHeadersToProcess), firstCrossLinkBlock)
headersToQuque := []*types.Header{} headersToQuque := []*block.Header{}
for _, header := range crossLinkHeadersToProcess { for _, header := range crossLinkHeadersToProcess {
if len(headersToQuque) > crossLinkBatchSize { if len(headersToQuque) > crossLinkBatchSize {
@ -156,7 +158,7 @@ func (node *Node) compareCrosslinkWithReceipts(cxp *types.CXReceiptsProof) error
} }
// VerifyCrosslinkHeader verifies the header is valid against the prevHeader. // VerifyCrosslinkHeader verifies the header is valid against the prevHeader.
func (node *Node) VerifyCrosslinkHeader(prevHeader, header *types.Header) error { func (node *Node) VerifyCrosslinkHeader(prevHeader, header *block.Header) error {
// TODO: add fork choice rule // TODO: add fork choice rule
if prevHeader.Hash() != header.ParentHash { if prevHeader.Hash() != header.ParentHash {

@ -25,6 +25,7 @@ import (
proto_discovery "github.com/harmony-one/harmony/api/proto/discovery" proto_discovery "github.com/harmony-one/harmony/api/proto/discovery"
"github.com/harmony-one/harmony/api/proto/message" "github.com/harmony-one/harmony/api/proto/message"
proto_node "github.com/harmony-one/harmony/api/proto/node" proto_node "github.com/harmony-one/harmony/api/proto/node"
"github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/contracts/structs" "github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -265,7 +266,7 @@ func (node *Node) BroadcastNewBlock(newBlock *types.Block) {
// BroadcastCrossLinkHeader is called by consensus leader to send the new header as cross link to beacon chain. // BroadcastCrossLinkHeader is called by consensus leader to send the new header as cross link to beacon chain.
func (node *Node) BroadcastCrossLinkHeader(newBlock *types.Block) { func (node *Node) BroadcastCrossLinkHeader(newBlock *types.Block) {
utils.Logger().Info().Msgf("Broadcasting new header to beacon chain groupID %s", node.NodeConfig.GetBeaconGroupID()) utils.Logger().Info().Msgf("Broadcasting new header to beacon chain groupID %s", node.NodeConfig.GetBeaconGroupID())
headers := []*types.Header{} headers := []*block.Header{}
lastLink, err := node.Beaconchain().ReadShardLastCrossLink(newBlock.ShardID()) lastLink, err := node.Beaconchain().ReadShardLastCrossLink(newBlock.ShardID())
var latestBlockNum uint64 var latestBlockNum uint64

@ -8,6 +8,7 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/internal/params" "github.com/harmony-one/harmony/internal/params"
"github.com/harmony-one/harmony/block"
consensus_engine "github.com/harmony-one/harmony/consensus/engine" consensus_engine "github.com/harmony-one/harmony/consensus/engine"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
@ -24,7 +25,7 @@ type environment struct {
state *state.DB // apply state changes here state *state.DB // apply state changes here
gasPool *core.GasPool // available gas used to pack transactions gasPool *core.GasPool // available gas used to pack transactions
header *types.Header header *block.Header
txs []*types.Transaction txs []*types.Transaction
receipts []*types.Receipt receipts []*types.Receipt
outcxs []*types.CXReceipt // cross shard transaction receipts (source shard) outcxs []*types.CXReceipt // cross shard transaction receipts (source shard)
@ -211,7 +212,7 @@ func (w *Worker) UpdateCurrent(coinbase common.Address) error {
// ... except if parent has a resharding assignment it increases by 1. // ... except if parent has a resharding assignment it increases by 1.
epoch = epoch.Add(epoch, common.Big1) epoch = epoch.Add(epoch, common.Big1)
} }
header := &types.Header{ header := &block.Header{
ParentHash: parent.Hash(), ParentHash: parent.Hash(),
Number: num.Add(num, common.Big1), Number: num.Add(num, common.Big1),
GasLimit: core.CalcGasLimit(parent, w.gasFloor, w.gasCeil), GasLimit: core.CalcGasLimit(parent, w.gasFloor, w.gasCeil),
@ -224,7 +225,7 @@ func (w *Worker) UpdateCurrent(coinbase common.Address) error {
} }
// makeCurrent creates a new environment for the current cycle. // makeCurrent creates a new environment for the current cycle.
func (w *Worker) makeCurrent(parent *types.Block, header *types.Header) error { func (w *Worker) makeCurrent(parent *types.Block, header *block.Header) error {
state, err := w.chain.StateAt(parent.Root()) state, err := w.chain.StateAt(parent.Root())
if err != nil { if err != nil {
return err return err
@ -306,7 +307,7 @@ func New(config *params.ChainConfig, chain *core.BlockChain, engine consensus_en
// ... except if parent has a resharding assignment it increases by 1. // ... except if parent has a resharding assignment it increases by 1.
epoch = epoch.Add(epoch, common.Big1) epoch = epoch.Add(epoch, common.Big1)
} }
header := &types.Header{ header := &block.Header{
ParentHash: parent.Hash(), ParentHash: parent.Hash(),
Number: num.Add(num, common.Big1), Number: num.Add(num, common.Big1),
GasLimit: core.CalcGasLimit(parent, worker.gasFloor, worker.gasCeil), GasLimit: core.CalcGasLimit(parent, worker.gasFloor, worker.gasCeil),

Loading…
Cancel
Save