minerva

package
v2.1.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2020 License: GPL-3.0 Imports: 30 Imported by: 10

README

Fundamentally achieving ASIC resistant: A brief introduction to Truehash algorithm

As we all know, TrueChain adopted hybrid consensus technology, It uses PBFT as fast chain to process transactions and PoW as snailchain to supervise and elect the committee.

PoW algorithm was put forward by Cynthia Dwork and Moni Naor in 1993. The application scenario of it then was to resist the attack of ddos and email spam. In 1999, Jacobsson came up with partial hash inversion algorithm which is also the method that Satoshi Nakamoto utilized in bitcoin network.

Take a look at the coins that issued after the bitcion, it is not hard to see that blockchain developers are experimenting different kinds of mining algorithm to achieve ASIC resistant. And it turns out to be that all the attempts are failed. Their whole idea is to adding the computation against the shortcomings of ASIC to make the algorithms harder. However, algorithm like Ethash and Equihash or others may merely delay the appearance time of ASIC at best but cannot fundamentally resist ASIC. For further research, we must understand why CPU/GPU is way much slower than ASIC. And the main reason is that von Neumann architecture is adopted for Diversity calculation.

Von Neumann architecture is roughly divided into three parts, that is internal storage, control unit and calculating element. The operation program and data are written in DDR and will be transferred to the calculation element when performing calculations. The computational bottleneck caused by transmission bandwidth is called the von neumann bottleneck.

The idea of avoiding the von neumann bottleneck is simple for operations with high uniqueness, such as the calculation of hash values, the idea is to abandon the von neumann architecture and write the algorithm directly into the calculation element to make it become ASIC. That is why ASIC has such an astonishing advantages of computing powers in calculating Bitcoin Sha-256d. Even then Ethash adopted the method of reading the big table, but essentially a computer program can still be hard -coded to calculation elements. Although there's memory grain around the ASIC but that can only increases the cost.

In order to achieve ASIC resistant fundamentally we can borrow the experience from Monero, that is periodic algorithm changing design. The problems with Monero is the unprofessional voting for hard fork by the community. And the biggest problem with them is that no one knows if the project team (they can manipulate the voting results easily) prepared ASIC for new algorithm.

Therefore,we must assure this mechanism is under the control of mining algorithm. And to achieve ASIC resistant fundamentally, the following rules must be satisfied:

  1. Command S as a collection of algorithm, all algorithms in S must pass through the von neumann bottleneck.
  2. Algorithm will change every T blocks, and the changing methods must meet up with the condition of Verifiable and unpredictable.
  3. No human intervention in algorithm switching.

The specific design ideas are as follows

The implementation of Truehash is to set G as a group, for every group member g, make rho_V(G) be the showcase of G in vector space V. In ordinary mining algorithm, when calculate blockheade, nonce and other information with operations like padding and so on, there will form a Vector nonce. By the exhaustion of different nonce to find the results that are less than the difficulty coefficient.

The changing parts of Truehash

Change hash(v(nonce)) to hash(rho(g)*v(nonce)). As long as G (Truehash utilizes permutation group which contains 2048 elements) is complex enough, this algorithm collection will not be entirely hard-coded within the calculation elements. Because the algorithm will switch randomly, the bottleneck of von neumann will be inevitable.

The principle of Truehash's switching algorithm is that the group elements will be changed every 12 thousand PoW block. The production time of 12 thousand poW blocks is 83 days. The new group element information is composed of blocks 1-8192 in the previous cycle, and the composition method is generated by analyzing the hash values of blocks 11001-11256.

Because the hash value of the block is unpredictable in advance, it's impossible for anyone to know anything about the new algorithm until the 11256 block comes along. From the 11,257th block of the last cycle, to the algorithm being invalidated, there is only 88 days in total, so it makes no sense to produce ASIC in such a short period of time.

Documentation

Overview

Package minerva implements the truechain hybrid consensus engine.

Index

Constants

View Source
const DATALENGTH = 2048 //2048 520
View Source
const DGSTSIZE = 32
View Source
const HEADSIZE = 32
View Source
const OFF_CYCLE_LEN = 8192 //8192  2080
View Source
const OFF_SKIP_LEN = 32768 //32768  8230
View Source
const OFF_STATR = 12 //in advance updata the algorithm
View Source
const PMTSIZE = 4
View Source
const SKIP_CYCLE_LEN = 2048 //2048 520
View Source
const STARTUPDATENUM = 10240 //10240  2600
View Source
const TBLSIZE = 16
View Source
const UPDATABLOCKLENGTH = 12000 //12000  3000

Variables

View Source
var (

	//ErrRewardedBlock is returned if a block to import is already rewarded.
	ErrRewardedBlock = errors.New("block already rewarded")
	ErrRewardEnd     = errors.New("Reward end")
)

Various error messages to mark blocks invalid. These should be private to prevent engine specific errors from being referenced in the remainder of the codebase, inherently breaking if the engine is swapped out. Please put common error types into the consensus package.

View Source
var (

	//SnailBlockRewardsBase Snail block rewards base value is 115.555555555555 * 10^12
	SnailBlockRewardsBase = 115555555555555

	// Big1e6 up to wei  SnailBlockRewardsBase * this is wei
	Big1e6 = big.NewInt(1e6)

	// SnailBlockRewardsChangeInterval Snail block rewards change interval 4500 blocks
	SnailBlockRewardsChangeInterval = 4500

	// SnailBlockRewardsChangePercentage snall block rewards change interval decrease %2
	SnailBlockRewardsChangePercentage = 2

	//BaseBig ...
	BaseBig = big.NewInt(1e18)

	//NetworkFragmentsNuber The number of main network fragments is currently fixed at 1
	NetworkFragmentsNuber = 1

	//MiningConstant Mining constant is 20
	MiningConstant = 20

	//SqrtMin pbft and miner allocation constant
	//Generating formula :TestOutSqrt
	SqrtMin = 25

	//SqrtMax ...
	SqrtMax = 6400

	RewardMinerDecayEpoch = 50000
	NewRewardBegin        = 53550
	NewRewardCoin         = new(big.Int).Mul(big.NewInt(80), BaseBig)
	RewardEndSnailHeight  = 1000000
)
View Source
var ErrInvalidDumpMagic = errors.New("invalid dump magic")

ErrInvalidDumpMagic errorinfo

View Source
var SqrtArray = []float64{} /* 6401 elements not displayed */

Calculation method Assuming that the number of shards is i, the formula is: Sqrt(i) / (Sqrt(i) + MiningConstant) For detailed generation, see the TestOutSqrt method in Consensus testing.

Functions

func CalcDifficulty

func CalcDifficulty(config *params.ChainConfig, time uint64, parents []*types.SnailHeader) *big.Int

CalcDifficulty 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.

func CalcFruitDifficulty

func CalcFruitDifficulty(config *params.ChainConfig, time uint64, fastTime uint64, pointer *types.SnailHeader) *big.Int

CalcFruitDifficulty is the Fruit difficulty adjustment algorithm need calc fruit difficulty each new fruit

func GetBlockReward added in v1.1.1

func GetBlockReward(num *big.Int) (committee, minerBlock, minerFruit *big.Int, e error)

GetBlockReward Reward for block allocation

func GetBlockReward3

func GetBlockReward3(num *big.Int) (committee, minerBlock, minerFruit, developercoin *big.Int, e error)

func GetParents

func GetParents(chain consensus.SnailChainReader, header *types.SnailHeader) []*types.SnailHeader

GetParents the calc different need parents

func LogPrint

func LogPrint(info string, addr common.Address, amount *big.Int)

LogPrint log debug

func MatMuliple

func MatMuliple(input []uint64, output []uint64, pmat []uint64) int

func NewDataset added in v0.10.2

func NewDataset(epoch uint64) interface{}

newDataset creates a new truehash mining dataset

func SeedHash

func SeedHash(block uint64) []byte

SeedHash is the seed to use for generating a verification cache and the mining dataset.

func TruehashLight added in v0.10.2

func TruehashLight(dataset []uint64, hash []byte, nonce uint64) ([]byte, []byte)

Types

type Config

type Config struct {
	CacheDir       string
	CachesInMem    int
	CachesOnDisk   int
	DatasetDir     string
	DatasetsInMem  int
	DatasetsOnDisk int
	PowMode        Mode
	Tip9           uint64
}

Config are the configuration parameters of the minerva.

type ConstSqrt

type ConstSqrt struct {
	Num  int     `json:"num"`
	Sqrt float64 `json:"sqrt"`
}

ConstSqrt ...

type Dataset added in v0.10.2

type Dataset struct {
	// contains filtered or unexported fields
}

dataset wraps an truehash dataset with some metadata to allow easier concurrent use.

func (*Dataset) Generate added in v0.10.2

func (d *Dataset) Generate(epoch uint64, headershash *[STARTUPDATENUM][]byte)

generate ensures that the dataset content is generated before use.

func (*Dataset) GetDataSet added in v0.10.2

func (d *Dataset) GetDataSet() []uint64

func (*Dataset) GetDataSetEpoch added in v0.10.2

func (d *Dataset) GetDataSetEpoch() uint64

func (*Dataset) GetDatasetSeedhash added in v1.1.1

func (d *Dataset) GetDatasetSeedhash(dataset []uint64) string

func (*Dataset) Hash added in v0.10.2

func (d *Dataset) Hash() common.Hash

func (*Dataset) UpdateTBL added in v0.10.2

func (d *Dataset) UpdateTBL(offset [OFF_SKIP_LEN]int, skip [OFF_SKIP_LEN]int, plookupTbl []uint64) []uint64

UpdateTBL Update dataset information

type Minerva

type Minerva struct {
	// contains filtered or unexported fields
}

Minerva consensus

func New

func New(config Config) *Minerva

New creates a full sized minerva hybrid consensus scheme.

func NewFakeDelayer

func NewFakeDelayer(delay time.Duration) *Minerva

NewFakeDelayer creates a minerva consensus engine with a fake PoW scheme that accepts all blocks as valid, but delays verifications by some time, though they still have to conform to the Ethereum consensus rules.

func NewFakeFailer

func NewFakeFailer(fail uint64) *Minerva

NewFakeFailer creates a minerva consensus engine with a fake PoW scheme that accepts all blocks as valid apart from the single one specified, though they still have to conform to the Ethereum consensus rules.

func NewFaker

func NewFaker() *Minerva

NewFaker creates a minerva consensus engine with a fake PoW scheme that accepts all blocks' seal as valid, though they still have to conform to the Ethereum consensus rules.

func NewFullFaker

func NewFullFaker() *Minerva

NewFullFaker creates an minerva consensus engine with a full fake scheme that accepts all blocks as valid, without checking any consensus rules whatsoever.

func NewShared

func NewShared() *Minerva

NewShared creates a full sized minerva shared between all requesters running in the same process.

func NewTester

func NewTester() *Minerva

NewTester creates a small sized minerva scheme useful only for testing purposes.

func (*Minerva) APIs

func (m *Minerva) APIs(chain consensus.ChainReader) []rpc.API

APIs implements consensus.Engine, returning the user facing RPC APIs. Currently that is empty.

func (*Minerva) Author

func (m *Minerva) Author(header *types.Header) (common.Address, error)

Author implements consensus.Engine, returning the header's coinbase as the proof-of-work verified author of the block.

func (*Minerva) AuthorSnail

func (m *Minerva) AuthorSnail(header *types.SnailHeader) (common.Address, error)

AuthorSnail return Snail mine coinbase

func (*Minerva) CalcFruitDifficulty

func (m *Minerva) CalcFruitDifficulty(chain consensus.SnailChainReader, time uint64, fastTime uint64, pointer *types.SnailHeader) *big.Int

CalcFruitDifficulty is Calc the Fruit difficulty again and compare the header diff

func (*Minerva) CalcSnailDifficulty

func (m *Minerva) CalcSnailDifficulty(chain consensus.SnailChainReader, time uint64, parents []*types.SnailHeader) *big.Int

CalcSnailDifficulty 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.

func (*Minerva) ConSeal

func (m *Minerva) ConSeal(chain consensus.SnailChainReader, block *types.SnailBlock, stop <-chan struct{}, send chan *types.SnailBlock)

ConSeal implements consensus.Engine, attempting to find a nonce that satisfies the block's difficulty requirements.

func (*Minerva) DataSetHash

func (m *Minerva) DataSetHash(epoch uint64) string

func (*Minerva) Finalize

func (m *Minerva) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB,
	txs []*types.Transaction, receipts []*types.Receipt, feeAmount *big.Int) (*types.Block, *types.ChainReward, error)

Finalize implements consensus.Engine, accumulating the block fruit and uncle rewards, setting the final state and assembling the block.

func (*Minerva) FinalizeCommittee added in v0.10.1

func (m *Minerva) FinalizeCommittee(block *types.Block) error

FinalizeCommittee upddate current committee state

func (*Minerva) FinalizeSnail

func (m *Minerva) FinalizeSnail(chain consensus.SnailChainReader, header *types.SnailHeader,
	uncles []*types.SnailHeader, fruits []*types.SnailBlock, signs []*types.PbftSign) (*types.SnailBlock, error)

FinalizeSnail implements consensus.Engine, accumulating the block fruit and uncle rewards, setting the final state and assembling the block.

func (*Minerva) GetDifficulty

func (m *Minerva) GetDifficulty(header *types.SnailHeader, isFruit bool) (*big.Int, *big.Int)

GetDifficulty get difficulty by header

func (*Minerva) GetElection

func (m *Minerva) GetElection() consensus.CommitteeElection

GetElection return election

func (*Minerva) GetRewardContentBySnailNumber added in v1.0.2

func (m *Minerva) GetRewardContentBySnailNumber(sBlock *types.SnailBlock) *types.SnailRewardContenet

GetRewardContentBySnailNumber retrieves SnailRewardContenet by snail block.

func (*Minerva) Hashrate

func (m *Minerva) Hashrate() float64

Hashrate implements PoW, returning the measured rate of the search invocations per second over the last minute.

func (*Minerva) NewTestData

func (m *Minerva) NewTestData(block uint64)

NewTestData Method test usage

func (*Minerva) Prepare

func (m *Minerva) Prepare(chain consensus.ChainReader, header *types.Header) error

Prepare implements consensus.Engine, initializing the difficulty field of a header to conform to the minerva protocol. The changes are done inline.

func (*Minerva) PrepareSnail

func (m *Minerva) PrepareSnail(fastchain consensus.ChainReader, chain consensus.SnailChainReader, header *types.SnailHeader) error

PrepareSnail implements consensus.Engine, initializing the difficulty field of a // header to conform to the minerva protocol. The changes are done inline.

func (*Minerva) PrepareSnailWithParent added in v1.1.1

func (m *Minerva) PrepareSnailWithParent(fastchain consensus.ChainReader, chain consensus.SnailChainReader, header *types.SnailHeader, parents []*types.SnailHeader) error

PrepareSnailWithParent implements consensus.Engine, initializing the difficulty field of a // header to conform to the minerva protocol. The changes are done inline.

func (*Minerva) Seal

func (m *Minerva) Seal(chain consensus.SnailChainReader, block *types.SnailBlock, stop <-chan struct{}) (*types.SnailBlock, error)

Seal implements consensus.Engine, attempting to find a nonce that satisfies the block's difficulty requirements.

func (*Minerva) SetElection

func (m *Minerva) SetElection(e consensus.CommitteeElection)

SetElection Append interface CommitteeElection after instantiation

func (*Minerva) SetSnailChainReader

func (m *Minerva) SetSnailChainReader(scr consensus.SnailChainReader)

SetSnailChainReader Append interface SnailChainReader after instantiations

func (*Minerva) SetSnailHeaderHash

func (m *Minerva) SetSnailHeaderHash(db etruedb.Database)

func (*Minerva) SetThreads

func (m *Minerva) SetThreads(threads int)

SetThreads updates the number of mining threads currently enabled. Calling this method does not start mining, only sets the thread count. If zero is specified, the miner will use all cores of the machine. Setting a thread count below zero is allowed and will cause the miner to idle, without any work being done.

func (*Minerva) Threads

func (m *Minerva) Threads() int

Threads returns the number of mining threads currently enabled. This doesn't necessarily mean that mining is running!

func (*Minerva) ValidateFruitHeader

func (m *Minerva) ValidateFruitHeader(block *types.SnailHeader, fruit *types.SnailHeader, chain consensus.SnailChainReader, fastchain consensus.ChainReader, checkpoint uint64) error

ValidateFruitHeader is to verify if the fruit is legal

func (*Minerva) ValidateRewarded

func (m *Minerva) ValidateRewarded(number uint64, hash common.Hash, fastchain consensus.ChainReader) error

ValidateRewarded verify whether the block has been rewarded.

func (*Minerva) VerifyFreshness

func (m *Minerva) VerifyFreshness(chain consensus.SnailChainReader, fruit *types.SnailHeader, headerNumber *big.Int, canonical bool) error

VerifyFreshness the fruit have fresh is 17 blocks

func (*Minerva) VerifyHeader

func (m *Minerva) VerifyHeader(chain consensus.ChainReader, header *types.Header) error

VerifyHeader checks whether a header conforms to the consensus rules of the stock Truechain m engine.

func (*Minerva) VerifyHeaders

func (m *Minerva) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header,
	seals []bool) (chan<- struct{}, <-chan error)

VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers concurrently. The method returns a quit channel to abort the operations and a results channel to retrieve the async verifications.

func (*Minerva) VerifySigns

func (m *Minerva) VerifySigns(fastnumber *big.Int, fastHash common.Hash, signs []*types.PbftSign) error

VerifySigns check the sings included in fast block or fruit

func (*Minerva) VerifySnailHeader

func (m *Minerva) VerifySnailHeader(chain consensus.SnailChainReader, fastchain consensus.ChainReader, header *types.SnailHeader, seal bool, isFruit bool) error

VerifySnailHeader verify snail Header number

func (*Minerva) VerifySnailHeaders

func (m *Minerva) VerifySnailHeaders(chain consensus.SnailChainReader, headers []*types.SnailHeader,
	seals []bool) (chan<- struct{}, <-chan error)

VerifySnailHeaders verify snail headers

func (*Minerva) VerifySnailSeal

func (m *Minerva) VerifySnailSeal(chain consensus.SnailChainReader, header *types.SnailHeader, isFruit bool) error

VerifySnailSeal implements consensus.Engine, checking whether the given block satisfies the PoW difficulty requirements.

func (*Minerva) VerifySnailSeal2 added in v0.10.1

func (m *Minerva) VerifySnailSeal2(hight *big.Int, nonce string, headNoNoncehash string, ftarg *big.Int, btarg *big.Int, haveFruits bool) (bool, bool, []byte)

VerifySnailSeal2 implements consensus.Engine, checking whether the given block satisfies the PoW difficulty requirements.

func (*Minerva) VerifySwitchInfo

func (m *Minerva) VerifySwitchInfo(fastnumber *big.Int, info []*types.CommitteeMember) error

VerifySwitchInfo verify the switch info of Committee

type Mode

type Mode uint

Mode defines the type and amount of PoW verification an minerva engine makes.

const (
	ModeNormal Mode = iota
	ModeShared
	ModeTest
	ModeFake
	ModeFullFake
)

constant

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL