github.com/pavelkrolevets/ton618@v1.9.26-0.20220108073458-82e0736ad23d/consensus/apos/apos.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package clique implements the proof-of-authority consensus engine. 18 package apos 19 20 import ( 21 "bytes" 22 "errors" 23 "io" 24 "math/big" 25 "math/rand" 26 "sync" 27 "time" 28 29 lru "github.com/hashicorp/golang-lru" 30 "github.com/pavelkrolevets/ton618/accounts" 31 "github.com/pavelkrolevets/ton618/common" 32 "github.com/pavelkrolevets/ton618/common/hexutil" 33 "github.com/pavelkrolevets/ton618/consensus" 34 "github.com/pavelkrolevets/ton618/consensus/misc" 35 "github.com/pavelkrolevets/ton618/core/state" 36 "github.com/pavelkrolevets/ton618/core/types" 37 "github.com/pavelkrolevets/ton618/crypto" 38 "github.com/pavelkrolevets/ton618/ethdb" 39 "github.com/pavelkrolevets/ton618/log" 40 "github.com/pavelkrolevets/ton618/params" 41 "github.com/pavelkrolevets/ton618/rlp" 42 "github.com/pavelkrolevets/ton618/rpc" 43 "github.com/pavelkrolevets/ton618/trie" 44 "golang.org/x/crypto/sha3" 45 ) 46 47 const ( 48 checkpointInterval = 1024 // Number of blocks after which to save the vote snapshot to the database 49 inmemorySnapshots = 128 // Number of recent vote snapshots to keep in memory 50 inmemorySignatures = 4096 // Number of recent block signatures to keep in memory 51 52 wiggleTime = 500 * time.Millisecond // Random delay (per signer) to allow concurrent signers 53 ) 54 55 // Authorized-proof-of-stake protocol constants. 56 var ( 57 blockReward = big.NewInt(1e+18) // Block reward in wei for successfully mining a block 58 epochLength = uint64(30000) // Default number of blocks after which to checkpoint and reset the pending votes 59 60 extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity 61 extraSeal = crypto.SignatureLength // Fixed number of extra-data suffix bytes reserved for signer seal 62 63 nonceAuthVote = hexutil.MustDecode("0xffffffffffffffff") // Magic nonce number to vote on adding a new signer 64 nonceDropVote = hexutil.MustDecode("0x0000000000000000") // Magic nonce number to vote on removing a signer. 65 66 uncleHash = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW. 67 68 diffInTurn = big.NewInt(2) // Block difficulty for in-turn signatures 69 diffNoTurn = big.NewInt(1) // Block difficulty for out-of-turn signatures 70 ) 71 72 // Various error messages to mark blocks invalid. These should be private to 73 // prevent engine specific errors from being referenced in the remainder of the 74 // codebase, inherently breaking if the engine is swapped out. Please put common 75 // error types into the consensus package. 76 var ( 77 // errUnknownBlock is returned when the list of signers is requested for a block 78 // that is not part of the local blockchain. 79 errUnknownBlock = errors.New("unknown block") 80 81 // errInvalidCheckpointBeneficiary is returned if a checkpoint/epoch transition 82 // block has a beneficiary set to non-zeroes. 83 errInvalidCheckpointBeneficiary = errors.New("beneficiary in checkpoint block non-zero") 84 85 // errInvalidVote is returned if a nonce value is something else that the two 86 // allowed constants of 0x00..0 or 0xff..f. 87 errInvalidVote = errors.New("vote nonce not 0x00..0 or 0xff..f") 88 89 // errInvalidCheckpointVote is returned if a checkpoint/epoch transition block 90 // has a vote nonce set to non-zeroes. 91 errInvalidCheckpointVote = errors.New("vote nonce in checkpoint block non-zero") 92 93 // errMissingVanity is returned if a block's extra-data section is shorter than 94 // 32 bytes, which is required to store the signer vanity. 95 errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing") 96 97 // errMissingSignature is returned if a block's extra-data section doesn't seem 98 // to contain a 65 byte secp256k1 signature. 99 errMissingSignature = errors.New("extra-data 65 byte signature suffix missing") 100 101 // errExtraSigners is returned if non-checkpoint block contain signer data in 102 // their extra-data fields. 103 errExtraSigners = errors.New("non-checkpoint block contains extra signer list") 104 105 // errInvalidCheckpointSigners is returned if a checkpoint block contains an 106 // invalid list of signers (i.e. non divisible by 20 bytes). 107 errInvalidCheckpointSigners = errors.New("invalid signer list on checkpoint block") 108 109 // errMismatchingCheckpointSigners is returned if a checkpoint block contains a 110 // list of signers different than the one the local node calculated. 111 errMismatchingCheckpointSigners = errors.New("mismatching signer list on checkpoint block") 112 113 // errInvalidMixDigest is returned if a block's mix digest is non-zero. 114 errInvalidMixDigest = errors.New("non-zero mix digest") 115 116 // errInvalidUncleHash is returned if a block contains an non-empty uncle list. 117 errInvalidUncleHash = errors.New("non empty uncle hash") 118 119 // errInvalidDifficulty is returned if the difficulty of a block neither 1 or 2. 120 errInvalidDifficulty = errors.New("invalid difficulty") 121 122 // errWrongDifficulty is returned if the difficulty of a block doesn't match the 123 // turn of the signer. 124 errWrongDifficulty = errors.New("wrong difficulty") 125 126 // errInvalidTimestamp is returned if the timestamp of a block is lower than 127 // the previous block's timestamp + the minimum block period. 128 errInvalidTimestamp = errors.New("invalid timestamp") 129 130 // errInvalidVotingChain is returned if an authorization list is attempted to 131 // be modified via out-of-range or non-contiguous headers. 132 errInvalidVotingChain = errors.New("invalid voting chain") 133 134 // errUnauthorizedSigner is returned if a header is signed by a non-authorized entity. 135 errUnauthorizedSigner = errors.New("unauthorized signer") 136 137 // errRecentlySigned is returned if a header is signed by an authorized entity 138 // that already signed a header recently, thus is temporarily not allowed to. 139 errRecentlySigned = errors.New("recently signed") 140 ) 141 142 // SignerFn hashes and signs the data to be signed by a backing account. 143 type SignerFn func(signer accounts.Account, mimeType string, message []byte) ([]byte, error) 144 145 // ecrecover extracts the Ethereum account address from a signed header. 146 func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) { 147 // If the signature's already cached, return that 148 hash := header.Hash() 149 if address, known := sigcache.Get(hash); known { 150 return address.(common.Address), nil 151 } 152 // Retrieve the signature from the header extra-data 153 if len(header.Extra) < extraSeal { 154 return common.Address{}, errMissingSignature 155 } 156 signature := header.Extra[len(header.Extra)-extraSeal:] 157 158 // Recover the public key and the Ethereum address 159 pubkey, err := crypto.Ecrecover(SealHash(header).Bytes(), signature) 160 if err != nil { 161 return common.Address{}, err 162 } 163 var signer common.Address 164 copy(signer[:], crypto.Keccak256(pubkey[1:])[12:]) 165 166 sigcache.Add(hash, signer) 167 return signer, nil 168 } 169 170 // Clique is the proof-of-authority consensus engine proposed to support the 171 // Ethereum testnet following the Ropsten attacks. 172 type Apos struct { 173 config *params.AposConfig // Consensus engine configuration parameters 174 db ethdb.Database // Database to store and retrieve snapshot checkpoints 175 176 recents *lru.ARCCache // Snapshots for recent block to speed up reorgs 177 signatures *lru.ARCCache // Signatures of recent blocks to speed up mining 178 179 proposals map[common.Address]bool // Current list of proposals we are pushing 180 181 signer common.Address // Ethereum address of the signing key 182 signFn SignerFn // Signer function to authorize hashes with 183 lock sync.RWMutex // Protects the signer fields 184 185 // The fields below are for testing only 186 fakeDiff bool // Skip difficulty verifications 187 state *state.StateDB 188 } 189 190 // New creates a Clique proof-of-authority consensus engine with the initial 191 // signers set to the ones provided by the user. 192 func New(config *params.AposConfig, db ethdb.Database) *Apos { 193 // Set any missing consensus parameters to their defaults 194 conf := *config 195 if conf.Epoch == 0 { 196 conf.Epoch = epochLength 197 } 198 // Allocate the snapshot caches and create the engine 199 recents, _ := lru.NewARC(inmemorySnapshots) 200 signatures, _ := lru.NewARC(inmemorySignatures) 201 202 return &Apos{ 203 config: &conf, 204 db: db, 205 recents: recents, 206 signatures: signatures, 207 proposals: make(map[common.Address]bool), 208 } 209 } 210 211 // Author implements consensus.Engine, returning the Ethereum address recovered 212 // from the signature in the header's extra-data section. 213 func (c *Apos) Author(header *types.Header) (common.Address, error) { 214 return ecrecover(header, c.signatures) 215 } 216 217 // VerifyHeader checks whether a header conforms to the consensus rules. 218 func (c *Apos) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error { 219 return c.verifyHeader(chain, header, nil) 220 } 221 222 // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The 223 // method returns a quit channel to abort the operations and a results channel to 224 // retrieve the async verifications (the order is that of the input slice). 225 func (c *Apos) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) { 226 abort := make(chan struct{}) 227 results := make(chan error, len(headers)) 228 229 go func() { 230 for i, header := range headers { 231 err := c.verifyHeader(chain, header, headers[:i]) 232 233 select { 234 case <-abort: 235 return 236 case results <- err: 237 } 238 } 239 }() 240 return abort, results 241 } 242 243 // verifyHeader checks whether a header conforms to the consensus rules.The 244 // caller may optionally pass in a batch of parents (ascending order) to avoid 245 // looking those up from the database. This is useful for concurrently verifying 246 // a batch of new headers. 247 func (c *Apos) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 248 if header.Number == nil { 249 return errUnknownBlock 250 } 251 number := header.Number.Uint64() 252 253 // Don't waste time checking blocks from the future 254 if header.Time > uint64(time.Now().Unix()) { 255 return consensus.ErrFutureBlock 256 } 257 // Checkpoint blocks need to enforce zero beneficiary 258 checkpoint := (number % c.config.Epoch) == 0 259 if checkpoint && header.Coinbase != (common.Address{}) { 260 return errInvalidCheckpointBeneficiary 261 } 262 // Nonces must be 0x00..0 or 0xff..f, zeroes enforced on checkpoints 263 if !bytes.Equal(header.Nonce[:], nonceAuthVote) && !bytes.Equal(header.Nonce[:], nonceDropVote) { 264 return errInvalidVote 265 } 266 if checkpoint && !bytes.Equal(header.Nonce[:], nonceDropVote) { 267 return errInvalidCheckpointVote 268 } 269 // Check that the extra-data contains both the vanity and signature 270 if len(header.Extra) < extraVanity { 271 return errMissingVanity 272 } 273 if len(header.Extra) < extraVanity+extraSeal { 274 return errMissingSignature 275 } 276 // Ensure that the extra-data contains a signer list on checkpoint, but none otherwise 277 signersBytes := len(header.Extra) - extraVanity - extraSeal 278 if !checkpoint && signersBytes != 0 { 279 return errExtraSigners 280 } 281 if checkpoint && signersBytes%common.AddressLength != 0 { 282 return errInvalidCheckpointSigners 283 } 284 // Ensure that the mix digest is zero as we don't have fork protection currently 285 if header.MixDigest != (common.Hash{}) { 286 return errInvalidMixDigest 287 } 288 // Ensure that the block doesn't contain any uncles which are meaningless in PoA 289 if header.UncleHash != uncleHash { 290 return errInvalidUncleHash 291 } 292 // Ensure that the block's difficulty is meaningful (may not be correct at this point) 293 if number > 0 { 294 if header.Difficulty == nil || (header.Difficulty.Cmp(diffInTurn) != 0 && header.Difficulty.Cmp(diffNoTurn) != 0) { 295 return errInvalidDifficulty 296 } 297 } 298 // If all checks passed, validate any special fields for hard forks 299 if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil { 300 return err 301 } 302 // All basic checks passed, verify cascading fields 303 return c.verifyCascadingFields(chain, header, parents) 304 } 305 306 // verifyCascadingFields verifies all the header fields that are not standalone, 307 // rather depend on a batch of previous headers. The caller may optionally pass 308 // in a batch of parents (ascending order) to avoid looking those up from the 309 // database. This is useful for concurrently verifying a batch of new headers. 310 func (c *Apos) verifyCascadingFields(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 311 // The genesis block is the always valid dead-end 312 number := header.Number.Uint64() 313 if number == 0 { 314 return nil 315 } 316 // Ensure that the block's timestamp isn't too close to its parent 317 var parent *types.Header 318 if len(parents) > 0 { 319 parent = parents[len(parents)-1] 320 } else { 321 parent = chain.GetHeader(header.ParentHash, number-1) 322 } 323 if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash { 324 return consensus.ErrUnknownAncestor 325 } 326 if parent.Time+c.config.Period > header.Time { 327 return errInvalidTimestamp 328 } 329 // Retrieve the snapshot needed to verify this header and cache it 330 snap, err := c.snapshot(chain, number-1, header.ParentHash, parents) 331 if err != nil { 332 return err 333 } 334 // If the block is a checkpoint block, verify the signer list 335 if number%c.config.Epoch == 0 { 336 signers := make([]byte, len(snap.Signers)*common.AddressLength) 337 for i, signer := range snap.signers() { 338 copy(signers[i*common.AddressLength:], signer[:]) 339 } 340 extraSuffix := len(header.Extra) - extraSeal 341 if !bytes.Equal(header.Extra[extraVanity:extraSuffix], signers) { 342 return errMismatchingCheckpointSigners 343 } 344 } 345 // All basic checks passed, verify the seal and return 346 return c.verifySeal(chain, header, parents) 347 } 348 349 // snapshot retrieves the authorization snapshot at a given point in time. 350 func (c *Apos) snapshot(chain consensus.ChainHeaderReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) { 351 // Search for a snapshot in memory or on disk for checkpoints 352 var ( 353 headers []*types.Header 354 snap *Snapshot 355 ) 356 for snap == nil { 357 // If an in-memory snapshot was found, use that 358 if s, ok := c.recents.Get(hash); ok { 359 snap = s.(*Snapshot) 360 break 361 } 362 // If an on-disk checkpoint snapshot can be found, use that 363 if number%checkpointInterval == 0 { 364 if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil { 365 log.Trace("Loaded voting snapshot from disk", "number", number, "hash", hash) 366 snap = s 367 break 368 } 369 } 370 // If we're at the genesis, snapshot the initial state. Alternatively if we're 371 // at a checkpoint block without a parent (light client CHT), or we have piled 372 // up more headers than allowed to be reorged (chain reinit from a freezer), 373 // consider the checkpoint trusted and snapshot it. 374 if number == 0 || (number%c.config.Epoch == 0 && (len(headers) > params.FullImmutabilityThreshold || chain.GetHeaderByNumber(number-1) == nil)) { 375 checkpoint := chain.GetHeaderByNumber(number) 376 if checkpoint != nil { 377 hash := checkpoint.Hash() 378 379 signers := make([]common.Address, (len(checkpoint.Extra)-extraVanity-extraSeal)/common.AddressLength) 380 for i := 0; i < len(signers); i++ { 381 copy(signers[i][:], checkpoint.Extra[extraVanity+i*common.AddressLength:]) 382 } 383 snap = newSnapshot(c.config, c.signatures, number, hash, signers) 384 if err := snap.store(c.db); err != nil { 385 return nil, err 386 } 387 log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash) 388 break 389 } 390 } 391 // No snapshot for this header, gather the header and move backward 392 var header *types.Header 393 if len(parents) > 0 { 394 // If we have explicit parents, pick from there (enforced) 395 header = parents[len(parents)-1] 396 if header.Hash() != hash || header.Number.Uint64() != number { 397 return nil, consensus.ErrUnknownAncestor 398 } 399 parents = parents[:len(parents)-1] 400 } else { 401 // No explicit parents (or no more left), reach out to the database 402 header = chain.GetHeader(hash, number) 403 if header == nil { 404 return nil, consensus.ErrUnknownAncestor 405 } 406 } 407 headers = append(headers, header) 408 number, hash = number-1, header.ParentHash 409 } 410 // Previous snapshot found, apply any pending headers on top of it 411 for i := 0; i < len(headers)/2; i++ { 412 headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i] 413 } 414 snap, err := snap.apply(headers, c.state) 415 if err != nil { 416 return nil, err 417 } 418 c.recents.Add(snap.Hash, snap) 419 420 // If we've generated a new checkpoint snapshot, save to disk 421 if snap.Number%checkpointInterval == 0 && len(headers) > 0 { 422 if err = snap.store(c.db); err != nil { 423 return nil, err 424 } 425 log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash) 426 } 427 return snap, err 428 } 429 430 // VerifyUncles implements consensus.Engine, always returning an error for any 431 // uncles as this consensus mechanism doesn't permit uncles. 432 func (c *Apos) VerifyUncles(chain consensus.ChainReader, block *types.Block) error { 433 if len(block.Uncles()) > 0 { 434 return errors.New("uncles not allowed") 435 } 436 return nil 437 } 438 439 // VerifySeal implements consensus.Engine, checking whether the signature contained 440 // in the header satisfies the consensus protocol requirements. 441 func (c *Apos) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error { 442 return c.verifySeal(chain, header, nil) 443 } 444 445 // verifySeal checks whether the signature contained in the header satisfies the 446 // consensus protocol requirements. The method accepts an optional list of parent 447 // headers that aren't yet part of the local blockchain to generate the snapshots 448 // from. 449 func (c *Apos) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 450 // Verifying the genesis block is not supported 451 number := header.Number.Uint64() 452 if number == 0 { 453 return errUnknownBlock 454 } 455 // Retrieve the snapshot needed to verify this header and cache it 456 snap, err := c.snapshot(chain, number-1, header.ParentHash, parents) 457 if err != nil { 458 return err 459 } 460 461 // Resolve the authorization key and check against signers 462 signer, err := ecrecover(header, c.signatures) 463 if err != nil { 464 return err 465 } 466 if _, ok := snap.Signers[signer]; !ok { 467 return errUnauthorizedSigner 468 } 469 for seen, recent := range snap.Recents { 470 if recent == signer { 471 // Signer is among recents, only fail if the current block doesn't shift it out 472 if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit { 473 return errRecentlySigned 474 } 475 } 476 } 477 // Ensure that the difficulty corresponds to the turn-ness of the signer 478 if !c.fakeDiff { 479 inturn := snap.inturn(header.Number.Uint64(), signer) 480 if inturn && header.Difficulty.Cmp(diffInTurn) != 0 { 481 return errWrongDifficulty 482 } 483 if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 { 484 return errWrongDifficulty 485 } 486 } 487 return nil 488 } 489 490 // Prepare implements consensus.Engine, preparing all the consensus fields of the 491 // header for running the transactions on top. 492 func (c *Apos) Prepare(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB) error { 493 // Add state pinter to engine if empty 494 if c.state == nil { 495 c.state = state 496 } 497 // If the block isn't a checkpoint, cast a random vote (good enough for now) 498 header.Coinbase = common.Address{} 499 header.Nonce = types.BlockNonce{} 500 501 number := header.Number.Uint64() 502 // Assemble the voting snapshot to check which votes make sense 503 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 504 if err != nil { 505 return err 506 } 507 if number%c.config.Epoch != 0 { 508 c.lock.RLock() 509 510 // Gather all the proposals that make sense voting on 511 addresses := make([]common.Address, 0, len(c.proposals)) 512 for address, authorize := range c.proposals { 513 if snap.validVote(address, authorize) { 514 addresses = append(addresses, address) 515 } 516 } 517 // If there's pending proposals, cast a vote on them 518 if len(addresses) > 0 { 519 header.Coinbase = addresses[rand.Intn(len(addresses))] 520 if c.proposals[header.Coinbase] { 521 copy(header.Nonce[:], nonceAuthVote) 522 } else { 523 copy(header.Nonce[:], nonceDropVote) 524 } 525 } 526 c.lock.RUnlock() 527 } 528 // Set the correct difficulty 529 header.Difficulty = calcDifficulty(snap, c.signer) 530 531 // Ensure the extra data has all its components 532 if len(header.Extra) < extraVanity { 533 header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...) 534 } 535 header.Extra = header.Extra[:extraVanity] 536 537 if number%c.config.Epoch == 0 { 538 for _, signer := range snap.signers() { 539 header.Extra = append(header.Extra, signer[:]...) 540 } 541 } 542 header.Extra = append(header.Extra, make([]byte, extraSeal)...) 543 544 // Mix digest is reserved for now, set to empty 545 header.MixDigest = common.Hash{} 546 547 // Ensure the timestamp has the correct delay 548 parent := chain.GetHeader(header.ParentHash, number-1) 549 if parent == nil { 550 return consensus.ErrUnknownAncestor 551 } 552 header.Time = parent.Time + c.config.Period 553 if header.Time < uint64(time.Now().Unix()) { 554 header.Time = uint64(time.Now().Unix()) 555 } 556 return nil 557 } 558 559 // Finalize implements consensus.Engine, ensuring no uncles are set, nor block 560 // rewards given. 561 func (c *Apos) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) { 562 // author, _ := c.Author(header) 563 // log.Info("Signer ", "Finalize", author.Hex()) 564 // Accumulate any block and commit the final state root 565 // accumulateRewards(chain.Config(), state, header, author) 566 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 567 header.UncleHash = types.CalcUncleHash(nil) 568 } 569 570 // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set, 571 // nor block rewards given, and returns the final block. 572 func (c *Apos) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) { 573 // author, _ := c.Author(header) 574 // log.Info("Signer ", "FinalizeAndAssemble", c.signer) 575 // Accumulate any block and commit the final state root 576 // accumulateRewards(chain.Config(), state, header, c.signer) 577 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 578 header.UncleHash = types.CalcUncleHash(nil) 579 580 // Assemble and return the final block for sealing 581 return types.NewBlock(header, txs, nil, receipts, new(trie.Trie)), nil 582 } 583 584 // Authorize injects a private key into the consensus engine to mint new blocks 585 // with. 586 func (c *Apos) Authorize(signer common.Address, signFn SignerFn) { 587 c.lock.Lock() 588 defer c.lock.Unlock() 589 590 c.signer = signer 591 c.signFn = signFn 592 } 593 594 // Seal implements consensus.Engine, attempting to create a sealed block using 595 // the local signing credentials. 596 func (c *Apos) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error { 597 header := block.Header() 598 599 // Sealing the genesis block is not supported 600 number := header.Number.Uint64() 601 if number == 0 { 602 return errUnknownBlock 603 } 604 // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing) 605 if c.config.Period == 0 && len(block.Transactions()) == 0 { 606 log.Info("Sealing paused, waiting for transactions") 607 return nil 608 } 609 // Don't hold the signer fields for the entire sealing procedure 610 c.lock.RLock() 611 signer, signFn := c.signer, c.signFn 612 c.lock.RUnlock() 613 614 // Bail out if we're unauthorized to sign a block 615 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 616 if err != nil { 617 return err 618 } 619 if _, authorized := snap.Signers[signer]; !authorized { 620 return errUnauthorizedSigner 621 } 622 // If we're amongst the recent signers, wait for the next block 623 for seen, recent := range snap.Recents { 624 if recent == signer { 625 // Signer is among recents, only wait if the current block doesn't shift it out 626 if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit { 627 log.Info("Signed recently, must wait for others") 628 return nil 629 } 630 } 631 } 632 // Sweet, the protocol permits us to sign the block, wait for our time 633 delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple 634 if header.Difficulty.Cmp(diffNoTurn) == 0 { 635 // It's not our turn explicitly to sign, delay it a bit 636 wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime 637 delay += time.Duration(rand.Int63n(int64(wiggle))) 638 639 log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle)) 640 } 641 // Sign all the things! 642 sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeDpos, DposRLP(header)) 643 if err != nil { 644 return err 645 } 646 copy(header.Extra[len(header.Extra)-extraSeal:], sighash) 647 // Wait until sealing is terminated or delay timeout. 648 log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay)) 649 go func() { 650 select { 651 case <-stop: 652 return 653 case <-time.After(delay): 654 } 655 656 select { 657 case results <- block.WithSeal(header): 658 default: 659 log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header)) 660 } 661 }() 662 663 return nil 664 } 665 666 // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty 667 // that a new block should have: 668 // * DIFF_NOTURN(2) if BLOCK_NUMBER % SIGNER_COUNT != SIGNER_INDEX 669 // * DIFF_INTURN(1) if BLOCK_NUMBER % SIGNER_COUNT == SIGNER_INDEX 670 func (c *Apos) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int { 671 snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil) 672 if err != nil { 673 return nil 674 } 675 return calcDifficulty(snap, c.signer) 676 } 677 678 func calcDifficulty(snap *Snapshot, signer common.Address) *big.Int { 679 if snap.inturn(snap.Number+1, signer) { 680 return new(big.Int).Set(diffInTurn) 681 } 682 return new(big.Int).Set(diffNoTurn) 683 } 684 685 // SealHash returns the hash of a block prior to it being sealed. 686 func (c *Apos) SealHash(header *types.Header) common.Hash { 687 return SealHash(header) 688 } 689 690 // Close implements consensus.Engine. It's a noop for clique as there are no background threads. 691 func (c *Apos) Close() error { 692 return nil 693 } 694 695 // APIs implements consensus.Engine, returning the user facing RPC API to allow 696 // controlling the signer voting. 697 func (c *Apos) APIs(chain consensus.ChainHeaderReader) []rpc.API { 698 return []rpc.API{{ 699 Namespace: "apos", 700 Version: "1.0", 701 Service: &API{chain: chain, apos: c}, 702 Public: false, 703 }} 704 } 705 706 // SealHash returns the hash of a block prior to it being sealed. 707 func SealHash(header *types.Header) (hash common.Hash) { 708 hasher := sha3.NewLegacyKeccak256() 709 encodeSigHeader(hasher, header) 710 hasher.Sum(hash[:0]) 711 return hash 712 } 713 714 // DposRLP returns the rlp bytes which needs to be signed for the proof-of-authority 715 // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature 716 // contained at the end of the extra data. 717 // 718 // Note, the method requires the extra data to be at least 65 bytes, otherwise it 719 // panics. This is done to avoid accidentally using both forms (signature present 720 // or not), which could be abused to produce different hashes for the same header. 721 func DposRLP(header *types.Header) []byte { 722 b := new(bytes.Buffer) 723 encodeSigHeader(b, header) 724 return b.Bytes() 725 } 726 727 func encodeSigHeader(w io.Writer, header *types.Header) { 728 err := rlp.Encode(w, []interface{}{ 729 header.ParentHash, 730 header.UncleHash, 731 header.Coinbase, 732 header.Root, 733 header.TxHash, 734 header.ReceiptHash, 735 header.Bloom, 736 header.Difficulty, 737 header.Number, 738 header.GasLimit, 739 header.GasUsed, 740 header.Time, 741 header.Extra[:len(header.Extra)-crypto.SignatureLength], // Yes, this will panic if extra is too short 742 header.MixDigest, 743 header.Nonce, 744 }) 745 if err != nil { 746 panic("can't encode: " + err.Error()) 747 } 748 } 749 750 // AccumulateRewards credits the coinbase of the given block with the mining 751 // reward. Rewards are deminishing with the block progression. 752 func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, signer common.Address) { 753 754 // Select the correct block reward based on chain progression ie blockReward / x^(blockNumber mod 10 000 000) 755 var quotent big.Int 756 quotent = *quotent.Quo(header.Number, big.NewInt(10000000)) 757 blockReward := blockReward.Div(blockReward, header.Number.Exp(header.Number, "ent, nil)) 758 // Accumulate the rewards for the miner 759 reward := new(big.Int).Set(blockReward) 760 log.Info("Reward to miner ", "address", signer.Hex(), "amount", reward.String()) 761 state.AddBalance(signer, reward) 762 }