parlia.go 45 KB

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