parlia.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. package parlia
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "math"
  10. "math/big"
  11. "math/rand"
  12. "sort"
  13. "strings"
  14. "sync"
  15. "time"
  16. lru "github.com/hashicorp/golang-lru"
  17. "golang.org/x/crypto/sha3"
  18. "github.com/ethereum/go-ethereum"
  19. "github.com/ethereum/go-ethereum/accounts"
  20. "github.com/ethereum/go-ethereum/accounts/abi"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/gopool"
  23. "github.com/ethereum/go-ethereum/common/hexutil"
  24. "github.com/ethereum/go-ethereum/consensus"
  25. "github.com/ethereum/go-ethereum/consensus/misc"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/forkid"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/systemcontracts"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/core/vm"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/internal/ethapi"
  35. "github.com/ethereum/go-ethereum/log"
  36. "github.com/ethereum/go-ethereum/params"
  37. "github.com/ethereum/go-ethereum/rlp"
  38. "github.com/ethereum/go-ethereum/rpc"
  39. "github.com/ethereum/go-ethereum/trie"
  40. )
  41. const (
  42. inMemorySnapshots = 128 // Number of recent snapshots to keep in memory
  43. inMemorySignatures = 4096 // Number of recent block signatures to keep in memory
  44. checkpointInterval = 1024 // Number of blocks after which to save the snapshot to the database
  45. defaultEpochLength = uint64(100) // Default number of blocks of checkpoint to update validatorSet from contract
  46. extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity
  47. extraSeal = 65 // Fixed number of extra-data suffix bytes reserved for signer seal
  48. nextForkHashSize = 4 // Fixed number of extra-data suffix bytes reserved for nextForkHash.
  49. validatorBytesLength = common.AddressLength
  50. wiggleTime = uint64(1) // second, Random delay (per signer) to allow concurrent signers
  51. initialBackOffTime = uint64(1) // second
  52. systemRewardPercent = 4 // it means 1/2^4 = 1/16 percentage of gas fee incoming will be distributed to system
  53. )
  54. var (
  55. uncleHash = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW.
  56. diffInTurn = big.NewInt(2) // Block difficulty for in-turn signatures
  57. diffNoTurn = big.NewInt(1) // Block difficulty for out-of-turn signatures
  58. // 100 native token
  59. maxSystemBalance = new(big.Int).Mul(big.NewInt(100), big.NewInt(params.Ether))
  60. systemContracts = map[common.Address]bool{
  61. common.HexToAddress(systemcontracts.ValidatorContract): true,
  62. common.HexToAddress(systemcontracts.SlashContract): true,
  63. common.HexToAddress(systemcontracts.SystemRewardContract): true,
  64. common.HexToAddress(systemcontracts.LightClientContract): true,
  65. common.HexToAddress(systemcontracts.RelayerHubContract): true,
  66. common.HexToAddress(systemcontracts.GovHubContract): true,
  67. common.HexToAddress(systemcontracts.TokenHubContract): true,
  68. common.HexToAddress(systemcontracts.RelayerIncentivizeContract): true,
  69. common.HexToAddress(systemcontracts.CrossChainContract): true,
  70. }
  71. )
  72. // Various error messages to mark blocks invalid. These should be private to
  73. // prevent engine specific errors from being referenced in the remainder of the
  74. // codebase, inherently breaking if the engine is swapped out. Please put common
  75. // error types into the consensus package.
  76. var (
  77. // errUnknownBlock is returned when the list of validators is requested for a block
  78. // that is not part of the local blockchain.
  79. errUnknownBlock = errors.New("unknown block")
  80. // errMissingVanity is returned if a block's extra-data section is shorter than
  81. // 32 bytes, which is required to store the signer vanity.
  82. errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing")
  83. // errMissingSignature is returned if a block's extra-data section doesn't seem
  84. // to contain a 65 byte secp256k1 signature.
  85. errMissingSignature = errors.New("extra-data 65 byte signature suffix missing")
  86. // errExtraValidators is returned if non-sprint-end block contain validator data in
  87. // their extra-data fields.
  88. errExtraValidators = errors.New("non-sprint-end block contains extra validator list")
  89. // errInvalidSpanValidators is returned if a block contains an
  90. // invalid list of validators (i.e. non divisible by 20 bytes).
  91. errInvalidSpanValidators = errors.New("invalid validator list on sprint end block")
  92. // errInvalidMixDigest is returned if a block's mix digest is non-zero.
  93. errInvalidMixDigest = errors.New("non-zero mix digest")
  94. // errInvalidUncleHash is returned if a block contains an non-empty uncle list.
  95. errInvalidUncleHash = errors.New("non empty uncle hash")
  96. // errMismatchingEpochValidators is returned if a sprint block contains a
  97. // list of validators different than the one the local node calculated.
  98. errMismatchingEpochValidators = errors.New("mismatching validator list on epoch block")
  99. // errInvalidDifficulty is returned if the difficulty of a block is missing.
  100. errInvalidDifficulty = errors.New("invalid difficulty")
  101. // errWrongDifficulty is returned if the difficulty of a block doesn't match the
  102. // turn of the signer.
  103. errWrongDifficulty = errors.New("wrong difficulty")
  104. // errOutOfRangeChain is returned if an authorization list is attempted to
  105. // be modified via out-of-range or non-contiguous headers.
  106. errOutOfRangeChain = errors.New("out of range or non-contiguous chain")
  107. // errBlockHashInconsistent is returned if an authorization list is attempted to
  108. // insert an inconsistent block.
  109. errBlockHashInconsistent = errors.New("the block hash is inconsistent")
  110. // errUnauthorizedValidator is returned if a header is signed by a non-authorized entity.
  111. errUnauthorizedValidator = errors.New("unauthorized validator")
  112. // errCoinBaseMisMatch is returned if a header's coinbase do not match with signature
  113. errCoinBaseMisMatch = errors.New("coinbase do not match with signature")
  114. // errRecentlySigned is returned if a header is signed by an authorized entity
  115. // that already signed a header recently, thus is temporarily not allowed to.
  116. errRecentlySigned = errors.New("recently signed")
  117. )
  118. // SignerFn is a signer callback function to request a header to be signed by a
  119. // backing account.
  120. type SignerFn func(accounts.Account, string, []byte) ([]byte, error)
  121. type SignerTxFn func(accounts.Account, *types.Transaction, *big.Int) (*types.Transaction, error)
  122. func isToSystemContract(to common.Address) bool {
  123. return systemContracts[to]
  124. }
  125. // ecrecover extracts the Ethereum account address from a signed header.
  126. func ecrecover(header *types.Header, sigCache *lru.ARCCache, chainId *big.Int) (common.Address, error) {
  127. // If the signature's already cached, return that
  128. hash := header.Hash()
  129. if address, known := sigCache.Get(hash); known {
  130. return address.(common.Address), nil
  131. }
  132. // Retrieve the signature from the header extra-data
  133. if len(header.Extra) < extraSeal {
  134. return common.Address{}, errMissingSignature
  135. }
  136. signature := header.Extra[len(header.Extra)-extraSeal:]
  137. // Recover the public key and the Ethereum address
  138. pubkey, err := crypto.Ecrecover(SealHash(header, chainId).Bytes(), signature)
  139. if err != nil {
  140. return common.Address{}, err
  141. }
  142. var signer common.Address
  143. copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  144. sigCache.Add(hash, signer)
  145. return signer, nil
  146. }
  147. // ParliaRLP returns the rlp bytes which needs to be signed for the parlia
  148. // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature
  149. // contained at the end of the extra data.
  150. //
  151. // Note, the method requires the extra data to be at least 65 bytes, otherwise it
  152. // panics. This is done to avoid accidentally using both forms (signature present
  153. // or not), which could be abused to produce different hashes for the same header.
  154. func ParliaRLP(header *types.Header, chainId *big.Int) []byte {
  155. b := new(bytes.Buffer)
  156. encodeSigHeader(b, header, chainId)
  157. return b.Bytes()
  158. }
  159. // Parlia is the consensus engine of BSC
  160. type Parlia struct {
  161. chainConfig *params.ChainConfig // Chain config
  162. config *params.ParliaConfig // Consensus engine configuration parameters for parlia consensus
  163. genesisHash common.Hash
  164. db ethdb.Database // Database to store and retrieve snapshot checkpoints
  165. recentSnaps *lru.ARCCache // Snapshots for recent block to speed up
  166. signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
  167. signer types.Signer
  168. val common.Address // Ethereum address of the signing key
  169. signFn SignerFn // Signer function to authorize hashes with
  170. signTxFn SignerTxFn
  171. lock sync.RWMutex // Protects the signer fields
  172. ethAPI *ethapi.PublicBlockChainAPI
  173. validatorSetABI abi.ABI
  174. slashABI abi.ABI
  175. // The fields below are for testing only
  176. fakeDiff bool // Skip difficulty verifications
  177. }
  178. // New creates a Parlia consensus engine.
  179. func New(
  180. chainConfig *params.ChainConfig,
  181. db ethdb.Database,
  182. ethAPI *ethapi.PublicBlockChainAPI,
  183. genesisHash common.Hash,
  184. ) *Parlia {
  185. // get parlia config
  186. parliaConfig := chainConfig.Parlia
  187. // Set any missing consensus parameters to their defaults
  188. if parliaConfig != nil && parliaConfig.Epoch == 0 {
  189. parliaConfig.Epoch = defaultEpochLength
  190. }
  191. // Allocate the snapshot caches and create the engine
  192. recentSnaps, err := lru.NewARC(inMemorySnapshots)
  193. if err != nil {
  194. panic(err)
  195. }
  196. signatures, err := lru.NewARC(inMemorySignatures)
  197. if err != nil {
  198. panic(err)
  199. }
  200. vABI, err := abi.JSON(strings.NewReader(validatorSetABI))
  201. if err != nil {
  202. panic(err)
  203. }
  204. sABI, err := abi.JSON(strings.NewReader(slashABI))
  205. if err != nil {
  206. panic(err)
  207. }
  208. c := &Parlia{
  209. chainConfig: chainConfig,
  210. config: parliaConfig,
  211. genesisHash: genesisHash,
  212. db: db,
  213. ethAPI: ethAPI,
  214. recentSnaps: recentSnaps,
  215. signatures: signatures,
  216. validatorSetABI: vABI,
  217. slashABI: sABI,
  218. signer: types.NewEIP155Signer(chainConfig.ChainID),
  219. }
  220. return c
  221. }
  222. func (p *Parlia) IsSystemTransaction(tx *types.Transaction, header *types.Header) (bool, error) {
  223. // deploy a contract
  224. if tx.To() == nil {
  225. return false, nil
  226. }
  227. sender, err := types.Sender(p.signer, tx)
  228. if err != nil {
  229. return false, errors.New("UnAuthorized transaction")
  230. }
  231. if sender == header.Coinbase && isToSystemContract(*tx.To()) && tx.GasPrice().Cmp(big.NewInt(0)) == 0 {
  232. return true, nil
  233. }
  234. return false, nil
  235. }
  236. func (p *Parlia) IsSystemContract(to *common.Address) bool {
  237. if to == nil {
  238. return false
  239. }
  240. return isToSystemContract(*to)
  241. }
  242. // Author implements consensus.Engine, returning the SystemAddress
  243. func (p *Parlia) Author(header *types.Header) (common.Address, error) {
  244. return header.Coinbase, nil
  245. }
  246. // VerifyHeader checks whether a header conforms to the consensus rules.
  247. func (p *Parlia) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
  248. return p.verifyHeader(chain, header, nil)
  249. }
  250. // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
  251. // method returns a quit channel to abort the operations and a results channel to
  252. // retrieve the async verifications (the order is that of the input slice).
  253. func (p *Parlia) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
  254. abort := make(chan struct{})
  255. results := make(chan error, len(headers))
  256. gopool.Submit(func() {
  257. for i, header := range headers {
  258. err := p.verifyHeader(chain, header, headers[:i])
  259. select {
  260. case <-abort:
  261. return
  262. case results <- err:
  263. }
  264. }
  265. })
  266. return abort, results
  267. }
  268. // verifyHeader checks whether a header conforms to the consensus rules.The
  269. // caller may optionally pass in a batch of parents (ascending order) to avoid
  270. // looking those up from the database. This is useful for concurrently verifying
  271. // a batch of new headers.
  272. func (p *Parlia) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
  273. if header.Number == nil {
  274. return errUnknownBlock
  275. }
  276. number := header.Number.Uint64()
  277. // Don't waste time checking blocks from the future
  278. if header.Time > uint64(time.Now().Unix()) {
  279. return consensus.ErrFutureBlock
  280. }
  281. // Check that the extra-data contains the vanity, validators and signature.
  282. if len(header.Extra) < extraVanity {
  283. return errMissingVanity
  284. }
  285. if len(header.Extra) < extraVanity+extraSeal {
  286. return errMissingSignature
  287. }
  288. // check extra data
  289. isEpoch := number%p.config.Epoch == 0
  290. // Ensure that the extra-data contains a signer list on checkpoint, but none otherwise
  291. signersBytes := len(header.Extra) - extraVanity - extraSeal
  292. if !isEpoch && signersBytes != 0 {
  293. return errExtraValidators
  294. }
  295. if isEpoch && signersBytes%validatorBytesLength != 0 {
  296. return errInvalidSpanValidators
  297. }
  298. // Ensure that the mix digest is zero as we don't have fork protection currently
  299. if header.MixDigest != (common.Hash{}) {
  300. return errInvalidMixDigest
  301. }
  302. // Ensure that the block doesn't contain any uncles which are meaningless in PoA
  303. if header.UncleHash != uncleHash {
  304. return errInvalidUncleHash
  305. }
  306. // Ensure that the block's difficulty is meaningful (may not be correct at this point)
  307. if number > 0 {
  308. if header.Difficulty == nil {
  309. return errInvalidDifficulty
  310. }
  311. }
  312. // If all checks passed, validate any special fields for hard forks
  313. if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
  314. return err
  315. }
  316. // All basic checks passed, verify cascading fields
  317. return p.verifyCascadingFields(chain, header, parents)
  318. }
  319. // verifyCascadingFields verifies all the header fields that are not standalone,
  320. // rather depend on a batch of previous headers. The caller may optionally pass
  321. // in a batch of parents (ascending order) to avoid looking those up from the
  322. // database. This is useful for concurrently verifying a batch of new headers.
  323. func (p *Parlia) verifyCascadingFields(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
  324. // The genesis block is the always valid dead-end
  325. number := header.Number.Uint64()
  326. if number == 0 {
  327. return nil
  328. }
  329. var parent *types.Header
  330. if len(parents) > 0 {
  331. parent = parents[len(parents)-1]
  332. } else {
  333. parent = chain.GetHeader(header.ParentHash, number-1)
  334. }
  335. if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
  336. return consensus.ErrUnknownAncestor
  337. }
  338. snap, err := p.snapshot(chain, number-1, header.ParentHash, parents)
  339. if err != nil {
  340. return err
  341. }
  342. err = p.blockTimeVerifyForRamanujanFork(snap, header, parent)
  343. if err != nil {
  344. return err
  345. }
  346. // Verify that the gas limit is <= 2^63-1
  347. capacity := uint64(0x7fffffffffffffff)
  348. if header.GasLimit > capacity {
  349. return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, capacity)
  350. }
  351. // Verify that the gasUsed is <= gasLimit
  352. if header.GasUsed > header.GasLimit {
  353. return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
  354. }
  355. // Verify that the gas limit remains within allowed bounds
  356. diff := int64(parent.GasLimit) - int64(header.GasLimit)
  357. if diff < 0 {
  358. diff *= -1
  359. }
  360. limit := parent.GasLimit / params.GasLimitBoundDivisor
  361. if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
  362. return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
  363. }
  364. // All basic checks passed, verify the seal and return
  365. return p.verifySeal(chain, header, parents)
  366. }
  367. // snapshot retrieves the authorization snapshot at a given point in time.
  368. func (p *Parlia) snapshot(chain consensus.ChainHeaderReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
  369. // Search for a snapshot in memory or on disk for checkpoints
  370. var (
  371. headers []*types.Header
  372. snap *Snapshot
  373. )
  374. for snap == nil {
  375. // If an in-memory snapshot was found, use that
  376. if s, ok := p.recentSnaps.Get(hash); ok {
  377. snap = s.(*Snapshot)
  378. break
  379. }
  380. // If an on-disk checkpoint snapshot can be found, use that
  381. if number%checkpointInterval == 0 {
  382. if s, err := loadSnapshot(p.config, p.signatures, p.db, hash, p.ethAPI); err == nil {
  383. log.Trace("Loaded snapshot from disk", "number", number, "hash", hash)
  384. snap = s
  385. break
  386. }
  387. }
  388. // If we're at the genesis, snapshot the initial state.
  389. if number == 0 {
  390. checkpoint := chain.GetHeaderByNumber(number)
  391. if checkpoint != nil {
  392. // get checkpoint data
  393. hash := checkpoint.Hash()
  394. validatorBytes := checkpoint.Extra[extraVanity : len(checkpoint.Extra)-extraSeal]
  395. // get validators from headers
  396. validators, err := ParseValidators(validatorBytes)
  397. if err != nil {
  398. return nil, err
  399. }
  400. // new snap shot
  401. snap = newSnapshot(p.config, p.signatures, number, hash, validators, p.ethAPI)
  402. if err := snap.store(p.db); err != nil {
  403. return nil, err
  404. }
  405. log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash)
  406. break
  407. }
  408. }
  409. // No snapshot for this header, gather the header and move backward
  410. var header *types.Header
  411. if len(parents) > 0 {
  412. // If we have explicit parents, pick from there (enforced)
  413. header = parents[len(parents)-1]
  414. if header.Hash() != hash || header.Number.Uint64() != number {
  415. return nil, consensus.ErrUnknownAncestor
  416. }
  417. parents = parents[:len(parents)-1]
  418. } else {
  419. // No explicit parents (or no more left), reach out to the database
  420. header = chain.GetHeader(hash, number)
  421. if header == nil {
  422. return nil, consensus.ErrUnknownAncestor
  423. }
  424. }
  425. headers = append(headers, header)
  426. number, hash = number-1, header.ParentHash
  427. }
  428. // check if snapshot is nil
  429. if snap == nil {
  430. return nil, fmt.Errorf("unknown error while retrieving snapshot at block number %v", number)
  431. }
  432. // Previous snapshot found, apply any pending headers on top of it
  433. for i := 0; i < len(headers)/2; i++ {
  434. headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
  435. }
  436. snap, err := snap.apply(headers, chain, parents, p.chainConfig.ChainID)
  437. if err != nil {
  438. return nil, err
  439. }
  440. p.recentSnaps.Add(snap.Hash, snap)
  441. // If we've generated a new checkpoint snapshot, save to disk
  442. if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
  443. if err = snap.store(p.db); err != nil {
  444. return nil, err
  445. }
  446. log.Trace("Stored snapshot to disk", "number", snap.Number, "hash", snap.Hash)
  447. }
  448. return snap, err
  449. }
  450. // VerifyUncles implements consensus.Engine, always returning an error for any
  451. // uncles as this consensus mechanism doesn't permit uncles.
  452. func (p *Parlia) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
  453. if len(block.Uncles()) > 0 {
  454. return errors.New("uncles not allowed")
  455. }
  456. return nil
  457. }
  458. // VerifySeal implements consensus.Engine, checking whether the signature contained
  459. // in the header satisfies the consensus protocol requirements.
  460. func (p *Parlia) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
  461. return p.verifySeal(chain, header, nil)
  462. }
  463. // verifySeal checks whether the signature contained in the header satisfies the
  464. // consensus protocol requirements. The method accepts an optional list of parent
  465. // headers that aren't yet part of the local blockchain to generate the snapshots
  466. // from.
  467. func (p *Parlia) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
  468. // Verifying the genesis block is not supported
  469. number := header.Number.Uint64()
  470. if number == 0 {
  471. return errUnknownBlock
  472. }
  473. // Retrieve the snapshot needed to verify this header and cache it
  474. snap, err := p.snapshot(chain, number-1, header.ParentHash, parents)
  475. if err != nil {
  476. return err
  477. }
  478. // Resolve the authorization key and check against validators
  479. signer, err := ecrecover(header, p.signatures, p.chainConfig.ChainID)
  480. if err != nil {
  481. return err
  482. }
  483. if signer != header.Coinbase {
  484. return errCoinBaseMisMatch
  485. }
  486. if _, ok := snap.Validators[signer]; !ok {
  487. return errUnauthorizedValidator
  488. }
  489. for seen, recent := range snap.Recents {
  490. if recent == signer {
  491. // Signer is among recents, only fail if the current block doesn't shift it out
  492. if limit := uint64(len(snap.Validators)/2 + 1); seen > number-limit {
  493. return errRecentlySigned
  494. }
  495. }
  496. }
  497. // Ensure that the difficulty corresponds to the turn-ness of the signer
  498. if !p.fakeDiff {
  499. inturn := snap.inturn(signer)
  500. if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
  501. return errWrongDifficulty
  502. }
  503. if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
  504. return errWrongDifficulty
  505. }
  506. }
  507. return nil
  508. }
  509. // Prepare implements consensus.Engine, preparing all the consensus fields of the
  510. // header for running the transactions on top.
  511. func (p *Parlia) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
  512. header.Coinbase = p.val
  513. header.Nonce = types.BlockNonce{}
  514. number := header.Number.Uint64()
  515. snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
  516. if err != nil {
  517. return err
  518. }
  519. // Set the correct difficulty
  520. header.Difficulty = CalcDifficulty(snap, p.val)
  521. // Ensure the extra data has all it's components
  522. if len(header.Extra) < extraVanity-nextForkHashSize {
  523. header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-nextForkHashSize-len(header.Extra))...)
  524. }
  525. header.Extra = header.Extra[:extraVanity-nextForkHashSize]
  526. nextForkHash := forkid.NextForkHash(p.chainConfig, p.genesisHash, number)
  527. header.Extra = append(header.Extra, nextForkHash[:]...)
  528. if number%p.config.Epoch == 0 {
  529. newValidators, err := p.getCurrentValidators(header.ParentHash)
  530. if err != nil {
  531. return err
  532. }
  533. // sort validator by address
  534. sort.Sort(validatorsAscending(newValidators))
  535. for _, validator := range newValidators {
  536. header.Extra = append(header.Extra, validator.Bytes()...)
  537. }
  538. }
  539. // add extra seal space
  540. header.Extra = append(header.Extra, make([]byte, extraSeal)...)
  541. // Mix digest is reserved for now, set to empty
  542. header.MixDigest = common.Hash{}
  543. // Ensure the timestamp has the correct delay
  544. parent := chain.GetHeader(header.ParentHash, number-1)
  545. if parent == nil {
  546. return consensus.ErrUnknownAncestor
  547. }
  548. header.Time = p.blockTimeForRamanujanFork(snap, header, parent)
  549. if header.Time < uint64(time.Now().Unix()) {
  550. header.Time = uint64(time.Now().Unix())
  551. }
  552. return nil
  553. }
  554. // Finalize implements consensus.Engine, ensuring no uncles are set, nor block
  555. // rewards given.
  556. func (p *Parlia) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs *[]*types.Transaction,
  557. uncles []*types.Header, receipts *[]*types.Receipt, systemTxs *[]*types.Transaction, usedGas *uint64) error {
  558. // warn if not in majority fork
  559. number := header.Number.Uint64()
  560. snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
  561. if err != nil {
  562. return err
  563. }
  564. nextForkHash := forkid.NextForkHash(p.chainConfig, p.genesisHash, number)
  565. if !snap.isMajorityFork(hex.EncodeToString(nextForkHash[:])) {
  566. log.Debug("there is a possible fork, and your client is not the majority. Please check...", "nextForkHash", hex.EncodeToString(nextForkHash[:]))
  567. }
  568. // If the block is a epoch end block, verify the validator list
  569. // The verification can only be done when the state is ready, it can't be done in VerifyHeader.
  570. if header.Number.Uint64()%p.config.Epoch == 0 {
  571. newValidators, err := p.getCurrentValidators(header.ParentHash)
  572. if err != nil {
  573. return err
  574. }
  575. // sort validator by address
  576. sort.Sort(validatorsAscending(newValidators))
  577. validatorsBytes := make([]byte, len(newValidators)*validatorBytesLength)
  578. for i, validator := range newValidators {
  579. copy(validatorsBytes[i*validatorBytesLength:], validator.Bytes())
  580. }
  581. extraSuffix := len(header.Extra) - extraSeal
  582. if !bytes.Equal(header.Extra[extraVanity:extraSuffix], validatorsBytes) {
  583. return errMismatchingEpochValidators
  584. }
  585. }
  586. // No block rewards in PoA, so the state remains as is and uncles are dropped
  587. cx := chainContext{Chain: chain, parlia: p}
  588. if header.Number.Cmp(common.Big1) == 0 {
  589. err := p.initContract(state, header, cx, txs, receipts, systemTxs, usedGas, false)
  590. if err != nil {
  591. log.Error("init contract failed")
  592. }
  593. }
  594. if header.Difficulty.Cmp(diffInTurn) != 0 {
  595. spoiledVal := snap.supposeValidator()
  596. signedRecently := false
  597. for _, recent := range snap.Recents {
  598. if recent == spoiledVal {
  599. signedRecently = true
  600. break
  601. }
  602. }
  603. if !signedRecently {
  604. log.Trace("slash validator", "block hash", header.Hash(), "address", spoiledVal)
  605. err = p.slash(spoiledVal, state, header, cx, txs, receipts, systemTxs, usedGas, false)
  606. if err != nil {
  607. // it is possible that slash validator failed because of the slash channel is disabled.
  608. log.Error("slash validator failed", "block hash", header.Hash(), "address", spoiledVal)
  609. }
  610. }
  611. }
  612. val := header.Coinbase
  613. err = p.distributeIncoming(val, state, header, cx, txs, receipts, systemTxs, usedGas, false)
  614. if err != nil {
  615. return err
  616. }
  617. if len(*systemTxs) > 0 {
  618. return errors.New("the length of systemTxs do not match")
  619. }
  620. return nil
  621. }
  622. // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
  623. // nor block rewards given, and returns the final block.
  624. func (p *Parlia) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB,
  625. txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, []*types.Receipt, error) {
  626. // No block rewards in PoA, so the state remains as is and uncles are dropped
  627. cx := chainContext{Chain: chain, parlia: p}
  628. if txs == nil {
  629. txs = make([]*types.Transaction, 0)
  630. }
  631. if receipts == nil {
  632. receipts = make([]*types.Receipt, 0)
  633. }
  634. if header.Number.Cmp(common.Big1) == 0 {
  635. err := p.initContract(state, header, cx, &txs, &receipts, nil, &header.GasUsed, true)
  636. if err != nil {
  637. log.Error("init contract failed")
  638. }
  639. }
  640. if header.Difficulty.Cmp(diffInTurn) != 0 {
  641. number := header.Number.Uint64()
  642. snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
  643. if err != nil {
  644. return nil, nil, err
  645. }
  646. spoiledVal := snap.supposeValidator()
  647. signedRecently := false
  648. for _, recent := range snap.Recents {
  649. if recent == spoiledVal {
  650. signedRecently = true
  651. break
  652. }
  653. }
  654. if !signedRecently {
  655. err = p.slash(spoiledVal, state, header, cx, &txs, &receipts, nil, &header.GasUsed, true)
  656. if err != nil {
  657. // it is possible that slash validator failed because of the slash channel is disabled.
  658. log.Error("slash validator failed", "block hash", header.Hash(), "address", spoiledVal)
  659. }
  660. }
  661. }
  662. err := p.distributeIncoming(p.val, state, header, cx, &txs, &receipts, nil, &header.GasUsed, true)
  663. if err != nil {
  664. return nil, nil, err
  665. }
  666. // should not happen. Once happen, stop the node is better than broadcast the block
  667. if header.GasLimit < header.GasUsed {
  668. return nil, nil, errors.New("gas consumption of system txs exceed the gas limit")
  669. }
  670. header.UncleHash = types.CalcUncleHash(nil)
  671. var blk *types.Block
  672. var rootHash common.Hash
  673. wg := sync.WaitGroup{}
  674. wg.Add(2)
  675. go func() {
  676. rootHash = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  677. wg.Done()
  678. }()
  679. go func() {
  680. blk = types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil))
  681. wg.Done()
  682. }()
  683. wg.Wait()
  684. blk.SetRoot(rootHash)
  685. // Assemble and return the final block for sealing
  686. return blk, receipts, nil
  687. }
  688. // Authorize injects a private key into the consensus engine to mint new blocks
  689. // with.
  690. func (p *Parlia) Authorize(val common.Address, signFn SignerFn, signTxFn SignerTxFn) {
  691. p.lock.Lock()
  692. defer p.lock.Unlock()
  693. p.val = val
  694. p.signFn = signFn
  695. p.signTxFn = signTxFn
  696. }
  697. func (p *Parlia) Delay(chain consensus.ChainReader, header *types.Header) *time.Duration {
  698. number := header.Number.Uint64()
  699. snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
  700. if err != nil {
  701. return nil
  702. }
  703. delay := p.delayForRamanujanFork(snap, header)
  704. return &delay
  705. }
  706. // Seal implements consensus.Engine, attempting to create a sealed block using
  707. // the local signing credentials.
  708. func (p *Parlia) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
  709. header := block.Header()
  710. // Sealing the genesis block is not supported
  711. number := header.Number.Uint64()
  712. if number == 0 {
  713. return errUnknownBlock
  714. }
  715. // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
  716. if p.config.Period == 0 && len(block.Transactions()) == 0 {
  717. log.Info("Sealing paused, waiting for transactions")
  718. return nil
  719. }
  720. // Don't hold the val fields for the entire sealing procedure
  721. p.lock.RLock()
  722. val, signFn := p.val, p.signFn
  723. p.lock.RUnlock()
  724. snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
  725. if err != nil {
  726. return err
  727. }
  728. // Bail out if we're unauthorized to sign a block
  729. if _, authorized := snap.Validators[val]; !authorized {
  730. return errUnauthorizedValidator
  731. }
  732. // If we're amongst the recent signers, wait for the next block
  733. for seen, recent := range snap.Recents {
  734. if recent == val {
  735. // Signer is among recents, only wait if the current block doesn't shift it out
  736. if limit := uint64(len(snap.Validators)/2 + 1); number < limit || seen > number-limit {
  737. log.Info("Signed recently, must wait for others")
  738. return nil
  739. }
  740. }
  741. }
  742. // Sweet, the protocol permits us to sign the block, wait for our time
  743. delay := p.delayForRamanujanFork(snap, header)
  744. log.Info("Sealing block with", "number", number, "delay", delay, "headerDifficulty", header.Difficulty, "val", val.Hex())
  745. // Sign all the things!
  746. sig, err := signFn(accounts.Account{Address: val}, accounts.MimetypeParlia, ParliaRLP(header, p.chainConfig.ChainID))
  747. if err != nil {
  748. return err
  749. }
  750. copy(header.Extra[len(header.Extra)-extraSeal:], sig)
  751. // Wait until sealing is terminated or delay timeout.
  752. log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
  753. go func() {
  754. select {
  755. case <-stop:
  756. return
  757. case <-time.After(delay):
  758. }
  759. select {
  760. case results <- block.WithSeal(header):
  761. default:
  762. log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header, p.chainConfig.ChainID))
  763. }
  764. }()
  765. return nil
  766. }
  767. func (p *Parlia) EnoughDistance(chain consensus.ChainReader, header *types.Header) bool {
  768. snap, err := p.snapshot(chain, header.Number.Uint64()-1, header.ParentHash, nil)
  769. if err != nil {
  770. return true
  771. }
  772. return snap.enoughDistance(p.val, header)
  773. }
  774. func (p *Parlia) IsLocalBlock(header *types.Header) bool {
  775. return p.val == header.Coinbase
  776. }
  777. func (p *Parlia) SignRecently(chain consensus.ChainReader, parent *types.Header) (bool, error) {
  778. snap, err := p.snapshot(chain, parent.Number.Uint64(), parent.ParentHash, nil)
  779. if err != nil {
  780. return true, err
  781. }
  782. // Bail out if we're unauthorized to sign a block
  783. if _, authorized := snap.Validators[p.val]; !authorized {
  784. return true, errUnauthorizedValidator
  785. }
  786. // If we're amongst the recent signers, wait for the next block
  787. number := parent.Number.Uint64() + 1
  788. for seen, recent := range snap.Recents {
  789. if recent == p.val {
  790. // Signer is among recents, only wait if the current block doesn't shift it out
  791. if limit := uint64(len(snap.Validators)/2 + 1); number < limit || seen > number-limit {
  792. return true, nil
  793. }
  794. }
  795. }
  796. return false, nil
  797. }
  798. // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
  799. // that a new block should have based on the previous blocks in the chain and the
  800. // current signer.
  801. func (p *Parlia) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
  802. snap, err := p.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
  803. if err != nil {
  804. return nil
  805. }
  806. return CalcDifficulty(snap, p.val)
  807. }
  808. // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
  809. // that a new block should have based on the previous blocks in the chain and the
  810. // current signer.
  811. func CalcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
  812. if snap.inturn(signer) {
  813. return new(big.Int).Set(diffInTurn)
  814. }
  815. return new(big.Int).Set(diffNoTurn)
  816. }
  817. // SealHash returns the hash of a block prior to it being sealed.
  818. func (p *Parlia) SealHash(header *types.Header) common.Hash {
  819. return SealHash(header, p.chainConfig.ChainID)
  820. }
  821. // APIs implements consensus.Engine, returning the user facing RPC API to query snapshot.
  822. func (p *Parlia) APIs(chain consensus.ChainHeaderReader) []rpc.API {
  823. return []rpc.API{{
  824. Namespace: "parlia",
  825. Version: "1.0",
  826. Service: &API{chain: chain, parlia: p},
  827. Public: false,
  828. }}
  829. }
  830. // Close implements consensus.Engine. It's a noop for parlia as there are no background threads.
  831. func (p *Parlia) Close() error {
  832. return nil
  833. }
  834. // ========================== interaction with contract/account =========
  835. // getCurrentValidators get current validators
  836. func (p *Parlia) getCurrentValidators(blockHash common.Hash) ([]common.Address, error) {
  837. // block
  838. blockNr := rpc.BlockNumberOrHashWithHash(blockHash, false)
  839. // method
  840. method := "getValidators"
  841. ctx, cancel := context.WithCancel(context.Background())
  842. defer cancel() // cancel when we are finished consuming integers
  843. data, err := p.validatorSetABI.Pack(method)
  844. if err != nil {
  845. log.Error("Unable to pack tx for getValidators", "error", err)
  846. return nil, err
  847. }
  848. // call
  849. msgData := (hexutil.Bytes)(data)
  850. toAddress := common.HexToAddress(systemcontracts.ValidatorContract)
  851. gas := (hexutil.Uint64)(uint64(math.MaxUint64 / 2))
  852. result, err := p.ethAPI.Call(ctx, ethapi.CallArgs{
  853. Gas: &gas,
  854. To: &toAddress,
  855. Data: &msgData,
  856. }, blockNr, nil)
  857. if err != nil {
  858. return nil, err
  859. }
  860. var (
  861. ret0 = new([]common.Address)
  862. )
  863. out := ret0
  864. if err := p.validatorSetABI.UnpackIntoInterface(out, method, result); err != nil {
  865. return nil, err
  866. }
  867. valz := make([]common.Address, len(*ret0))
  868. for i, a := range *ret0 {
  869. valz[i] = a
  870. }
  871. return valz, nil
  872. }
  873. // slash spoiled validators
  874. func (p *Parlia) distributeIncoming(val common.Address, state *state.StateDB, header *types.Header, chain core.ChainContext,
  875. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  876. coinbase := header.Coinbase
  877. balance := state.GetBalance(consensus.SystemAddress)
  878. if balance.Cmp(common.Big0) <= 0 {
  879. return nil
  880. }
  881. state.SetBalance(consensus.SystemAddress, big.NewInt(0))
  882. state.AddBalance(coinbase, balance)
  883. doDistributeSysReward := state.GetBalance(common.HexToAddress(systemcontracts.SystemRewardContract)).Cmp(maxSystemBalance) < 0
  884. if doDistributeSysReward {
  885. var rewards = new(big.Int)
  886. rewards = rewards.Rsh(balance, systemRewardPercent)
  887. if rewards.Cmp(common.Big0) > 0 {
  888. err := p.distributeToSystem(rewards, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  889. if err != nil {
  890. return err
  891. }
  892. log.Trace("distribute to system reward pool", "block hash", header.Hash(), "amount", rewards)
  893. balance = balance.Sub(balance, rewards)
  894. }
  895. }
  896. log.Trace("distribute to validator contract", "block hash", header.Hash(), "amount", balance)
  897. return p.distributeToValidator(balance, val, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  898. }
  899. // slash spoiled validators
  900. func (p *Parlia) slash(spoiledVal common.Address, state *state.StateDB, header *types.Header, chain core.ChainContext,
  901. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  902. // method
  903. method := "slash"
  904. // get packed data
  905. data, err := p.slashABI.Pack(method,
  906. spoiledVal,
  907. )
  908. if err != nil {
  909. log.Error("Unable to pack tx for slash", "error", err)
  910. return err
  911. }
  912. // get system message
  913. msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.SlashContract), data, common.Big0)
  914. // apply message
  915. return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  916. }
  917. // init contract
  918. func (p *Parlia) initContract(state *state.StateDB, header *types.Header, chain core.ChainContext,
  919. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  920. // method
  921. method := "init"
  922. // contracts
  923. contracts := []string{
  924. systemcontracts.ValidatorContract,
  925. systemcontracts.SlashContract,
  926. systemcontracts.LightClientContract,
  927. systemcontracts.RelayerHubContract,
  928. systemcontracts.TokenHubContract,
  929. systemcontracts.RelayerIncentivizeContract,
  930. systemcontracts.CrossChainContract,
  931. }
  932. // get packed data
  933. data, err := p.validatorSetABI.Pack(method)
  934. if err != nil {
  935. log.Error("Unable to pack tx for init validator set", "error", err)
  936. return err
  937. }
  938. for _, c := range contracts {
  939. msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(c), data, common.Big0)
  940. // apply message
  941. log.Trace("init contract", "block hash", header.Hash(), "contract", c)
  942. err = p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  943. if err != nil {
  944. return err
  945. }
  946. }
  947. return nil
  948. }
  949. func (p *Parlia) distributeToSystem(amount *big.Int, state *state.StateDB, header *types.Header, chain core.ChainContext,
  950. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  951. // get system message
  952. msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.SystemRewardContract), nil, amount)
  953. // apply message
  954. return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  955. }
  956. // slash spoiled validators
  957. func (p *Parlia) distributeToValidator(amount *big.Int, validator common.Address,
  958. state *state.StateDB, header *types.Header, chain core.ChainContext,
  959. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  960. // method
  961. method := "deposit"
  962. // get packed data
  963. data, err := p.validatorSetABI.Pack(method,
  964. validator,
  965. )
  966. if err != nil {
  967. log.Error("Unable to pack tx for deposit", "error", err)
  968. return err
  969. }
  970. // get system message
  971. msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.ValidatorContract), data, amount)
  972. // apply message
  973. return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  974. }
  975. // get system message
  976. func (p *Parlia) getSystemMessage(from, toAddress common.Address, data []byte, value *big.Int) callmsg {
  977. return callmsg{
  978. ethereum.CallMsg{
  979. From: from,
  980. Gas: math.MaxUint64 / 2,
  981. GasPrice: big.NewInt(0),
  982. Value: value,
  983. To: &toAddress,
  984. Data: data,
  985. },
  986. }
  987. }
  988. func (p *Parlia) applyTransaction(
  989. msg callmsg,
  990. state *state.StateDB,
  991. header *types.Header,
  992. chainContext core.ChainContext,
  993. txs *[]*types.Transaction, receipts *[]*types.Receipt,
  994. receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool,
  995. ) (err error) {
  996. nonce := state.GetNonce(msg.From())
  997. expectedTx := types.NewTransaction(nonce, *msg.To(), msg.Value(), msg.Gas(), msg.GasPrice(), msg.Data())
  998. expectedHash := p.signer.Hash(expectedTx)
  999. if msg.From() == p.val && mining {
  1000. expectedTx, err = p.signTxFn(accounts.Account{Address: msg.From()}, expectedTx, p.chainConfig.ChainID)
  1001. if err != nil {
  1002. return err
  1003. }
  1004. } else {
  1005. if receivedTxs == nil || len(*receivedTxs) == 0 || (*receivedTxs)[0] == nil {
  1006. return errors.New("supposed to get a actual transaction, but get none")
  1007. }
  1008. actualTx := (*receivedTxs)[0]
  1009. if !bytes.Equal(p.signer.Hash(actualTx).Bytes(), expectedHash.Bytes()) {
  1010. return fmt.Errorf("expected tx hash %v, get %v, nonce %d, to %s, value %s, gas %d, gasPrice %s, data %s", expectedHash.String(), actualTx.Hash().String(),
  1011. expectedTx.Nonce(),
  1012. expectedTx.To().String(),
  1013. expectedTx.Value().String(),
  1014. expectedTx.Gas(),
  1015. expectedTx.GasPrice().String(),
  1016. hex.EncodeToString(expectedTx.Data()),
  1017. )
  1018. }
  1019. expectedTx = actualTx
  1020. // move to next
  1021. *receivedTxs = (*receivedTxs)[1:]
  1022. }
  1023. state.Prepare(expectedTx.Hash(), common.Hash{}, len(*txs))
  1024. gasUsed, err := applyMessage(msg, state, header, p.chainConfig, chainContext)
  1025. if err != nil {
  1026. return err
  1027. }
  1028. *txs = append(*txs, expectedTx)
  1029. var root []byte
  1030. if p.chainConfig.IsByzantium(header.Number) {
  1031. state.Finalise(true)
  1032. } else {
  1033. root = state.IntermediateRoot(p.chainConfig.IsEIP158(header.Number)).Bytes()
  1034. }
  1035. *usedGas += gasUsed
  1036. receipt := types.NewReceipt(root, false, *usedGas)
  1037. receipt.TxHash = expectedTx.Hash()
  1038. receipt.GasUsed = gasUsed
  1039. // Set the receipt logs and create a bloom for filtering
  1040. receipt.Logs = state.GetLogs(expectedTx.Hash())
  1041. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  1042. receipt.BlockHash = state.BlockHash()
  1043. receipt.BlockNumber = header.Number
  1044. receipt.TransactionIndex = uint(state.TxIndex())
  1045. *receipts = append(*receipts, receipt)
  1046. state.SetNonce(msg.From(), nonce+1)
  1047. return nil
  1048. }
  1049. // =========================== utility function ==========================
  1050. // SealHash returns the hash of a block prior to it being sealed.
  1051. func SealHash(header *types.Header, chainId *big.Int) (hash common.Hash) {
  1052. hasher := sha3.NewLegacyKeccak256()
  1053. encodeSigHeader(hasher, header, chainId)
  1054. hasher.Sum(hash[:0])
  1055. return hash
  1056. }
  1057. func encodeSigHeader(w io.Writer, header *types.Header, chainId *big.Int) {
  1058. err := rlp.Encode(w, []interface{}{
  1059. chainId,
  1060. header.ParentHash,
  1061. header.UncleHash,
  1062. header.Coinbase,
  1063. header.Root,
  1064. header.TxHash,
  1065. header.ReceiptHash,
  1066. header.Bloom,
  1067. header.Difficulty,
  1068. header.Number,
  1069. header.GasLimit,
  1070. header.GasUsed,
  1071. header.Time,
  1072. header.Extra[:len(header.Extra)-65], // this will panic if extra is too short, should check before calling encodeSigHeader
  1073. header.MixDigest,
  1074. header.Nonce,
  1075. })
  1076. if err != nil {
  1077. panic("can't encode: " + err.Error())
  1078. }
  1079. }
  1080. func backOffTime(snap *Snapshot, val common.Address) uint64 {
  1081. if snap.inturn(val) {
  1082. return 0
  1083. } else {
  1084. idx := snap.indexOfVal(val)
  1085. if idx < 0 {
  1086. // The backOffTime does not matter when a validator is not authorized.
  1087. return 0
  1088. }
  1089. s := rand.NewSource(int64(snap.Number))
  1090. r := rand.New(s)
  1091. n := len(snap.Validators)
  1092. backOffSteps := make([]uint64, 0, n)
  1093. for idx := uint64(0); idx < uint64(n); idx++ {
  1094. backOffSteps = append(backOffSteps, idx)
  1095. }
  1096. r.Shuffle(n, func(i, j int) {
  1097. backOffSteps[i], backOffSteps[j] = backOffSteps[j], backOffSteps[i]
  1098. })
  1099. delay := initialBackOffTime + backOffSteps[idx]*wiggleTime
  1100. return delay
  1101. }
  1102. }
  1103. // chain context
  1104. type chainContext struct {
  1105. Chain consensus.ChainHeaderReader
  1106. parlia consensus.Engine
  1107. }
  1108. func (c chainContext) Engine() consensus.Engine {
  1109. return c.parlia
  1110. }
  1111. func (c chainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
  1112. return c.Chain.GetHeader(hash, number)
  1113. }
  1114. // callmsg implements core.Message to allow passing it as a transaction simulator.
  1115. type callmsg struct {
  1116. ethereum.CallMsg
  1117. }
  1118. func (m callmsg) From() common.Address { return m.CallMsg.From }
  1119. func (m callmsg) Nonce() uint64 { return 0 }
  1120. func (m callmsg) CheckNonce() bool { return false }
  1121. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  1122. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  1123. func (m callmsg) Gas() uint64 { return m.CallMsg.Gas }
  1124. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  1125. func (m callmsg) Data() []byte { return m.CallMsg.Data }
  1126. // apply message
  1127. func applyMessage(
  1128. msg callmsg,
  1129. state *state.StateDB,
  1130. header *types.Header,
  1131. chainConfig *params.ChainConfig,
  1132. chainContext core.ChainContext,
  1133. ) (uint64, error) {
  1134. // Create a new context to be used in the EVM environment
  1135. context := core.NewEVMBlockContext(header, chainContext, nil)
  1136. // Create a new environment which holds all relevant information
  1137. // about the transaction and calling mechanisms.
  1138. vmenv := vm.NewEVM(context, vm.TxContext{Origin: msg.From(), GasPrice: big.NewInt(0)}, state, chainConfig, vm.Config{})
  1139. // Apply the transaction to the current state (included in the env)
  1140. ret, returnGas, err := vmenv.Call(
  1141. vm.AccountRef(msg.From()),
  1142. *msg.To(),
  1143. msg.Data(),
  1144. msg.Gas(),
  1145. msg.Value(),
  1146. )
  1147. if err != nil {
  1148. log.Error("apply message failed", "msg", string(ret), "err", err)
  1149. }
  1150. return msg.Gas() - returnGas, err
  1151. }