parlia.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  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. // The blocking time should be no more than half of period
  705. half := time.Duration(p.config.Period) * time.Second / 2
  706. if delay > half {
  707. delay = half
  708. }
  709. return &delay
  710. }
  711. // Seal implements consensus.Engine, attempting to create a sealed block using
  712. // the local signing credentials.
  713. func (p *Parlia) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
  714. header := block.Header()
  715. // Sealing the genesis block is not supported
  716. number := header.Number.Uint64()
  717. if number == 0 {
  718. return errUnknownBlock
  719. }
  720. // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
  721. if p.config.Period == 0 && len(block.Transactions()) == 0 {
  722. log.Info("Sealing paused, waiting for transactions")
  723. return nil
  724. }
  725. // Don't hold the val fields for the entire sealing procedure
  726. p.lock.RLock()
  727. val, signFn := p.val, p.signFn
  728. p.lock.RUnlock()
  729. snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
  730. if err != nil {
  731. return err
  732. }
  733. // Bail out if we're unauthorized to sign a block
  734. if _, authorized := snap.Validators[val]; !authorized {
  735. return errUnauthorizedValidator
  736. }
  737. // If we're amongst the recent signers, wait for the next block
  738. for seen, recent := range snap.Recents {
  739. if recent == val {
  740. // Signer is among recents, only wait if the current block doesn't shift it out
  741. if limit := uint64(len(snap.Validators)/2 + 1); number < limit || seen > number-limit {
  742. log.Info("Signed recently, must wait for others")
  743. return nil
  744. }
  745. }
  746. }
  747. // Sweet, the protocol permits us to sign the block, wait for our time
  748. delay := p.delayForRamanujanFork(snap, header)
  749. log.Info("Sealing block with", "number", number, "delay", delay, "headerDifficulty", header.Difficulty, "val", val.Hex())
  750. // Sign all the things!
  751. sig, err := signFn(accounts.Account{Address: val}, accounts.MimetypeParlia, ParliaRLP(header, p.chainConfig.ChainID))
  752. if err != nil {
  753. return err
  754. }
  755. copy(header.Extra[len(header.Extra)-extraSeal:], sig)
  756. // Wait until sealing is terminated or delay timeout.
  757. log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
  758. go func() {
  759. select {
  760. case <-stop:
  761. return
  762. case <-time.After(delay):
  763. }
  764. select {
  765. case results <- block.WithSeal(header):
  766. default:
  767. log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header, p.chainConfig.ChainID))
  768. }
  769. }()
  770. return nil
  771. }
  772. func (p *Parlia) EnoughDistance(chain consensus.ChainReader, header *types.Header) bool {
  773. snap, err := p.snapshot(chain, header.Number.Uint64()-1, header.ParentHash, nil)
  774. if err != nil {
  775. return true
  776. }
  777. return snap.enoughDistance(p.val, header)
  778. }
  779. func (p *Parlia) AllowLightProcess(chain consensus.ChainReader, currentHeader *types.Header) bool {
  780. snap, err := p.snapshot(chain, currentHeader.Number.Uint64()-1, currentHeader.ParentHash, nil)
  781. if err != nil {
  782. return true
  783. }
  784. idx := snap.indexOfVal(p.val)
  785. // validator is not allowed to diff sync
  786. return idx < 0
  787. }
  788. func (p *Parlia) IsLocalBlock(header *types.Header) bool {
  789. return p.val == header.Coinbase
  790. }
  791. func (p *Parlia) SignRecently(chain consensus.ChainReader, parent *types.Header) (bool, error) {
  792. snap, err := p.snapshot(chain, parent.Number.Uint64(), parent.ParentHash, nil)
  793. if err != nil {
  794. return true, err
  795. }
  796. // Bail out if we're unauthorized to sign a block
  797. if _, authorized := snap.Validators[p.val]; !authorized {
  798. return true, errUnauthorizedValidator
  799. }
  800. // If we're amongst the recent signers, wait for the next block
  801. number := parent.Number.Uint64() + 1
  802. for seen, recent := range snap.Recents {
  803. if recent == p.val {
  804. // Signer is among recents, only wait if the current block doesn't shift it out
  805. if limit := uint64(len(snap.Validators)/2 + 1); number < limit || seen > number-limit {
  806. return true, nil
  807. }
  808. }
  809. }
  810. return false, nil
  811. }
  812. // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
  813. // that a new block should have based on the previous blocks in the chain and the
  814. // current signer.
  815. func (p *Parlia) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
  816. snap, err := p.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
  817. if err != nil {
  818. return nil
  819. }
  820. return CalcDifficulty(snap, p.val)
  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 CalcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
  826. if snap.inturn(signer) {
  827. return new(big.Int).Set(diffInTurn)
  828. }
  829. return new(big.Int).Set(diffNoTurn)
  830. }
  831. // SealHash returns the hash of a block prior to it being sealed.
  832. func (p *Parlia) SealHash(header *types.Header) common.Hash {
  833. return SealHash(header, p.chainConfig.ChainID)
  834. }
  835. // APIs implements consensus.Engine, returning the user facing RPC API to query snapshot.
  836. func (p *Parlia) APIs(chain consensus.ChainHeaderReader) []rpc.API {
  837. return []rpc.API{{
  838. Namespace: "parlia",
  839. Version: "1.0",
  840. Service: &API{chain: chain, parlia: p},
  841. Public: false,
  842. }}
  843. }
  844. // Close implements consensus.Engine. It's a noop for parlia as there are no background threads.
  845. func (p *Parlia) Close() error {
  846. return nil
  847. }
  848. // ========================== interaction with contract/account =========
  849. // getCurrentValidators get current validators
  850. func (p *Parlia) getCurrentValidators(blockHash common.Hash) ([]common.Address, error) {
  851. // block
  852. blockNr := rpc.BlockNumberOrHashWithHash(blockHash, false)
  853. // method
  854. method := "getValidators"
  855. ctx, cancel := context.WithCancel(context.Background())
  856. defer cancel() // cancel when we are finished consuming integers
  857. data, err := p.validatorSetABI.Pack(method)
  858. if err != nil {
  859. log.Error("Unable to pack tx for getValidators", "error", err)
  860. return nil, err
  861. }
  862. // call
  863. msgData := (hexutil.Bytes)(data)
  864. toAddress := common.HexToAddress(systemcontracts.ValidatorContract)
  865. gas := (hexutil.Uint64)(uint64(math.MaxUint64 / 2))
  866. result, err := p.ethAPI.Call(ctx, ethapi.CallArgs{
  867. Gas: &gas,
  868. To: &toAddress,
  869. Data: &msgData,
  870. }, blockNr, nil)
  871. if err != nil {
  872. return nil, err
  873. }
  874. var (
  875. ret0 = new([]common.Address)
  876. )
  877. out := ret0
  878. if err := p.validatorSetABI.UnpackIntoInterface(out, method, result); err != nil {
  879. return nil, err
  880. }
  881. valz := make([]common.Address, len(*ret0))
  882. for i, a := range *ret0 {
  883. valz[i] = a
  884. }
  885. return valz, nil
  886. }
  887. // slash spoiled validators
  888. func (p *Parlia) distributeIncoming(val common.Address, state *state.StateDB, header *types.Header, chain core.ChainContext,
  889. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  890. coinbase := header.Coinbase
  891. balance := state.GetBalance(consensus.SystemAddress)
  892. if balance.Cmp(common.Big0) <= 0 {
  893. return nil
  894. }
  895. state.SetBalance(consensus.SystemAddress, big.NewInt(0))
  896. state.AddBalance(coinbase, balance)
  897. doDistributeSysReward := state.GetBalance(common.HexToAddress(systemcontracts.SystemRewardContract)).Cmp(maxSystemBalance) < 0
  898. if doDistributeSysReward {
  899. var rewards = new(big.Int)
  900. rewards = rewards.Rsh(balance, systemRewardPercent)
  901. if rewards.Cmp(common.Big0) > 0 {
  902. err := p.distributeToSystem(rewards, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  903. if err != nil {
  904. return err
  905. }
  906. log.Trace("distribute to system reward pool", "block hash", header.Hash(), "amount", rewards)
  907. balance = balance.Sub(balance, rewards)
  908. }
  909. }
  910. log.Trace("distribute to validator contract", "block hash", header.Hash(), "amount", balance)
  911. return p.distributeToValidator(balance, val, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  912. }
  913. // slash spoiled validators
  914. func (p *Parlia) slash(spoiledVal common.Address, state *state.StateDB, header *types.Header, chain core.ChainContext,
  915. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  916. // method
  917. method := "slash"
  918. // get packed data
  919. data, err := p.slashABI.Pack(method,
  920. spoiledVal,
  921. )
  922. if err != nil {
  923. log.Error("Unable to pack tx for slash", "error", err)
  924. return err
  925. }
  926. // get system message
  927. msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.SlashContract), data, common.Big0)
  928. // apply message
  929. return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  930. }
  931. // init contract
  932. func (p *Parlia) initContract(state *state.StateDB, header *types.Header, chain core.ChainContext,
  933. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  934. // method
  935. method := "init"
  936. // contracts
  937. contracts := []string{
  938. systemcontracts.ValidatorContract,
  939. systemcontracts.SlashContract,
  940. systemcontracts.LightClientContract,
  941. systemcontracts.RelayerHubContract,
  942. systemcontracts.TokenHubContract,
  943. systemcontracts.RelayerIncentivizeContract,
  944. systemcontracts.CrossChainContract,
  945. }
  946. // get packed data
  947. data, err := p.validatorSetABI.Pack(method)
  948. if err != nil {
  949. log.Error("Unable to pack tx for init validator set", "error", err)
  950. return err
  951. }
  952. for _, c := range contracts {
  953. msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(c), data, common.Big0)
  954. // apply message
  955. log.Trace("init contract", "block hash", header.Hash(), "contract", c)
  956. err = p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  957. if err != nil {
  958. return err
  959. }
  960. }
  961. return nil
  962. }
  963. func (p *Parlia) distributeToSystem(amount *big.Int, state *state.StateDB, header *types.Header, chain core.ChainContext,
  964. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  965. // get system message
  966. msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.SystemRewardContract), nil, amount)
  967. // apply message
  968. return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  969. }
  970. // slash spoiled validators
  971. func (p *Parlia) distributeToValidator(amount *big.Int, validator common.Address,
  972. state *state.StateDB, header *types.Header, chain core.ChainContext,
  973. txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  974. // method
  975. method := "deposit"
  976. // get packed data
  977. data, err := p.validatorSetABI.Pack(method,
  978. validator,
  979. )
  980. if err != nil {
  981. log.Error("Unable to pack tx for deposit", "error", err)
  982. return err
  983. }
  984. // get system message
  985. msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.ValidatorContract), data, amount)
  986. // apply message
  987. return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  988. }
  989. // get system message
  990. func (p *Parlia) getSystemMessage(from, toAddress common.Address, data []byte, value *big.Int) callmsg {
  991. return callmsg{
  992. ethereum.CallMsg{
  993. From: from,
  994. Gas: math.MaxUint64 / 2,
  995. GasPrice: big.NewInt(0),
  996. Value: value,
  997. To: &toAddress,
  998. Data: data,
  999. },
  1000. }
  1001. }
  1002. func (p *Parlia) applyTransaction(
  1003. msg callmsg,
  1004. state *state.StateDB,
  1005. header *types.Header,
  1006. chainContext core.ChainContext,
  1007. txs *[]*types.Transaction, receipts *[]*types.Receipt,
  1008. receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool,
  1009. ) (err error) {
  1010. nonce := state.GetNonce(msg.From())
  1011. expectedTx := types.NewTransaction(nonce, *msg.To(), msg.Value(), msg.Gas(), msg.GasPrice(), msg.Data())
  1012. expectedHash := p.signer.Hash(expectedTx)
  1013. if msg.From() == p.val && mining {
  1014. expectedTx, err = p.signTxFn(accounts.Account{Address: msg.From()}, expectedTx, p.chainConfig.ChainID)
  1015. if err != nil {
  1016. return err
  1017. }
  1018. } else {
  1019. if receivedTxs == nil || len(*receivedTxs) == 0 || (*receivedTxs)[0] == nil {
  1020. return errors.New("supposed to get a actual transaction, but get none")
  1021. }
  1022. actualTx := (*receivedTxs)[0]
  1023. if !bytes.Equal(p.signer.Hash(actualTx).Bytes(), expectedHash.Bytes()) {
  1024. 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(),
  1025. expectedTx.Nonce(),
  1026. expectedTx.To().String(),
  1027. expectedTx.Value().String(),
  1028. expectedTx.Gas(),
  1029. expectedTx.GasPrice().String(),
  1030. hex.EncodeToString(expectedTx.Data()),
  1031. )
  1032. }
  1033. expectedTx = actualTx
  1034. // move to next
  1035. *receivedTxs = (*receivedTxs)[1:]
  1036. }
  1037. state.Prepare(expectedTx.Hash(), common.Hash{}, len(*txs))
  1038. gasUsed, err := applyMessage(msg, state, header, p.chainConfig, chainContext)
  1039. if err != nil {
  1040. return err
  1041. }
  1042. *txs = append(*txs, expectedTx)
  1043. var root []byte
  1044. if p.chainConfig.IsByzantium(header.Number) {
  1045. state.Finalise(true)
  1046. } else {
  1047. root = state.IntermediateRoot(p.chainConfig.IsEIP158(header.Number)).Bytes()
  1048. }
  1049. *usedGas += gasUsed
  1050. receipt := types.NewReceipt(root, false, *usedGas)
  1051. receipt.TxHash = expectedTx.Hash()
  1052. receipt.GasUsed = gasUsed
  1053. // Set the receipt logs and create a bloom for filtering
  1054. receipt.Logs = state.GetLogs(expectedTx.Hash())
  1055. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  1056. receipt.BlockHash = state.BlockHash()
  1057. receipt.BlockNumber = header.Number
  1058. receipt.TransactionIndex = uint(state.TxIndex())
  1059. *receipts = append(*receipts, receipt)
  1060. state.SetNonce(msg.From(), nonce+1)
  1061. return nil
  1062. }
  1063. // =========================== utility function ==========================
  1064. // SealHash returns the hash of a block prior to it being sealed.
  1065. func SealHash(header *types.Header, chainId *big.Int) (hash common.Hash) {
  1066. hasher := sha3.NewLegacyKeccak256()
  1067. encodeSigHeader(hasher, header, chainId)
  1068. hasher.Sum(hash[:0])
  1069. return hash
  1070. }
  1071. func encodeSigHeader(w io.Writer, header *types.Header, chainId *big.Int) {
  1072. err := rlp.Encode(w, []interface{}{
  1073. chainId,
  1074. header.ParentHash,
  1075. header.UncleHash,
  1076. header.Coinbase,
  1077. header.Root,
  1078. header.TxHash,
  1079. header.ReceiptHash,
  1080. header.Bloom,
  1081. header.Difficulty,
  1082. header.Number,
  1083. header.GasLimit,
  1084. header.GasUsed,
  1085. header.Time,
  1086. header.Extra[:len(header.Extra)-65], // this will panic if extra is too short, should check before calling encodeSigHeader
  1087. header.MixDigest,
  1088. header.Nonce,
  1089. })
  1090. if err != nil {
  1091. panic("can't encode: " + err.Error())
  1092. }
  1093. }
  1094. func backOffTime(snap *Snapshot, val common.Address) uint64 {
  1095. if snap.inturn(val) {
  1096. return 0
  1097. } else {
  1098. idx := snap.indexOfVal(val)
  1099. if idx < 0 {
  1100. // The backOffTime does not matter when a validator is not authorized.
  1101. return 0
  1102. }
  1103. s := rand.NewSource(int64(snap.Number))
  1104. r := rand.New(s)
  1105. n := len(snap.Validators)
  1106. backOffSteps := make([]uint64, 0, n)
  1107. for idx := uint64(0); idx < uint64(n); idx++ {
  1108. backOffSteps = append(backOffSteps, idx)
  1109. }
  1110. r.Shuffle(n, func(i, j int) {
  1111. backOffSteps[i], backOffSteps[j] = backOffSteps[j], backOffSteps[i]
  1112. })
  1113. delay := initialBackOffTime + backOffSteps[idx]*wiggleTime
  1114. return delay
  1115. }
  1116. }
  1117. // chain context
  1118. type chainContext struct {
  1119. Chain consensus.ChainHeaderReader
  1120. parlia consensus.Engine
  1121. }
  1122. func (c chainContext) Engine() consensus.Engine {
  1123. return c.parlia
  1124. }
  1125. func (c chainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
  1126. return c.Chain.GetHeader(hash, number)
  1127. }
  1128. // callmsg implements core.Message to allow passing it as a transaction simulator.
  1129. type callmsg struct {
  1130. ethereum.CallMsg
  1131. }
  1132. func (m callmsg) From() common.Address { return m.CallMsg.From }
  1133. func (m callmsg) Nonce() uint64 { return 0 }
  1134. func (m callmsg) CheckNonce() bool { return false }
  1135. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  1136. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  1137. func (m callmsg) Gas() uint64 { return m.CallMsg.Gas }
  1138. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  1139. func (m callmsg) Data() []byte { return m.CallMsg.Data }
  1140. // apply message
  1141. func applyMessage(
  1142. msg callmsg,
  1143. state *state.StateDB,
  1144. header *types.Header,
  1145. chainConfig *params.ChainConfig,
  1146. chainContext core.ChainContext,
  1147. ) (uint64, error) {
  1148. // Create a new context to be used in the EVM environment
  1149. context := core.NewEVMBlockContext(header, chainContext, nil)
  1150. // Create a new environment which holds all relevant information
  1151. // about the transaction and calling mechanisms.
  1152. vmenv := vm.NewEVM(context, vm.TxContext{Origin: msg.From(), GasPrice: big.NewInt(0)}, state, chainConfig, vm.Config{})
  1153. // Apply the transaction to the current state (included in the env)
  1154. ret, returnGas, err := vmenv.Call(
  1155. vm.AccountRef(msg.From()),
  1156. *msg.To(),
  1157. msg.Data(),
  1158. msg.Gas(),
  1159. msg.Value(),
  1160. )
  1161. if err != nil {
  1162. log.Error("apply message failed", "msg", string(ret), "err", err)
  1163. }
  1164. return msg.Gas() - returnGas, err
  1165. }