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