parlia.go 44 KB

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