satoshi.go 48 KB

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