1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645(*****************************************************************************)(* *)(* 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)moduleSc_rollup_address_comparable=structincludeSc_rollup_repr.Address(* TODO: https://gitlab.com/tezos/tezos/-/issues/2648
Fill in real benchmarked values.
Need to create benchmark and fill in values.
*)letcompare_cost_rollup=Saturation_repr.safe_int15end(* This will not create the map yet, as functions to consume gas have not
been defined yet. However, it will make the type of the carbonated map
available to be used in the definition of type back.
*)moduleSc_rollup_address_map_builder=Carbonated_map.Make_builder(Sc_rollup_address_comparable)(*
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_endorsement_power:int;(** Number of endorsement slots recorded for the current block. *)allowed_endorsements:(consensus_pk*int)Slot_repr.Map.t;(** Endorsements rights for the current block. Only an endorsement
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. *)allowed_preendorsements:(consensus_pk*int)Slot_repr.Map.t;(** Preendorsements rights for the current block. Only a preendorsement
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. *)grand_parent_endorsements_seen:Signature.Public_key_hash.Set.t;(** Record the endorsements already seen for the grand
parent. This only useful for the partial construction mode. *)endorsements_seen:Slot_repr.Set.t;(** Record the endorsements already seen. Only initial slots are indexed. *)preendorsements_seen:Slot_repr.Set.t;(** Record the preendorsements already seen. Only initial slots
are indexed. *)locked_round_evidence:(Round_repr.t*int)option;(** Record the preendorsement power for a locked round. *)preendorsements_quorum_round:Round_repr.toption;(** in block construction mode, record the round of preendorsements
included in a block. *)endorsement_branch:(Block_hash.t*Block_payload_hash.t)option;grand_parent_branch:(Block_hash.t*Block_payload_hash.t)option;}(** Invariant:
- [slot \in endorsements_seen => Int_map.mem slot allowed_endorsements]
- [slot \in preendorsements_seen => Int_map.mem slot allowed_preendorsements]
- [ |endorsements_seen| > 0 => |included endorsements| > 0]
*)letempty:t={current_endorsement_power=0;allowed_endorsements=Slot_repr.Map.empty;allowed_preendorsements=Slot_repr.Map.empty;grand_parent_endorsements_seen=Signature.Public_key_hash.Set.empty;endorsements_seen=Slot_repr.Set.empty;preendorsements_seen=Slot_repr.Set.empty;locked_round_evidence=None;preendorsements_quorum_round=None;endorsement_branch=None;grand_parent_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_grand_parent_endorsementtpkh=error_when(Signature.Public_key_hash.Set.mempkht.grand_parent_endorsements_seen)Double_inclusion_of_consensus_operation>|?fun()->{twithgrand_parent_endorsements_seen=Signature.Public_key_hash.Set.addpkht.grand_parent_endorsements_seen;}letrecord_endorsementt~initial_slot~power=error_when(Slot_repr.Set.meminitial_slott.endorsements_seen)Double_inclusion_of_consensus_operation>|?fun()->{twithcurrent_endorsement_power=t.current_endorsement_power+power;endorsements_seen=Slot_repr.Set.addinitial_slott.endorsements_seen;}letrecord_preendorsement~initial_slot~powerroundt=error_when(Slot_repr.Set.meminitial_slott.preendorsements_seen)Double_inclusion_of_consensus_operation>|?fun()->letlocked_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;preendorsements_seen=Slot_repr.Set.addinitial_slott.preendorsements_seen;}letset_preendorsements_quorum_roundroundt=matcht.preendorsements_quorum_roundwith|Someround'->(* If the rounds are different, an error should have already
been raised. *)assert(Round_repr.equalroundround');t|None->{twithpreendorsements_quorum_round=Someround}letinitialize_with_endorsements_and_preendorsements~allowed_endorsements~allowed_preendorsementst={twithallowed_endorsements;allowed_preendorsements}letlocked_round_evidencet=t.locked_round_evidenceletendorsement_brancht=t.endorsement_branchletgrand_parent_brancht=t.grand_parent_branchletset_endorsement_branchtendorsement_branch={twithendorsement_branch=Someendorsement_branch}letset_grand_parent_branchtgrand_parent_branch={twithgrand_parent_branch=Somegrand_parent_branch}endtypeback={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:Tez_repr.tSignature.Public_key_hash.Map.toption;tx_rollup_current_messages:Tx_rollup_inbox_repr.Merkle.treeTx_rollup_repr.Map.t;sc_rollup_current_messages:Context.treeSc_rollup_address_map_builder.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_endorsement_slot_accountability:Dal_endorsement_repr.Accountability.t;}(*
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]tx_rollupctxt=ctxt.back.constants.tx_rolluplet[@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]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}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.")Data_encoding.(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=ifCompare.Int.(internal_noncectxt>=65_535)thenerrorToo_many_internal_operationselseok(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'=letprevious=get_collected_feesctxtinTez_repr.(previous+?fees')>|?funfees->update_feesctxtfeesletspend_collected_fees_only_call_from_tokenctxtfees'=letprevious=get_collected_feesctxtinTez_repr.(previous-?fees')>|?funfees->update_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=matchorigination_noncectxtwith|None->errorUndefined_operation_nonce|Somecur_origination_nonce->letorigination_nonce=Some(Origination_nonce.incrcur_origination_nonce)inletctxt=update_origination_noncectxtorigination_nonceinok(ctxt,cur_origination_nonce)letget_origination_noncectxt=matchorigination_noncectxtwith|None->errorUndefined_operation_nonce|Someorigination_nonce->okorigination_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_reprincheck_gas_limit~hard_gas_limit_per_operation:(constantsctxt).hard_gas_limit_per_operation~gas_limit>>?fun()->letblock_gas=block_gas_levelctxtinletlimit=Arith.fpgas_limitinifArith.(limit>block_gas)thenerrorBlock_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=matchGas_limit_repr.raw_consume(remaining_operation_gasctxt)costwith|Somegas_counter->Ok(update_remaining_operation_gasctxtgas_counter)|None->ifunlimited_operation_gasctxtthenokctxtelseerrorOperation_quota_exceededletcheck_enough_gasctxtcost=consume_gasctxtcost>>?fun_->Result.return_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.zero(* Once gas consuming functions have been defined,
we can instantiate the carbonated map.
See [Sc_rollup_carbonated_map_maker] above.
*)moduleGas=structtypecontext=tletconsume=consume_gasendmoduleSc_rollup_carbonated_map=Sc_rollup_address_map_builder.Make(Gas)typemissing_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"string))(functionIncompatible_protocol_versionarg->Somearg|_->None)(funarg->Incompatible_protocol_versionarg);case(Tag1)~title:"Missing_key"(obj2(req"missing_key"(liststring))(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"(liststring)))(functionExisting_keykey->Somekey|_->None)(funkey->Existing_keykey);case(Tag3)~title:"Corrupted_data"(obj1(req"corrupted_data"(liststring)))(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=error(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. *)letversion_value="lima_015"letversion="v1"letcycle_eras_key=[version;"cycle_eras"]letconstants_key=[version;"constants"]letprotocol_param_key=["protocol_parameters"]letget_cycle_erasctxt=Context.findctxtcycle_eras_key>|=function|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=letbytes=Data_encoding.Binary.to_bytes_exnLevel_repr.cycle_eras_encodingcycle_erasinContext.addctxtcycle_eras_keybytes>|=oktypeerror+=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"bytes))(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"string))(function|Failed_to_decode_parameter(json,msg)->Some(json,msg)|_->None)(fun(json,msg)->Failed_to_decode_parameter(json,msg))letget_proto_paramctxt=Context.findctxtprotocol_param_key>>=function|None->failwith"Missing protocol parameters."|Somebytes->(matchData_encoding.Binary.of_bytes_optData_encoding.jsonbyteswith|None->fail(Failed_to_parse_parameterbytes)|Somejson->(Context.removectxtprotocol_param_key>|=functxt->matchData_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->Parameters_repr.check_paramsparam>>?fun()->ok(param,ctxt)))letadd_constantsctxtconstants=letbytes=Data_encoding.Binary.to_bytes_exnConstants_parametric_repr.encodingconstantsinContext.addctxtconstants_keybytesletget_constantsctxt=Context.findctxtconstants_key>|=function|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->okconstants)letpatch_constantsctxtf=letconstants=f(constantsctxt)inadd_constants(contextctxt)constants>|=funcontext->letctxt=update_contextctxtcontextinupdate_constantsctxtconstantsletcheck_initedctxt=Context.findctxtversion_key>|=function|None->failwith"Internal error: un-initialized context."|Somebytes->lets=Bytes.to_stringbytesinifCompare.String.(s=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~timestampctxt=Raw_level_repr.of_int32level>>?=funlevel->check_initedctxt>>=?fun()->get_constantsctxt>>=?funconstants->Round_repr.Durations.create~first_round_duration:constants.minimal_block_delay~delay_increment_per_round:constants.delay_increment_per_round>>?=funround_durations->get_cycle_erasctxt>|=?funcycle_eras->check_cycle_erascycle_erasconstants;letlevel=Level_repr.level_from_raw~cycle_eraslevelin{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;tx_rollup_current_messages=Tx_rollup_repr.Map.empty;sc_rollup_current_messages=Sc_rollup_carbonated_map.empty;dal_slot_fee_market=Dal_slot_repr.Slot_market.init~length:constants.Constants_parametric_repr.dal.number_of_slots;dal_endorsement_slot_accountability=Dal_endorsement_repr.Accountability.init~length:constants.Constants_parametric_repr.dal.number_of_slots;};}typeprevious_protocol=GenesisofParameters_repr.t|Kathmandu_014letcheck_and_update_protocol_versionctxt=(Context.findctxtversion_key>>=function|None->failwith"Internal error: un-initialized context in check_first_block."|Somebytes->lets=Bytes.to_stringbytesinifCompare.String.(s=version_value)thenfailwith"Internal error: previously initialized context."elseifCompare.String.(s="genesis")thenget_proto_paramctxt>|=?fun(param,ctxt)->(Genesisparam,ctxt)elseifCompare.String.(s="kathmandu_014")thenreturn(Kathmandu_014,ctxt)elseLwt.return@@storage_error(Incompatible_protocol_versions))>>=?fun(previous_proto,ctxt)->Context.addctxtversion_key(Bytes.of_stringversion_value)>|=functxt->ok(previous_proto,ctxt)(* only for the migration *)let[@warning"-32"]get_previous_protocol_constantsctxt=Context.findctxtconstants_key>>=function|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->Lwt.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~timestampctxt=check_and_update_protocol_versionctxt>>=?fun(previous_proto,ctxt)->(matchprevious_protowith|Genesisparam->Raw_level_repr.of_int32level>>?=funfirst_level->letcycle_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;}inLevel_repr.create_cycle_eras[cycle_era]>>?=funcycle_eras->set_cycle_erasctxtcycle_eras>>=?functxt->add_constantsctxtparam.constants>|=ok|Kathmandu_014->get_previous_protocol_constantsctxt>>=func->lettx_rollup=Constants_parametric_repr.{enable=c.tx_rollup.enable;origination_size=c.tx_rollup.origination_size;hard_size_limit_per_inbox=c.tx_rollup.hard_size_limit_per_inbox;hard_size_limit_per_message=c.tx_rollup.hard_size_limit_per_message;max_withdrawals_per_batch=c.tx_rollup.max_withdrawals_per_batch;max_ticket_payload_size=c.tx_rollup.max_ticket_payload_size;commitment_bond=c.tx_rollup.commitment_bond;finality_period=c.tx_rollup.finality_period;withdraw_period=c.tx_rollup.withdraw_period;max_inboxes_count=c.tx_rollup.max_inboxes_count;max_messages_per_inbox=c.tx_rollup.max_messages_per_inbox;max_commitments_count=c.tx_rollup.max_commitments_count;cost_per_byte_ema_factor=c.tx_rollup.cost_per_byte_ema_factor;rejection_max_proof_size=c.tx_rollup.rejection_max_proof_size;sunset_level=c.tx_rollup.sunset_level;}inletdal=Constants_parametric_repr.{feature_enable=false;number_of_slots=256;number_of_shards=2048;endorsement_lag=1;availability_threshold=50;slot_size=1lsl20;redundancy_factor=16;page_size=4096;}in(* Inherit values that existed in previous protocol and haven't changed.
Assign values to new constants or those with new default value. *)letsc_rollup=Constants_parametric_repr.{enable=c.sc_rollup.enable;origination_size=c.sc_rollup.origination_size;challenge_window_in_blocks=c.sc_rollup.challenge_window_in_blocks;(*
The following value is chosen to limit the length of inbox
refutation proofs. In the worst case, the length of inbox
refutation proofs are logarithmic (in basis 2) in the
number of messages in the inboxes during the commitment
period.
With the following value, an inbox refutation proof is
made of at most 35 hashes, hence a payload bounded by
35 * 48 bytes, which far below than the 32kb of a Tezos
operations.
*)max_number_of_messages_per_commitment_period=c.sc_rollup.commitment_period_in_blocks*10_000_000;(* TODO: https://gitlab.com/tezos/tezos/-/issues/2756
The following constants need to be refined. *)stake_amount=Tez_repr.of_mutez_exn10_000_000_000L;commitment_period_in_blocks=c.sc_rollup.commitment_period_in_blocks;max_lookahead_in_blocks=c.sc_rollup.max_lookahead_in_blocks;(* Number of active levels kept for executing outbox messages.
WARNING: Changing this value impacts the storage charge for
applying messages from the outbox. It also requires migration for
remapping existing active outbox levels to new indices. *)max_active_outbox_levels=c.sc_rollup.max_active_outbox_levels;(* Maximum number of outbox messages per level.
WARNING: changing this value impacts the storage cost charged
for applying messages from the outbox. *)max_outbox_messages_per_level=c.sc_rollup.max_outbox_messages_per_level;(* The default number of required sections in a dissection *)number_of_sections_in_dissection=32;timeout_period_in_blocks=20_160;(* We store multiple cemented commitments because we want to
allow the execution of outbox messages against cemented
commitments that are older than the last cemented commitment.
The execution of an outbox message is a manager operation,
and manager operations are kept in the mempool for one
hour. Hence we only need to ensure that an outbox message
can be validated against a cemented commitment produced in the
last hour. If we assume that the rollup is operating without
issues, that is no commitments are being refuted and commitments
are published and cemented regularly by one rollup node, we can
expect commitments to be cemented approximately every 15
minutes, or equivalently we can expect 5 commitments to be
published in one hour (at minutes 0, 15, 30, 45 and 60).
Therefore, we need to keep 5 cemented commitments to guarantee
that the execution of an outbox operation can always be
validated against a cemented commitment while it is in the
mempool. *)max_number_of_stored_cemented_commitments=5;}inletzk_rollup=Constants_parametric_repr.{enable=false;origination_size=4_000;min_pending_to_process=10;}inletconstants=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.tokens_per_roll;vdf_difficulty=c.vdf_difficulty;seed_nonce_revelation_tip=c.seed_nonce_revelation_tip;origination_size=c.origination_size;max_operations_time_to_live=c.max_operations_time_to_live;baking_reward_fixed_portion=c.baking_reward_fixed_portion;baking_reward_bonus_per_slot=c.baking_reward_bonus_per_slot;endorsing_reward_per_slot=c.endorsing_reward_per_slot;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_subsidy=c.liquidity_baking_subsidy;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;max_slashing_period=c.max_slashing_period;frozen_deposits_percentage=c.frozen_deposits_percentage;double_baking_punishment=c.double_baking_punishment;ratio_of_frozen_deposits_slashed_per_double_endorsement=c.ratio_of_frozen_deposits_slashed_per_double_endorsement;(* 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;tx_rollup;dal;sc_rollup;zk_rollup;}inadd_constantsctxtconstants>>=functxt->returnctxt)>>=?functxt->preparectxt~level~predecessor_timestamp:timestamp~timestamp>|=?functxt->(previous_proto,ctxt)letactivatectxth=Updater.activate(contextctxt)h>|=update_contextctxt(* 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=Context.find(contextctxt)k>|=function|None->storage_error(Missing_key(k,Get))|Somev->okvletget_treectxtk=Context.find_tree(contextctxt)k>|=function|None->storage_error(Missing_key(k,Get))|Somev->okvletfindctxtk=Context.find(contextctxt)kletfind_treectxtk=Context.find_tree(contextctxt)kletaddctxtkv=Context.add(contextctxt)kv>|=update_contextctxtletadd_treectxtkv=Context.add_tree(contextctxt)kv>|=update_contextctxtletinitctxtkv=Context.mem(contextctxt)k>>=function|true->Lwt.return@@storage_error(Existing_keyk)|_->Context.add(contextctxt)kv>|=funcontext->ok(update_contextctxtcontext)letinit_treectxtkv:_tzresultLwt.t=Context.mem_tree(contextctxt)k>>=function|true->Lwt.return@@storage_error(Existing_keyk)|_->Context.add_tree(contextctxt)kv>|=funcontext->ok(update_contextctxtcontext)letupdatectxtkv=Context.mem(contextctxt)k>>=function|false->Lwt.return@@storage_error(Missing_key(k,Set))|_->Context.add(contextctxt)kv>|=funcontext->ok(update_contextctxtcontext)letupdate_treectxtkv=Context.mem_tree(contextctxt)k>>=function|false->Lwt.return@@storage_error(Missing_key(k,Set))|_->Context.add_tree(contextctxt)kv>|=funcontext->ok(update_contextctxtcontext)(* Verify that the key is present before deleting *)letremove_existingctxtk=Context.mem(contextctxt)k>>=function|false->Lwt.return@@storage_error(Missing_key(k,Del))|_->Context.remove(contextctxt)k>|=funcontext->ok(update_contextctxtcontext)(* Verify that the key is present before deleting *)letremove_existing_treectxtk=Context.mem_tree(contextctxt)k>>=function|false->Lwt.return@@storage_error(Missing_key(k,Del))|_->Context.remove(contextctxt)k>|=funcontext->ok(update_contextctxtcontext)(* Do not verify before deleting *)letremovectxtk=Context.remove(contextctxt)k>|=update_contextctxtletadd_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=findtk>|=function|None->storage_error(Missing_key(k,Get))|Somev->okvletget_treetk=find_treetk>|=function|None->storage_error(Missing_key(k,Get))|Somev->okvletinittkv=memtk>>=function|true->Lwt.return@@storage_error(Existing_keyk)|_->addtkv>|=okletinit_treetkv=mem_treetk>>=function|true->Lwt.return@@storage_error(Existing_keyk)|_->add_treetkv>|=okletupdatetkv=memtk>>=function|false->Lwt.return@@storage_error(Missing_key(k,Set))|_->addtkv>|=okletupdate_treetkv=mem_treetk>>=function|false->Lwt.return@@storage_error(Missing_key(k,Set))|_->add_treetkv>|=ok(* Verify that the key is present before deleting *)letremove_existingtk=memtk>>=function|false->Lwt.return@@storage_error(Missing_key(k,Del))|_->removetk>|=ok(* Verify that the key is present before deleting *)letremove_existing_treetk=mem_treetk>>=function|false->Lwt.return@@storage_error(Missing_key(k,Del))|_->removetk>|=okletadd_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=f(temporary_lazy_storage_idsctxt)>|=fun(ctxt,temporary_lazy_storage_ids)->update_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=Context.Cache.set_cache_layout(contextc)layout>>=functxt->Lwt.return(update_contextcctxt)letupdateckv=Context.Cache.update(contextc)kv|>update_contextcletsyncccache_nonce=Context.Cache.sync(contextc)~cache_nonce>>=functxt->Lwt.return(update_contextcctxt)letclearc=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_seenctxtmoduleMigration_from_Kathmandu=structletreset_samplersctxt=letctxt=update_sampler_statectxtCycle_repr.Map.emptyinokctxtendletinit_sampler_for_cyclectxtcycleseedstate=letmap=sampler_statectxtinifCycle_repr.Map.memcyclemapthenerror(Sampler_already_setcycle)elseletmap=Cycle_repr.Map.addcycle(seed,state)mapinletctxt=update_sampler_statectxtmapinokctxtletsampler_for_cycle~readctxtcycle=letmap=sampler_statectxtinmatchCycle_repr.Map.findcyclemapwith|Some(seed,state)->return(ctxt,seed,state)|None->readctxt>>=?fun(seed,state)->letmap=Cycle_repr.Map.addcycle(seed,state)mapinletctxt=update_sampler_statectxtmapinreturn(ctxt,seed,state)letstake_distribution_for_current_cyclectxt=matchctxt.back.stake_distribution_for_current_cyclewith|None->errorStake_distribution_not_set|Somes->oksletinit_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_endorsements:t->(consensus_pk*int)slot_mapvalallowed_preendorsements:t->(consensus_pk*int)slot_mapvalcurrent_endorsement_power:t->intvalinitialize_consensus_operation:t->allowed_endorsements:(consensus_pk*int)slot_map->allowed_preendorsements:(consensus_pk*int)slot_map->tvalrecord_grand_parent_endorsement:t->Signature.Public_key_hash.t->ttzresultvalrecord_endorsement:t->initial_slot:slot->power:int->ttzresultvalrecord_preendorsement:t->initial_slot:slot->power:int->round->ttzresultvalendorsements_seen:t->slot_setvalget_preendorsements_quorum_round:t->roundoptionvalset_preendorsements_quorum_round:t->round->tvallocked_round_evidence:t->(round*int)optionvalset_endorsement_branch:t->Block_hash.t*Block_payload_hash.t->tvalendorsement_branch:t->(Block_hash.t*Block_payload_hash.t)optionvalset_grand_parent_branch:t->Block_hash.t*Block_payload_hash.t->tvalgrand_parent_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]allowed_endorsementsctxt=ctxt.back.consensus.allowed_endorsementslet[@inline]allowed_preendorsementsctxt=ctxt.back.consensus.allowed_preendorsementslet[@inline]current_endorsement_powerctxt=ctxt.back.consensus.current_endorsement_powerlet[@inline]get_preendorsements_quorum_roundctxt=ctxt.back.consensus.preendorsements_quorum_roundlet[@inline]locked_round_evidencectxt=Raw_consensus.locked_round_evidencectxt.back.consensuslet[@inline]update_consensus_withctxtf={ctxtwithback={ctxt.backwithconsensus=fctxt.back.consensus}}let[@inline]update_consensus_with_tzresultctxtf=fctxt.back.consensus>|?funconsensus->{ctxtwithback={ctxt.backwithconsensus}}let[@inline]initialize_consensus_operationctxt~allowed_endorsements~allowed_preendorsements=update_consensus_withctxt(Raw_consensus.initialize_with_endorsements_and_preendorsements~allowed_endorsements~allowed_preendorsements)let[@inline]record_grand_parent_endorsementctxtpkh=update_consensus_with_tzresultctxt(functxt->Raw_consensus.record_grand_parent_endorsementctxtpkh)let[@inline]record_preendorsementctxt~initial_slot~powerround=update_consensus_with_tzresultctxt(Raw_consensus.record_preendorsement~initial_slot~powerround)let[@inline]record_endorsementctxt~initial_slot~power=update_consensus_with_tzresultctxt(Raw_consensus.record_endorsement~initial_slot~power)let[@inline]endorsements_seenctxt=ctxt.back.consensus.endorsements_seenlet[@inline]set_preendorsements_quorum_roundctxtround=update_consensus_withctxt(Raw_consensus.set_preendorsements_quorum_roundround)let[@inline]endorsement_branchctxt=Raw_consensus.endorsement_branchctxt.back.consensuslet[@inline]set_endorsement_branchctxtbranch=update_consensus_withctxt(functxt->Raw_consensus.set_endorsement_branchctxtbranch)let[@inline]grand_parent_branchctxt=Raw_consensus.grand_parent_branchctxt.back.consensuslet[@inline]set_grand_parent_branchctxtbranch=update_consensus_withctxt(functxt->Raw_consensus.set_grand_parent_branchctxtbranch)endmoduleTx_rollup=structletadd_messagectxtrollupmessage=letroot=refTx_rollup_inbox_repr.Merkle.(rootempty)inletupdaterelement=lettree=Option.valueelement~default:Tx_rollup_inbox_repr.Merkle.(empty)inlettree=Tx_rollup_inbox_repr.Merkle.add_messagetreemessageinroot:=Tx_rollup_inbox_repr.Merkle.roottree;Sometreeinletmap=Tx_rollup_repr.Map.updaterollupupdaterctxt.back.tx_rollup_current_messagesinletback={ctxt.backwithtx_rollup_current_messages=map}in({ctxtwithback},!root)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_messagesctxtrollup=letopenTzresult_syntaxinlet+messages,ctxt=Sc_rollup_carbonated_map.findctxtrollupctxt.back.sc_rollup_current_messagesin(messages,ctxt)letset_current_messagesctxtrolluptree=letopenTzresult_syntaxinlet+sc_rollup_current_messages,ctxt=Sc_rollup_carbonated_map.updatectxtrollup(functxt_prev_tree->return(Sometree,ctxt))ctxt.back.sc_rollup_current_messagesinletback={ctxt.backwithsc_rollup_current_messages}in{ctxtwithback}endmoduleDal=structtypeerror+=|Dal_register_invalid_slotof{length:int;slot:Dal_slot_repr.t}let()=register_error_kind`Permanent~id:"dal_register_invalid_slot"~title:"Dal register invalid slot"~description:"Attempt to register a slot which is invalid (the index is out of \
bounds)."~pp:(funppf(length,slot)->Format.fprintfppf"The slot provided is invalid. Slot index should be between 0 and \
%d. Found: %a."lengthDal_slot_repr.Index.ppslot.Dal_slot_repr.id.index)Data_encoding.(obj2(req"length"int31)(req"slot"Dal_slot_repr.encoding))(function|Dal_register_invalid_slot{length;slot}->Some(length,slot)|_->None)(fun(length,slot)->Dal_register_invalid_slot{length;slot})letrecord_available_shardsctxtslotsshards=letdal_endorsement_slot_accountability=Dal_endorsement_repr.Accountability.record_shards_availabilityctxt.back.dal_endorsement_slot_accountabilityslotsshardsin{ctxtwithback={ctxt.backwithdal_endorsement_slot_accountability}}letregister_slotctxtslot=matchDal_slot_repr.Slot_market.registerctxt.back.dal_slot_fee_marketslotwith|None->letlength=Dal_slot_repr.Slot_market.lengthctxt.back.dal_slot_fee_marketinerror(Dal_register_invalid_slot{length;slot})|Some(dal_slot_fee_market,updated)->ok({ctxtwithback={ctxt.backwithdal_slot_fee_market}},updated)letcandidatesctxt=Dal_slot_repr.Slot_market.candidatesctxt.back.dal_slot_fee_marketletis_slot_availablectxt=letthreshold=ctxt.back.constants.Constants_parametric_repr.dal.availability_thresholdinletnumber_of_shards=ctxt.back.constants.Constants_parametric_repr.dal.number_of_shardsinDal_endorsement_repr.Accountability.is_slot_availablectxt.back.dal_endorsement_slot_accountability~threshold~number_of_shards(* DAL/FIXME https://gitlab.com/tezos/tezos/-/issues/3110
We have to choose for the sampling. Here we use the one used by
the consensus which is hackish and probably not what we want at
the end. However, it should be enough for a prototype. This has a
very bad complexity too. *)letreccompute_shards?(index=0)ctxt~endorser=letmax_shards=ctxt.back.constants.dal.number_of_shardsinSlot_repr.Map.fold_e(fun_(consensus_key,power)(index,shards)->letlimit=Compare.Int.min(index+power)max_shardsin(* Early fail when we have reached the desired number of shards *)ifCompare.Int.(index>=max_shards)thenErrorshardselseifSignature.Public_key_hash.(consensus_key.consensus_pkh=endorser)thenletshards=Misc.(index-->(limit-1))inOk(index+power,shards)elseOk(index+power,shards))ctxt.back.consensus.allowed_endorsements(index,[])|>function|Ok(index,[])->(* This happens if the number of Tenderbake slots is below the
number of shards. Therefore, we reuse the committee using a
shift (index being the size of the committee). *)compute_shards~indexctxt~endorser|Ok(_index,shards)->shards|Errorshards->shardsletshardsctxt~endorser=compute_shards~index:0ctxt~endorserend