forked from cerc-io/ipld-eth-server
Vdb 269- fetch logs by hash (#122)
* Upgrade geth from 1.8.15 to 1.8.18 * Update vat_tune to use shared repository methods * Query blockchain by block hash instead of block number range * Remove hash validation from repositories * Fix vow flog integration test * Update README Travis build sticker * Update constants formatting per go fmt * Update EthPublicKeyParser.ParsePublicKey to use discv5.PubkeyID method * Address PR comments
This commit is contained in:
+34
-23
@@ -93,27 +93,33 @@ var (
|
||||
|
||||
// errMissingSignature is returned if a block's extra-data section doesn't seem
|
||||
// to contain a 65 byte secp256k1 signature.
|
||||
errMissingSignature = errors.New("extra-data 65 byte suffix signature missing")
|
||||
errMissingSignature = errors.New("extra-data 65 byte signature suffix missing")
|
||||
|
||||
// errExtraSigners is returned if non-checkpoint block contain signer data in
|
||||
// their extra-data fields.
|
||||
errExtraSigners = errors.New("non-checkpoint block contains extra signer list")
|
||||
|
||||
// errInvalidCheckpointSigners is returned if a checkpoint block contains an
|
||||
// invalid list of signers (i.e. non divisible by 20 bytes, or not the correct
|
||||
// ones).
|
||||
// invalid list of signers (i.e. non divisible by 20 bytes).
|
||||
errInvalidCheckpointSigners = errors.New("invalid signer list on checkpoint block")
|
||||
|
||||
// errMismatchingCheckpointSigners is returned if a checkpoint block contains a
|
||||
// list of signers different than the one the local node calculated.
|
||||
errMismatchingCheckpointSigners = errors.New("mismatching signer list on checkpoint block")
|
||||
|
||||
// errInvalidMixDigest is returned if a block's mix digest is non-zero.
|
||||
errInvalidMixDigest = errors.New("non-zero mix digest")
|
||||
|
||||
// errInvalidUncleHash is returned if a block contains an non-empty uncle list.
|
||||
errInvalidUncleHash = errors.New("non empty uncle hash")
|
||||
|
||||
// errInvalidDifficulty is returned if the difficulty of a block is not either
|
||||
// of 1 or 2, or if the value does not match the turn of the signer.
|
||||
// errInvalidDifficulty is returned if the difficulty of a block neither 1 or 2.
|
||||
errInvalidDifficulty = errors.New("invalid difficulty")
|
||||
|
||||
// errWrongDifficulty is returned if the difficulty of a block doesn't match the
|
||||
// turn of the signer.
|
||||
errWrongDifficulty = errors.New("wrong difficulty")
|
||||
|
||||
// ErrInvalidTimestamp is returned if the timestamp of a block is lower than
|
||||
// the previous block's timestamp + the minimum block period.
|
||||
ErrInvalidTimestamp = errors.New("invalid timestamp")
|
||||
@@ -122,13 +128,12 @@ var (
|
||||
// be modified via out-of-range or non-contiguous headers.
|
||||
errInvalidVotingChain = errors.New("invalid voting chain")
|
||||
|
||||
// errUnauthorized is returned if a header is signed by a non-authorized entity.
|
||||
errUnauthorized = errors.New("unauthorized")
|
||||
// errUnauthorizedSigner is returned if a header is signed by a non-authorized entity.
|
||||
errUnauthorizedSigner = errors.New("unauthorized signer")
|
||||
|
||||
// errWaitTransactions is returned if an empty block is attempted to be sealed
|
||||
// on an instant chain (0 second period). It's important to refuse these as the
|
||||
// block reward is zero, so an empty block just bloats the chain... fast.
|
||||
errWaitTransactions = errors.New("waiting for transactions")
|
||||
// errRecentlySigned is returned if a header is signed by an authorized entity
|
||||
// that already signed a header recently, thus is temporarily not allowed to.
|
||||
errRecentlySigned = errors.New("recently signed")
|
||||
)
|
||||
|
||||
// SignerFn is a signer callback function to request a hash to be signed by a
|
||||
@@ -205,6 +210,9 @@ type Clique struct {
|
||||
signer common.Address // Ethereum address of the signing key
|
||||
signFn SignerFn // Signer function to authorize hashes with
|
||||
lock sync.RWMutex // Protects the signer fields
|
||||
|
||||
// The fields below are for testing only
|
||||
fakeDiff bool // Skip difficulty verifications
|
||||
}
|
||||
|
||||
// New creates a Clique proof-of-authority consensus engine with the initial
|
||||
@@ -359,7 +367,7 @@ func (c *Clique) verifyCascadingFields(chain consensus.ChainReader, header *type
|
||||
}
|
||||
extraSuffix := len(header.Extra) - extraSeal
|
||||
if !bytes.Equal(header.Extra[extraVanity:extraSuffix], signers) {
|
||||
return errInvalidCheckpointSigners
|
||||
return errMismatchingCheckpointSigners
|
||||
}
|
||||
}
|
||||
// All basic checks passed, verify the seal and return
|
||||
@@ -388,7 +396,7 @@ func (c *Clique) snapshot(chain consensus.ChainReader, number uint64, hash commo
|
||||
}
|
||||
}
|
||||
// If we're at an checkpoint block, make a snapshot if it's known
|
||||
if number%c.config.Epoch == 0 {
|
||||
if number == 0 || (number%c.config.Epoch == 0 && chain.GetHeaderByNumber(number-1) == nil) {
|
||||
checkpoint := chain.GetHeaderByNumber(number)
|
||||
if checkpoint != nil {
|
||||
hash := checkpoint.Hash()
|
||||
@@ -481,23 +489,25 @@ func (c *Clique) verifySeal(chain consensus.ChainReader, header *types.Header, p
|
||||
return err
|
||||
}
|
||||
if _, ok := snap.Signers[signer]; !ok {
|
||||
return errUnauthorized
|
||||
return errUnauthorizedSigner
|
||||
}
|
||||
for seen, recent := range snap.Recents {
|
||||
if recent == signer {
|
||||
// Signer is among recents, only fail if the current block doesn't shift it out
|
||||
if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit {
|
||||
return errUnauthorized
|
||||
return errRecentlySigned
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ensure that the difficulty corresponds to the turn-ness of the signer
|
||||
inturn := snap.inturn(header.Number.Uint64(), signer)
|
||||
if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
|
||||
return errInvalidDifficulty
|
||||
}
|
||||
if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
|
||||
return errInvalidDifficulty
|
||||
if !c.fakeDiff {
|
||||
inturn := snap.inturn(header.Number.Uint64(), signer)
|
||||
if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
|
||||
return errWrongDifficulty
|
||||
}
|
||||
if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
|
||||
return errWrongDifficulty
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -600,7 +610,8 @@ func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, results c
|
||||
}
|
||||
// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
|
||||
if c.config.Period == 0 && len(block.Transactions()) == 0 {
|
||||
return errWaitTransactions
|
||||
log.Info("Sealing paused, waiting for transactions")
|
||||
return nil
|
||||
}
|
||||
// Don't hold the signer fields for the entire sealing procedure
|
||||
c.lock.RLock()
|
||||
@@ -613,7 +624,7 @@ func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, results c
|
||||
return err
|
||||
}
|
||||
if _, authorized := snap.Signers[signer]; !authorized {
|
||||
return errUnauthorized
|
||||
return errUnauthorizedSigner
|
||||
}
|
||||
// If we're amongst the recent signers, wait for the next block
|
||||
for seen, recent := range snap.Recents {
|
||||
|
||||
+8
-8
@@ -57,12 +57,12 @@ type Snapshot struct {
|
||||
Tally map[common.Address]Tally `json:"tally"` // Current vote tally to avoid recalculating
|
||||
}
|
||||
|
||||
// signers implements the sort interface to allow sorting a list of addresses
|
||||
type signers []common.Address
|
||||
// signersAscending implements the sort interface to allow sorting a list of addresses
|
||||
type signersAscending []common.Address
|
||||
|
||||
func (s signers) Len() int { return len(s) }
|
||||
func (s signers) Less(i, j int) bool { return bytes.Compare(s[i][:], s[j][:]) < 0 }
|
||||
func (s signers) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s signersAscending) Len() int { return len(s) }
|
||||
func (s signersAscending) Less(i, j int) bool { return bytes.Compare(s[i][:], s[j][:]) < 0 }
|
||||
func (s signersAscending) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
|
||||
// newSnapshot creates a new snapshot with the specified startup parameters. This
|
||||
// method does not initialize the set of recent signers, so only ever use if for
|
||||
@@ -214,11 +214,11 @@ func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := snap.Signers[signer]; !ok {
|
||||
return nil, errUnauthorized
|
||||
return nil, errUnauthorizedSigner
|
||||
}
|
||||
for _, recent := range snap.Recents {
|
||||
if recent == signer {
|
||||
return nil, errUnauthorized
|
||||
return nil, errRecentlySigned
|
||||
}
|
||||
}
|
||||
snap.Recents[number] = signer
|
||||
@@ -298,7 +298,7 @@ func (s *Snapshot) signers() []common.Address {
|
||||
for sig := range s.Signers {
|
||||
sigs = append(sigs, sig)
|
||||
}
|
||||
sort.Sort(signers(sigs))
|
||||
sort.Sort(signersAscending(sigs))
|
||||
return sigs
|
||||
}
|
||||
|
||||
|
||||
+146
-48
@@ -19,24 +19,18 @@ package clique
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"math/big"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core"
|
||||
"github.com/ethereum/go-ethereum/core/rawdb"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/core/vm"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/ethdb"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
)
|
||||
|
||||
type testerVote struct {
|
||||
signer string
|
||||
voted string
|
||||
auth bool
|
||||
}
|
||||
|
||||
// testerAccountPool is a pool to maintain currently active tester accounts,
|
||||
// mapped from textual names used in the tests below to actual Ethereum private
|
||||
// keys capable of signing transactions.
|
||||
@@ -50,17 +44,26 @@ func newTesterAccountPool() *testerAccountPool {
|
||||
}
|
||||
}
|
||||
|
||||
func (ap *testerAccountPool) sign(header *types.Header, signer string) {
|
||||
// Ensure we have a persistent key for the signer
|
||||
if ap.accounts[signer] == nil {
|
||||
ap.accounts[signer], _ = crypto.GenerateKey()
|
||||
// checkpoint creates a Clique checkpoint signer section from the provided list
|
||||
// of authorized signers and embeds it into the provided header.
|
||||
func (ap *testerAccountPool) checkpoint(header *types.Header, signers []string) {
|
||||
auths := make([]common.Address, len(signers))
|
||||
for i, signer := range signers {
|
||||
auths[i] = ap.address(signer)
|
||||
}
|
||||
sort.Sort(signersAscending(auths))
|
||||
for i, auth := range auths {
|
||||
copy(header.Extra[extraVanity+i*common.AddressLength:], auth.Bytes())
|
||||
}
|
||||
// Sign the header and embed the signature in extra data
|
||||
sig, _ := crypto.Sign(sigHash(header).Bytes(), ap.accounts[signer])
|
||||
copy(header.Extra[len(header.Extra)-65:], sig)
|
||||
}
|
||||
|
||||
// address retrieves the Ethereum address of a tester account by label, creating
|
||||
// a new account if no previous one exists yet.
|
||||
func (ap *testerAccountPool) address(account string) common.Address {
|
||||
// Return the zero account for non-addresses
|
||||
if account == "" {
|
||||
return common.Address{}
|
||||
}
|
||||
// Ensure we have a persistent key for the account
|
||||
if ap.accounts[account] == nil {
|
||||
ap.accounts[account], _ = crypto.GenerateKey()
|
||||
@@ -69,32 +72,38 @@ func (ap *testerAccountPool) address(account string) common.Address {
|
||||
return crypto.PubkeyToAddress(ap.accounts[account].PublicKey)
|
||||
}
|
||||
|
||||
// testerChainReader implements consensus.ChainReader to access the genesis
|
||||
// block. All other methods and requests will panic.
|
||||
type testerChainReader struct {
|
||||
db ethdb.Database
|
||||
}
|
||||
|
||||
func (r *testerChainReader) Config() *params.ChainConfig { return params.AllCliqueProtocolChanges }
|
||||
func (r *testerChainReader) CurrentHeader() *types.Header { panic("not supported") }
|
||||
func (r *testerChainReader) GetHeader(common.Hash, uint64) *types.Header { panic("not supported") }
|
||||
func (r *testerChainReader) GetBlock(common.Hash, uint64) *types.Block { panic("not supported") }
|
||||
func (r *testerChainReader) GetHeaderByHash(common.Hash) *types.Header { panic("not supported") }
|
||||
func (r *testerChainReader) GetHeaderByNumber(number uint64) *types.Header {
|
||||
if number == 0 {
|
||||
return rawdb.ReadHeader(r.db, rawdb.ReadCanonicalHash(r.db, 0), 0)
|
||||
// sign calculates a Clique digital signature for the given block and embeds it
|
||||
// back into the header.
|
||||
func (ap *testerAccountPool) sign(header *types.Header, signer string) {
|
||||
// Ensure we have a persistent key for the signer
|
||||
if ap.accounts[signer] == nil {
|
||||
ap.accounts[signer], _ = crypto.GenerateKey()
|
||||
}
|
||||
return nil
|
||||
// Sign the header and embed the signature in extra data
|
||||
sig, _ := crypto.Sign(sigHash(header).Bytes(), ap.accounts[signer])
|
||||
copy(header.Extra[len(header.Extra)-extraSeal:], sig)
|
||||
}
|
||||
|
||||
// Tests that voting is evaluated correctly for various simple and complex scenarios.
|
||||
func TestVoting(t *testing.T) {
|
||||
// testerVote represents a single block signed by a parcitular account, where
|
||||
// the account may or may not have cast a Clique vote.
|
||||
type testerVote struct {
|
||||
signer string
|
||||
voted string
|
||||
auth bool
|
||||
checkpoint []string
|
||||
newbatch bool
|
||||
}
|
||||
|
||||
// Tests that Clique signer voting is evaluated correctly for various simple and
|
||||
// complex scenarios, as well as that a few special corner cases fail correctly.
|
||||
func TestClique(t *testing.T) {
|
||||
// Define the various voting scenarios to test
|
||||
tests := []struct {
|
||||
epoch uint64
|
||||
signers []string
|
||||
votes []testerVote
|
||||
results []string
|
||||
failure error
|
||||
}{
|
||||
{
|
||||
// Single signer, no votes cast
|
||||
@@ -322,10 +331,49 @@ func TestVoting(t *testing.T) {
|
||||
votes: []testerVote{
|
||||
{signer: "A", voted: "C", auth: true},
|
||||
{signer: "B"},
|
||||
{signer: "A"}, // Checkpoint block, (don't vote here, it's validated outside of snapshots)
|
||||
{signer: "A", checkpoint: []string{"A", "B"}},
|
||||
{signer: "B", voted: "C", auth: true},
|
||||
},
|
||||
results: []string{"A", "B"},
|
||||
}, {
|
||||
// An unauthorized signer should not be able to sign blocks
|
||||
signers: []string{"A"},
|
||||
votes: []testerVote{
|
||||
{signer: "B"},
|
||||
},
|
||||
failure: errUnauthorizedSigner,
|
||||
}, {
|
||||
// An authorized signer that signed recenty should not be able to sign again
|
||||
signers: []string{"A", "B"},
|
||||
votes: []testerVote{
|
||||
{signer: "A"},
|
||||
{signer: "A"},
|
||||
},
|
||||
failure: errRecentlySigned,
|
||||
}, {
|
||||
// Recent signatures should not reset on checkpoint blocks imported in a batch
|
||||
epoch: 3,
|
||||
signers: []string{"A", "B", "C"},
|
||||
votes: []testerVote{
|
||||
{signer: "A"},
|
||||
{signer: "B"},
|
||||
{signer: "A", checkpoint: []string{"A", "B", "C"}},
|
||||
{signer: "A"},
|
||||
},
|
||||
failure: errRecentlySigned,
|
||||
}, {
|
||||
// Recent signatures should not reset on checkpoint blocks imported in a new
|
||||
// batch (https://github.com/ethereum/go-ethereum/issues/17593). Whilst this
|
||||
// seems overly specific and weird, it was a Rinkeby consensus split.
|
||||
epoch: 3,
|
||||
signers: []string{"A", "B", "C"},
|
||||
votes: []testerVote{
|
||||
{signer: "A"},
|
||||
{signer: "B"},
|
||||
{signer: "A", checkpoint: []string{"A", "B", "C"}},
|
||||
{signer: "A", newbatch: true},
|
||||
},
|
||||
failure: errRecentlySigned,
|
||||
},
|
||||
}
|
||||
// Run through the scenarios and test them
|
||||
@@ -356,28 +404,78 @@ func TestVoting(t *testing.T) {
|
||||
genesis.Commit(db)
|
||||
|
||||
// Assemble a chain of headers from the cast votes
|
||||
headers := make([]*types.Header, len(tt.votes))
|
||||
for j, vote := range tt.votes {
|
||||
headers[j] = &types.Header{
|
||||
Number: big.NewInt(int64(j) + 1),
|
||||
Time: big.NewInt(int64(j) * 15),
|
||||
Coinbase: accounts.address(vote.voted),
|
||||
Extra: make([]byte, extraVanity+extraSeal),
|
||||
config := *params.TestChainConfig
|
||||
config.Clique = ¶ms.CliqueConfig{
|
||||
Period: 1,
|
||||
Epoch: tt.epoch,
|
||||
}
|
||||
engine := New(config.Clique, db)
|
||||
engine.fakeDiff = true
|
||||
|
||||
blocks, _ := core.GenerateChain(&config, genesis.ToBlock(db), engine, db, len(tt.votes), func(j int, gen *core.BlockGen) {
|
||||
// Cast the vote contained in this block
|
||||
gen.SetCoinbase(accounts.address(tt.votes[j].voted))
|
||||
if tt.votes[j].auth {
|
||||
var nonce types.BlockNonce
|
||||
copy(nonce[:], nonceAuthVote)
|
||||
gen.SetNonce(nonce)
|
||||
}
|
||||
})
|
||||
// Iterate through the blocks and seal them individually
|
||||
for j, block := range blocks {
|
||||
// Geth the header and prepare it for signing
|
||||
header := block.Header()
|
||||
if j > 0 {
|
||||
headers[j].ParentHash = headers[j-1].Hash()
|
||||
header.ParentHash = blocks[j-1].Hash()
|
||||
}
|
||||
if vote.auth {
|
||||
copy(headers[j].Nonce[:], nonceAuthVote)
|
||||
header.Extra = make([]byte, extraVanity+extraSeal)
|
||||
if auths := tt.votes[j].checkpoint; auths != nil {
|
||||
header.Extra = make([]byte, extraVanity+len(auths)*common.AddressLength+extraSeal)
|
||||
accounts.checkpoint(header, auths)
|
||||
}
|
||||
accounts.sign(headers[j], vote.signer)
|
||||
header.Difficulty = diffInTurn // Ignored, we just need a valid number
|
||||
|
||||
// Generate the signature, embed it into the header and the block
|
||||
accounts.sign(header, tt.votes[j].signer)
|
||||
blocks[j] = block.WithSeal(header)
|
||||
}
|
||||
// Split the blocks up into individual import batches (cornercase testing)
|
||||
batches := [][]*types.Block{nil}
|
||||
for j, block := range blocks {
|
||||
if tt.votes[j].newbatch {
|
||||
batches = append(batches, nil)
|
||||
}
|
||||
batches[len(batches)-1] = append(batches[len(batches)-1], block)
|
||||
}
|
||||
// Pass all the headers through clique and ensure tallying succeeds
|
||||
head := headers[len(headers)-1]
|
||||
|
||||
snap, err := New(¶ms.CliqueConfig{Epoch: tt.epoch}, db).snapshot(&testerChainReader{db: db}, head.Number.Uint64(), head.Hash(), headers)
|
||||
chain, err := core.NewBlockChain(db, nil, &config, engine, vm.Config{}, nil)
|
||||
if err != nil {
|
||||
t.Errorf("test %d: failed to create voting snapshot: %v", i, err)
|
||||
t.Errorf("test %d: failed to create test chain: %v", i, err)
|
||||
continue
|
||||
}
|
||||
failed := false
|
||||
for j := 0; j < len(batches)-1; j++ {
|
||||
if k, err := chain.InsertChain(batches[j]); err != nil {
|
||||
t.Errorf("test %d: failed to import batch %d, block %d: %v", i, j, k, err)
|
||||
failed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if failed {
|
||||
continue
|
||||
}
|
||||
if _, err = chain.InsertChain(batches[len(batches)-1]); err != tt.failure {
|
||||
t.Errorf("test %d: failure mismatch: have %v, want %v", i, err, tt.failure)
|
||||
}
|
||||
if tt.failure != nil {
|
||||
continue
|
||||
}
|
||||
// No failure was produced or requested, generate the final voting snapshot
|
||||
head := blocks[len(blocks)-1]
|
||||
|
||||
snap, err := engine.snapshot(chain, head.NumberU64(), head.Hash(), nil)
|
||||
if err != nil {
|
||||
t.Errorf("test %d: failed to retrieve voting snapshot: %v", i, err)
|
||||
continue
|
||||
}
|
||||
// Verify the final list of signers against the expected ones
|
||||
|
||||
+1
-1
@@ -90,7 +90,7 @@ type Engine interface {
|
||||
// the result into the given channel.
|
||||
//
|
||||
// Note, the method returns immediately and will send the result async. More
|
||||
// than one result may also be returned depending on the consensus algorothm.
|
||||
// than one result may also be returned depending on the consensus algorithm.
|
||||
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.
|
||||
|
||||
+6
-5
@@ -37,27 +37,28 @@ type API struct {
|
||||
// result[0] - 32 bytes hex encoded current block header pow-hash
|
||||
// result[1] - 32 bytes hex encoded seed hash used for DAG
|
||||
// result[2] - 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
|
||||
func (api *API) GetWork() ([3]string, error) {
|
||||
// result[3] - hex encoded block number
|
||||
func (api *API) GetWork() ([4]string, error) {
|
||||
if api.ethash.config.PowMode != ModeNormal && api.ethash.config.PowMode != ModeTest {
|
||||
return [3]string{}, errors.New("not supported")
|
||||
return [4]string{}, errors.New("not supported")
|
||||
}
|
||||
|
||||
var (
|
||||
workCh = make(chan [3]string, 1)
|
||||
workCh = make(chan [4]string, 1)
|
||||
errc = make(chan error, 1)
|
||||
)
|
||||
|
||||
select {
|
||||
case api.ethash.fetchWorkCh <- &sealWork{errc: errc, res: workCh}:
|
||||
case <-api.ethash.exitCh:
|
||||
return [3]string{}, errEthashStopped
|
||||
return [4]string{}, errEthashStopped
|
||||
}
|
||||
|
||||
select {
|
||||
case work := <-workCh:
|
||||
return work, nil
|
||||
case err := <-errc:
|
||||
return [3]string{}, err
|
||||
return [4]string{}, err
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+78
-56
@@ -38,10 +38,24 @@ import (
|
||||
|
||||
// Ethash proof-of-work protocol constants.
|
||||
var (
|
||||
FrontierBlockReward = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
|
||||
ByzantiumBlockReward = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
|
||||
maxUncles = 2 // Maximum number of uncles allowed in a single block
|
||||
allowedFutureBlockTime = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks
|
||||
FrontierBlockReward = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
|
||||
ByzantiumBlockReward = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
|
||||
ConstantinopleBlockReward = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople
|
||||
maxUncles = 2 // Maximum number of uncles allowed in a single block
|
||||
allowedFutureBlockTime = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks
|
||||
|
||||
// calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople.
|
||||
// It returns the difficulty that a new block should have when created at time given the
|
||||
// parent block's time and difficulty. The calculation uses the Byzantium rules, but with
|
||||
// bomb offset 5M.
|
||||
// Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234
|
||||
calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000))
|
||||
|
||||
// calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
|
||||
// the difficulty that a new block should have when created at time given the
|
||||
// parent block's time and difficulty. The calculation uses the Byzantium rules.
|
||||
// Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649
|
||||
calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000))
|
||||
)
|
||||
|
||||
// Various error messages to mark blocks invalid. These should be private to
|
||||
@@ -299,6 +313,8 @@ func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, p
|
||||
func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
|
||||
next := new(big.Int).Add(parent.Number, big1)
|
||||
switch {
|
||||
case config.IsConstantinople(next):
|
||||
return calcDifficultyConstantinople(time, parent)
|
||||
case config.IsByzantium(next):
|
||||
return calcDifficultyByzantium(time, parent)
|
||||
case config.IsHomestead(next):
|
||||
@@ -316,66 +332,69 @@ var (
|
||||
big9 = big.NewInt(9)
|
||||
big10 = big.NewInt(10)
|
||||
bigMinus99 = big.NewInt(-99)
|
||||
big2999999 = big.NewInt(2999999)
|
||||
)
|
||||
|
||||
// calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
|
||||
// the difficulty that a new block should have when created at time given the
|
||||
// parent block's time and difficulty. The calculation uses the Byzantium rules.
|
||||
func calcDifficultyByzantium(time uint64, parent *types.Header) *big.Int {
|
||||
// https://github.com/ethereum/EIPs/issues/100.
|
||||
// algorithm:
|
||||
// diff = (parent_diff +
|
||||
// (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
|
||||
// ) + 2^(periodCount - 2)
|
||||
// makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
|
||||
// the difficulty is calculated with Byzantium rules, which differs from Homestead in
|
||||
// how uncles affect the calculation
|
||||
func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
|
||||
// Note, the calculations below looks at the parent number, which is 1 below
|
||||
// the block number. Thus we remove one from the delay given
|
||||
bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
|
||||
return func(time uint64, parent *types.Header) *big.Int {
|
||||
// https://github.com/ethereum/EIPs/issues/100.
|
||||
// algorithm:
|
||||
// diff = (parent_diff +
|
||||
// (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
|
||||
// ) + 2^(periodCount - 2)
|
||||
|
||||
bigTime := new(big.Int).SetUint64(time)
|
||||
bigParentTime := new(big.Int).Set(parent.Time)
|
||||
bigTime := new(big.Int).SetUint64(time)
|
||||
bigParentTime := new(big.Int).Set(parent.Time)
|
||||
|
||||
// holds intermediate values to make the algo easier to read & audit
|
||||
x := new(big.Int)
|
||||
y := new(big.Int)
|
||||
// holds intermediate values to make the algo easier to read & audit
|
||||
x := new(big.Int)
|
||||
y := new(big.Int)
|
||||
|
||||
// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
|
||||
x.Sub(bigTime, bigParentTime)
|
||||
x.Div(x, big9)
|
||||
if parent.UncleHash == types.EmptyUncleHash {
|
||||
x.Sub(big1, x)
|
||||
} else {
|
||||
x.Sub(big2, x)
|
||||
}
|
||||
// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
|
||||
if x.Cmp(bigMinus99) < 0 {
|
||||
x.Set(bigMinus99)
|
||||
}
|
||||
// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
|
||||
y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
|
||||
x.Mul(y, x)
|
||||
x.Add(parent.Difficulty, x)
|
||||
// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
|
||||
x.Sub(bigTime, bigParentTime)
|
||||
x.Div(x, big9)
|
||||
if parent.UncleHash == types.EmptyUncleHash {
|
||||
x.Sub(big1, x)
|
||||
} else {
|
||||
x.Sub(big2, x)
|
||||
}
|
||||
// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
|
||||
if x.Cmp(bigMinus99) < 0 {
|
||||
x.Set(bigMinus99)
|
||||
}
|
||||
// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
|
||||
y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
|
||||
x.Mul(y, x)
|
||||
x.Add(parent.Difficulty, x)
|
||||
|
||||
// minimum difficulty can ever be (before exponential factor)
|
||||
if x.Cmp(params.MinimumDifficulty) < 0 {
|
||||
x.Set(params.MinimumDifficulty)
|
||||
}
|
||||
// calculate a fake block number for the ice-age delay:
|
||||
// https://github.com/ethereum/EIPs/pull/669
|
||||
// fake_block_number = max(0, block.number - 3_000_000)
|
||||
fakeBlockNumber := new(big.Int)
|
||||
if parent.Number.Cmp(big2999999) >= 0 {
|
||||
fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, big2999999) // Note, parent is 1 less than the actual block number
|
||||
}
|
||||
// for the exponential factor
|
||||
periodCount := fakeBlockNumber
|
||||
periodCount.Div(periodCount, expDiffPeriod)
|
||||
// minimum difficulty can ever be (before exponential factor)
|
||||
if x.Cmp(params.MinimumDifficulty) < 0 {
|
||||
x.Set(params.MinimumDifficulty)
|
||||
}
|
||||
// calculate a fake block number for the ice-age delay
|
||||
// Specification: https://eips.ethereum.org/EIPS/eip-1234
|
||||
fakeBlockNumber := new(big.Int)
|
||||
if parent.Number.Cmp(bombDelayFromParent) >= 0 {
|
||||
fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
|
||||
}
|
||||
// for the exponential factor
|
||||
periodCount := fakeBlockNumber
|
||||
periodCount.Div(periodCount, expDiffPeriod)
|
||||
|
||||
// the exponential factor, commonly referred to as "the bomb"
|
||||
// diff = diff + 2^(periodCount - 2)
|
||||
if periodCount.Cmp(big1) > 0 {
|
||||
y.Sub(periodCount, big2)
|
||||
y.Exp(big2, y, nil)
|
||||
x.Add(x, y)
|
||||
// the exponential factor, commonly referred to as "the bomb"
|
||||
// diff = diff + 2^(periodCount - 2)
|
||||
if periodCount.Cmp(big1) > 0 {
|
||||
y.Sub(periodCount, big2)
|
||||
y.Exp(big2, y, nil)
|
||||
x.Add(x, y)
|
||||
}
|
||||
return x
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
// calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
|
||||
@@ -592,6 +611,9 @@ func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header
|
||||
if config.IsByzantium(header.Number) {
|
||||
blockReward = ByzantiumBlockReward
|
||||
}
|
||||
if config.IsConstantinople(header.Number) {
|
||||
blockReward = ConstantinopleBlockReward
|
||||
}
|
||||
// Accumulate the rewards for the miner and any included uncles
|
||||
reward := new(big.Int).Set(blockReward)
|
||||
r := new(big.Int)
|
||||
|
||||
+3
-3
@@ -432,7 +432,7 @@ type hashrate struct {
|
||||
// sealWork wraps a seal work package for remote sealer.
|
||||
type sealWork struct {
|
||||
errc chan error
|
||||
res chan [3]string
|
||||
res chan [4]string
|
||||
}
|
||||
|
||||
// Ethash is a consensus engine based on proof-of-work implementing the ethash
|
||||
@@ -485,7 +485,7 @@ func New(config Config, notify []string, noverify bool) *Ethash {
|
||||
caches: newlru("cache", config.CachesInMem, newCache),
|
||||
datasets: newlru("dataset", config.DatasetsInMem, newDataset),
|
||||
update: make(chan struct{}),
|
||||
hashrate: metrics.NewMeter(),
|
||||
hashrate: metrics.NewMeterForced(),
|
||||
workCh: make(chan *sealTask),
|
||||
fetchWorkCh: make(chan *sealWork),
|
||||
submitWorkCh: make(chan *mineResult),
|
||||
@@ -505,7 +505,7 @@ func NewTester(notify []string, noverify bool) *Ethash {
|
||||
caches: newlru("cache", 1, newCache),
|
||||
datasets: newlru("dataset", 1, newDataset),
|
||||
update: make(chan struct{}),
|
||||
hashrate: metrics.NewMeter(),
|
||||
hashrate: metrics.NewMeterForced(),
|
||||
workCh: make(chan *sealTask),
|
||||
fetchWorkCh: make(chan *sealWork),
|
||||
submitWorkCh: make(chan *mineResult),
|
||||
|
||||
+1
-1
@@ -107,7 +107,7 @@ func TestRemoteSealer(t *testing.T) {
|
||||
ethash.Seal(nil, block, results, nil)
|
||||
|
||||
var (
|
||||
work [3]string
|
||||
work [4]string
|
||||
err error
|
||||
)
|
||||
if work, err = api.GetWork(); err != nil || work[0] != sealhash.Hex() {
|
||||
|
||||
+4
-1
@@ -30,6 +30,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/consensus"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
@@ -193,7 +194,7 @@ func (ethash *Ethash) remote(notify []string, noverify bool) {
|
||||
|
||||
results chan<- *types.Block
|
||||
currentBlock *types.Block
|
||||
currentWork [3]string
|
||||
currentWork [4]string
|
||||
|
||||
notifyTransport = &http.Transport{}
|
||||
notifyClient = &http.Client{
|
||||
@@ -234,12 +235,14 @@ func (ethash *Ethash) remote(notify []string, noverify bool) {
|
||||
// result[0], 32 bytes hex encoded current block header pow-hash
|
||||
// result[1], 32 bytes hex encoded seed hash used for DAG
|
||||
// result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
|
||||
// result[3], hex encoded block number
|
||||
makeWork := func(block *types.Block) {
|
||||
hash := ethash.SealHash(block.Header())
|
||||
|
||||
currentWork[0] = hash.Hex()
|
||||
currentWork[1] = common.BytesToHash(SeedHash(block.NumberU64())).Hex()
|
||||
currentWork[2] = common.BytesToHash(new(big.Int).Div(two256, block.Difficulty()).Bytes()).Hex()
|
||||
currentWork[3] = hexutil.EncodeBig(block.Number())
|
||||
|
||||
// Trace the seal work fetched by remote sealer.
|
||||
currentBlock = block
|
||||
|
||||
+14
-2
@@ -40,6 +40,18 @@ func TestRemoteNotify(t *testing.T) {
|
||||
|
||||
go server.Serve(listener)
|
||||
|
||||
// Wait for server to start listening
|
||||
var tries int
|
||||
for tries = 0; tries < 10; tries++ {
|
||||
conn, _ := net.DialTimeout("tcp", listener.Addr().String(), 1*time.Second)
|
||||
if conn != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if tries == 10 {
|
||||
t.Fatal("tcp listener not ready for more than 10 seconds")
|
||||
}
|
||||
|
||||
// Create the custom ethash engine
|
||||
ethash := NewTester([]string{"http://" + listener.Addr().String()}, false)
|
||||
defer ethash.Close()
|
||||
@@ -61,7 +73,7 @@ func TestRemoteNotify(t *testing.T) {
|
||||
if want := common.BytesToHash(target.Bytes()).Hex(); work[2] != want {
|
||||
t.Errorf("work packet target mismatch: have %s, want %s", work[2], want)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("notification timed out")
|
||||
}
|
||||
}
|
||||
@@ -108,7 +120,7 @@ func TestRemoteMultiNotify(t *testing.T) {
|
||||
for i := 0; i < cap(sink); i++ {
|
||||
select {
|
||||
case <-sink:
|
||||
case <-time.After(250 * time.Millisecond):
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("notification %d timed out", i)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user