github.com/core-coin/go-core/v2@v2.1.9/consensus/cryptore/consensus.go (about) 1 // Copyright 2023 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package cryptore 18 19 import ( 20 "errors" 21 "fmt" 22 "math/big" 23 "runtime" 24 "time" 25 26 "github.com/core-coin/go-randomy" 27 28 "github.com/core-coin/go-core/v2/common" 29 "github.com/core-coin/go-core/v2/consensus" 30 "github.com/core-coin/go-core/v2/core/state" 31 "github.com/core-coin/go-core/v2/core/types" 32 "github.com/core-coin/go-core/v2/params" 33 "github.com/core-coin/go-core/v2/rlp" 34 "github.com/core-coin/go-core/v2/trie" 35 36 mapset "github.com/deckarep/golang-set" 37 "golang.org/x/crypto/sha3" 38 ) 39 40 // Cryptore proof-of-work protocol constants. 41 var ( 42 BlockReward = big.NewInt(5e+18) // Block reward in ore for successfully mining a block 43 maxUncles = 2 // Maximum number of uncles allowed in a single block 44 allowedFutureBlockTime = 8 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks 45 46 calcDifficulty = makeDifficultyCalculator() 47 ) 48 49 // Various error messages to mark blocks invalid. These should be private to 50 // prevent engine specific errors from being referenced in the remainder of the 51 // codebase, inherently breaking if the engine is swapped out. Please put common 52 // error types into the consensus package. 53 var ( 54 errOlderBlockTime = errors.New("timestamp older than parent") 55 errTooManyUncles = errors.New("too many uncles") 56 errDuplicateUncle = errors.New("duplicate uncle") 57 errUncleIsAncestor = errors.New("uncle is ancestor") 58 errDanglingUncle = errors.New("uncle's parent is not ancestor") 59 errInvalidDifficulty = errors.New("non-positive difficulty") 60 errInvalidPoW = errors.New("invalid proof-of-work") 61 ) 62 63 // Author implements consensus.Engine, returning the header's coinbase as the 64 // proof-of-work verified author of the block. 65 func (cryptore *Cryptore) Author(header *types.Header) (common.Address, error) { 66 return header.Coinbase, nil 67 } 68 69 // VerifyHeader checks whether a header conforms to the consensus rules of the 70 // stock Core cryptore engine. 71 func (cryptore *Cryptore) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error { 72 // If we're running a full engine faking, accept any input as valid 73 if cryptore.config.PowMode == ModeFullFake { 74 return nil 75 } 76 // Short circuit if the header is known, or its parent not 77 number := header.Number.Uint64() 78 if chain.GetHeader(header.Hash(), number) != nil { 79 return nil 80 } 81 parent := chain.GetHeader(header.ParentHash, number-1) 82 if parent == nil { 83 return consensus.ErrUnknownAncestor 84 } 85 // Sanity checks passed, do a proper verification 86 return cryptore.verifyHeader(chain, header, parent, false, seal) 87 } 88 89 // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers 90 // concurrently. The method returns a quit channel to abort the operations and 91 // a results channel to retrieve the async verifications. 92 func (cryptore *Cryptore) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) { 93 // If we're running a full engine faking, accept any input as valid 94 if cryptore.config.PowMode == ModeFullFake || len(headers) == 0 { 95 abort, results := make(chan struct{}), make(chan error, len(headers)) 96 for i := 0; i < len(headers); i++ { 97 results <- nil 98 } 99 return abort, results 100 } 101 102 // Spawn as many workers as allowed threads 103 workers := runtime.GOMAXPROCS(0) 104 if len(headers) < workers { 105 workers = len(headers) 106 } 107 108 // Create a task channel and spawn the verifiers 109 var ( 110 inputs = make(chan int) 111 done = make(chan int, workers) 112 errors = make([]error, len(headers)) 113 abort = make(chan struct{}) 114 ) 115 for i := 0; i < workers; i++ { 116 go func() { 117 for index := range inputs { 118 errors[index] = cryptore.verifyHeaderWorker(chain, headers, seals, index) 119 done <- index 120 } 121 }() 122 } 123 124 errorsOut := make(chan error, len(headers)) 125 go func() { 126 defer close(inputs) 127 var ( 128 in, out = 0, 0 129 checked = make([]bool, len(headers)) 130 inputs = inputs 131 ) 132 for { 133 select { 134 case inputs <- in: 135 if in++; in == len(headers) { 136 // Reached end of headers. Stop sending to workers. 137 inputs = nil 138 } 139 case index := <-done: 140 for checked[index] = true; checked[out]; out++ { 141 errorsOut <- errors[out] 142 if out == len(headers)-1 { 143 return 144 } 145 } 146 case <-abort: 147 return 148 } 149 } 150 }() 151 return abort, errorsOut 152 } 153 154 func (cryptore *Cryptore) verifyHeaderWorker(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool, index int) error { 155 var parent *types.Header 156 if index == 0 { 157 parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1) 158 } else if headers[index-1].Hash() == headers[index].ParentHash { 159 parent = headers[index-1] 160 } 161 if parent == nil { 162 return consensus.ErrUnknownAncestor 163 } 164 if chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()) != nil { 165 return nil // known block 166 } 167 return cryptore.verifyHeader(chain, headers[index], parent, false, seals[index]) 168 } 169 170 // VerifyUncles verifies that the given block's uncles conform to the consensus 171 // rules of the stock Core cryptore engine. 172 func (cryptore *Cryptore) VerifyUncles(chain consensus.ChainReader, block *types.Block) error { 173 // If we're running a full engine faking, accept any input as valid 174 if cryptore.config.PowMode == ModeFullFake { 175 return nil 176 } 177 // Verify that there are at most 2 uncles included in this block 178 if len(block.Uncles()) > maxUncles { 179 return errTooManyUncles 180 } 181 if len(block.Uncles()) == 0 { 182 return nil 183 } 184 // Gather the set of past uncles and ancestors 185 uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header) 186 187 number, parent := block.NumberU64()-1, block.ParentHash() 188 for i := 0; i < 7; i++ { 189 ancestor := chain.GetBlock(parent, number) 190 if ancestor == nil { 191 break 192 } 193 ancestors[ancestor.Hash()] = ancestor.Header() 194 for _, uncle := range ancestor.Uncles() { 195 uncles.Add(uncle.Hash()) 196 } 197 parent, number = ancestor.ParentHash(), number-1 198 } 199 ancestors[block.Hash()] = block.Header() 200 uncles.Add(block.Hash()) 201 202 // Verify each of the uncles that it's recent, but not an ancestor 203 for _, uncle := range block.Uncles() { 204 // Make sure every uncle is rewarded only once 205 hash := uncle.Hash() 206 if uncles.Contains(hash) { 207 return errDuplicateUncle 208 } 209 uncles.Add(hash) 210 211 // Make sure the uncle has a valid ancestry 212 if ancestors[hash] != nil { 213 return errUncleIsAncestor 214 } 215 if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() { 216 return errDanglingUncle 217 } 218 if err := cryptore.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil { 219 return err 220 } 221 } 222 return nil 223 } 224 225 // verifyHeader checks whether a header conforms to the consensus rules of the 226 // stock Core cryptore engine. 227 // See YP section 4.3.4. "Block Header Validity" 228 func (cryptore *Cryptore) verifyHeader(chain consensus.ChainHeaderReader, header, parent *types.Header, uncle bool, seal bool) error { 229 // Ensure that the header's extra-data section is of a reasonable size 230 if uint64(len(header.Extra)) > params.MaximumExtraDataSize { 231 return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize) 232 } 233 // Verify the header's timestamp 234 if !uncle { 235 if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) { 236 return consensus.ErrFutureBlock 237 } 238 } 239 if header.Time <= parent.Time { 240 return errOlderBlockTime 241 } 242 // Verify the block's difficulty based on its timestamp and parent's difficulty 243 expected := cryptore.CalcDifficulty(chain, header.Time, parent) 244 245 if expected.Cmp(header.Difficulty) != 0 { 246 return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected) 247 } 248 // Verify that the energy limit is <= 2^63-1 249 cap := uint64(0x7fffffffffffffff) 250 if header.EnergyLimit > cap { 251 return fmt.Errorf("invalid energyLimit: have %v, max %v", header.EnergyLimit, cap) 252 } 253 // Verify that the energyUsed is <= energyLimit 254 if header.EnergyUsed > header.EnergyLimit { 255 return fmt.Errorf("invalid energyUsed: have %d, energyLimit %d", header.EnergyUsed, header.EnergyLimit) 256 } 257 258 // Verify that the energy limit remains within allowed bounds 259 diff := int64(parent.EnergyLimit) - int64(header.EnergyLimit) 260 if diff < 0 { 261 diff *= -1 262 } 263 limit := parent.EnergyLimit / params.EnergyLimitBoundDivisor 264 265 if uint64(diff) >= limit || header.EnergyLimit < params.MinEnergyLimit { 266 return fmt.Errorf("invalid energy limit: have %d, want %d += %d", header.EnergyLimit, parent.EnergyLimit, limit) 267 } 268 // Verify that the block number is parent's +1 269 if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 { 270 return consensus.ErrInvalidNumber 271 } 272 // Verify the engine specific seal securing the block 273 if seal { 274 if err := cryptore.VerifySeal(chain, header); err != nil { 275 return err 276 } 277 } 278 return nil 279 } 280 281 // CalcDifficulty is the difficulty adjustment algorithm. It returns 282 // the difficulty that a new block should have when created at time 283 // given the parent block's time and difficulty. 284 func (cryptore *Cryptore) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int { 285 return CalcDifficulty(chain.Config(), time, parent) 286 } 287 288 // CalcDifficulty is the difficulty adjustment algorithm. It returns 289 // the difficulty that a new block should have when created at time 290 // given the parent block's time and difficulty. 291 func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int { 292 return calcDifficulty(time, parent) 293 } 294 295 // Some weird constants to avoid constant memory allocs for them. 296 var ( 297 expDiffPeriod = big.NewInt(100000) 298 big1 = big.NewInt(1) 299 big2 = big.NewInt(2) 300 big5 = big.NewInt(5) 301 bigMinus99 = big.NewInt(-99) 302 ) 303 304 // makeDifficultyCalculator creates a difficultyCalculator. 305 // the difficulty is calculated with rules 306 func makeDifficultyCalculator() func(time uint64, parent *types.Header) *big.Int { 307 // Note, the calculations below looks at the parent number, which is 1 below 308 // the block number. Thus we remove one from the delay given 309 return func(time uint64, parent *types.Header) *big.Int { 310 // https://github.com/core/CIPs/issues/100. 311 // algorithm: 312 // diff = (parent_diff + 313 // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 314 // ) + 2^(periodCount - 2) 315 316 bigTime := new(big.Int).SetUint64(time) 317 bigParentTime := new(big.Int).SetUint64(parent.Time) 318 319 // holds intermediate values to make the algo easier to read & audit 320 x := new(big.Int) 321 y := new(big.Int) 322 323 // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9 324 x.Sub(bigTime, bigParentTime) 325 x.Div(x, big5) 326 if parent.UncleHash == types.EmptyUncleHash { 327 x.Sub(big1, x) 328 } else { 329 x.Sub(big2, x) 330 } 331 // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99) 332 if x.Cmp(bigMinus99) < 0 { 333 x.Set(bigMinus99) 334 } 335 // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 336 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 337 x.Mul(y, x) 338 x.Add(parent.Difficulty, x) 339 340 // minimum difficulty can ever be (before exponential factor) 341 if x.Cmp(params.MinimumDifficulty) < 0 { 342 x.Set(params.MinimumDifficulty) 343 } 344 return x 345 } 346 } 347 348 // VerifySeal implements consensus.Engine, checking whether the given block satisfies 349 // the PoW difficulty requirements. 350 func (cryptore *Cryptore) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error { 351 return cryptore.verifySeal(chain, header) 352 } 353 354 // verifySeal checks whether a block satisfies the PoW difficulty requirements. 355 func (cryptore *Cryptore) verifySeal(chain consensus.ChainHeaderReader, header *types.Header) error { 356 // If we're running a fake PoW, accept any seal as valid 357 if cryptore.config.PowMode == ModeFake || cryptore.config.PowMode == ModeFullFake { 358 time.Sleep(cryptore.fakeDelay) 359 if cryptore.fakeFail == header.Number.Uint64() { 360 return errInvalidPoW 361 } 362 return nil 363 } 364 // If we're running a shared PoW, delegate verification to it 365 if cryptore.shared != nil { 366 return cryptore.shared.verifySeal(chain, header) 367 } 368 // Ensure that we have a valid difficulty for the block 369 if header.Difficulty.Sign() <= 0 { 370 return errInvalidDifficulty 371 } 372 373 // Recompute PoW values 374 var result []byte 375 cryptore.sealVM.Add(1) 376 result, err := randomy.RandomY(cryptore.randomYVM, cryptore.vmMutex, cryptore.SealHash(header).Bytes(), header.Nonce.Uint64()) 377 cryptore.sealVM.Done() 378 if err != nil { 379 return err 380 } 381 382 target := new(big.Int).Div(two256, header.Difficulty) 383 if new(big.Int).SetBytes(result).Cmp(target) > 0 { 384 return errInvalidPoW 385 } 386 return nil 387 } 388 389 // Prepare implements consensus.Engine, initializing the difficulty field of a 390 // header to conform to the cryptore protocol. The changes are done inline. 391 func (cryptore *Cryptore) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error { 392 parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1) 393 if parent == nil { 394 return consensus.ErrUnknownAncestor 395 } 396 header.Difficulty = cryptore.CalcDifficulty(chain, header.Time, parent) 397 return nil 398 } 399 400 // Finalize implements consensus.Engine, accumulating the block and uncle rewards, 401 // setting the final state on the header 402 func (cryptore *Cryptore) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) { 403 // Accumulate any block and uncle rewards and commit the final state root 404 accumulateRewards(state, header, uncles) 405 header.Root = state.IntermediateRoot(true) 406 } 407 408 // FinalizeAndAssemble implements consensus.Engine, accumulating the block and 409 // uncle rewards, setting the final state and assembling the block. 410 func (cryptore *Cryptore) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) { 411 // Accumulate any block and uncle rewards and commit the final state root 412 accumulateRewards(state, header, uncles) 413 header.Root = state.IntermediateRoot(true) 414 415 // Header seems complete, assemble into a block and return 416 return types.NewBlock(header, txs, uncles, receipts, new(trie.Trie)), nil 417 } 418 419 // SealHash returns the hash of a block prior to it being sealed. 420 func (cryptore *Cryptore) SealHash(header *types.Header) (hash common.Hash) { 421 hasher := sha3.New256() 422 423 rlp.Encode(hasher, []interface{}{ 424 header.ParentHash, 425 header.UncleHash, 426 header.Coinbase, 427 header.Root, 428 header.TxHash, 429 header.ReceiptHash, 430 header.Bloom, 431 header.Difficulty, 432 header.Number, 433 header.EnergyLimit, 434 header.EnergyUsed, 435 header.Time, 436 header.Extra, 437 }) 438 hasher.Sum(hash[:0]) 439 return hash 440 } 441 442 // Some weird constants to avoid constant memory allocs for them. 443 var ( 444 big8 = big.NewInt(8) 445 big32 = big.NewInt(32) 446 ) 447 448 // AccumulateRewards credits the coinbase of the given block with the mining 449 // reward. The total reward consists of the static block reward and rewards for 450 // included uncles. The coinbase of each uncle block is also rewarded. 451 func accumulateRewards(state *state.StateDB, header *types.Header, uncles []*types.Header) { 452 // Select the correct block reward based on chain progression 453 blockReward := BlockReward 454 // Accumulate the rewards for the miner and any included uncles 455 reward := new(big.Int).Set(blockReward) 456 r := new(big.Int) 457 for _, uncle := range uncles { 458 r.Add(uncle.Number, big8) 459 r.Sub(r, header.Number) 460 r.Mul(r, blockReward) 461 r.Div(r, big8) 462 state.AddBalance(uncle.Coinbase, r) 463 464 r.Div(blockReward, big32) 465 reward.Add(reward, r) 466 } 467 state.AddBalance(header.Coinbase, reward) 468 }