12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009(*****************************************************************************)(* *)(* 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*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
consensus attestation power and DAL attestation power. This is
[None] only in mempool mode. *)allowed_preattestations:(consensus_pk*int*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
consensus attestation power and DAL attestation 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}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: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_cryptobox:Dal.toption;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~number_of_slots:constants.Constants_parametric_repr.dal.number_of_slots;dal_cryptobox=None;adaptive_issuance_enable;};}typeprevious_protocol=GenesisofParameters_repr.t|Oxford_018letcheck_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="oxford_018")thenreturn(Oxford_018,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)letupdate_block_time_related_constants(c:Constants_parametric_repr.t)=letdivide_periodp=Period_repr.of_seconds_exnInt64.(div(mul(Period_repr.to_secondsp)2L)3L)inletminimal_block_delay=divide_periodc.minimal_block_delayinletdelay_increment_per_round=divide_periodc.delay_increment_per_roundinlethard_gas_limit_per_block=lettwo=Z.(succone)inletthree=Z.(succtwo)inGas_limit_repr.Arith.(integral_exn(Z.div(Z.mul(integral_to_zc.hard_gas_limit_per_block)two)three))inlethalf_morex=Int32.(div(mul3lx)2l)inletblocks_per_cycle=half_morec.blocks_per_cycleinletblocks_per_commitment=half_morec.blocks_per_commitmentinletnonce_revelation_threshold=half_morec.nonce_revelation_thresholdinletmax_operations_time_to_live=3*c.max_operations_time_to_live/2inletblock_time=Int64.to_int(Period_repr.to_secondsminimal_block_delay)inletsc_rollup=Constants_parametric_repr.update_sc_rollup_parameterc.sc_rollup~block_timein{cwithsc_rollup;blocks_per_cycle;blocks_per_commitment;nonce_revelation_threshold;max_operations_time_to_live;minimal_block_delay;delay_increment_per_round;hard_gas_limit_per_block;}letupdate_cycle_erasctxtlevel~prev_blocks_per_cycle~blocks_per_cycle~blocks_per_commitment=letopenLwt_result_syntaxinlet*cycle_eras=get_cycle_erasctxtinletcurrent_era=Level_repr.current_eracycle_erasinletcurrent_cycle=letlevel_position=Int32.sublevel(Raw_level_repr.to_int32current_era.first_level)inCycle_repr.addcurrent_era.first_cycle(Int32.to_int(Int32.divlevel_positionprev_blocks_per_cycle))inletnew_cycle_era=Level_repr.{first_level=Raw_level_repr.of_int32_exn(Int32.succlevel);first_cycle=Cycle_repr.succcurrent_cycle;blocks_per_cycle;blocks_per_commitment;}inlet*?new_cycle_eras=Level_repr.add_cycle_eranew_cycle_eracycle_erasinset_cycle_erasctxtnew_cycle_eras(* 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~timestamp_chain_idctxt=letopenLwt_result_syntaxinlet*previous_proto,ctxt=check_and_update_protocol_versionctxtinlet*ctxt,previous_proto_constants=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.constantsinreturn(result,None)|Oxford_018->let*!c=get_previous_protocol_constantsctxtin(* When modifying the line below, be careful that the values are
compatible with the encodings exported by the environment did not
change. *)letcryptobox_parameters={Dal.page_size=3967;slot_size=126_944;redundancy_factor=8;number_of_shards=512;}inletdal=Constants_parametric_repr.{feature_enable=true;incentives_enable=false;number_of_slots=32;attestation_lag=8;attestation_threshold=66;cryptobox_parameters;}in(* This test prevents the activation of the protocol if the
set of parameters given for the DAL is invalid. *)let*?()=matchDal.makecryptobox_parameterswith|Ok_cryptobox->ok()|Error(`Failexplanation)->error(Dal_errors_repr.Dal_cryptobox_error{explanation})inletdal_activation_level=ifc.dal.feature_enablethen(* if dal was enable in previous protocol, do as if it were always
activated *)Raw_level_repr.succRaw_level_repr.rootelse(* dal activates at first level of the new protocol. *)Raw_level_repr.of_int32_exn(Int32.succlevel)inletdal_attested_slots_validity_lag=(* A rollup node shouldn't import a page of an attested slot whose attested
level is too far in the past w.r.t. the current level. Importation window
is fixed to 241_920 levels below. It is the number of blocks produced
during 28 days (4 weeks) with a block time of 10 seconds. *)241_920inletreveal_activation_level:Constants_parametric_repr.sc_rollup_reveal_activation_level=let({raw_data={blake2B};metadata;dal_page=_;dal_parameters=_;}:Constants_parametric_previous_repr.sc_rollup_reveal_activation_level)=c.sc_rollup.reveal_activation_levelin{raw_data={blake2B};metadata;dal_page=dal_activation_level;dal_parameters=dal_activation_level;(* Warning: the semantics of valid slots needs to be adapted if the
value of this parameter is changed in the future.
- If it is increased, some attested slots that were outdated with
the old value will become valid again.
- If it is decreased, some attested slots that were valid with
the old value will become outdated.
In both cases, the status of slots before and after the value
change is different. So, the behaviour if a valid slot is
imported before the value upgrade but a refutation game
targetting a page of that slot is started after the upgrade is
not the correct/expected one. *)dal_attested_slots_validity_lag;}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=c.sc_rollup.private_enable;riscv_pvm_enable=c.sc_rollup.riscv_pvm_enable;}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.zk_rollup.max_ticket_payload_size;}inletadaptive_rewards_params=Constants_parametric_repr.{issuance_ratio_final_min=Q.(0_25//100_00);(* 0.25% *)issuance_ratio_final_max=Q.(10//100)(* 10% *);issuance_ratio_initial_min=Q.(45//1000);(* 4.5% *)issuance_ratio_initial_max=Q.(55//1000);(* 5.5% *)initial_period=10;(* 1 month *)transition_period=50;(* 5 months *)max_bonus=c.adaptive_issuance.adaptive_rewards_params.max_bonus;growth_rate=c.adaptive_issuance.adaptive_rewards_params.growth_rate;center_dz=c.adaptive_issuance.adaptive_rewards_params.center_dz;radius_dz=c.adaptive_issuance.adaptive_rewards_params.radius_dz;}inletadaptive_issuance=Constants_parametric_repr.{global_limit_of_staking_over_baking=c.adaptive_issuance.global_limit_of_staking_over_baking;edge_of_staking_over_delegation=c.adaptive_issuance.edge_of_staking_over_delegation;launch_ema_threshold=0l;adaptive_rewards_params;activation_vote_enable=true;autostaking_enable=c.adaptive_issuance.autostaking_enable;force_activation=false;ns_enable=true;}inletliquidity_baking_subsidy=Tez_repr.(mul_exnone5)inlet(issuance_weights:Constants_parametric_repr.issuance_weights)=let({base_total_issued_per_minute;baking_reward_fixed_portion_weight;baking_reward_bonus_weight;attesting_reward_weight;liquidity_baking_subsidy_weight=_;seed_nonce_revelation_tip_weight;vdf_revelation_tip_weight;}:Constants_parametric_previous_repr.issuance_weights)=c.issuance_weightsinletbase_total_issued_per_minute=letx=Tez_repr.(sub_optbase_total_issued_per_minuteliquidity_baking_subsidy)inmatchxwithNone->assertfalse|Somex->xin{base_total_issued_per_minute;baking_reward_fixed_portion_weight;baking_reward_bonus_weight;attesting_reward_weight;seed_nonce_revelation_tip_weight;vdf_revelation_tip_weight;}inletdirect_ticket_spending_enable=falseinletconsensus_rights_delay=(* We change the consensus_rights_delay value only for mainnet *)ifCompare.Int.(c.preserved_cycles=5)then2elsec.preserved_cyclesinletConstants_repr.Generated.{max_slashing_threshold;_}=Constants_repr.Generated.generate~consensus_committee_size:c.consensus_committee_sizeinletconstants=Constants_parametric_repr.{consensus_rights_delay;blocks_preservation_cycles=1;delegate_parameters_activation_delay=c.preserved_cycles;blocks_per_cycle=c.blocks_per_cycle;blocks_per_commitment=c.blocks_per_commitment;nonce_revelation_threshold=c.nonce_revelation_threshold;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=c.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_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;limit_of_delegation_over_baking=c.limit_of_delegation_over_baking;percentage_of_frozen_deposits_slashed_per_double_baking=Percentage.convert_from_o_to_pc.percentage_of_frozen_deposits_slashed_per_double_baking;percentage_of_frozen_deposits_slashed_per_double_attestation=Percentage.convert_from_o_to_pc.percentage_of_frozen_deposits_slashed_per_double_attestation;max_slashing_per_block=Percentage.p100;max_slashing_threshold;(* 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;}inletblock_time_is_at_least_8s=(* This check is used to trigger the constants changes at migration on
this protocol for network that have block time strictly greater
than 7s such as mainnet and ghostnet *)Compare.Int64.(Period_repr.to_secondsc.minimal_block_delay>=8L)inlet*ctxt,constants=ifblock_time_is_at_least_8sthenletnew_constants:Constants_parametric_repr.t=update_block_time_related_constantsconstantsinlet*ctxt=update_cycle_erasctxtlevel~prev_blocks_per_cycle:constants.blocks_per_cycle~blocks_per_cycle:new_constants.blocks_per_cycle~blocks_per_commitment:new_constants.blocks_per_commitmentinreturn(ctxt,new_constants)elsereturn(ctxt,constants)inlet*!ctxt=add_constantsctxtconstantsinreturn(ctxt,Somec)inlet+ctxt=preparectxt~level~predecessor_timestamp:timestamp~timestamp~adaptive_issuance_enable:falsein(previous_proto,previous_proto_constants,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*int)slot_mapoptionvalallowed_preattestations:t->(consensus_pk*int*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*int)slot_mapoption->allowed_preattestations:(consensus_pk*int*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_syntaxin(* Dal.make takes some time (on the order of 10ms) so we memoize
its result to avoid calling it more than once per block. *)matchctxt.back.dal_cryptoboxwith|Somecryptobox->return(ctxt,cryptobox)|None->(letConstants_parametric_repr.{dal={cryptobox_parameters;_};_}=ctxt.back.constantsinmatchDal.makecryptobox_parameterswith|Okcryptobox->letback={ctxt.backwithdal_cryptobox=Somecryptobox}inreturn({ctxtwithback},cryptobox)|Error(`Failexplanation)->tzfail(Dal_errors_repr.Dal_cryptobox_error{explanation}))letnumber_of_slotsctxt=ctxt.back.constants.dal.number_of_slotsletnumber_of_shardsctxt=ctxt.back.constants.dal.cryptobox_parameters.number_of_shardsletrecord_number_of_attested_shardsctxtattestationnumber=letdal_attestation_slot_accountability=Dal_attestation_repr.Accountability.record_number_of_attested_shardsctxt.back.dal_attestation_slot_accountabilityattestationnumberin{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_commitment_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_shardsend(* 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