github.com/ImPedro29/bor@v0.2.7/consensus/bor/bor.go (about) 1 package bor 2 3 import ( 4 "bytes" 5 "context" 6 "encoding/hex" 7 "encoding/json" 8 "errors" 9 "fmt" 10 "io" 11 "math" 12 "math/big" 13 "sort" 14 "strconv" 15 "strings" 16 "sync" 17 "time" 18 19 lru "github.com/hashicorp/golang-lru" 20 "golang.org/x/crypto/sha3" 21 22 ethereum "github.com/ethereum/go-ethereum" 23 "github.com/ethereum/go-ethereum/accounts" 24 "github.com/ethereum/go-ethereum/accounts/abi" 25 "github.com/ethereum/go-ethereum/common" 26 "github.com/ethereum/go-ethereum/common/hexutil" 27 "github.com/ethereum/go-ethereum/consensus" 28 "github.com/ethereum/go-ethereum/consensus/misc" 29 "github.com/ethereum/go-ethereum/core" 30 "github.com/ethereum/go-ethereum/core/state" 31 "github.com/ethereum/go-ethereum/core/types" 32 "github.com/ethereum/go-ethereum/core/vm" 33 "github.com/ethereum/go-ethereum/crypto" 34 "github.com/ethereum/go-ethereum/ethdb" 35 "github.com/ethereum/go-ethereum/event" 36 "github.com/ethereum/go-ethereum/internal/ethapi" 37 "github.com/ethereum/go-ethereum/log" 38 "github.com/ethereum/go-ethereum/params" 39 "github.com/ethereum/go-ethereum/rlp" 40 "github.com/ethereum/go-ethereum/rpc" 41 "github.com/ethereum/go-ethereum/trie" 42 ) 43 44 const ( 45 checkpointInterval = 1024 // Number of blocks after which to save the vote snapshot to the database 46 inmemorySnapshots = 128 // Number of recent vote snapshots to keep in memory 47 inmemorySignatures = 4096 // Number of recent block signatures to keep in memory 48 ) 49 50 // Bor protocol constants. 51 var ( 52 defaultSprintLength = uint64(64) // Default number of blocks after which to checkpoint and reset the pending votes 53 54 extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity 55 extraSeal = 65 // Fixed number of extra-data suffix bytes reserved for signer seal 56 57 uncleHash = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW. 58 59 diffInTurn = big.NewInt(2) // Block difficulty for in-turn signatures 60 diffNoTurn = big.NewInt(1) // Block difficulty for out-of-turn signatures 61 62 validatorHeaderBytesLength = common.AddressLength + 20 // address + power 63 systemAddress = common.HexToAddress("0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE") 64 ) 65 66 // Various error messages to mark blocks invalid. These should be private to 67 // prevent engine specific errors from being referenced in the remainder of the 68 // codebase, inherently breaking if the engine is swapped out. Please put common 69 // error types into the consensus package. 70 var ( 71 // errUnknownBlock is returned when the list of signers is requested for a block 72 // that is not part of the local blockchain. 73 errUnknownBlock = errors.New("unknown block") 74 75 // errInvalidCheckpointBeneficiary is returned if a checkpoint/epoch transition 76 // block has a beneficiary set to non-zeroes. 77 errInvalidCheckpointBeneficiary = errors.New("beneficiary in checkpoint block non-zero") 78 79 // errInvalidVote is returned if a nonce value is something else that the two 80 // allowed constants of 0x00..0 or 0xff..f. 81 errInvalidVote = errors.New("vote nonce not 0x00..0 or 0xff..f") 82 83 // errInvalidCheckpointVote is returned if a checkpoint/epoch transition block 84 // has a vote nonce set to non-zeroes. 85 errInvalidCheckpointVote = errors.New("vote nonce in checkpoint block non-zero") 86 87 // errMissingVanity is returned if a block's extra-data section is shorter than 88 // 32 bytes, which is required to store the signer vanity. 89 errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing") 90 91 // errMissingSignature is returned if a block's extra-data section doesn't seem 92 // to contain a 65 byte secp256k1 signature. 93 errMissingSignature = errors.New("extra-data 65 byte signature suffix missing") 94 95 // errExtraValidators is returned if non-sprint-end block contain validator data in 96 // their extra-data fields. 97 errExtraValidators = errors.New("non-sprint-end block contains extra validator list") 98 99 // errInvalidSpanValidators is returned if a block contains an 100 // invalid list of validators (i.e. non divisible by 40 bytes). 101 errInvalidSpanValidators = errors.New("invalid validator list on sprint end block") 102 103 // errInvalidMixDigest is returned if a block's mix digest is non-zero. 104 errInvalidMixDigest = errors.New("non-zero mix digest") 105 106 // errInvalidUncleHash is returned if a block contains an non-empty uncle list. 107 errInvalidUncleHash = errors.New("non empty uncle hash") 108 109 // errInvalidDifficulty is returned if the difficulty of a block neither 1 or 2. 110 errInvalidDifficulty = errors.New("invalid difficulty") 111 112 // ErrInvalidTimestamp is returned if the timestamp of a block is lower than 113 // the previous block's timestamp + the minimum block period. 114 ErrInvalidTimestamp = errors.New("invalid timestamp") 115 116 // errOutOfRangeChain is returned if an authorization list is attempted to 117 // be modified via out-of-range or non-contiguous headers. 118 errOutOfRangeChain = errors.New("out of range or non-contiguous chain") 119 ) 120 121 // SignerFn is a signer callback function to request a header to be signed by a 122 // backing account. 123 type SignerFn func(accounts.Account, string, []byte) ([]byte, error) 124 125 // ecrecover extracts the Ethereum account address from a signed header. 126 func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) { 127 // If the signature's already cached, return that 128 hash := header.Hash() 129 if address, known := sigcache.Get(hash); known { 130 return address.(common.Address), nil 131 } 132 // Retrieve the signature from the header extra-data 133 if len(header.Extra) < extraSeal { 134 return common.Address{}, errMissingSignature 135 } 136 signature := header.Extra[len(header.Extra)-extraSeal:] 137 138 // Recover the public key and the Ethereum address 139 pubkey, err := crypto.Ecrecover(SealHash(header).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 146 sigcache.Add(hash, signer) 147 return signer, nil 148 } 149 150 // SealHash returns the hash of a block prior to it being sealed. 151 func SealHash(header *types.Header) (hash common.Hash) { 152 hasher := sha3.NewLegacyKeccak256() 153 encodeSigHeader(hasher, header) 154 hasher.Sum(hash[:0]) 155 return hash 156 } 157 158 func encodeSigHeader(w io.Writer, header *types.Header) { 159 err := rlp.Encode(w, []interface{}{ 160 header.ParentHash, 161 header.UncleHash, 162 header.Coinbase, 163 header.Root, 164 header.TxHash, 165 header.ReceiptHash, 166 header.Bloom, 167 header.Difficulty, 168 header.Number, 169 header.GasLimit, 170 header.GasUsed, 171 header.Time, 172 header.Extra[:len(header.Extra)-65], // Yes, this will panic if extra is too short 173 header.MixDigest, 174 header.Nonce, 175 }) 176 if err != nil { 177 panic("can't encode: " + err.Error()) 178 } 179 } 180 181 // CalcProducerDelay is the block delay algorithm based on block time, period, producerDelay and turn-ness of a signer 182 func CalcProducerDelay(number uint64, succession int, c *params.BorConfig) uint64 { 183 // When the block is the first block of the sprint, it is expected to be delayed by `producerDelay`. 184 // That is to allow time for block propagation in the last sprint 185 delay := c.Period 186 if number%c.Sprint == 0 { 187 delay = c.ProducerDelay 188 } 189 if succession > 0 { 190 delay += uint64(succession) * c.BackupMultiplier 191 } 192 return delay 193 } 194 195 // BorRLP returns the rlp bytes which needs to be signed for the bor 196 // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature 197 // contained at the end of the extra data. 198 // 199 // Note, the method requires the extra data to be at least 65 bytes, otherwise it 200 // panics. This is done to avoid accidentally using both forms (signature present 201 // or not), which could be abused to produce different hashes for the same header. 202 func BorRLP(header *types.Header) []byte { 203 b := new(bytes.Buffer) 204 encodeSigHeader(b, header) 205 return b.Bytes() 206 } 207 208 // Bor is the matic-bor consensus engine 209 type Bor struct { 210 chainConfig *params.ChainConfig // Chain config 211 config *params.BorConfig // Consensus engine configuration parameters for bor consensus 212 db ethdb.Database // Database to store and retrieve snapshot checkpoints 213 214 recents *lru.ARCCache // Snapshots for recent block to speed up reorgs 215 signatures *lru.ARCCache // Signatures of recent blocks to speed up mining 216 217 signer common.Address // Ethereum address of the signing key 218 signFn SignerFn // Signer function to authorize hashes with 219 lock sync.RWMutex // Protects the signer fields 220 221 ethAPI *ethapi.PublicBlockChainAPI 222 GenesisContractsClient *GenesisContractsClient 223 validatorSetABI abi.ABI 224 stateReceiverABI abi.ABI 225 HeimdallClient IHeimdallClient 226 WithoutHeimdall bool 227 228 scope event.SubscriptionScope 229 // The fields below are for testing only 230 fakeDiff bool // Skip difficulty verifications 231 } 232 233 // New creates a Matic Bor consensus engine. 234 func New( 235 chainConfig *params.ChainConfig, 236 db ethdb.Database, 237 ethAPI *ethapi.PublicBlockChainAPI, 238 heimdallURL string, 239 withoutHeimdall bool, 240 ) *Bor { 241 // get bor config 242 borConfig := chainConfig.Bor 243 244 // Set any missing consensus parameters to their defaults 245 if borConfig != nil && borConfig.Sprint == 0 { 246 borConfig.Sprint = defaultSprintLength 247 } 248 249 // Allocate the snapshot caches and create the engine 250 recents, _ := lru.NewARC(inmemorySnapshots) 251 signatures, _ := lru.NewARC(inmemorySignatures) 252 vABI, _ := abi.JSON(strings.NewReader(validatorsetABI)) 253 sABI, _ := abi.JSON(strings.NewReader(stateReceiverABI)) 254 heimdallClient, _ := NewHeimdallClient(heimdallURL) 255 genesisContractsClient := NewGenesisContractsClient(chainConfig, borConfig.ValidatorContract, borConfig.StateReceiverContract, ethAPI) 256 c := &Bor{ 257 chainConfig: chainConfig, 258 config: borConfig, 259 db: db, 260 ethAPI: ethAPI, 261 recents: recents, 262 signatures: signatures, 263 validatorSetABI: vABI, 264 stateReceiverABI: sABI, 265 GenesisContractsClient: genesisContractsClient, 266 HeimdallClient: heimdallClient, 267 WithoutHeimdall: withoutHeimdall, 268 } 269 270 return c 271 } 272 273 // Author implements consensus.Engine, returning the Ethereum address recovered 274 // from the signature in the header's extra-data section. 275 func (c *Bor) Author(header *types.Header) (common.Address, error) { 276 return ecrecover(header, c.signatures) 277 } 278 279 // VerifyHeader checks whether a header conforms to the consensus rules. 280 func (c *Bor) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error { 281 return c.verifyHeader(chain, header, nil) 282 } 283 284 // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The 285 // method returns a quit channel to abort the operations and a results channel to 286 // retrieve the async verifications (the order is that of the input slice). 287 func (c *Bor) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) { 288 abort := make(chan struct{}) 289 results := make(chan error, len(headers)) 290 291 go func() { 292 for i, header := range headers { 293 err := c.verifyHeader(chain, header, headers[:i]) 294 295 select { 296 case <-abort: 297 return 298 case results <- err: 299 } 300 } 301 }() 302 return abort, results 303 } 304 305 // verifyHeader checks whether a header conforms to the consensus rules.The 306 // caller may optionally pass in a batch of parents (ascending order) to avoid 307 // looking those up from the database. This is useful for concurrently verifying 308 // a batch of new headers. 309 func (c *Bor) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 310 if header.Number == nil { 311 return errUnknownBlock 312 } 313 number := header.Number.Uint64() 314 315 // Don't waste time checking blocks from the future 316 if header.Time > uint64(time.Now().Unix()) { 317 return consensus.ErrFutureBlock 318 } 319 320 if err := validateHeaderExtraField(header.Extra); err != nil { 321 return err 322 } 323 324 // check extr adata 325 isSprintEnd := (number+1)%c.config.Sprint == 0 326 327 // Ensure that the extra-data contains a signer list on checkpoint, but none otherwise 328 signersBytes := len(header.Extra) - extraVanity - extraSeal 329 if !isSprintEnd && signersBytes != 0 { 330 return errExtraValidators 331 } 332 if isSprintEnd && signersBytes%validatorHeaderBytesLength != 0 { 333 return errInvalidSpanValidators 334 } 335 // Ensure that the mix digest is zero as we don't have fork protection currently 336 if header.MixDigest != (common.Hash{}) { 337 return errInvalidMixDigest 338 } 339 // Ensure that the block doesn't contain any uncles which are meaningless in PoA 340 if header.UncleHash != uncleHash { 341 return errInvalidUncleHash 342 } 343 // Ensure that the block's difficulty is meaningful (may not be correct at this point) 344 if number > 0 { 345 if header.Difficulty == nil { 346 return errInvalidDifficulty 347 } 348 } 349 // If all checks passed, validate any special fields for hard forks 350 if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil { 351 return err 352 } 353 // All basic checks passed, verify cascading fields 354 return c.verifyCascadingFields(chain, header, parents) 355 } 356 357 // validateHeaderExtraField validates that the extra-data contains both the vanity and signature. 358 // header.Extra = header.Vanity + header.ProducerBytes (optional) + header.Seal 359 func validateHeaderExtraField(extraBytes []byte) error { 360 if len(extraBytes) < extraVanity { 361 return errMissingVanity 362 } 363 if len(extraBytes) < extraVanity+extraSeal { 364 return errMissingSignature 365 } 366 return nil 367 } 368 369 // verifyCascadingFields verifies all the header fields that are not standalone, 370 // rather depend on a batch of previous headers. The caller may optionally pass 371 // in a batch of parents (ascending order) to avoid looking those up from the 372 // database. This is useful for concurrently verifying a batch of new headers. 373 func (c *Bor) verifyCascadingFields(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 374 // The genesis block is the always valid dead-end 375 number := header.Number.Uint64() 376 if number == 0 { 377 return nil 378 } 379 380 // Ensure that the block's timestamp isn't too close to it's parent 381 var parent *types.Header 382 if len(parents) > 0 { 383 parent = parents[len(parents)-1] 384 } else { 385 parent = chain.GetHeader(header.ParentHash, number-1) 386 } 387 388 if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash { 389 return consensus.ErrUnknownAncestor 390 } 391 392 if parent.Time+c.config.Period > header.Time { 393 return ErrInvalidTimestamp 394 } 395 396 // Retrieve the snapshot needed to verify this header and cache it 397 snap, err := c.snapshot(chain, number-1, header.ParentHash, parents) 398 if err != nil { 399 return err 400 } 401 402 // verify the validator list in the last sprint block 403 if isSprintStart(number, c.config.Sprint) { 404 parentValidatorBytes := parent.Extra[extraVanity : len(parent.Extra)-extraSeal] 405 validatorsBytes := make([]byte, len(snap.ValidatorSet.Validators)*validatorHeaderBytesLength) 406 407 currentValidators := snap.ValidatorSet.Copy().Validators 408 // sort validator by address 409 sort.Sort(ValidatorsByAddress(currentValidators)) 410 for i, validator := range currentValidators { 411 copy(validatorsBytes[i*validatorHeaderBytesLength:], validator.HeaderBytes()) 412 } 413 // len(header.Extra) >= extraVanity+extraSeal has already been validated in validateHeaderExtraField, so this won't result in a panic 414 if !bytes.Equal(parentValidatorBytes, validatorsBytes) { 415 return &MismatchingValidatorsError{number - 1, validatorsBytes, parentValidatorBytes} 416 } 417 } 418 419 // All basic checks passed, verify the seal and return 420 return c.verifySeal(chain, header, parents) 421 } 422 423 // snapshot retrieves the authorization snapshot at a given point in time. 424 func (c *Bor) snapshot(chain consensus.ChainHeaderReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) { 425 // Search for a snapshot in memory or on disk for checkpoints 426 var ( 427 headers []*types.Header 428 snap *Snapshot 429 ) 430 431 for snap == nil { 432 // If an in-memory snapshot was found, use that 433 if s, ok := c.recents.Get(hash); ok { 434 snap = s.(*Snapshot) 435 break 436 } 437 438 // If an on-disk checkpoint snapshot can be found, use that 439 if number%checkpointInterval == 0 { 440 if s, err := loadSnapshot(c.config, c.signatures, c.db, hash, c.ethAPI); err == nil { 441 log.Trace("Loaded snapshot from disk", "number", number, "hash", hash) 442 snap = s 443 break 444 } 445 } 446 447 // If we're at the genesis, snapshot the initial state. Alternatively if we're 448 // at a checkpoint block without a parent (light client CHT), or we have piled 449 // up more headers than allowed to be reorged (chain reinit from a freezer), 450 // consider the checkpoint trusted and snapshot it. 451 // TODO fix this 452 if number == 0 { 453 checkpoint := chain.GetHeaderByNumber(number) 454 if checkpoint != nil { 455 // get checkpoint data 456 hash := checkpoint.Hash() 457 458 // get validators and current span 459 validators, err := c.GetCurrentValidators(hash, number+1) 460 if err != nil { 461 return nil, err 462 } 463 464 // new snap shot 465 snap = newSnapshot(c.config, c.signatures, number, hash, validators, c.ethAPI) 466 if err := snap.store(c.db); err != nil { 467 return nil, err 468 } 469 log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash) 470 break 471 } 472 } 473 474 // No snapshot for this header, gather the header and move backward 475 var header *types.Header 476 if len(parents) > 0 { 477 // If we have explicit parents, pick from there (enforced) 478 header = parents[len(parents)-1] 479 if header.Hash() != hash || header.Number.Uint64() != number { 480 return nil, consensus.ErrUnknownAncestor 481 } 482 parents = parents[:len(parents)-1] 483 } else { 484 // No explicit parents (or no more left), reach out to the database 485 header = chain.GetHeader(hash, number) 486 if header == nil { 487 return nil, consensus.ErrUnknownAncestor 488 } 489 } 490 headers = append(headers, header) 491 number, hash = number-1, header.ParentHash 492 } 493 494 // check if snapshot is nil 495 if snap == nil { 496 return nil, fmt.Errorf("Unknown error while retrieving snapshot at block number %v", number) 497 } 498 499 // Previous snapshot found, apply any pending headers on top of it 500 for i := 0; i < len(headers)/2; i++ { 501 headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i] 502 } 503 504 snap, err := snap.apply(headers) 505 if err != nil { 506 return nil, err 507 } 508 c.recents.Add(snap.Hash, snap) 509 510 // If we've generated a new checkpoint snapshot, save to disk 511 if snap.Number%checkpointInterval == 0 && len(headers) > 0 { 512 if err = snap.store(c.db); err != nil { 513 return nil, err 514 } 515 log.Trace("Stored snapshot to disk", "number", snap.Number, "hash", snap.Hash) 516 } 517 return snap, err 518 } 519 520 // VerifyUncles implements consensus.Engine, always returning an error for any 521 // uncles as this consensus mechanism doesn't permit uncles. 522 func (c *Bor) VerifyUncles(chain consensus.ChainReader, block *types.Block) error { 523 if len(block.Uncles()) > 0 { 524 return errors.New("uncles not allowed") 525 } 526 return nil 527 } 528 529 // VerifySeal implements consensus.Engine, checking whether the signature contained 530 // in the header satisfies the consensus protocol requirements. 531 func (c *Bor) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error { 532 return c.verifySeal(chain, header, nil) 533 } 534 535 // verifySeal checks whether the signature contained in the header satisfies the 536 // consensus protocol requirements. The method accepts an optional list of parent 537 // headers that aren't yet part of the local blockchain to generate the snapshots 538 // from. 539 func (c *Bor) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 540 // Verifying the genesis block is not supported 541 number := header.Number.Uint64() 542 if number == 0 { 543 return errUnknownBlock 544 } 545 // Retrieve the snapshot needed to verify this header and cache it 546 snap, err := c.snapshot(chain, number-1, header.ParentHash, parents) 547 if err != nil { 548 return err 549 } 550 551 // Resolve the authorization key and check against signers 552 signer, err := ecrecover(header, c.signatures) 553 if err != nil { 554 return err 555 } 556 if !snap.ValidatorSet.HasAddress(signer.Bytes()) { 557 // Check the UnauthorizedSignerError.Error() msg to see why we pass number-1 558 return &UnauthorizedSignerError{number - 1, signer.Bytes()} 559 } 560 561 succession, err := snap.GetSignerSuccessionNumber(signer) 562 if err != nil { 563 return err 564 } 565 566 var parent *types.Header 567 if len(parents) > 0 { // if parents is nil, len(parents) is zero 568 parent = parents[len(parents)-1] 569 } else if number > 0 { 570 parent = chain.GetHeader(header.ParentHash, number-1) 571 } 572 573 if parent != nil && header.Time < parent.Time+CalcProducerDelay(number, succession, c.config) { 574 return &BlockTooSoonError{number, succession} 575 } 576 577 // Ensure that the difficulty corresponds to the turn-ness of the signer 578 if !c.fakeDiff { 579 difficulty := snap.Difficulty(signer) 580 if header.Difficulty.Uint64() != difficulty { 581 return &WrongDifficultyError{number, difficulty, header.Difficulty.Uint64(), signer.Bytes()} 582 } 583 } 584 585 return nil 586 } 587 588 // Prepare implements consensus.Engine, preparing all the consensus fields of the 589 // header for running the transactions on top. 590 func (c *Bor) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error { 591 // If the block isn't a checkpoint, cast a random vote (good enough for now) 592 header.Coinbase = common.Address{} 593 header.Nonce = types.BlockNonce{} 594 595 number := header.Number.Uint64() 596 // Assemble the validator snapshot to check which votes make sense 597 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 598 if err != nil { 599 return err 600 } 601 602 // Set the correct difficulty 603 header.Difficulty = new(big.Int).SetUint64(snap.Difficulty(c.signer)) 604 605 // Ensure the extra data has all it's components 606 if len(header.Extra) < extraVanity { 607 header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...) 608 } 609 header.Extra = header.Extra[:extraVanity] 610 611 // get validator set if number 612 if (number+1)%c.config.Sprint == 0 { 613 newValidators, err := c.GetCurrentValidators(header.ParentHash, number+1) 614 if err != nil { 615 return errors.New("unknown validators") 616 } 617 618 // sort validator by address 619 sort.Sort(ValidatorsByAddress(newValidators)) 620 for _, validator := range newValidators { 621 header.Extra = append(header.Extra, validator.HeaderBytes()...) 622 } 623 } 624 625 // add extra seal space 626 header.Extra = append(header.Extra, make([]byte, extraSeal)...) 627 628 // Mix digest is reserved for now, set to empty 629 header.MixDigest = common.Hash{} 630 631 // Ensure the timestamp has the correct delay 632 parent := chain.GetHeader(header.ParentHash, number-1) 633 if parent == nil { 634 return consensus.ErrUnknownAncestor 635 } 636 637 var succession int 638 // if signer is not empty 639 if bytes.Compare(c.signer.Bytes(), common.Address{}.Bytes()) != 0 { 640 succession, err = snap.GetSignerSuccessionNumber(c.signer) 641 if err != nil { 642 return err 643 } 644 } 645 646 header.Time = parent.Time + CalcProducerDelay(number, succession, c.config) 647 if header.Time < uint64(time.Now().Unix()) { 648 header.Time = uint64(time.Now().Unix()) 649 } 650 return nil 651 } 652 653 // Finalize implements consensus.Engine, ensuring no uncles are set, nor block 654 // rewards given. 655 func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) { 656 stateSyncData := []*types.StateSyncData{} 657 658 var err error 659 headerNumber := header.Number.Uint64() 660 if headerNumber%c.config.Sprint == 0 { 661 cx := chainContext{Chain: chain, Bor: c} 662 // check and commit span 663 if err := c.checkAndCommitSpan(state, header, cx); err != nil { 664 log.Error("Error while committing span", "error", err) 665 return 666 } 667 668 if !c.WithoutHeimdall { 669 // commit statees 670 stateSyncData, err = c.CommitStates(state, header, cx) 671 if err != nil { 672 log.Error("Error while committing states", "error", err) 673 return 674 } 675 } 676 } 677 678 // No block rewards in PoA, so the state remains as is and uncles are dropped 679 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 680 header.UncleHash = types.CalcUncleHash(nil) 681 682 // Set state sync data to blockchain 683 bc := chain.(*core.BlockChain) 684 bc.SetStateSync(stateSyncData) 685 } 686 687 // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set, 688 // nor block rewards given, and returns the final block. 689 func (c *Bor) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) { 690 stateSyncData := []*types.StateSyncData{} 691 692 headerNumber := header.Number.Uint64() 693 if headerNumber%c.config.Sprint == 0 { 694 cx := chainContext{Chain: chain, Bor: c} 695 696 // check and commit span 697 err := c.checkAndCommitSpan(state, header, cx) 698 if err != nil { 699 log.Error("Error while committing span", "error", err) 700 return nil, err 701 } 702 703 if !c.WithoutHeimdall { 704 // commit states 705 stateSyncData, err = c.CommitStates(state, header, cx) 706 if err != nil { 707 log.Error("Error while committing states", "error", err) 708 return nil, err 709 } 710 } 711 } 712 713 // No block rewards in PoA, so the state remains as is and uncles are dropped 714 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 715 header.UncleHash = types.CalcUncleHash(nil) 716 717 // Assemble block 718 block := types.NewBlock(header, txs, nil, receipts, new(trie.Trie)) 719 720 // set state sync 721 bc := chain.(*core.BlockChain) 722 bc.SetStateSync(stateSyncData) 723 724 // return the final block for sealing 725 return block, nil 726 } 727 728 // Authorize injects a private key into the consensus engine to mint new blocks 729 // with. 730 func (c *Bor) Authorize(signer common.Address, signFn SignerFn) { 731 c.lock.Lock() 732 defer c.lock.Unlock() 733 734 c.signer = signer 735 c.signFn = signFn 736 } 737 738 // Seal implements consensus.Engine, attempting to create a sealed block using 739 // the local signing credentials. 740 func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error { 741 header := block.Header() 742 // Sealing the genesis block is not supported 743 number := header.Number.Uint64() 744 if number == 0 { 745 return errUnknownBlock 746 } 747 // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing) 748 if c.config.Period == 0 && len(block.Transactions()) == 0 { 749 log.Info("Sealing paused, waiting for transactions") 750 return nil 751 } 752 // Don't hold the signer fields for the entire sealing procedure 753 c.lock.RLock() 754 signer, signFn := c.signer, c.signFn 755 c.lock.RUnlock() 756 757 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 758 if err != nil { 759 return err 760 } 761 762 // Bail out if we're unauthorized to sign a block 763 if !snap.ValidatorSet.HasAddress(signer.Bytes()) { 764 // Check the UnauthorizedSignerError.Error() msg to see why we pass number-1 765 return &UnauthorizedSignerError{number - 1, signer.Bytes()} 766 } 767 768 successionNumber, err := snap.GetSignerSuccessionNumber(signer) 769 if err != nil { 770 return err 771 } 772 773 // Sweet, the protocol permits us to sign the block, wait for our time 774 delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple 775 // wiggle was already accounted for in header.Time, this is just for logging 776 wiggle := time.Duration(successionNumber) * time.Duration(c.config.BackupMultiplier) * time.Second 777 778 // Sign all the things! 779 sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeBor, BorRLP(header)) 780 if err != nil { 781 return err 782 } 783 copy(header.Extra[len(header.Extra)-extraSeal:], sighash) 784 785 // Wait until sealing is terminated or delay timeout. 786 log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay)) 787 go func() { 788 select { 789 case <-stop: 790 log.Debug("Discarding sealing operation for block", "number", number) 791 return 792 case <-time.After(delay): 793 if wiggle > 0 { 794 log.Info( 795 "Sealing out-of-turn", 796 "number", number, 797 "wiggle", common.PrettyDuration(wiggle), 798 "in-turn-signer", snap.ValidatorSet.GetProposer().Address.Hex(), 799 ) 800 } 801 log.Info( 802 "Sealing successful", 803 "number", number, 804 "delay", delay, 805 "headerDifficulty", header.Difficulty, 806 ) 807 } 808 select { 809 case results <- block.WithSeal(header): 810 default: 811 log.Warn("Sealing result was not read by miner", "number", number, "sealhash", SealHash(header)) 812 } 813 }() 814 return nil 815 } 816 817 // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty 818 // that a new block should have based on the previous blocks in the chain and the 819 // current signer. 820 func (c *Bor) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int { 821 snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil) 822 if err != nil { 823 return nil 824 } 825 return new(big.Int).SetUint64(snap.Difficulty(c.signer)) 826 } 827 828 // SealHash returns the hash of a block prior to it being sealed. 829 func (c *Bor) SealHash(header *types.Header) common.Hash { 830 return SealHash(header) 831 } 832 833 // APIs implements consensus.Engine, returning the user facing RPC API to allow 834 // controlling the signer voting. 835 func (c *Bor) APIs(chain consensus.ChainHeaderReader) []rpc.API { 836 return []rpc.API{{ 837 Namespace: "bor", 838 Version: "1.0", 839 Service: &API{chain: chain, bor: c}, 840 Public: false, 841 }} 842 } 843 844 // Close implements consensus.Engine. It's a noop for bor as there are no background threads. 845 func (c *Bor) Close() error { 846 return nil 847 } 848 849 // GetCurrentSpan get current span from contract 850 func (c *Bor) GetCurrentSpan(headerHash common.Hash) (*Span, error) { 851 // block 852 blockNr := rpc.BlockNumberOrHashWithHash(headerHash, false) 853 854 // method 855 method := "getCurrentSpan" 856 857 ctx, cancel := context.WithCancel(context.Background()) 858 defer cancel() 859 860 data, err := c.validatorSetABI.Pack(method) 861 if err != nil { 862 log.Error("Unable to pack tx for getCurrentSpan", "error", err) 863 return nil, err 864 } 865 866 msgData := (hexutil.Bytes)(data) 867 toAddress := common.HexToAddress(c.config.ValidatorContract) 868 gas := (hexutil.Uint64)(uint64(math.MaxUint64 / 2)) 869 result, err := c.ethAPI.Call(ctx, ethapi.CallArgs{ 870 Gas: &gas, 871 To: &toAddress, 872 Data: &msgData, 873 }, blockNr, nil) 874 if err != nil { 875 return nil, err 876 } 877 878 // span result 879 ret := new(struct { 880 Number *big.Int 881 StartBlock *big.Int 882 EndBlock *big.Int 883 }) 884 if err := c.validatorSetABI.UnpackIntoInterface(ret, method, result); err != nil { 885 return nil, err 886 } 887 888 // create new span 889 span := Span{ 890 ID: ret.Number.Uint64(), 891 StartBlock: ret.StartBlock.Uint64(), 892 EndBlock: ret.EndBlock.Uint64(), 893 } 894 895 return &span, nil 896 } 897 898 // GetCurrentValidators get current validators 899 func (c *Bor) GetCurrentValidators(headerHash common.Hash, blockNumber uint64) ([]*Validator, error) { 900 // block 901 blockNr := rpc.BlockNumberOrHashWithHash(headerHash, false) 902 903 // method 904 method := "getBorValidators" 905 906 ctx, cancel := context.WithCancel(context.Background()) 907 defer cancel() 908 909 data, err := c.validatorSetABI.Pack(method, big.NewInt(0).SetUint64(blockNumber)) 910 if err != nil { 911 log.Error("Unable to pack tx for getValidator", "error", err) 912 return nil, err 913 } 914 915 // call 916 msgData := (hexutil.Bytes)(data) 917 toAddress := common.HexToAddress(c.config.ValidatorContract) 918 gas := (hexutil.Uint64)(uint64(math.MaxUint64 / 2)) 919 result, err := c.ethAPI.Call(ctx, ethapi.CallArgs{ 920 Gas: &gas, 921 To: &toAddress, 922 Data: &msgData, 923 }, blockNr, nil) 924 if err != nil { 925 panic(err) 926 // return nil, err 927 } 928 929 var ( 930 ret0 = new([]common.Address) 931 ret1 = new([]*big.Int) 932 ) 933 out := &[]interface{}{ 934 ret0, 935 ret1, 936 } 937 938 if err := c.validatorSetABI.UnpackIntoInterface(out, method, result); err != nil { 939 return nil, err 940 } 941 942 valz := make([]*Validator, len(*ret0)) 943 for i, a := range *ret0 { 944 valz[i] = &Validator{ 945 Address: a, 946 VotingPower: (*ret1)[i].Int64(), 947 } 948 } 949 950 return valz, nil 951 } 952 953 func (c *Bor) checkAndCommitSpan( 954 state *state.StateDB, 955 header *types.Header, 956 chain core.ChainContext, 957 ) error { 958 headerNumber := header.Number.Uint64() 959 span, err := c.GetCurrentSpan(header.ParentHash) 960 if err != nil { 961 return err 962 } 963 if c.needToCommitSpan(span, headerNumber) { 964 err := c.fetchAndCommitSpan(span.ID+1, state, header, chain) 965 return err 966 } 967 return nil 968 } 969 970 func (c *Bor) needToCommitSpan(span *Span, headerNumber uint64) bool { 971 // if span is nil 972 if span == nil { 973 return false 974 } 975 976 // check span is not set initially 977 if span.EndBlock == 0 { 978 return true 979 } 980 981 // if current block is first block of last sprint in current span 982 if span.EndBlock > c.config.Sprint && span.EndBlock-c.config.Sprint+1 == headerNumber { 983 return true 984 } 985 986 return false 987 } 988 989 func (c *Bor) fetchAndCommitSpan( 990 newSpanID uint64, 991 state *state.StateDB, 992 header *types.Header, 993 chain core.ChainContext, 994 ) error { 995 var heimdallSpan HeimdallSpan 996 997 if c.WithoutHeimdall { 998 s, err := c.getNextHeimdallSpanForTest(newSpanID, state, header, chain) 999 if err != nil { 1000 return err 1001 } 1002 heimdallSpan = *s 1003 } else { 1004 response, err := c.HeimdallClient.FetchWithRetry(fmt.Sprintf("bor/span/%d", newSpanID), "") 1005 if err != nil { 1006 return err 1007 } 1008 1009 if err := json.Unmarshal(response.Result, &heimdallSpan); err != nil { 1010 return err 1011 } 1012 } 1013 1014 // check if chain id matches with heimdall span 1015 if heimdallSpan.ChainID != c.chainConfig.ChainID.String() { 1016 return fmt.Errorf( 1017 "Chain id proposed span, %s, and bor chain id, %s, doesn't match", 1018 heimdallSpan.ChainID, 1019 c.chainConfig.ChainID, 1020 ) 1021 } 1022 1023 // get validators bytes 1024 var validators []MinimalVal 1025 for _, val := range heimdallSpan.ValidatorSet.Validators { 1026 validators = append(validators, val.MinimalVal()) 1027 } 1028 validatorBytes, err := rlp.EncodeToBytes(validators) 1029 if err != nil { 1030 return err 1031 } 1032 1033 // get producers bytes 1034 var producers []MinimalVal 1035 for _, val := range heimdallSpan.SelectedProducers { 1036 producers = append(producers, val.MinimalVal()) 1037 } 1038 producerBytes, err := rlp.EncodeToBytes(producers) 1039 if err != nil { 1040 return err 1041 } 1042 1043 // method 1044 method := "commitSpan" 1045 log.Info("✅ Committing new span", 1046 "id", heimdallSpan.ID, 1047 "startBlock", heimdallSpan.StartBlock, 1048 "endBlock", heimdallSpan.EndBlock, 1049 "validatorBytes", hex.EncodeToString(validatorBytes), 1050 "producerBytes", hex.EncodeToString(producerBytes), 1051 ) 1052 1053 // get packed data 1054 data, err := c.validatorSetABI.Pack(method, 1055 big.NewInt(0).SetUint64(heimdallSpan.ID), 1056 big.NewInt(0).SetUint64(heimdallSpan.StartBlock), 1057 big.NewInt(0).SetUint64(heimdallSpan.EndBlock), 1058 validatorBytes, 1059 producerBytes, 1060 ) 1061 if err != nil { 1062 log.Error("Unable to pack tx for commitSpan", "error", err) 1063 return err 1064 } 1065 1066 // get system message 1067 msg := getSystemMessage(common.HexToAddress(c.config.ValidatorContract), data) 1068 1069 // apply message 1070 return applyMessage(msg, state, header, c.chainConfig, chain) 1071 } 1072 1073 // GetPendingStateProposals get pending state proposals 1074 func (c *Bor) GetPendingStateProposals(snapshotNumber uint64) ([]*big.Int, error) { 1075 // block 1076 blockNr := rpc.BlockNumber(snapshotNumber) 1077 1078 // method 1079 method := "getPendingStates" 1080 1081 data, err := c.stateReceiverABI.Pack(method) 1082 if err != nil { 1083 log.Error("Unable to pack tx for getPendingStates", "error", err) 1084 return nil, err 1085 } 1086 1087 msgData := (hexutil.Bytes)(data) 1088 toAddress := common.HexToAddress(c.config.StateReceiverContract) 1089 gas := (hexutil.Uint64)(uint64(math.MaxUint64 / 2)) 1090 result, err := c.ethAPI.Call(context.Background(), ethapi.CallArgs{ 1091 Gas: &gas, 1092 To: &toAddress, 1093 Data: &msgData, 1094 }, rpc.BlockNumberOrHash{BlockNumber: &blockNr}, nil) 1095 if err != nil { 1096 return nil, err 1097 } 1098 1099 var ret = new([]*big.Int) 1100 if err = c.stateReceiverABI.UnpackIntoInterface(ret, method, result); err != nil { 1101 return nil, err 1102 } 1103 1104 return *ret, nil 1105 } 1106 1107 // CommitStates commit states 1108 func (c *Bor) CommitStates( 1109 state *state.StateDB, 1110 header *types.Header, 1111 chain chainContext, 1112 ) ([]*types.StateSyncData, error) { 1113 stateSyncs := make([]*types.StateSyncData, 0) 1114 number := header.Number.Uint64() 1115 _lastStateID, err := c.GenesisContractsClient.LastStateId(number - 1) 1116 if err != nil { 1117 return nil, err 1118 } 1119 1120 to := time.Unix(int64(chain.Chain.GetHeaderByNumber(number-c.config.Sprint).Time), 0) 1121 lastStateID := _lastStateID.Uint64() 1122 log.Info( 1123 "Fetching state updates from Heimdall", 1124 "fromID", lastStateID+1, 1125 "to", to.Format(time.RFC3339)) 1126 eventRecords, err := c.HeimdallClient.FetchStateSyncEvents(lastStateID+1, to.Unix()) 1127 if c.config.OverrideStateSyncRecords != nil { 1128 if val, ok := c.config.OverrideStateSyncRecords[strconv.FormatUint(number, 10)]; ok { 1129 eventRecords = eventRecords[0:val] 1130 } 1131 } 1132 1133 chainID := c.chainConfig.ChainID.String() 1134 for _, eventRecord := range eventRecords { 1135 if eventRecord.ID <= lastStateID { 1136 continue 1137 } 1138 if err := validateEventRecord(eventRecord, number, to, lastStateID, chainID); err != nil { 1139 log.Error(err.Error()) 1140 break 1141 } 1142 1143 stateData := types.StateSyncData{ 1144 ID: eventRecord.ID, 1145 Contract: eventRecord.Contract, 1146 Data: hex.EncodeToString(eventRecord.Data), 1147 TxHash: eventRecord.TxHash, 1148 } 1149 stateSyncs = append(stateSyncs, &stateData) 1150 1151 if err := c.GenesisContractsClient.CommitState(eventRecord, state, header, chain); err != nil { 1152 return nil, err 1153 } 1154 lastStateID++ 1155 } 1156 return stateSyncs, nil 1157 } 1158 1159 func validateEventRecord(eventRecord *EventRecordWithTime, number uint64, to time.Time, lastStateID uint64, chainID string) error { 1160 // event id should be sequential and event.Time should lie in the range [from, to) 1161 if lastStateID+1 != eventRecord.ID || eventRecord.ChainID != chainID || !eventRecord.Time.Before(to) { 1162 return &InvalidStateReceivedError{number, lastStateID, &to, eventRecord} 1163 } 1164 return nil 1165 } 1166 1167 func (c *Bor) SetHeimdallClient(h IHeimdallClient) { 1168 c.HeimdallClient = h 1169 } 1170 1171 // 1172 // Private methods 1173 // 1174 1175 func (c *Bor) getNextHeimdallSpanForTest( 1176 newSpanID uint64, 1177 state *state.StateDB, 1178 header *types.Header, 1179 chain core.ChainContext, 1180 ) (*HeimdallSpan, error) { 1181 headerNumber := header.Number.Uint64() 1182 span, err := c.GetCurrentSpan(header.ParentHash) 1183 if err != nil { 1184 return nil, err 1185 } 1186 1187 // get local chain context object 1188 localContext := chain.(chainContext) 1189 // Retrieve the snapshot needed to verify this header and cache it 1190 snap, err := c.snapshot(localContext.Chain, headerNumber-1, header.ParentHash, nil) 1191 if err != nil { 1192 return nil, err 1193 } 1194 1195 // new span 1196 span.ID = newSpanID 1197 if span.EndBlock == 0 { 1198 span.StartBlock = 256 1199 } else { 1200 span.StartBlock = span.EndBlock + 1 1201 } 1202 span.EndBlock = span.StartBlock + (100 * c.config.Sprint) - 1 1203 1204 selectedProducers := make([]Validator, len(snap.ValidatorSet.Validators)) 1205 for i, v := range snap.ValidatorSet.Validators { 1206 selectedProducers[i] = *v 1207 } 1208 heimdallSpan := &HeimdallSpan{ 1209 Span: *span, 1210 ValidatorSet: *snap.ValidatorSet, 1211 SelectedProducers: selectedProducers, 1212 ChainID: c.chainConfig.ChainID.String(), 1213 } 1214 1215 return heimdallSpan, nil 1216 } 1217 1218 // 1219 // Chain context 1220 // 1221 1222 // chain context 1223 type chainContext struct { 1224 Chain consensus.ChainHeaderReader 1225 Bor consensus.Engine 1226 } 1227 1228 func (c chainContext) Engine() consensus.Engine { 1229 return c.Bor 1230 } 1231 1232 func (c chainContext) GetHeader(hash common.Hash, number uint64) *types.Header { 1233 return c.Chain.GetHeader(hash, number) 1234 } 1235 1236 // callmsg implements core.Message to allow passing it as a transaction simulator. 1237 type callmsg struct { 1238 ethereum.CallMsg 1239 } 1240 1241 func (m callmsg) From() common.Address { return m.CallMsg.From } 1242 func (m callmsg) Nonce() uint64 { return 0 } 1243 func (m callmsg) CheckNonce() bool { return false } 1244 func (m callmsg) To() *common.Address { return m.CallMsg.To } 1245 func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice } 1246 func (m callmsg) Gas() uint64 { return m.CallMsg.Gas } 1247 func (m callmsg) Value() *big.Int { return m.CallMsg.Value } 1248 func (m callmsg) Data() []byte { return m.CallMsg.Data } 1249 1250 // get system message 1251 func getSystemMessage(toAddress common.Address, data []byte) callmsg { 1252 return callmsg{ 1253 ethereum.CallMsg{ 1254 From: systemAddress, 1255 Gas: math.MaxUint64 / 2, 1256 GasPrice: big.NewInt(0), 1257 Value: big.NewInt(0), 1258 To: &toAddress, 1259 Data: data, 1260 }, 1261 } 1262 } 1263 1264 // apply message 1265 func applyMessage( 1266 msg callmsg, 1267 state *state.StateDB, 1268 header *types.Header, 1269 chainConfig *params.ChainConfig, 1270 chainContext core.ChainContext, 1271 ) error { 1272 // Create a new context to be used in the EVM environment 1273 blockContext := core.NewEVMBlockContext(header, chainContext, &header.Coinbase) 1274 // Create a new environment which holds all relevant information 1275 // about the transaction and calling mechanisms. 1276 vmenv := vm.NewEVM(blockContext, vm.TxContext{}, state, chainConfig, vm.Config{}) 1277 // Apply the transaction to the current state (included in the env) 1278 _, _, err := vmenv.Call( 1279 vm.AccountRef(msg.From()), 1280 *msg.To(), 1281 msg.Data(), 1282 msg.Gas(), 1283 msg.Value(), 1284 ) 1285 // Update the state with pending changes 1286 if err != nil { 1287 state.Finalise(true) 1288 } 1289 1290 return nil 1291 } 1292 1293 func validatorContains(a []*Validator, x *Validator) (*Validator, bool) { 1294 for _, n := range a { 1295 if bytes.Compare(n.Address.Bytes(), x.Address.Bytes()) == 0 { 1296 return n, true 1297 } 1298 } 1299 return nil, false 1300 } 1301 1302 func getUpdatedValidatorSet(oldValidatorSet *ValidatorSet, newVals []*Validator) *ValidatorSet { 1303 v := oldValidatorSet 1304 oldVals := v.Validators 1305 1306 var changes []*Validator 1307 for _, ov := range oldVals { 1308 if f, ok := validatorContains(newVals, ov); ok { 1309 ov.VotingPower = f.VotingPower 1310 } else { 1311 ov.VotingPower = 0 1312 } 1313 1314 changes = append(changes, ov) 1315 } 1316 1317 for _, nv := range newVals { 1318 if _, ok := validatorContains(changes, nv); !ok { 1319 changes = append(changes, nv) 1320 } 1321 } 1322 1323 v.UpdateWithChangeSet(changes) 1324 return v 1325 } 1326 1327 func isSprintStart(number, sprint uint64) bool { 1328 return number%sprint == 0 1329 }