123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)(* Copyright (c) 2021-2022 Trili Tech, <contact@trili.tech> *)(* *)(* 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. *)(* *)(*****************************************************************************)moduleInt_set=Set.Make(Compare.Int)(*
Gas levels maintenance
=======================
The context maintains two levels of gas, one corresponds to the gas
available for the current operation while the other is the gas
available for the current block. Both levels are maintained
independently: [consume_gas] only decreases the operation level,
and block level should be updated with [consume_gas_limit_in_block].
A layered context
=================
Updating the context [remaining_operation_gas] is a critical routine
called very frequently by the operations performed by the protocol.
On the contrary, other fields are less frequently updated.
In a previous version of the context datatype definition, all
the fields were represented at the toplevel. To update the remaining
gas, we had to copy ~25 fields (that is 200 bytes).
With the following layered representation, we only have to
copy 2 fields (16 bytes) during [remaining_operation_gas] update.
This has a significant impact on the Michelson runtime efficiency.
Here are the fields on the [back] of the context:
*)typeconsensus_pk={delegate:Signature.Public_key_hash.t;consensus_pk:Signature.Public_key.t;consensus_pkh:Signature.Public_key_hash.t;}letconsensus_pk_encoding=letopenData_encodinginconv(fun{delegate;consensus_pk;consensus_pkh}->ifSignature.Public_key_hash.equalconsensus_pkhdelegatethen(consensus_pk,None)else(consensus_pk,Somedelegate))(fun(consensus_pk,delegate)->letconsensus_pkh=Signature.Public_key.hashconsensus_pkinletdelegate=matchdelegatewithNone->consensus_pkh|Somedel->delin{delegate;consensus_pk;consensus_pkh})(obj2(req"consensus_pk"Signature.Public_key.encoding)(opt"delegate"Signature.Public_key_hash.encoding))moduleRaw_consensus=struct(** Consensus operations are indexed by their [initial slots]. Given
a delegate, the [initial slot] is the lowest slot assigned to
this delegate. *)typet={current_attestation_power:int;(** Number of attestation slots recorded for the current block. *)allowed_attestations:(consensus_pk*int)Slot_repr.Map.toption;(** Attestations rights for the current block. Only an attestation
for the lowest slot in the block can be recorded. The map
associates to each initial slot the [pkh] associated to this
slot with its power. This is [None] only in mempool mode. *)allowed_preattestations:(consensus_pk*int)Slot_repr.Map.toption;(** Preattestations rights for the current block. Only a preattestation
for the lowest slot in the block can be recorded. The map
associates to each initial slot the [pkh] associated to this
slot with its power. This is [None] only in mempool mode, or in
application mode when there is no locked round (so the block
cannot contain any preattestations). *)forbidden_delegates:Signature.Public_key_hash.Set.t;(** Delegates that are not allowed to bake or attest blocks; i.e.,
delegates which have zero frozen deposit due to a previous
slashing. *)attestations_seen:Slot_repr.Set.t;(** Record the attestations already seen. Only initial slots are indexed. *)preattestations_seen:Slot_repr.Set.t;(** Record the preattestations already seen. Only initial slots
are indexed. *)locked_round_evidence:(Round_repr.t*int)option;(** Record the preattestation power for a locked round. *)preattestations_quorum_round:Round_repr.toption;(** in block construction mode, record the round of preattestations
included in a block. *)attestation_branch:(Block_hash.t*Block_payload_hash.t)option;}(** Invariant:
- [slot \in attestations_seen => Int_map.mem slot allowed_attestations]
- [slot \in preattestations_seen => Int_map.mem slot allowed_preattestations]
- [ |attestations_seen| > 0 => |included attestations| > 0]
*)letempty:t={current_attestation_power=0;allowed_attestations=SomeSlot_repr.Map.empty;allowed_preattestations=SomeSlot_repr.Map.empty;forbidden_delegates=Signature.Public_key_hash.Set.empty;attestations_seen=Slot_repr.Set.empty;preattestations_seen=Slot_repr.Set.empty;locked_round_evidence=None;preattestations_quorum_round=None;attestation_branch=None;}typeerror+=Double_inclusion_of_consensus_operationlet()=register_error_kind`Branch~id:"operation.double_inclusion_of_consensus_operation"~title:"Double inclusion of consensus operation"~description:"double inclusion of consensus operation"~pp:(funppf()->Format.fprintfppf"Double inclusion of consensus operation")Data_encoding.empty(function|Double_inclusion_of_consensus_operation->Some()|_->None)(fun()->Double_inclusion_of_consensus_operation)letrecord_attestationt~initial_slot~power=letopenResult_syntaxinlet+()=error_when(Slot_repr.Set.meminitial_slott.attestations_seen)Double_inclusion_of_consensus_operationin{twithcurrent_attestation_power=t.current_attestation_power+power;attestations_seen=Slot_repr.Set.addinitial_slott.attestations_seen;}letrecord_preattestation~initial_slot~powerroundt=letopenResult_syntaxinlet+()=error_when(Slot_repr.Set.meminitial_slott.preattestations_seen)Double_inclusion_of_consensus_operationinletlocked_round_evidence=matcht.locked_round_evidencewith|None->Some(round,power)|Some(_stored_round,evidences)->(* In mempool mode, round and stored_round can be different.
It doesn't matter in that case since quorum certificates
are not used in mempool.
For other cases [Apply.check_round] verifies it. *)Some(round,evidences+power)in{twithlocked_round_evidence;preattestations_seen=Slot_repr.Set.addinitial_slott.preattestations_seen;}letset_forbidden_delegatesdelegatest={twithforbidden_delegates=delegates}letforbid_delegatedelegatet={twithforbidden_delegates=Signature.Public_key_hash.Set.adddelegatet.forbidden_delegates;}letset_preattestations_quorum_roundroundt=matcht.preattestations_quorum_roundwith|Someround'->(* If the rounds are different, an error should have already
been raised. *)assert(Round_repr.equalroundround');t|None->{twithpreattestations_quorum_round=Someround}letinitialize_with_attestations_and_preattestations~allowed_attestations~allowed_preattestationst={twithallowed_attestations;allowed_preattestations}letlocked_round_evidencet=t.locked_round_evidenceletattestation_brancht=t.attestation_branchletset_attestation_branchtattestation_branch={twithattestation_branch=Someattestation_branch}endtypedal_committee={pkh_to_shards:(Dal_attestation_repr.shard_index*int)Signature.Public_key_hash.Map.t;shard_to_pkh:Signature.Public_key_hash.tDal_attestation_repr.Shard_map.t;}letempty_dal_committee={pkh_to_shards=Signature.Public_key_hash.Map.empty;shard_to_pkh=Dal_attestation_repr.Shard_map.empty;}typeback={context:Context.t;constants:Constants_parametric_repr.t;round_durations:Round_repr.Durations.t;cycle_eras:Level_repr.cycle_eras;level:Level_repr.t;predecessor_timestamp:Time.t;timestamp:Time.t;fees:Tez_repr.t;origination_nonce:Origination_nonce.toption;temporary_lazy_storage_ids:Lazy_storage_kind.Temp_ids.t;internal_nonce:int;internal_nonces_used:Int_set.t;remaining_block_gas:Gas_limit_repr.Arith.fp;unlimited_operation_gas:bool;consensus:Raw_consensus.t;non_consensus_operations_rev:Operation_hash.tlist;dictator_proposal_seen:bool;sampler_state:(Seed_repr.seed*consensus_pkSampler.t)Cycle_repr.Map.t;stake_distribution_for_current_cycle:Stake_repr.tSignature.Public_key_hash.Map.toption;reward_coeff_for_current_cycle:Q.t;sc_rollup_current_messages:Sc_rollup_inbox_merkelized_payload_hashes_repr.t;dal_slot_fee_market:Dal_slot_repr.Slot_market.t;(* DAL/FIXME https://gitlab.com/tezos/tezos/-/issues/3105
We associate to a slot header some fees. This enable the use
of a fee market for slot publication. However, this is not
resilient from the game theory point of view. Probably we can find
better incentives here. In any case, because we want the following
invariant:
- For each level and for each slot there is at most one slot
header.
- We need to provide an incentive to avoid byzantines to post
dummy slot headers. *)dal_attestation_slot_accountability:Dal_attestation_repr.Accountability.t;dal_committee:dal_committee;adaptive_issuance_enable:bool;}(*
The context is simply a record with two fields which
limits the cost of updating the [remaining_operation_gas].
*)typet={remaining_operation_gas:Gas_limit_repr.Arith.fp;back:back}typeroot=t(*
Context fields accessors
========================
To have the context related code more robust to evolutions,
we introduce accessors to get and to update the context
components.
*)let[@inline]contextctxt=ctxt.back.contextlet[@inline]current_levelctxt=ctxt.back.levellet[@inline]predecessor_timestampctxt=ctxt.back.predecessor_timestamplet[@inline]current_timestampctxt=ctxt.back.timestamplet[@inline]round_durationsctxt=ctxt.back.round_durationslet[@inline]cycle_erasctxt=ctxt.back.cycle_eraslet[@inline]constantsctxt=ctxt.back.constantslet[@inline]sc_rollupctxt=ctxt.back.constants.sc_rolluplet[@inline]zk_rollupctxt=ctxt.back.constants.zk_rolluplet[@inline]recoverctxt=ctxt.back.contextlet[@inline]feesctxt=ctxt.back.feeslet[@inline]origination_noncectxt=ctxt.back.origination_noncelet[@inline]internal_noncectxt=ctxt.back.internal_noncelet[@inline]internal_nonces_usedctxt=ctxt.back.internal_nonces_usedlet[@inline]remaining_block_gasctxt=ctxt.back.remaining_block_gaslet[@inline]unlimited_operation_gasctxt=ctxt.back.unlimited_operation_gaslet[@inline]temporary_lazy_storage_idsctxt=ctxt.back.temporary_lazy_storage_idslet[@inline]remaining_operation_gasctxt=ctxt.remaining_operation_gaslet[@inline]non_consensus_operations_revctxt=ctxt.back.non_consensus_operations_revlet[@inline]dictator_proposal_seenctxt=ctxt.back.dictator_proposal_seenlet[@inline]sampler_statectxt=ctxt.back.sampler_statelet[@inline]reward_coeff_for_current_cyclectxt=ctxt.back.reward_coeff_for_current_cyclelet[@inline]adaptive_issuance_enablectxt=ctxt.back.adaptive_issuance_enablelet[@inline]update_backctxtback={ctxtwithback}let[@inline]update_remaining_block_gasctxtremaining_block_gas=update_backctxt{ctxt.backwithremaining_block_gas}let[@inline]update_remaining_operation_gasctxtremaining_operation_gas={ctxtwithremaining_operation_gas}let[@inline]update_unlimited_operation_gasctxtunlimited_operation_gas=update_backctxt{ctxt.backwithunlimited_operation_gas}let[@inline]update_contextctxtcontext=update_backctxt{ctxt.backwithcontext}let[@inline]update_constantsctxtconstants=update_backctxt{ctxt.backwithconstants}let[@inline]update_origination_noncectxtorigination_nonce=update_backctxt{ctxt.backwithorigination_nonce}let[@inline]update_internal_noncectxtinternal_nonce=update_backctxt{ctxt.backwithinternal_nonce}let[@inline]update_internal_nonces_usedctxtinternal_nonces_used=update_backctxt{ctxt.backwithinternal_nonces_used}let[@inline]update_feesctxtfees=update_backctxt{ctxt.backwithfees}let[@inline]update_temporary_lazy_storage_idsctxttemporary_lazy_storage_ids=update_backctxt{ctxt.backwithtemporary_lazy_storage_ids}let[@inline]update_non_consensus_operations_revctxtnon_consensus_operations_rev=update_backctxt{ctxt.backwithnon_consensus_operations_rev}let[@inline]update_dictator_proposal_seenctxtdictator_proposal_seen=update_backctxt{ctxt.backwithdictator_proposal_seen}let[@inline]update_sampler_statectxtsampler_state=update_backctxt{ctxt.backwithsampler_state}let[@inline]update_reward_coeff_for_current_cyclectxtreward_coeff_for_current_cycle=update_backctxt{ctxt.backwithreward_coeff_for_current_cycle}let[@inline]set_adaptive_issuance_enablectxt=update_backctxt{ctxt.backwithadaptive_issuance_enable=true}typeerror+=Too_many_internal_operations(* `Permanent *)typeerror+=Block_quota_exceeded(* `Temporary *)typeerror+=Operation_quota_exceeded(* `Temporary *)typeerror+=Stake_distribution_not_set(* `Branch *)typeerror+=Sampler_already_setofCycle_repr.t(* `Permanent *)let()=letopenData_encodinginregister_error_kind`Permanent~id:"too_many_internal_operations"~title:"Too many internal operations"~description:"A transaction exceeded the hard limit of internal operations it can emit"empty(functionToo_many_internal_operations->Some()|_->None)(fun()->Too_many_internal_operations);register_error_kind`Temporary~id:"gas_exhausted.operation"~title:"Gas quota exceeded for the operation"~description:"A script or one of its callee took more time than the operation said it \
would"empty(functionOperation_quota_exceeded->Some()|_->None)(fun()->Operation_quota_exceeded);register_error_kind`Temporary~id:"gas_exhausted.block"~title:"Gas quota exceeded for the block"~description:"The sum of gas consumed by all the operations in the block exceeds the \
hard gas limit per block"empty(functionBlock_quota_exceeded->Some()|_->None)(fun()->Block_quota_exceeded);register_error_kind`Permanent~id:"delegate.stake_distribution_not_set"~title:"Stake distribution not set"~description:"The stake distribution for the current cycle is not set."~pp:(funppf()->Format.fprintfppf"The stake distribution for the current cycle is not set.")empty(functionStake_distribution_not_set->Some()|_->None)(fun()->Stake_distribution_not_set);register_error_kind`Permanent~id:"sampler_already_set"~title:"Sampler already set"~description:"Internal error: Raw_context.set_sampler_for_cycle was called twice for \
a given cycle"~pp:(funppfc->Format.fprintfppf"Internal error: sampler already set for cycle %a."Cycle_repr.ppc)(obj1(req"cycle"Cycle_repr.encoding))(functionSampler_already_setc->Somec|_->None)(func->Sampler_already_setc)letfresh_internal_noncectxt=letopenResult_syntaxinifCompare.Int.(internal_noncectxt>=65_535)thentzfailToo_many_internal_operationselsereturn(update_internal_noncectxt(internal_noncectxt+1),internal_noncectxt)letreset_internal_noncectxt=letctxt=update_internal_noncectxt0inupdate_internal_nonces_usedctxtInt_set.emptyletrecord_internal_noncectxtk=update_internal_nonces_usedctxt(Int_set.addk(internal_nonces_usedctxt))letinternal_nonce_already_recordedctxtk=Int_set.memk(internal_nonces_usedctxt)letget_collected_feesctxt=feesctxtletcredit_collected_fees_only_call_from_tokenctxtfees'=letopenResult_syntaxinletprevious=get_collected_feesctxtinlet+fees=Tez_repr.(previous+?fees')inupdate_feesctxtfeesletspend_collected_fees_only_call_from_tokenctxtfees'=letopenResult_syntaxinletprevious=get_collected_feesctxtinlet+fees=Tez_repr.(previous-?fees')inupdate_feesctxtfeestypeerror+=Undefined_operation_nonce(* `Permanent *)let()=letopenData_encodinginregister_error_kind`Permanent~id:"undefined_operation_nonce"~title:"Ill timed access to the origination nonce"~description:"An origination was attempted out of the scope of a manager operation"empty(functionUndefined_operation_nonce->Some()|_->None)(fun()->Undefined_operation_nonce)letinit_origination_noncectxtoperation_hash=letorigination_nonce=Some(Origination_nonce.initialoperation_hash)inupdate_origination_noncectxtorigination_nonceletincrement_origination_noncectxt=letopenResult_syntaxinmatchorigination_noncectxtwith|None->tzfailUndefined_operation_nonce|Somecur_origination_nonce->letorigination_nonce=Some(Origination_nonce.incrcur_origination_nonce)inletctxt=update_origination_noncectxtorigination_nonceinreturn(ctxt,cur_origination_nonce)letget_origination_noncectxt=letopenResult_syntaxinmatchorigination_noncectxtwith|None->tzfailUndefined_operation_nonce|Someorigination_nonce->returnorigination_nonceletunset_origination_noncectxt=update_origination_noncectxtNoneletgas_levelctxt=letopenGas_limit_reprinifunlimited_operation_gasctxtthenUnaccountedelseLimited{remaining=remaining_operation_gasctxt}letblock_gas_level=remaining_block_gasletconsume_gas_limit_in_blockctxtgas_limit=letopenGas_limit_reprinletopenResult_syntaxinlet*()=check_gas_limit~hard_gas_limit_per_operation:(constantsctxt).hard_gas_limit_per_operation~gas_limitinletblock_gas=block_gas_levelctxtinletlimit=Arith.fpgas_limitinifArith.(limit>block_gas)thentzfailBlock_quota_exceededelseletlevel=Arith.sub(block_gas_levelctxt)limitinletctxt=update_remaining_block_gasctxtlevelinOkctxtletset_gas_limitctxt(remaining:'aGas_limit_repr.Arith.t)=letopenGas_limit_reprinletremaining_operation_gas=Arith.fpremaininginletctxt=update_unlimited_operation_gasctxtfalsein{ctxtwithremaining_operation_gas}letset_gas_unlimitedctxt=update_unlimited_operation_gasctxttrueletconsume_gasctxtcost=letopenResult_syntaxinmatchGas_limit_repr.raw_consume(remaining_operation_gasctxt)costwith|Somegas_counter->Ok(update_remaining_operation_gasctxtgas_counter)|None->ifunlimited_operation_gasctxtthenreturnctxtelsetzfailOperation_quota_exceededletcheck_enough_gasctxtcost=letopenResult_syntaxinlet*(_:t)=consume_gasctxtcostinreturn_unitletgas_consumed~since~until=match(gas_levelsince,gas_leveluntil)with|Limited{remaining=before},Limited{remaining=after}->Gas_limit_repr.Arith.subbeforeafter|_,_->Gas_limit_repr.Arith.zerotypemissing_key_kind=Get|Set|Del|Copytypestorage_error=|Incompatible_protocol_versionofstring|Missing_keyofstringlist*missing_key_kind|Existing_keyofstringlist|Corrupted_dataofstringlistletstorage_error_encoding=letopenData_encodinginunion[case(Tag0)~title:"Incompatible_protocol_version"(obj1(req"incompatible_protocol_version"@@stringPlain))(functionIncompatible_protocol_versionarg->Somearg|_->None)(funarg->Incompatible_protocol_versionarg);case(Tag1)~title:"Missing_key"(obj2(req"missing_key"(list@@stringPlain))(req"function"(string_enum[("get",Get);("set",Set);("del",Del);("copy",Copy)])))(functionMissing_key(key,f)->Some(key,f)|_->None)(fun(key,f)->Missing_key(key,f));case(Tag2)~title:"Existing_key"(obj1(req"existing_key"(list@@stringPlain)))(functionExisting_keykey->Somekey|_->None)(funkey->Existing_keykey);case(Tag3)~title:"Corrupted_data"(obj1(req"corrupted_data"(list@@stringPlain)))(functionCorrupted_datakey->Somekey|_->None)(funkey->Corrupted_datakey);]letpp_storage_errorppf=function|Incompatible_protocol_versionversion->Format.fprintfppf"Found a context with an unexpected version '%s'."version|Missing_key(key,Get)->Format.fprintfppf"Missing key '%s'."(String.concat"/"key)|Missing_key(key,Set)->Format.fprintfppf"Cannot set undefined key '%s'."(String.concat"/"key)|Missing_key(key,Del)->Format.fprintfppf"Cannot delete undefined key '%s'."(String.concat"/"key)|Missing_key(key,Copy)->Format.fprintfppf"Cannot copy undefined key '%s'."(String.concat"/"key)|Existing_keykey->Format.fprintfppf"Cannot initialize defined key '%s'."(String.concat"/"key)|Corrupted_datakey->Format.fprintfppf"Failed to parse the data at '%s'."(String.concat"/"key)typeerror+=Storage_errorofstorage_errorlet()=register_error_kind`Permanent~id:"context.storage_error"~title:"Storage error (fatal internal error)"~description:"An error that should never happen unless something has been deleted or \
corrupted in the database."~pp:(funppferr->Format.fprintfppf"@[<v 2>Storage error:@ %a@]"pp_storage_errorerr)storage_error_encoding(functionStorage_errorerr->Someerr|_->None)(funerr->Storage_errorerr)letstorage_errorerr=Result_syntax.tzfail(Storage_errorerr)(* Initialization *********************************************************)(* This key should always be populated for every version of the
protocol. It's absence meaning that the context is empty. *)letversion_key=["version"](* This value is set by the snapshot_alpha.sh script, don't change it. *)letprotocol_migration_internal_message=Sc_rollup_inbox_message_repr.Protocol_migrationConstants_repr.version_valueletprotocol_migration_serialized_message=matchSc_rollup_inbox_message_repr.serialize(Internalprotocol_migration_internal_message)with|Okmsg->msg|Errortrace->Format.kasprintffailwith"%s: Could not serialize protocol message : %a"__LOC__pp_tracetraceletcycle_eras_key=[Constants_repr.version;"cycle_eras"]letconstants_key=[Constants_repr.version;"constants"]letprotocol_param_key=["protocol_parameters"]letget_cycle_erasctxt=letopenLwt_syntaxinlet+bytes_opt=Context.findctxtcycle_eras_keyinmatchbytes_optwith|None->storage_error(Missing_key(cycle_eras_key,Get))|Somebytes->(matchData_encoding.Binary.of_bytes_optLevel_repr.cycle_eras_encodingbyteswith|None->storage_error(Corrupted_datacycle_eras_key)|Somecycle_eras->Okcycle_eras)letset_cycle_erasctxtcycle_eras=letopenLwt_result_syntaxinletbytes=Data_encoding.Binary.to_bytes_exnLevel_repr.cycle_eras_encodingcycle_erasinlet*!ctxt=Context.addctxtcycle_eras_keybytesinreturnctxttypeerror+=Failed_to_parse_parameterofbytestypeerror+=Failed_to_decode_parameterofData_encoding.json*stringlet()=register_error_kind`Temporary~id:"context.failed_to_parse_parameter"~title:"Failed to parse parameter"~description:"The protocol parameters are not valid JSON."~pp:(funppfbytes->Format.fprintfppf"@[<v 2>Cannot parse the protocol parameter:@ %s@]"(Bytes.to_stringbytes))Data_encoding.(obj1(req"contents"@@bytesHex))(functionFailed_to_parse_parameterdata->Somedata|_->None)(fundata->Failed_to_parse_parameterdata);register_error_kind`Temporary~id:"context.failed_to_decode_parameter"~title:"Failed to decode parameter"~description:"Unexpected JSON object."~pp:(funppf(json,msg)->Format.fprintfppf"@[<v 2>Cannot decode the protocol parameter:@ %s@ %a@]"msgData_encoding.Json.ppjson)Data_encoding.(obj2(req"contents"json)(req"error"@@stringPlain))(function|Failed_to_decode_parameter(json,msg)->Some(json,msg)|_->None)(fun(json,msg)->Failed_to_decode_parameter(json,msg))letget_proto_paramctxt=letopenLwt_result_syntaxinlet*!bytes_opt=Context.findctxtprotocol_param_keyinmatchbytes_optwith|None->failwith"Missing protocol parameters."|Somebytes->(matchData_encoding.Binary.of_bytes_optData_encoding.jsonbyteswith|None->tzfail(Failed_to_parse_parameterbytes)|Somejson->(let*!ctxt=Context.removectxtprotocol_param_keyinmatchData_encoding.Json.destructParameters_repr.encodingjsonwith|exception(Data_encoding.Json.Cannot_destruct_asexn)->Format.kasprintffailwith"Invalid protocol_parameters: %a %a"(funppf->Data_encoding.Json.print_errorppf)exnData_encoding.Json.ppjson|param->let*?()=Parameters_repr.check_paramsparaminreturn(param,ctxt)))letadd_constantsctxtconstants=letbytes=Data_encoding.Binary.to_bytes_exnConstants_parametric_repr.encodingconstantsinContext.addctxtconstants_keybytesletget_constantsctxt=letopenLwt_result_syntaxinlet*!bytes_opt=Context.findctxtconstants_keyinmatchbytes_optwith|None->failwith"Internal error: cannot read constants in context."|Somebytes->(matchData_encoding.Binary.of_bytes_optConstants_parametric_repr.encodingbyteswith|None->failwith"Internal error: cannot parse constants in context."|Someconstants->returnconstants)letpatch_constantsctxtf=letopenLwt_syntaxinletconstants=f(constantsctxt)inlet+context=add_constants(contextctxt)constantsinletctxt=update_contextctxtcontextinupdate_constantsctxtconstantsletcheck_initedctxt=letopenLwt_syntaxinlet+bytes_opt=Context.findctxtversion_keyinmatchbytes_optwith|None->failwith"Internal error: un-initialized context."|Somebytes->lets=Bytes.to_stringbytesinifCompare.String.(s=Constants_repr.version_value)thenResult.return_unitelsestorage_error(Incompatible_protocol_versions)letcheck_cycle_eras(cycle_eras:Level_repr.cycle_eras)(constants:Constants_parametric_repr.t)=letcurrent_era=Level_repr.current_eracycle_erasinassert(Compare.Int32.(current_era.blocks_per_cycle=constants.blocks_per_cycle));assert(Compare.Int32.(current_era.blocks_per_commitment=constants.blocks_per_commitment))letprepare~level~predecessor_timestamp~timestamp~adaptive_issuance_enablectxt=letopenLwt_result_syntaxinlet*?level=Raw_level_repr.of_int32levelinlet*()=check_initedctxtinlet*constants=get_constantsctxtinlet*?round_durations=Round_repr.Durations.create~first_round_duration:constants.minimal_block_delay~delay_increment_per_round:constants.delay_increment_per_roundinlet+cycle_eras=get_cycle_erasctxtincheck_cycle_erascycle_erasconstants;letlevel=Level_repr.level_from_raw~cycle_eraslevelinletsc_rollup_current_messages=Sc_rollup_inbox_repr.init_witness_no_historyin{remaining_operation_gas=Gas_limit_repr.Arith.zero;back={context=ctxt;constants;level;predecessor_timestamp;timestamp;round_durations;cycle_eras;fees=Tez_repr.zero;origination_nonce=None;temporary_lazy_storage_ids=Lazy_storage_kind.Temp_ids.init;internal_nonce=0;internal_nonces_used=Int_set.empty;remaining_block_gas=Gas_limit_repr.Arith.fpconstants.Constants_parametric_repr.hard_gas_limit_per_block;unlimited_operation_gas=true;consensus=Raw_consensus.empty;non_consensus_operations_rev=[];dictator_proposal_seen=false;sampler_state=Cycle_repr.Map.empty;stake_distribution_for_current_cycle=None;reward_coeff_for_current_cycle=Q.one;sc_rollup_current_messages;dal_slot_fee_market=Dal_slot_repr.Slot_market.init~length:constants.Constants_parametric_repr.dal.number_of_slots;dal_attestation_slot_accountability=Dal_attestation_repr.Accountability.init~length:constants.Constants_parametric_repr.dal.number_of_slots;dal_committee=empty_dal_committee;adaptive_issuance_enable;};}typeprevious_protocol=GenesisofParameters_repr.t|Nairobi_017letcheck_and_update_protocol_versionctxt=letopenLwt_result_syntaxinlet*previous_proto,ctxt=let*!bytes_opt=Context.findctxtversion_keyinmatchbytes_optwith|None->failwith"Internal error: un-initialized context in check_first_block."|Somebytes->lets=Bytes.to_stringbytesinifCompare.String.(s=Constants_repr.version_value)thenfailwith"Internal error: previously initialized context."elseifCompare.String.(s="genesis")thenlet+param,ctxt=get_proto_paramctxtin(Genesisparam,ctxt)elseifCompare.String.(s="nairobi_017")thenreturn(Nairobi_017,ctxt)elseLwt.return@@storage_error(Incompatible_protocol_versions)inlet*!ctxt=Context.addctxtversion_key(Bytes.of_stringConstants_repr.version_value)inreturn(previous_proto,ctxt)(* only for the migration *)let[@warning"-32"]get_previous_protocol_constantsctxt=letopenLwt_syntaxinlet*bytes_opt=Context.findctxtconstants_keyinmatchbytes_optwith|None->failwith"Internal error: cannot read previous protocol constants in context."|Somebytes->(matchData_encoding.Binary.of_bytes_optConstants_parametric_previous_repr.encodingbyteswith|None->failwith"Internal error: cannot parse previous protocol constants in \
context."|Someconstants->returnconstants)(* You should ensure that if the type `Constants_parametric_repr.t` is
different from `Constants_parametric_previous_repr.t` or the value of these
constants is modified, is changed from the previous protocol, then
you `propagate` these constants to the new protocol by writing them
onto the context via the function `add_constants` or
`patch_constants`.
This migration can be achieved also implicitly by modifying the
encoding directly in a way which is compatible with the previous
protocol. However, by doing so, you do not change the value of
these constants inside the context. *)letprepare_first_block~level~timestampchain_idctxt=letopenLwt_result_syntaxinlet*previous_proto,ctxt=check_and_update_protocol_versionctxtinlet*ctxt=matchprevious_protowith|Genesisparam->let*?first_level=Raw_level_repr.of_int32levelinletcycle_era={Level_repr.first_level;first_cycle=Cycle_repr.root;blocks_per_cycle=param.constants.blocks_per_cycle;blocks_per_commitment=param.constants.blocks_per_commitment;}inlet*?cycle_eras=Level_repr.create_cycle_eras[cycle_era]inlet*ctxt=set_cycle_erasctxtcycle_erasinlet*!result=add_constantsctxtparam.constantsinreturnresult|Nairobi_017->let*!c=get_previous_protocol_constantsctxtinletcryptobox_parameters={Dal.page_size=c.dal.cryptobox_parameters.page_size;number_of_shards=c.dal.cryptobox_parameters.number_of_shards;slot_size=c.dal.cryptobox_parameters.slot_size;redundancy_factor=c.dal.cryptobox_parameters.redundancy_factor;}inletdal=Constants_parametric_repr.{feature_enable=c.dal.feature_enable;number_of_slots=c.dal.number_of_slots;attestation_lag=4;attestation_threshold=c.dal.attestation_threshold;blocks_per_epoch=1l;cryptobox_parameters;}in(* This test prevents the activation of the protocol if the
set of parameters given for the DAL is invalid. *)let*?()=ifdal.feature_enablethenmatchDal.makecryptobox_parameterswith|Ok_cryptobox->ok()|Error(`Failexplanation)->error(Dal_errors_repr.Dal_cryptobox_error{explanation})elseok()inletdal_activation_level=ifc.dal.feature_enablethenRaw_level_repr.rootelseifdal.feature_enablethen(* First level of the protocol with dal activated. *)Raw_level_repr.of_int32_exn(Int32.succlevel)else(* Deactivate the reveal if the dal is not enabled.
assert (not (c.dal.feature_enable || dal.feature_enable))
We set the activation level to [pred max_int] to deactivate
the feature. The [pred] is needed to not trigger an encoding
exception with the value [Int32.int_min] (see
tezt/tests/mockup.ml). *)Raw_level_repr.of_int32_exnInt32.(predmax_int)in(* When stitching from Oxford and after, [Raw_level_repr.root]
should be replaced by the previous value, that is
[c.reveal_activation_level.*]. *)letreveal_activation_level:Constants_parametric_repr.sc_rollup_reveal_activation_level={raw_data={blake2B=Raw_level_repr.root};metadata=Raw_level_repr.root;dal_page=dal_activation_level;dal_parameters=dal_activation_level;}inletsc_rollup=Constants_parametric_repr.{arith_pvm_enable=c.sc_rollup.arith_pvm_enable;origination_size=c.sc_rollup.origination_size;challenge_window_in_blocks=c.sc_rollup.challenge_window_in_blocks;stake_amount=c.sc_rollup.stake_amount;commitment_period_in_blocks=c.sc_rollup.commitment_period_in_blocks;max_lookahead_in_blocks=c.sc_rollup.max_lookahead_in_blocks;max_active_outbox_levels=c.sc_rollup.max_active_outbox_levels;max_outbox_messages_per_level=c.sc_rollup.max_outbox_messages_per_level;number_of_sections_in_dissection=c.sc_rollup.number_of_sections_in_dissection;timeout_period_in_blocks=c.sc_rollup.timeout_period_in_blocks;max_number_of_stored_cemented_commitments=c.sc_rollup.max_number_of_stored_cemented_commitments;max_number_of_parallel_games=c.sc_rollup.max_number_of_parallel_games;reveal_activation_level;private_enable=true;riscv_pvm_enable=false;}inletzk_rollup=Constants_parametric_repr.{enable=c.zk_rollup.enable;origination_size=c.zk_rollup.origination_size;min_pending_to_process=c.zk_rollup.min_pending_to_process;max_ticket_payload_size=c.tx_rollup.max_ticket_payload_size;}inletadaptive_rewards_params=Constants_parametric_repr.{issuance_ratio_min=Q.(5//10_000)(* 0.05% *);issuance_ratio_max=Q.(5//100);max_bonus=Issuance_bonus_repr.max_bonus_parameter_of_Q_exnQ.(5//100);growth_rate=Q.(1//100);center_dz=Q.(50//100);radius_dz=Q.(2//100);}inletadaptive_issuance=Constants_parametric_repr.{global_limit_of_staking_over_baking=5;edge_of_staking_over_delegation=2;launch_ema_threshold=(ifChain_id.equalConstants_repr.mainnet_idchain_idthen(* 80% of the max ema (which is 2 billion) *)1_600_000_000lelse(* 5% for testnets *)100_000_000l);adaptive_rewards_params;activation_vote_enable=false;autostaking_enable=true;}inletissuance_weights=letc_gen=Constants_repr.Generated.generate~consensus_committee_size:c.consensus_committee_sizeinc_gen.issuance_weightsinletpercentage_of_frozen_deposits_slashed_per_double_baking=Int_percentage.p5inletpercentage_of_frozen_deposits_slashed_per_double_attestation=Int_percentage.of_ratio_boundedc.ratio_of_frozen_deposits_slashed_per_double_attestationinletlimit_of_delegation_over_baking=(100/c.frozen_deposits_percentage)-1inletminimal_frozen_stake=Tez_repr.(div_exnc.minimal_stake(limit_of_delegation_over_baking+1))inletdirect_ticket_spending_enable=falseinletconstants=Constants_parametric_repr.{preserved_cycles=c.preserved_cycles;blocks_per_cycle=c.blocks_per_cycle;blocks_per_commitment=c.blocks_per_commitment;nonce_revelation_threshold=c.nonce_revelation_threshold;blocks_per_stake_snapshot=c.blocks_per_stake_snapshot;cycles_per_voting_period=c.cycles_per_voting_period;hard_gas_limit_per_operation=c.hard_gas_limit_per_operation;hard_gas_limit_per_block=c.hard_gas_limit_per_block;proof_of_work_threshold=c.proof_of_work_threshold;minimal_stake=c.minimal_stake;minimal_frozen_stake;vdf_difficulty=c.vdf_difficulty;origination_size=c.origination_size;max_operations_time_to_live=c.max_operations_time_to_live;issuance_weights;cost_per_byte=c.cost_per_byte;hard_storage_limit_per_operation=c.hard_storage_limit_per_operation;quorum_min=c.quorum_min;quorum_max=c.quorum_max;min_proposal_quorum=c.min_proposal_quorum;liquidity_baking_toggle_ema_threshold=c.liquidity_baking_toggle_ema_threshold;minimal_block_delay=c.minimal_block_delay;delay_increment_per_round=c.delay_increment_per_round;consensus_committee_size=c.consensus_committee_size;consensus_threshold=c.consensus_threshold;minimal_participation_ratio=c.minimal_participation_ratio;limit_of_delegation_over_baking;percentage_of_frozen_deposits_slashed_per_double_baking;percentage_of_frozen_deposits_slashed_per_double_attestation;(* The `testnet_dictator` should absolutely be None on mainnet *)testnet_dictator=c.testnet_dictator;initial_seed=c.initial_seed;cache_script_size=c.cache_script_size;cache_stake_distribution_cycles=c.cache_stake_distribution_cycles;cache_sampler_state_cycles=c.cache_sampler_state_cycles;dal;sc_rollup;zk_rollup;adaptive_issuance;direct_ticket_spending_enable;}inlet*!ctxt=add_constantsctxtconstantsinreturnctxtinlet+ctxt=preparectxt~level~predecessor_timestamp:timestamp~timestamp~adaptive_issuance_enable:falsein(previous_proto,ctxt)letactivatectxth=letopenLwt_syntaxinlet+new_ctxt=Updater.activate(contextctxt)hinupdate_contextctxtnew_ctxt(* Generic context ********************************************************)typekey=stringlisttypevalue=bytestypetree=Context.treemoduletypeT=Raw_context_intf.Twithtyperoot:=rootandtypekey:=keyandtypevalue:=valueandtypetree:=treeletmemctxtk=Context.mem(contextctxt)kletmem_treectxtk=Context.mem_tree(contextctxt)kletgetctxtk=letopenLwt_result_syntaxinlet*!v_opt=Context.find(contextctxt)kinmatchv_optwith|None->Lwt.return@@storage_error(Missing_key(k,Get))|Somev->returnvletget_treectxtk=letopenLwt_result_syntaxinlet*!v_opt=Context.find_tree(contextctxt)kinmatchv_optwith|None->Lwt.return@@storage_error(Missing_key(k,Get))|Somev->returnvletfindctxtk=Context.find(contextctxt)kletfind_treectxtk=Context.find_tree(contextctxt)kletaddctxtkv=letopenLwt_syntaxinlet+new_ctxt=Context.add(contextctxt)kvinupdate_contextctxtnew_ctxtletadd_treectxtkv=letopenLwt_syntaxinlet+new_ctxt=Context.add_tree(contextctxt)kvinupdate_contextctxtnew_ctxtletinitctxtkv=letopenLwt_result_syntaxinlet*!result=Context.mem(contextctxt)kinmatchresultwith|true->Lwt.return@@storage_error(Existing_keyk)|_->let*!context=Context.add(contextctxt)kvinreturn(update_contextctxtcontext)letinit_treectxtkv:_tzresultLwt.t=letopenLwt_result_syntaxinlet*!result=Context.mem_tree(contextctxt)kinmatchresultwith|true->Lwt.return@@storage_error(Existing_keyk)|_->let*!context=Context.add_tree(contextctxt)kvinreturn(update_contextctxtcontext)letupdatectxtkv=letopenLwt_result_syntaxinlet*!result=Context.mem(contextctxt)kinmatchresultwith|false->Lwt.return@@storage_error(Missing_key(k,Set))|_->let*!context=Context.add(contextctxt)kvinreturn(update_contextctxtcontext)letupdate_treectxtkv=letopenLwt_result_syntaxinlet*!result=Context.mem_tree(contextctxt)kinmatchresultwith|false->Lwt.return@@storage_error(Missing_key(k,Set))|_->let*!context=Context.add_tree(contextctxt)kvinreturn(update_contextctxtcontext)(* Verify that the key is present before deleting *)letremove_existingctxtk=letopenLwt_result_syntaxinlet*!result=Context.mem(contextctxt)kinmatchresultwith|false->Lwt.return@@storage_error(Missing_key(k,Del))|_->let*!context=Context.remove(contextctxt)kinreturn(update_contextctxtcontext)(* Verify that the key is present before deleting *)letremove_existing_treectxtk=letopenLwt_result_syntaxinlet*!result=Context.mem_tree(contextctxt)kinmatchresultwith|false->Lwt.return@@storage_error(Missing_key(k,Del))|_->let*!context=Context.remove(contextctxt)kinreturn(update_contextctxtcontext)(* Do not verify before deleting *)letremovectxtk=letopenLwt_syntaxinlet+new_ctxt=Context.remove(contextctxt)kinupdate_contextctxtnew_ctxtletadd_or_removectxtk=function|None->removectxtk|Somev->addctxtkvletadd_or_remove_treectxtk=function|None->removectxtk|Somev->add_treectxtkvletlistctxt?offset?lengthk=Context.list(contextctxt)?offset?lengthkletfold?depthctxtk~order~init~f=Context.fold?depth(contextctxt)k~order~init~fletconfigctxt=Context.config(contextctxt)moduleProof=Context.Proofletlengthctxtkey=Context.length(contextctxt)keymoduleTree:Raw_context_intf.TREEwithtypet:=tandtypekey:=keyandtypevalue:=valueandtypetree:=tree=structincludeContext.Treeletemptyctxt=Context.Tree.empty(contextctxt)letgettk=letopenLwt_result_syntaxinlet*!result=findtkinmatchresultwith|None->Lwt.return@@storage_error(Missing_key(k,Get))|Somev->returnvletget_treetk=letopenLwt_result_syntaxinlet*!result=find_treetkinmatchresultwith|None->Lwt.return@@storage_error(Missing_key(k,Get))|Somev->returnvletinittkv=letopenLwt_result_syntaxinlet*!result=memtkinmatchresultwith|true->Lwt.return@@storage_error(Existing_keyk)|_->let*!tree=addtkvinreturntreeletinit_treetkv=letopenLwt_result_syntaxinlet*!result=mem_treetkinmatchresultwith|true->Lwt.return@@storage_error(Existing_keyk)|_->let*!tree=add_treetkvinreturntreeletupdatetkv=letopenLwt_result_syntaxinlet*!result=memtkinmatchresultwith|false->Lwt.return@@storage_error(Missing_key(k,Set))|_->let*!tree=addtkvinreturntreeletupdate_treetkv=letopenLwt_result_syntaxinlet*!result=mem_treetkinmatchresultwith|false->Lwt.return@@storage_error(Missing_key(k,Set))|_->let*!tree=add_treetkvinreturntree(* Verify that the key is present before deleting *)letremove_existingtk=letopenLwt_result_syntaxinlet*!result=memtkinmatchresultwith|false->Lwt.return@@storage_error(Missing_key(k,Del))|_->let*!tree=removetkinreturntree(* Verify that the key is present before deleting *)letremove_existing_treetk=letopenLwt_result_syntaxinlet*!result=mem_treetkinmatchresultwith|false->Lwt.return@@storage_error(Missing_key(k,Del))|_->let*!tree=removetkinreturntreeletadd_or_removetk=functionNone->removetk|Somev->addtkvletadd_or_remove_treetk=function|None->removetk|Somev->add_treetkvendletverify_tree_proofprooff=Context.verify_tree_proofprooffletverify_stream_proofprooff=Context.verify_stream_proofprooffletequal_config=Context.equal_configletprojectx=xletabsolute_key_k=kletdescription=Storage_description.create()letfold_map_temporary_lazy_storage_idsctxtf=f(temporary_lazy_storage_idsctxt)|>fun(temporary_lazy_storage_ids,x)->(update_temporary_lazy_storage_idsctxttemporary_lazy_storage_ids,x)letmap_temporary_lazy_storage_ids_sctxtf=letopenLwt_syntaxinlet+ctxt,temporary_lazy_storage_ids=f(temporary_lazy_storage_idsctxt)inupdate_temporary_lazy_storage_idsctxttemporary_lazy_storage_idsmoduleCache=structtypekey=Context.Cache.keytypevalue=Context.Cache.value=..letkey_of_identifier=Context.Cache.key_of_identifierletidentifier_of_key=Context.Cache.identifier_of_keyletppfmtctxt=Context.Cache.ppfmt(contextctxt)letfindck=Context.Cache.find(contextc)kletset_cache_layoutclayout=letopenLwt_syntaxinlet+ctxt=Context.Cache.set_cache_layout(contextc)layoutinupdate_contextcctxtletupdateckv=Context.Cache.update(contextc)kv|>update_contextcletsyncccache_nonce=letopenLwt_syntaxinlet+ctxt=Context.Cache.sync(contextc)~cache_nonceinupdate_contextcctxtletclearc=Context.Cache.clear(contextc)|>update_contextcletlist_keysc~cache_index=Context.Cache.list_keys(contextc)~cache_indexletkey_rankckey=Context.Cache.key_rank(contextc)keyletcache_size_limitc~cache_index=Context.Cache.cache_size_limit(contextc)~cache_indexletcache_sizec~cache_index=Context.Cache.cache_size(contextc)~cache_indexletfuture_cache_expectationc~time_in_blocks=Context.Cache.future_cache_expectation(contextc)~time_in_blocks|>update_contextcendletrecord_non_consensus_operation_hashctxtoperation_hash=update_non_consensus_operations_revctxt(operation_hash::non_consensus_operations_revctxt)letnon_consensus_operationsctxt=List.rev(non_consensus_operations_revctxt)letrecord_dictator_proposal_seenctxt=update_dictator_proposal_seenctxttrueletdictator_proposal_seenctxt=dictator_proposal_seenctxtletinit_sampler_for_cyclectxtcycleseedstate=letopenResult_syntaxinletmap=sampler_statectxtinifCycle_repr.Map.memcyclemapthentzfail(Sampler_already_setcycle)elseletmap=Cycle_repr.Map.addcycle(seed,state)mapinletctxt=update_sampler_statectxtmapinreturnctxtletsampler_for_cycle~readctxtcycle=letopenLwt_result_syntaxinletmap=sampler_statectxtinmatchCycle_repr.Map.findcyclemapwith|Some(seed,state)->return(ctxt,seed,state)|None->let*seed,state=readctxtinletmap=Cycle_repr.Map.addcycle(seed,state)mapinletctxt=update_sampler_statectxtmapinreturn(ctxt,seed,state)letfind_stake_distribution_for_current_cyclectxt=ctxt.back.stake_distribution_for_current_cycleletstake_distribution_for_current_cyclectxt=letopenResult_syntaxinmatchctxt.back.stake_distribution_for_current_cyclewith|None->tzfailStake_distribution_not_set|Somes->returnsletinit_stake_distribution_for_current_cyclectxtstake_distribution_for_current_cycle=update_backctxt{ctxt.backwithstake_distribution_for_current_cycle=Somestake_distribution_for_current_cycle;}moduleInternal_for_tests=structletadd_levelctxtl=letnew_level=Level_repr.Internal_for_tests.add_levelctxt.back.levellinletnew_back={ctxt.backwithlevel=new_level}in{ctxtwithback=new_back}letadd_cyclesctxtl=letblocks_per_cycle=Int32.to_int(constantsctxt).blocks_per_cycleinletnew_level=Level_repr.Internal_for_tests.add_cycles~blocks_per_cyclectxt.back.levellinletnew_back={ctxt.backwithlevel=new_level}in{ctxtwithback=new_back}endmoduletypeCONSENSUS=sigtypettype'valueslot_maptypeslot_settypeslottyperoundtypeconsensus_pkvalallowed_attestations:t->(consensus_pk*int)slot_mapoptionvalallowed_preattestations:t->(consensus_pk*int)slot_mapoptionvalforbidden_delegates:t->Signature.Public_key_hash.Set.ttypeerror+=Slot_map_not_foundof{loc:string}valcurrent_attestation_power:t->intvalinitialize_consensus_operation:t->allowed_attestations:(consensus_pk*int)slot_mapoption->allowed_preattestations:(consensus_pk*int)slot_mapoption->tvalrecord_attestation:t->initial_slot:slot->power:int->ttzresultvalrecord_preattestation:t->initial_slot:slot->power:int->round->ttzresultvalforbid_delegate:t->Signature.Public_key_hash.t->tvalset_forbidden_delegates:t->Signature.Public_key_hash.Set.t->tvalattestations_seen:t->slot_setvalget_preattestations_quorum_round:t->roundoptionvalset_preattestations_quorum_round:t->round->tvallocked_round_evidence:t->(round*int)optionvalset_attestation_branch:t->Block_hash.t*Block_payload_hash.t->tvalattestation_branch:t->(Block_hash.t*Block_payload_hash.t)optionendmoduleConsensus:CONSENSUSwithtypet:=tandtypeslot:=Slot_repr.tandtype'aslot_map:='aSlot_repr.Map.tandtypeslot_set:=Slot_repr.Set.tandtyperound:=Round_repr.tandtypeconsensus_pk:=consensus_pk=structlet[@inline]update_consensus_withctxtf={ctxtwithback={ctxt.backwithconsensus=fctxt.back.consensus}}let[@inline]update_consensus_with_tzresultctxtf=letopenResult_syntaxinlet+consensus=fctxt.back.consensusin{ctxtwithback={ctxt.backwithconsensus}}let[@inline]allowed_attestationsctxt=ctxt.back.consensus.allowed_attestationslet[@inline]allowed_preattestationsctxt=ctxt.back.consensus.allowed_preattestationslet[@inline]forbidden_delegatesctxt=ctxt.back.consensus.forbidden_delegateslet[@inline]set_forbidden_delegatesctxtdelegates=update_consensus_withctxt(Raw_consensus.set_forbidden_delegatesdelegates)let[@inline]current_attestation_powerctxt=ctxt.back.consensus.current_attestation_powerlet[@inline]get_preattestations_quorum_roundctxt=ctxt.back.consensus.preattestations_quorum_roundlet[@inline]locked_round_evidencectxt=Raw_consensus.locked_round_evidencectxt.back.consensuslet[@inline]initialize_consensus_operationctxt~allowed_attestations~allowed_preattestations=update_consensus_withctxt(Raw_consensus.initialize_with_attestations_and_preattestations~allowed_attestations~allowed_preattestations)let[@inline]record_preattestationctxt~initial_slot~powerround=update_consensus_with_tzresultctxt(Raw_consensus.record_preattestation~initial_slot~powerround)let[@inline]record_attestationctxt~initial_slot~power=update_consensus_with_tzresultctxt(Raw_consensus.record_attestation~initial_slot~power)let[@inline]forbid_delegatectxtdelegate=update_consensus_withctxt(Raw_consensus.forbid_delegatedelegate)let[@inline]attestations_seenctxt=ctxt.back.consensus.attestations_seenlet[@inline]set_preattestations_quorum_roundctxtround=update_consensus_withctxt(Raw_consensus.set_preattestations_quorum_roundround)let[@inline]attestation_branchctxt=Raw_consensus.attestation_branchctxt.back.consensuslet[@inline]set_attestation_branchctxtbranch=update_consensus_withctxt(functxt->Raw_consensus.set_attestation_branchctxtbranch)typeerror+=Slot_map_not_foundof{loc:string}let()=register_error_kind`Permanent~id:"raw_context.consensus.slot_map_not_found"~title:"Slot map not found"~description:"Pre-computed map by first slot not found."Data_encoding.(obj1(req"loc"(stringPlain)))(functionSlot_map_not_found{loc}->Someloc|_->None)(funloc->Slot_map_not_found{loc})end(*
To optimize message insertion in smart contract rollup inboxes, we
maintain the sequence of current messages of each rollup used in
the block in a in-memory map.
*)moduleSc_rollup_in_memory_inbox=structletcurrent_messagesctxt=ctxt.back.sc_rollup_current_messagesletset_current_messagesctxtwitness={ctxtwithback={ctxt.backwithsc_rollup_current_messages=witness}}endmoduleDal=structtypecryptobox=Dal.tletmakectxt=letopenResult_syntaxinletConstants_parametric_repr.{dal={cryptobox_parameters;_};_}=ctxt.back.constantsinmatchDal.makecryptobox_parameterswith|Okcryptobox->returncryptobox|Error(`Failexplanation)->tzfail(Dal_errors_repr.Dal_cryptobox_error{explanation})letnumber_of_slotsctxt=ctxt.back.constants.dal.number_of_slotsletrecord_attested_shardsctxtattestationshards=letdal_attestation_slot_accountability=Dal_attestation_repr.Accountability.record_attested_shardsctxt.back.dal_attestation_slot_accountabilityattestationshardsin{ctxtwithback={ctxt.backwithdal_attestation_slot_accountability}}letregister_slot_headerctxtslot_header=letopenResult_syntaxinmatchDal_slot_repr.Slot_market.registerctxt.back.dal_slot_fee_marketslot_headerwith|None->letlength=Dal_slot_repr.Slot_market.lengthctxt.back.dal_slot_fee_marketintzfail(Dal_errors_repr.Dal_register_invalid_slot_header{length;slot_header})|Some(dal_slot_fee_market,updated)->ifnotupdatedthentzfail(Dal_errors_repr.Dal_publish_slot_header_duplicate{slot_header})elsereturn{ctxtwithback={ctxt.backwithdal_slot_fee_market}}letcandidatesctxt=Dal_slot_repr.Slot_market.candidatesctxt.back.dal_slot_fee_marketletis_slot_index_attestedctxt=letthreshold=ctxt.back.constants.Constants_parametric_repr.dal.attestation_thresholdinletnumber_of_shards=ctxt.back.constants.Constants_parametric_repr.dal.cryptobox_parameters.number_of_shardsinDal_attestation_repr.Accountability.is_slot_attestedctxt.back.dal_attestation_slot_accountability~threshold~number_of_shardstypecommittee=dal_committee={pkh_to_shards:(Dal_attestation_repr.shard_index*int)Signature.Public_key_hash.Map.t;shard_to_pkh:Signature.Public_key_hash.tDal_attestation_repr.Shard_map.t;}(* DAL/FIXME https://gitlab.com/tezos/tezos/-/issues/3110
A committee is selected by the callback function
[pkh_from_tenderbake_slot]. We use a callback because of circular
dependencies. It is not clear whether it will be the final choice
for the DAL committee. The current solution is a bit hackish but
should work. If we decide to differ from the Tenderbake
committee, one could just draw a new committee.
The problem with drawing a new committee is that it is not
guaranteed that everyone in the DAL committee will be in the
Tenderbake committee. Consequently, either we decide to have a
new consensus operation which does not count for Tenderbake,
and/or we take into account for the model of DAL that at every
level, a percentage of DAL attestations cannot be received. *)letcompute_committeectxtpkh_from_tenderbake_slot=letopenLwt_result_syntaxinletConstants_parametric_repr.{dal={cryptobox_parameters={number_of_shards;_};_};consensus_committee_size;_;}=ctxt.back.constantsin(* We first draw a committee by drawing slots from the Tenderbake
committee. To have a compact representation of slots, we can
sort the Tenderbake slots by [pkh], so that a committee is
actually only an interval. This is done by recomputing a
committee from the first one. *)letupdate_committeecommitteepkh~slot_index~power={pkh_to_shards=Signature.Public_key_hash.Map.updatepkh(function|None->Some(slot_index,power)|Some(initial_shard_index,old_power)->Some(initial_shard_index,old_power+power))committee.pkh_to_shards;shard_to_pkh=List.fold_left(funshard_to_pkhslot->Dal_attestation_repr.Shard_map.addslotpkhshard_to_pkh)committee.shard_to_pkhMisc.(slot_index-->(slot_index+(power-1)));}inletreccompute_powerindexcommittee=ifCompare.Int.(index<0)thenreturncommitteeelseletshard_index=indexmodconsensus_committee_sizeinlet*?slot=Slot_repr.of_intshard_indexinlet*_ctxt,pkh=pkh_from_tenderbake_slotslotin(* The [Slot_repr] module is related to the Tenderbake committee. *)letslot_index=Slot_repr.to_intslotin(* An optimisation could be to return only [pkh_to_shards] map
because the second one is not used. This can be done later
on, if it is a good optimisation. *)letcommittee=update_committeecommitteepkh~slot_index~power:1incompute_power(index-1)committeein(* This committee is an intermediate to compute the final DAL
committee. This one only projects the Tenderbake committee into
the DAL committee. The next one reorders the slots so that they
are grouped by public key hash. *)let*unordered_committee=compute_power(number_of_shards-1)empty_dal_committeeinletdal_committee=Signature.Public_key_hash.Map.fold(funpkh(_,power)(total_power,committee)->letcommittee=update_committeecommitteepkh~slot_index:total_power~powerinletnew_total_power=total_power+powerin(new_total_power,committee))unordered_committee.pkh_to_shards(0,empty_dal_committee)|>sndinreturndal_committeeletinit_committeectxtcommittee={ctxtwithback={ctxt.backwithdal_committee=committee}}letshards_of_attesterctxt~attester:pkh=letrecmakeacc(initial_shard_index,power)=ifCompare.Int.(power<=0)thenList.revaccelsemake(initial_shard_index::acc)(initial_shard_index+1,power-1)inSignature.Public_key_hash.Map.find_optpkhctxt.back.dal_committee.pkh_to_shards|>Option.map(funpre_shards->make[]pre_shards)end(* The type for relative context accesses instead from the root. In order for
the carbonated storage functions to consume the gas, this has gas infomation
*)typelocal_context={tree:tree;path:key;remaining_operation_gas:Gas_limit_repr.Arith.fp;unlimited_operation_gas:bool;}letwith_local_contextctxtkeyf=letopenLwt_result_syntaxinlet*!tree_opt=find_treectxtkeyinlettree=matchtree_optwithNone->Tree.emptyctxt|Sometree->treeinletlocal_ctxt={tree;path=key;remaining_operation_gas=remaining_operation_gasctxt;unlimited_operation_gas=unlimited_operation_gasctxt;}inlet*local_ctxt,res=flocal_ctxtinlet*!ctxt=add_treectxtkeylocal_ctxt.treeinupdate_remaining_operation_gasctxtlocal_ctxt.remaining_operation_gas|>functxt->update_unlimited_operation_gasctxtlocal_ctxt.unlimited_operation_gas|>functxt->return(ctxt,res)moduleLocal_context:sigincludeRaw_context_intf.VIEWwithtypet=local_contextandtypekey:=keyandtypevalue:=valueandtypetree:=treevalconsume_gas:local_context->Gas_limit_repr.cost->local_contexttzresultvalabsolute_key:local_context->key->keyend=structtypet=local_contextletconsume_gaslocalcost=letopenResult_syntaxinmatchGas_limit_repr.raw_consumelocal.remaining_operation_gascostwith|Somegas_counter->Ok{localwithremaining_operation_gas=gas_counter}|None->iflocal.unlimited_operation_gasthenreturnlocalelsetzfailOperation_quota_exceededlettreelocal=local.treeletupdate_root_treelocaltree={localwithtree}letabsolute_keylocalkey=local.path@keyletfindlocal=Tree.find(treelocal)letfind_treelocal=Tree.find_tree(treelocal)letmemlocal=Tree.mem(treelocal)letmem_treelocal=Tree.mem_tree(treelocal)letgetlocal=Tree.get(treelocal)letget_treelocal=Tree.get_tree(treelocal)letupdatelocalkeyb=letopenLwt_result_syntaxinlet+tree=Tree.update(treelocal)keybinupdate_root_treelocaltreeletupdate_treelocalkeyb=letopenLwt_result_syntaxinlet+tree=Tree.update_tree(treelocal)keybinupdate_root_treelocaltreeletinitlocalkeyb=letopenLwt_result_syntaxinlet+tree=Tree.init(treelocal)keybinupdate_root_treelocaltreeletinit_treelocalkeyt=letopenLwt_result_syntaxinlet+tree=Tree.init_tree(treelocal)keytinupdate_root_treelocaltreeletaddlocalib=letopenLwt_syntaxinlet+tree=Tree.add(treelocal)ibinupdate_root_treelocaltreeletadd_treelocalit=letopenLwt_syntaxinlet+tree=Tree.add_tree(treelocal)itinupdate_root_treelocaltreeletremovelocali=letopenLwt_syntaxinlet+tree=Tree.remove(treelocal)iinupdate_root_treelocaltreeletremove_existinglocalkey=letopenLwt_result_syntaxinlet+tree=Tree.remove_existing(treelocal)keyinupdate_root_treelocaltreeletremove_existing_treelocalkey=letopenLwt_result_syntaxinlet+tree=Tree.remove_existing_tree(treelocal)keyinupdate_root_treelocaltreeletadd_or_removelocalkeyvopt=letopenLwt_syntaxinlet+tree=Tree.add_or_remove(treelocal)keyvoptinupdate_root_treelocaltreeletadd_or_remove_treelocalkeytopt=letopenLwt_syntaxinlet+tree=Tree.add_or_remove_tree(treelocal)keytoptinupdate_root_treelocaltreeletfold?depthlocalkey~order~init~f=Tree.fold?depth(treelocal)key~order~init~fletlistlocal?offset?lengthkey=Tree.list(treelocal)?offset?lengthkeyletconfiglocal=Tree.config(treelocal)letlengthlocali=Tree.length(treelocal)iend