123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)moduleInt_set=Set.Make(Compare.Int)(*
Gas levels maintainance
=======================
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.
When gas is consumed, we must morally decrement these two levels to
check if one of them hits zero. However, since these decrements are
the same on both levels, it is not strictly necessary to update the
two levels: we can simply maintain the minimum of both levels in a
[gas_counter]. The meaning of [gas_counter] is denoted by
[gas_counter_status]: *)typegas_counter_status=(* When the operation gas is unaccounted: *)|Unlimited_operation_gas(* When the operation gas level is the minimum: *)|Count_operation_gasof{block_gas_delta:Gas_limit_repr.Arith.fp}(* When the block gas level is the minimum. *)|Count_block_gasof{operation_gas_delta:Gas_limit_repr.Arith.fp}(*
In each case, we keep enough information in [gas_counter_status] to
reconstruct the level that is not represented by [gas_counter]. In
the gas [Unlimited_operation_gas], the block gas level is stored
in [gas_counter].
[Raw_context] interface provides two accessors for the operation
gas level and the block gas level. These accessors compute these values
on-the-fly based on the current value of [gas_counter] and
[gas_counter_status].
A layered context
=================
Updating the context [gas_counter] 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
[gas_counter], 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 [gas_counter] update. This
has a significant impact on the Michelson runtime efficiency.
Here are the fields on the [back] of the context:
*)typeback={context:Context.t;constants:Constants_repr.parametric;first_level:Raw_level_repr.t;level:Level_repr.t;predecessor_timestamp:Time.t;timestamp:Time.t;fitness:Int64.t;deposits:Tez_repr.tSignature.Public_key_hash.Map.t;included_endorsements:int;allowed_endorsements:(Signature.Public_key.t*intlist*bool)Signature.Public_key_hash.Map.t;fees:Tez_repr.t;rewards:Tez_repr.t;storage_space_to_pay:Z.toption;allocated_contracts:intoption;origination_nonce:Contract_repr.origination_nonceoption;temporary_lazy_storage_ids:Lazy_storage_kind.Temp_ids.t;internal_nonce:int;internal_nonces_used:Int_set.t;gas_counter_status:gas_counter_status;}(*
The context is simply a record with two fields which
limits the cost of updating the [gas_counter].
*)typet={gas_counter: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]storage_space_to_payctxt=ctxt.back.storage_space_to_paylet[@inline]predecessor_timestampctxt=ctxt.back.predecessor_timestamplet[@inline]current_timestampctxt=ctxt.back.timestamplet[@inline]current_fitnessctxt=ctxt.back.fitnesslet[@inline]first_levelctxt=ctxt.back.first_levellet[@inline]constantsctxt=ctxt.back.constantslet[@inline]recoverctxt=ctxt.back.contextlet[@inline]feesctxt=ctxt.back.feeslet[@inline]origination_noncectxt=ctxt.back.origination_noncelet[@inline]depositsctxt=ctxt.back.depositslet[@inline]allowed_endorsementsctxt=ctxt.back.allowed_endorsementslet[@inline]included_endorsementsctxt=ctxt.back.included_endorsementslet[@inline]internal_noncectxt=ctxt.back.internal_noncelet[@inline]internal_nonces_usedctxt=ctxt.back.internal_nonces_usedlet[@inline]gas_counter_statusctxt=ctxt.back.gas_counter_statuslet[@inline]rewardsctxt=ctxt.back.rewardslet[@inline]allocated_contractsctxt=ctxt.back.allocated_contractslet[@inline]temporary_lazy_storage_idsctxt=ctxt.back.temporary_lazy_storage_idslet[@inline]gas_counterctxt=ctxt.gas_counterlet[@inline]update_gas_counterctxtgas_counter={ctxtwithgas_counter}let[@inline]update_backctxtback={ctxtwithback}let[@inline]update_gas_counter_statusctxtgas_counter_status=update_backctxt{ctxt.backwithgas_counter_status}let[@inline]update_contextctxtcontext=update_backctxt{ctxt.backwithcontext}let[@inline]update_constantsctxtconstants=update_backctxt{ctxt.backwithconstants}let[@inline]update_fitnessctxtfitness=update_backctxt{ctxt.backwithfitness}let[@inline]update_depositsctxtdeposits=update_backctxt{ctxt.backwithdeposits}let[@inline]update_allowed_endorsementsctxtallowed_endorsements=update_backctxt{ctxt.backwithallowed_endorsements}let[@inline]update_rewardsctxtrewards=update_backctxt{ctxt.backwithrewards}let[@inline]update_storage_space_to_payctxtstorage_space_to_pay=update_backctxt{ctxt.backwithstorage_space_to_pay}let[@inline]update_allocated_contractsctxtallocated_contracts=update_backctxt{ctxt.backwithallocated_contracts}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_included_endorsementsctxtincluded_endorsements=update_backctxt{ctxt.backwithincluded_endorsements}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}letrecord_endorsementctxtk=matchSignature.Public_key_hash.Map.find_optk(allowed_endorsementsctxt)with|None->assertfalse|Some(_,_,true)->assertfalse(* right already used *)|Some(d,s,false)->letctxt=update_included_endorsementsctxt(included_endorsementsctxt+List.lengths)inupdate_allowed_endorsementsctxt(Signature.Public_key_hash.Map.addk(d,s,true)(allowed_endorsementsctxt))letinit_endorsementsctxtallowed_endorsements'=ifSignature.Public_key_hash.Map.is_emptyallowed_endorsements'thenassertfalse(* can't initialize to empty *)elseifSignature.Public_key_hash.Map.is_empty(allowed_endorsementsctxt)thenupdate_allowed_endorsementsctxtallowed_endorsements'elseassertfalsetypeerror+=Too_many_internal_operations(* `Permanent *)typeerror+=Block_quota_exceeded(* `Temporary *)typeerror+=Operation_quota_exceeded(* `Temporary *)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)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)letset_current_fitnessctxtfitness=update_fitnessctxtfitnessletadd_feesctxtfees'=Tez_repr.(feesctxt+?fees')>|?update_feesctxtletadd_rewardsctxtrewards'=Tez_repr.(rewardsctxt+?rewards')>|?update_rewardsctxtletadd_depositctxtdelegatedeposit=letopenSignature.Public_key_hash.Mapinletprevious=matchfind_optdelegate(depositsctxt)with|Sometz->tz|None->Tez_repr.zeroinTez_repr.(previous+?deposit)>|?fundeposit->letdeposits=adddelegatedeposit(depositsctxt)inupdate_depositsctxtdepositsletget_deposits=depositsletget_rewards=rewardsletget_fees=feestypeerror+=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(Contract_repr.initial_origination_nonceoperation_hash)inupdate_origination_noncectxtorigination_nonceletincrement_origination_noncectxt=matchorigination_noncectxtwith|None->errorUndefined_operation_nonce|Somecur_origination_nonce->letorigination_nonce=Some(Contract_repr.incr_origination_noncecur_origination_nonce)inletctxt=update_origination_noncectxtorigination_nonceinok(ctxt,cur_origination_nonce)letorigination_noncectxt=matchorigination_noncectxtwith|None->errorUndefined_operation_nonce|Someorigination_nonce->okorigination_nonceletunset_origination_noncectxt=update_origination_noncectxtNonetypeerror+=Gas_limit_too_high(* `Permanent *)let()=letopenData_encodinginregister_error_kind`Permanent~id:"gas_limit_too_high"~title:"Gas limit out of protocol hard bounds"~description:"A transaction tried to exceed the hard limit on gas"empty(functionGas_limit_too_high->Some()|_->None)(fun()->Gas_limit_too_high)letgas_levelctxt=letopenGas_limit_reprinmatchgas_counter_statusctxtwith|Unlimited_operation_gas->Unaccounted|Count_block_gas{operation_gas_delta}->Limited{remaining=Arith.(add(gas_counterctxt)operation_gas_delta)}|Count_operation_gas_->Limited{remaining=gas_counterctxt}letblock_gas_levelctxt=letopenGas_limit_reprinmatchgas_counter_statusctxtwith|Unlimited_operation_gas|Count_block_gas_->gas_counterctxt|Count_operation_gas{block_gas_delta}->Arith.(add(gas_counterctxt)block_gas_delta)letcheck_gas_limitctxt(remaining:'aGas_limit_repr.Arith.t)=ifGas_limit_repr.Arith.(remaining>(constantsctxt).hard_gas_limit_per_operation||remaining<zero)thenerrorGas_limit_too_highelseok_unitletset_gas_limitctxt(remaining:'aGas_limit_repr.Arith.t)=letopenGas_limit_reprinletremaining=Arith.fpremaininginletblock_gas=block_gas_levelctxtinlet(gas_counter_status,gas_counter)=ifArith.(remaining<block_gas)thenletblock_gas_delta=Arith.subblock_gasremainingin(Count_operation_gas{block_gas_delta},remaining)elseletoperation_gas_delta=Arith.subremainingblock_gasin(Count_block_gas{operation_gas_delta},block_gas)inletctxt=update_gas_counter_statusctxtgas_counter_statusin{ctxtwithgas_counter}letset_gas_unlimitedctxt=letblock_gas=block_gas_levelctxtinletctxt={ctxtwithgas_counter=block_gas}inupdate_gas_counter_statusctxtUnlimited_operation_gasletis_gas_unlimitedctxt=matchctxt.back.gas_counter_statuswith|Unlimited_operation_gas->true|_->falseletis_counting_block_gasctxt=matchgas_counter_statusctxtwithCount_block_gas_->true|_->falseletconsume_gasctxtcost=ifis_gas_unlimitedctxtthenokctxtelsematchGas_limit_repr.raw_consume(gas_counterctxt)costwith|Somegas_counter->Ok(update_gas_counterctxtgas_counter)|None->ifis_counting_block_gasctxtthenerrorBlock_quota_exceededelseerrorOperation_quota_exceededletcheck_enough_gasctxtcost=consume_gasctxtcost>>?fun_->ok_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.zeroletinit_storage_space_to_payctxt=matchstorage_space_to_payctxtwith|Some_->assertfalse|None->letctxt=update_storage_space_to_payctxt(SomeZ.zero)inupdate_allocated_contractsctxt(Some0)letclear_storage_space_to_payctxt=match(storage_space_to_payctxt,allocated_contractsctxt)with|(None,_)|(_,None)->assertfalse|(Somestorage_space_to_pay,Someallocated_contracts)->letctxt=update_storage_space_to_payctxtNoneinletctxt=update_allocated_contractsctxtNonein(ctxt,storage_space_to_pay,allocated_contracts)letupdate_storage_space_to_payctxtn=matchstorage_space_to_payctxtwith|None->assertfalse|Somestorage_space_to_pay->update_storage_space_to_payctxt(Some(Z.addnstorage_space_to_pay))letupdate_allocated_contracts_countctxt=matchallocated_contractsctxtwith|None->assertfalse|Someallocated_contracts->update_allocated_contractsctxt(Some(succallocated_contracts))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="florence_009"letversion="v1"letfirst_level_key=[version;"first_level"]letconstants_key=[version;"constants"]letprotocol_param_key=["protocol_parameters"]letget_first_levelctxt=Context.findctxtfirst_level_key>|=function|None->storage_error(Missing_key(first_level_key,Get))|Somebytes->(matchData_encoding.Binary.of_bytesRaw_level_repr.encodingbyteswith|None->storage_error(Corrupted_datafirst_level_key)|Somelevel->oklevel)letset_first_levelctxtlevel=letbytes=Data_encoding.Binary.to_bytes_exnRaw_level_repr.encodinglevelinContext.addctxtfirst_level_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_bytesData_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->ok(param,ctxt)))letadd_constantsctxtconstants=letbytes=Data_encoding.Binary.to_bytes_exnConstants_repr.parametric_encodingconstantsinContext.addctxtconstants_keybytesletget_constantsctxt=Context.findctxtconstants_key>|=function|None->failwith"Internal error: cannot read constants in context."|Somebytes->(matchData_encoding.Binary.of_bytesConstants_repr.parametric_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)thenok_unitelsestorage_error(Incompatible_protocol_versions)letprepare~level~predecessor_timestamp~timestamp~fitnessctxt=Raw_level_repr.of_int32level>>?=funlevel->Fitness_repr.to_int64fitness>>?=funfitness->check_initedctxt>>=?fun()->get_constantsctxt>>=?funconstants->get_first_levelctxt>|=?funfirst_level->letlevel=Level_repr.level_from_raw~first_level~blocks_per_cycle:constants.Constants_repr.blocks_per_cycle~blocks_per_commitment:constants.Constants_repr.blocks_per_commitmentlevelin{gas_counter=Gas_limit_repr.Arith.fpconstants.Constants_repr.hard_gas_limit_per_block;back={context=ctxt;constants;level;predecessor_timestamp;timestamp;fitness;first_level;allowed_endorsements=Signature.Public_key_hash.Map.empty;included_endorsements=0;fees=Tez_repr.zero;rewards=Tez_repr.zero;deposits=Signature.Public_key_hash.Map.empty;storage_space_to_pay=None;allocated_contracts=None;origination_nonce=None;temporary_lazy_storage_ids=Lazy_storage_kind.Temp_ids.init;internal_nonce=0;internal_nonces_used=Int_set.empty;gas_counter_status=Unlimited_operation_gas;};}typeprevious_protocol=GenesisofParameters_repr.t|Edo_008letcheck_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="edo_008")thenreturn(Edo_008,ctxt)elseLwt.return@@storage_error(Incompatible_protocol_versions))>>=?fun(previous_proto,ctxt)->Context.addctxtversion_key(Bytes.of_stringversion_value)>|=functxt->ok(previous_proto,ctxt)letprepare_first_block~level~timestamp~fitnessctxt=check_and_update_protocol_versionctxt>>=?fun(previous_proto,ctxt)->(matchprevious_protowith|Genesisparam->Raw_level_repr.of_int32level>>?=funfirst_level->set_first_levelctxtfirst_level>>=?functxt->add_constantsctxtparam.constants>|=ok|Edo_008->returnctxt)>>=?functxt->preparectxt~level~predecessor_timestamp:timestamp~timestamp~fitness>|=?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>|=functionNone->storage_error(Missing_key(k,Get))|Somev->okvletget_treectxtk=Context.find_tree(contextctxt)k>|=functionNone->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~init~f=Context.fold?depth(contextctxt)k~init~fmoduleTree=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_treetkvendletprojectx=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_ids