Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source
Source file baking.ml
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)openAlpha_contextopenMisctypeerror+=Invalid_fitness_gapofint64*int64(* `Permanent *)typeerror+=|Timestamp_too_earlyof{minimal_time:Timestamp.t;provided_time:Timestamp.t;priority:int;endorsing_power_opt:intoption;}(* `Permanent *)typeerror+=Unexpected_endorsement(* `Permanent *)typeerror+=Invalid_endorsement_slotofint(* `Permanent *)typeerror+=Unexpected_endorsement_slotofint(* `Permanent *)typeerror+=|Invalid_block_signatureofBlock_hash.t*Signature.Public_key_hash.t(* `Permanent *)typeerror+=Invalid_signature(* `Permanent *)typeerror+=Invalid_stamp(* `Permanent *)let()=register_error_kind`Permanent~id:"baking.timestamp_too_early"~title:"Block forged too early"~description:"The block timestamp is before the minimal valid one."~pp:(funppf(minimal_time,provided_time,priority,endorsing_power)->letmessage_regarding_endorsements=matchendorsing_powerwith|None->""|Somepower->Format.asprintf" and endorsing power %d"powerinFormat.fprintfppf"Block forged too early: %a is before the minimal time %a for priority \
%d%s)"Time.pp_humprovided_timeTime.pp_humminimal_timeprioritymessage_regarding_endorsements)Data_encoding.(obj4(req"minimal_time"Time.encoding)(req"provided_time"Time.encoding)(req"priority"int31)(opt"endorsing_power"int31))(function|Timestamp_too_early{minimal_time;provided_time;priority;endorsing_power_opt}->Some(minimal_time,provided_time,priority,endorsing_power_opt)|_->None)(fun(minimal_time,provided_time,priority,endorsing_power_opt)->Timestamp_too_early{minimal_time;provided_time;priority;endorsing_power_opt});register_error_kind`Permanent~id:"baking.invalid_fitness_gap"~title:"Invalid fitness gap"~description:"The gap of fitness is out of bounds"~pp:(funppf(m,g)->Format.fprintfppf"The gap of fitness %Ld is not between 0 and %Ld"gm)Data_encoding.(obj2(req"maximum"int64)(req"provided"int64))(functionInvalid_fitness_gap(m,g)->Some(m,g)|_->None)(fun(m,g)->Invalid_fitness_gap(m,g));register_error_kind`Permanent~id:"baking.invalid_block_signature"~title:"Invalid block signature"~description:"A block was not signed with the expected private key."~pp:(funppf(block,pkh)->Format.fprintfppf"Invalid signature for block %a. Expected: %a."Block_hash.pp_shortblockSignature.Public_key_hash.pp_shortpkh)Data_encoding.(obj2(req"block"Block_hash.encoding)(req"expected"Signature.Public_key_hash.encoding))(function|Invalid_block_signature(block,pkh)->Some(block,pkh)|_->None)(fun(block,pkh)->Invalid_block_signature(block,pkh));register_error_kind`Permanent~id:"baking.invalid_signature"~title:"Invalid block signature"~description:"The block's signature is invalid"~pp:(funppf()->Format.fprintfppf"Invalid block signature")Data_encoding.empty(functionInvalid_signature->Some()|_->None)(fun()->Invalid_signature);register_error_kind`Permanent~id:"baking.insufficient_proof_of_work"~title:"Insufficient block proof-of-work stamp"~description:"The block's proof-of-work stamp is insufficient"~pp:(funppf()->Format.fprintfppf"Insufficient proof-of-work stamp")Data_encoding.empty(functionInvalid_stamp->Some()|_->None)(fun()->Invalid_stamp);register_error_kind`Permanent~id:"baking.unexpected_endorsement"~title:"Endorsement from unexpected delegate"~description:"The operation is signed by a delegate without endorsement rights."~pp:(funppf()->Format.fprintfppf"The endorsement is signed by a delegate without endorsement rights.")Data_encoding.unit(functionUnexpected_endorsement->Some()|_->None)(fun()->Unexpected_endorsement);register_error_kind`Permanent~id:"baking.invalid_endorsement_slot"~title:"Endorsement slot out of range"~description:"The endorsement slot provided is negative or too high."~pp:(funppfv->Format.fprintfppf"Endorsement slot %d provided is negative or too high."v)Data_encoding.(obj1(req"slot"uint16))(functionInvalid_endorsement_slotv->Somev|_->None)(funv->Invalid_endorsement_slotv);register_error_kind`Permanent~id:"baking.unexpected_endorsement_slot"~title:"Endorsement slot not the smallest possible"~description:"The endorsement slot provided is not the smallest possible."~pp:(funppfv->Format.fprintfppf"Endorsement slot %d provided is not the smallest possible."v)Data_encoding.(obj1(req"slot"uint16))(functionUnexpected_endorsement_slotv->Somev|_->None)(funv->Unexpected_endorsement_slotv)(* The function implements the fast-path case in [minimal_time]. (See
[minimal_valid_time] for the definition of the fast-path.) *)letminimal_time_fastpath_caseminimal_block_delaypred_timestamp=Timestamp.(pred_timestamp+?minimal_block_delay)(* The function implements the slow-path case in [minimal_time]. (See
[minimal_valid_time] for the definition of the slow-path.) *)letminimal_time_slowpath_casetime_between_blocksprioritypred_timestamp=let[@coq_struct"durations"]reccumsum_time_between_blocksaccdurationsp=ifCompare.Int32.(<=)p0lthenokaccelsematchdurationswith|[]->cumsum_time_between_blocksacc[Period.one_minute]p|[last]->Period.multplast>>?funperiod->Timestamp.(acc+?period)|first::durations->Timestamp.(acc+?first)>>?funacc->letp=Int32.predpincumsum_time_between_blocksaccdurationspincumsum_time_between_blockspred_timestamptime_between_blocks(Int32.succpriority)letminimal_timeconstants~prioritypred_timestamp=letpriority=Int32.of_intpriorityinifCompare.Int32.(priority=0l)thenminimal_time_fastpath_caseconstants.Constants.minimal_block_delaypred_timestampelseminimal_time_slowpath_caseconstants.time_between_blocksprioritypred_timestampletearlier_predecessor_timestampctxtlevel=letcurrent=Level.currentctxtinletcurrent_timestamp=Timestamp.currentctxtinletgap=Level.difflevelcurrentinletstep=Constants.minimal_block_delayctxtinifCompare.Int32.(gap<1l)thenfailwith"Baking.earlier_block_timestamp: past block."elsePeriod.mult(Int32.predgap)step>>?fundelay->Timestamp.(current_timestamp+?delay)letcheck_timestampc~prioritypred_timestamp=minimal_time(Constants.parametricc)~prioritypred_timestamp>>?funminimal_time->lettimestamp=Timestamp.currentcinrecord_trace(Timestamp_too_early{minimal_time;provided_time=timestamp;priority;endorsing_power_opt=None;})Timestamp.(timestamp-?minimal_time)>>?fun_block_delay->ok()typeerror+=Incorrect_priority(* `Permanent *)typeerror+=Incorrect_number_of_endorsements(* `Permanent *)let()=register_error_kind`Permanent~id:"incorrect_priority"~title:"Incorrect priority"~description:"Block priority must be non-negative."~pp:(funppf()->Format.fprintfppf"The block priority must be non-negative.")Data_encoding.unit(functionIncorrect_priority->Some()|_->None)(fun()->Incorrect_priority)let()=letdescription="The number of endorsements must be non-negative and at most the \
endorsers_per_block constant."inregister_error_kind`Permanent~id:"incorrect_number_of_endorsements"~title:"Incorrect number of endorsements"~description~pp:(funppf()->Format.fprintfppf"%s"description)Data_encoding.unit(functionIncorrect_number_of_endorsements->Some()|_->None)(fun()->Incorrect_number_of_endorsements)letrecreward_for_priorityreward_per_prioprio=matchreward_per_priowith|[]->(* Empty reward list in parameters means no rewards *)Tez.zero|[last]->last|first::rest->ifCompare.Int.(prio<=0)thenfirstelsereward_for_priorityrest(predprio)letbaking_rewardctxt~block_priority~included_endorsements=error_unlessCompare.Int.(block_priority>=0)Incorrect_priority>>?fun()->error_unlessCompare.Int.(included_endorsements>=0&&included_endorsements<=Constants.endorsers_per_blockctxt)Incorrect_number_of_endorsements>>?fun()->letreward_per_endorsement=reward_for_priority(Constants.baking_reward_per_endorsementctxt)block_priorityinTez.(reward_per_endorsement*?Int64.of_intincluded_endorsements)letendorsing_rewardctxt~block_prioritynum_slots=error_unlessCompare.Int.(block_priority>=0)Incorrect_priority>>?fun()->letreward_per_endorsement=reward_for_priority(Constants.endorsement_rewardctxt)block_priorityinTez.(reward_per_endorsement*?Int64.of_intnum_slots)letbaking_prioritiesclevel=letrecfpriority=Roll.baking_rights_ownerclevel~priority>|=?fundelegate->LCons(delegate,fun()->f(succpriority))inf0letendorsement_rightsctxtlevel=List.fold_right_es(funslotacc->Roll.endorsement_rights_ownerctxtlevel~slot>|=?funpk->letpkh=Signature.Public_key.hashpkinletright=matchSignature.Public_key_hash.Map.findpkhaccwith|None->(pk,[slot],false)|Some(pk,slots,used)->(pk,slot::slots,used)inSignature.Public_key_hash.Map.addpkhrightacc)(0-->(Constants.endorsers_per_blockctxt-1))Signature.Public_key_hash.Map.emptylet[@coq_axiom_with_reason"gadt"]check_endorsement_rightctxtchain_id~slot(op:Kind.endorsementOperation.t)=ifCompare.Int.(slot<0(* should not happen because of binary format *))||Compare.Int.(slot>=Constants.endorsers_per_blockctxt)thenfail(Invalid_endorsement_slotslot)elselet(Single(Endorsement{level;_}))=op.protocol_data.contentsinRoll.endorsement_rights_ownerctxt(Level.from_rawctxtlevel)~slot>>=?funpk->letpkh=Signature.Public_key.hashpkinmatchOperation.check_signaturepkchain_idopwith|Error_->failUnexpected_endorsement|Ok()->returnpkhletcheck_endorsement_slots_at_current_levelctxt~slotpkh=letendorsements=Alpha_context.allowed_endorsementsctxtinmatchSignature.Public_key_hash.Map.findpkhendorsementswith|None->failUnexpected_endorsement(* unexpected *)|Some(_pk,(top_slot::_asslots),v)->error_unlessCompare.Int.(slot=top_slot)(Unexpected_endorsement_slotslot)>>?=fun()->return(slots,v)|Some(_pk,[],_)->fail(Unexpected_endorsement_slotslot)letselect_delegatedelegatedelegate_listmax_priority=letrecloopaccln=ifCompare.Int.(n>=max_priority)thenreturn(List.revacc)elselet(LCons(pk,t))=linletacc=ifSignature.Public_key_hash.equaldelegate(Signature.Public_key.hashpk)thenn::accelseaccint()>>=?funt->loopacct(succn)inloop[]delegate_list0letfirst_baking_prioritiesctxt?(max_priority=32)delegatelevel=baking_prioritiesctxtlevel>>=?fundelegate_list->select_delegatedelegatedelegate_listmax_priorityletcheck_hashhashstamp_threshold=letbytes=Block_hash.to_byteshashinletword=TzEndian.get_int64bytes0inCompare.Uint64.(word<=stamp_threshold)letcheck_header_proof_of_work_stampshellcontentsstamp_threshold=lethash=Block_header.hash{shell;protocol_data={contents;signature=Signature.zero}}incheck_hashhashstamp_thresholdletcheck_proof_of_work_stampctxtblock=letproof_of_work_threshold=Constants.proof_of_work_thresholdctxtinifcheck_header_proof_of_work_stampblock.Block_header.shellblock.protocol_data.contentsproof_of_work_thresholdthenok_unitelseerrorInvalid_stampletcheck_signatureblockchain_idkey=letcheck_signaturekey{Block_header.shell;protocol_data={contents;signature}}=letunsigned_header=Data_encoding.Binary.to_bytes_exnBlock_header.unsigned_encoding(shell,contents)inSignature.check~watermark:(Block_headerchain_id)keysignatureunsigned_headerinifcheck_signaturekeyblockthenreturn_unitelsefail(Invalid_block_signature(Block_header.hashblock,Signature.Public_key.hashkey))letmax_fitness_gap_ctxt=1Lletcheck_fitness_gapctxt(block:Block_header.t)=letcurrent_fitness=Fitness.currentctxtinFitness.to_int64block.shell.fitness>>?funannounced_fitness->letgap=Int64.subannounced_fitnesscurrent_fitnessinifCompare.Int64.(gap<=0L||max_fitness_gapctxt<gap)thenerror(Invalid_fitness_gap(max_fitness_gapctxt,gap))elseok_unit(* The minimal threshold on the endorsing power for the fast-path case
is 60% of the maximal endorsing power. *)letfastpath_endorsing_power_thresholdmaximal_endorsing_power=3*maximal_endorsing_power/5(* This function computes the minimal time at which a block is
valid. It distinguishes between the "fast-path" case, when the
priority is 0 and the endorsing power is at least 60% of the
maximal endorsing power, and the "slow-path" case, when this
condition is not satisfied. *)letminimal_valid_timeconstants~priority~endorsing_power~predecessor_timestamp=ifCompare.Int.(priority=0)&&Compare.Int.(endorsing_power>=fastpath_endorsing_power_thresholdconstants.Constants.endorsers_per_block)thenminimal_time_fastpath_caseconstants.minimal_block_delaypredecessor_timestampelseminimal_time_slowpath_caseconstants.time_between_blocks(Int32.of_intpriority)predecessor_timestamp>>?funminimal_time->letdelay_per_missing_endorsement=constants.Constants.delay_per_missing_endorsementinletmissing_endorsements=letminimal_required_endorsements=constants.Constants.initial_endorsersinCompare.Int.max0(minimal_required_endorsements-endorsing_power)inPeriod.mult(Int32.of_intmissing_endorsements)delay_per_missing_endorsement>|?fundelay->Time.addminimal_time(Period.to_secondsdelay)