12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Nomadic Development. <contact@tezcore.com> *)(* Copyright (c) 2021-2022 Nomadic Labs, <contact@nomadic-labs.com> *)(* Copyright (c) 2022 TriliTech <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. *)(* *)(*****************************************************************************)openProtocolopenEnvironmentopenAlpha_contextopenEnvironment.Error_monad(** The assumed number of blocks between operation-creation time and
the actual time when the operation is included in a block. *)letdefault_operation_inclusion_latency=3letparse_operation(op:Operation.raw)=matchData_encoding.Binary.of_bytes_optOperation.protocol_data_encodingop.protowith|Someprotocol_data->ok{shell=op.shell;protocol_data}|None->errorPlugin_errors.Cannot_parse_operationletpath=RPC_path.(open_root/"helpers")moduleRegistration=structletpatched_services=ref(RPC_directory.empty:Updater.rpc_contextRPC_directory.t)letregister0_fullctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(functxtqi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtqi)letregister0~chunkedsf=register0_fullctxt~chunkeds(fun{context;_}->fcontext)letregister0_fullctxt_successor_level~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(functxtqi->letmode=ifq#successor_levelthen`Successor_levelelse`Head_levelinServices_registration.rpc_initctxtmode>>=?functxt->fctxtqi)letregister0_successor_level~chunkedsf=register0_fullctxt_successor_level~chunkeds(fun{context;_}->fcontext)letregister0_noctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(fun_qi->fqi)letopt_register0_fullctxt~chunkedsf=patched_services:=RPC_directory.opt_register~chunked!patched_servicess(functxtqi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtqi)letopt_register0~chunkedsf=opt_register0_fullctxt~chunkeds(fun{context;_}->fcontext)letregister1_fullctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(fun(ctxt,arg)qi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtargqi)letopt_register1_fullctxt~chunkedsf=patched_services:=RPC_directory.opt_register~chunked!patched_servicess(fun(ctxt,arg)qi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtargqi)letregister1~chunkedsf=register1_fullctxt~chunkeds(fun{context;_}x->fcontextx)letopt_register1~chunkedsf=opt_register1_fullctxt~chunkeds(fun{context;_}x->fcontextx)letregister2_fullctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(fun((ctxt,arg1),arg2)qi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtarg1arg2qi)letregister2~chunkedsf=register2_fullctxt~chunkeds(fun{context;_}a1a2qi->fcontexta1a2qi)endletunparsing_mode_encoding=letopenScript_ir_translatorinletopenData_encodinginunion~tag_size:`Uint8[case(Tag0)~title:"Readable"(constant"Readable")(functionReadable->Some()|Optimized|Optimized_legacy->None)(fun()->Readable);case(Tag1)~title:"Optimized"(constant"Optimized")(functionOptimized->Some()|Readable|Optimized_legacy->None)(fun()->Optimized);case(Tag2)~title:"Optimized_legacy"(constant"Optimized_legacy")(functionOptimized_legacy->Some()|Readable|Optimized->None)(fun()->Optimized_legacy);]moduleScripts=structmoduleS=structopenData_encodingletpath=RPC_path.(path/"scripts")letrun_code_input_encoding=merge_objs(obj10(req"script"Script.expr_encoding)(req"storage"Script.expr_encoding)(req"input"Script.expr_encoding)(req"amount"Tez.encoding)(opt"balance"Tez.encoding)(req"chain_id"Chain_id.encoding)(opt"source"Contract.encoding)(opt"payer"Contract.encoding)(opt"self"Contract.originated_encoding)(dft"entrypoint"Entrypoint.simple_encodingEntrypoint.default))(obj4(opt"unparsing_mode"unparsing_mode_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"now"Script_timestamp.encoding)(opt"level"Script_int.n_encoding))letrun_code_output_encoding=conv(fun(storage,operations,lazy_storage_diff)->(storage,operations,lazy_storage_diff))(fun(storage,operations,lazy_storage_diff)->(storage,operations,lazy_storage_diff))(obj3(req"storage"Script.expr_encoding)(req"operations"(listApply_internal_results.internal_contents_encoding))(opt"lazy_storage_diff"Lazy_storage.encoding))lettrace_code_input_encoding=run_code_input_encodinglettrace_encoding=def"scripted.trace"@@list@@obj3(req"location"Script.location_encoding)(req"gas"Gas.encoding)(req"stack"(listScript.expr_encoding))lettrace_code_output_encoding=conv(fun(storage,operations,trace,lazy_storage_diff)->(storage,operations,trace,lazy_storage_diff))(fun(storage,operations,trace,lazy_storage_diff)->(storage,operations,trace,lazy_storage_diff))(obj4(req"storage"Script.expr_encoding)(req"operations"(listApply_internal_results.internal_contents_encoding))(req"trace"trace_encoding)(opt"lazy_storage_diff"Lazy_storage.encoding))letrun_tzip4_view_encoding=letopenData_encodinginobj10(req"contract"Contract.originated_encoding)(req"entrypoint"Entrypoint.simple_encoding)(req"input"Script.expr_encoding)(req"chain_id"Chain_id.encoding)(opt"source"Contract.encoding)(opt"payer"Contract.encoding)(opt"gas"Gas.Arith.z_integral_encoding)(req"unparsing_mode"unparsing_mode_encoding)(opt"now"Script_timestamp.encoding)(opt"level"Script_int.n_encoding)letrun_script_view_encoding=letopenData_encodinginmerge_objs(obj10(req"contract"Contract.originated_encoding)(req"view"string)(req"input"Script.expr_encoding)(dft"unlimited_gas"boolfalse)(req"chain_id"Chain_id.encoding)(opt"source"Contract.encoding)(opt"payer"Contract.encoding)(opt"gas"Gas.Arith.z_integral_encoding)(req"unparsing_mode"unparsing_mode_encoding)(opt"now"Script_timestamp.encoding))(obj1(opt"level"Script_int.n_encoding))letrun_code=RPC_service.post_service~description:"Run a piece of code in the current context"~query:RPC_query.empty~input:run_code_input_encoding~output:run_code_output_encodingRPC_path.(path/"run_code")lettrace_code=RPC_service.post_service~description:"Run a piece of code in the current context, keeping a trace"~query:RPC_query.empty~input:trace_code_input_encoding~output:trace_code_output_encodingRPC_path.(path/"trace_code")letrun_tzip4_view=RPC_service.post_service~description:"Simulate a call to a view following the TZIP-4 standard. See \
https://gitlab.com/tezos/tzip/-/blob/master/proposals/tzip-4/tzip-4.md#view-entrypoints."~input:run_tzip4_view_encoding~output:(obj1(req"data"Script.expr_encoding))~query:RPC_query.empty(* This path should be deprecated in the future *)RPC_path.(path/"run_view")letrun_script_view=RPC_service.post_service~description:"Simulate a call to a michelson view"~input:run_script_view_encoding~output:(obj1(req"data"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"run_script_view")lettypecheck_code=RPC_service.post_service~description:"Typecheck a piece of code in the current context"~query:RPC_query.empty~input:(obj4(req"program"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"legacy"bool)(opt"show_types"bool))~output:(obj2(req"type_map"Script_tc_errors_registration.type_map_enc)(req"gas"Gas.encoding))RPC_path.(path/"typecheck_code")letscript_size=RPC_service.post_service~description:"Compute the size of a script in the current context"~query:RPC_query.empty~input:(obj4(req"program"Script.expr_encoding)(req"storage"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"legacy"bool))~output:(obj1(req"script_size"int31))RPC_path.(path/"script_size")lettypecheck_data=RPC_service.post_service~description:"Check that some data expression is well formed and of a given type \
in the current context"~query:RPC_query.empty~input:(obj4(req"data"Script.expr_encoding)(req"type"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"legacy"bool))~output:(obj1(req"gas"Gas.encoding))RPC_path.(path/"typecheck_data")letpack_data=RPC_service.post_service~description:"Computes the serialized version of some data expression using the \
same algorithm as script instruction PACK"~input:(obj3(req"data"Script.expr_encoding)(req"type"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding))~output:(obj2(req"packed"bytes)(req"gas"Gas.encoding))~query:RPC_query.emptyRPC_path.(path/"pack_data")letnormalize_data=RPC_service.post_service~description:"Normalizes some data expression using the requested unparsing mode"~input:(obj4(req"data"Script.expr_encoding)(req"type"Script.expr_encoding)(req"unparsing_mode"unparsing_mode_encoding)(opt"legacy"bool))~output:(obj1(req"normalized"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"normalize_data")letnormalize_script=RPC_service.post_service~description:"Normalizes a Michelson script using the requested unparsing mode"~input:(obj2(req"script"Script.expr_encoding)(req"unparsing_mode"unparsing_mode_encoding))~output:(obj1(req"normalized"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"normalize_script")letnormalize_type=RPC_service.post_service~description:"Normalizes some Michelson type by expanding `pair a b c` as `pair a \
(pair b c)"~input:(obj1(req"type"Script.expr_encoding))~output:(obj1(req"normalized"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"normalize_type")letrun_operation=RPC_service.post_service~description:"Run an operation with the context of the given block and without \
signature checks. Return the operation application result, \
including the consumed gas."~query:RPC_query.empty~input:(obj2(req"operation"Operation.encoding)(req"chain_id"Chain_id.encoding))~output:Apply_results.operation_data_and_metadata_encodingRPC_path.(path/"run_operation")letsimulate_query=letopenRPC_queryinquery(funsuccessor_level->objectmethodsuccessor_level=successor_levelend)|+flag~descr:"If true, the simulation is done on the successor level of the \
current context.""successor_level"(funt->t#successor_level)|>sealletsimulate_operation=RPC_service.post_service~description:"Simulate running an operation at some future moment (based on the \
number of blocks given in the `latency` argument), and return the \
operation application result. The result is the same as \
run_operation except for the consumed gas, which depends on the \
contents of the cache at that future moment. This RPC estimates \
future gas consumption by trying to predict the state of the cache \
using some heuristics."~query:simulate_query~input:(obj4(opt"blocks_before_activation"int32)(req"operation"Operation.encoding)(req"chain_id"Chain_id.encoding)(dft"latency"int16default_operation_inclusion_latency))~output:Apply_results.operation_data_and_metadata_encodingRPC_path.(path/"simulate_operation")letsimulate_tx_rollup_operation=RPC_service.post_service~description:"Simulate a tx rollup operation"~query:RPC_query.empty~input:(obj4(opt"blocks_before_activation"int32)(req"operation"Operation.encoding)(req"chain_id"Chain_id.encoding)(dft"latency"int16default_operation_inclusion_latency))~output:Apply_results.operation_data_and_metadata_encodingRPC_path.(path/"simulate_tx_rollup_operation")letentrypoint_type=RPC_service.post_service~description:"Return the type of the given entrypoint"~query:RPC_query.empty~input:(obj2(req"script"Script.expr_encoding)(dft"entrypoint"Entrypoint.simple_encodingEntrypoint.default))~output:(obj1(req"entrypoint_type"Script.expr_encoding))RPC_path.(path/"entrypoint")letlist_entrypoints=RPC_service.post_service~description:"Return the list of entrypoints of the given script"~query:RPC_query.empty~input:(obj1(req"script"Script.expr_encoding))~output:(obj2(dft"unreachable"(Data_encoding.list(obj1(req"path"(Data_encoding.listMichelson_v1_primitives.prim_encoding))))[])(req"entrypoints"(assocScript.expr_encoding)))RPC_path.(path/"entrypoints")endmoduletypeUNPARSING_MODE=sigvalunparsing_mode:Script_ir_translator.unparsing_modeendmoduleTraced_interpreter(Unparsing_mode:UNPARSING_MODE)=structtypelog_element=|Log:context*Script.location*('a*'s)*('a,'s)Script_typed_ir.stack_ty->log_elementletunparse_stackctxt(stack,stack_ty)=(* We drop the gas limit as this function is only used for debugging/errors. *)letctxt=Gas.set_unlimitedctxtinletrecunparse_stack:typeas.(a,s)Script_typed_ir.stack_ty*(a*s)->Script.exprlisttzresultLwt.t=function|Bot_t,(EmptyCell,EmptyCell)->return_nil|Item_t(ty,rest_ty),(v,rest)->Script_ir_translator.unparse_datactxtUnparsing_mode.unparsing_modetyv>>=?fun(data,_ctxt)->unparse_stack(rest_ty,rest)>|=?funrest->letdata=Micheline.strip_locationsdataindata::restinunparse_stack(stack_ty,stack)lettrace_logger():Script_typed_ir.logger=letlog:log_elementlistref=ref[]inletlog_interp_ctxtlocstystack=log:=Log(ctxt,loc,stack,sty)::!loginletlog_entry__ctxt_loc_sty_stack=()inletlog_exit_ctxtlocstystack=log:=Log(ctxt,loc,stack,sty)::!loginletlog_control_=()inletget_log()=List.map_es(fun(Log(ctxt,loc,stack,stack_ty))->tracePlugin_errors.Cannot_serialize_log(unparse_stackctxt(stack,stack_ty))>>=?funstack->return(loc,Gas.levelctxt,stack))!log>>=?funres->return(Some(List.revres))in{log_exit;log_entry;log_interp;get_log;log_control}letexecutectxtstep_constants~script~entrypoint~parameter=letopenScript_interpreterinletlogger=trace_logger()inexecute~logger~cached_script:NonectxtUnparsing_mode.unparsing_modestep_constants~script~entrypoint~parameter~internal:true>>=?funres->logger.get_log()>|=?funtrace->lettrace=Option.value~default:[]tracein(res,trace)endlettypecheck_data:legacy:bool->context->Script.expr*Script.expr->contexttzresultLwt.t=fun~legacyctxt(data,exp_ty)->record_trace(Script_tc_errors.Ill_formed_type(None,exp_ty,0))(Script_ir_translator.parse_passable_tyctxt~legacy(Micheline.rootexp_ty))>>?=fun(Ex_tyexp_ty,ctxt)->trace_eval(fun()->letexp_ty=Script_ir_translator.serialize_ty_for_errorexp_tyinScript_tc_errors.Ill_typed_data(None,data,exp_ty))(letallow_forged=true(* Safe since we ignore the value afterwards. *)inScript_ir_translator.parse_datactxt~legacy~allow_forgedexp_ty(Micheline.rootdata))>|=?fun(_,ctxt)->ctxtmoduleUnparse_types=struct(* Same as the unparsing functions for types in Script_ir_translator but
does not consume gas and never folds (pair a (pair b c)) *)openMichelineopenMichelson_v1_primitivesopenScript_typed_irletunparse_memo_size~locmemo_size=letz=Alpha_context.Sapling.Memo_size.unparse_to_zmemo_sizeinInt(loc,z)letrecunparse_ty:typeaacloc.loc:loc->(a,ac)ty->(loc,Script.prim)Micheline.node=fun~locty->letreturn(name,args,annot)=Prim(loc,name,args,annot)inmatchtywith|Unit_t->return(T_unit,[],[])|Int_t->return(T_int,[],[])|Nat_t->return(T_nat,[],[])|Signature_t->return(T_signature,[],[])|String_t->return(T_string,[],[])|Bytes_t->return(T_bytes,[],[])|Mutez_t->return(T_mutez,[],[])|Bool_t->return(T_bool,[],[])|Key_hash_t->return(T_key_hash,[],[])|Key_t->return(T_key,[],[])|Timestamp_t->return(T_timestamp,[],[])|Address_t->return(T_address,[],[])|Tx_rollup_l2_address_t->return(T_tx_rollup_l2_address,[],[])|Operation_t->return(T_operation,[],[])|Chain_id_t->return(T_chain_id,[],[])|Never_t->return(T_never,[],[])|Bls12_381_g1_t->return(T_bls12_381_g1,[],[])|Bls12_381_g2_t->return(T_bls12_381_g2,[],[])|Bls12_381_fr_t->return(T_bls12_381_fr,[],[])|Contract_t(ut,_meta)->lett=unparse_ty~locutinreturn(T_contract,[t],[])|Pair_t(utl,utr,_meta,_)->letannot=[]inlettl=unparse_ty~locutlinlettr=unparse_ty~locutrinreturn(T_pair,[tl;tr],annot)|Union_t(utl,utr,_meta,_)->letannot=[]inlettl=unparse_ty~locutlinlettr=unparse_ty~locutrinreturn(T_or,[tl;tr],annot)|Lambda_t(uta,utr,_meta)->letta=unparse_ty~locutainlettr=unparse_ty~locutrinreturn(T_lambda,[ta;tr],[])|Option_t(ut,_meta,_)->letannot=[]inletut=unparse_ty~locutinreturn(T_option,[ut],annot)|List_t(ut,_meta)->lett=unparse_ty~locutinreturn(T_list,[t],[])|Ticket_t(ut,_meta)->lett=unparse_ty~locutinreturn(T_ticket,[t],[])|Set_t(ut,_meta)->lett=unparse_ty~locutinreturn(T_set,[t],[])|Map_t(uta,utr,_meta)->letta=unparse_ty~locutainlettr=unparse_ty~locutrinreturn(T_map,[ta;tr],[])|Big_map_t(uta,utr,_meta)->letta=unparse_ty~locutainlettr=unparse_ty~locutrinreturn(T_big_map,[ta;tr],[])|Sapling_transaction_tmemo_size->return(T_sapling_transaction,[unparse_memo_size~locmemo_size],[])|Sapling_transaction_deprecated_tmemo_size->return(T_sapling_transaction_deprecated,[unparse_memo_size~locmemo_size],[])|Sapling_state_tmemo_size->return(T_sapling_state,[unparse_memo_size~locmemo_size],[])|Chest_t->return(T_chest,[],[])|Chest_key_t->return(T_chest_key,[],[])endletrecpp_instr_name:typeabcd.Format.formatter->(a,b,c,d)Script_typed_ir.kinstr->unit=letopenScript_typed_irinletopenFormatinfunfmt->function|IDrop_->pp_print_stringfmt"DROP"|IDup_->pp_print_stringfmt"DUP"|ISwap_->pp_print_stringfmt"SWAP"|IConst_->pp_print_stringfmt"CONST"|ICons_pair_->pp_print_stringfmt"PAIR"|ICar_->pp_print_stringfmt"CAR"|ICdr_->pp_print_stringfmt"CDR"|IUnpair_->pp_print_stringfmt"UNPAIR"|ICons_some_->pp_print_stringfmt"SOME"|ICons_none_->pp_print_stringfmt"NONE"|IIf_none_->pp_print_stringfmt"IF_NONE"|IOpt_map_->pp_print_stringfmt"MAP"|ICons_left_->pp_print_stringfmt"LEFT"|ICons_right_->pp_print_stringfmt"RIGHT"|IIf_left_->pp_print_stringfmt"IF_LEFT"|ICons_list_->pp_print_stringfmt"CONS"|INil_->pp_print_stringfmt"NIL"|IIf_cons_->pp_print_stringfmt"IF_CONS"|IList_map_->pp_print_stringfmt"MAP"|IList_iter_->pp_print_stringfmt"ITER"|IList_size_->pp_print_stringfmt"SIZE"|IEmpty_set_->pp_print_stringfmt"EMPTY_SET"|ISet_iter_->pp_print_stringfmt"ITER"|ISet_mem_->pp_print_stringfmt"MEM"|ISet_update_->pp_print_stringfmt"UPDATE"|ISet_size_->pp_print_stringfmt"SIZE"|IEmpty_map_->pp_print_stringfmt"EMPTY_MAP"|IMap_map_->pp_print_stringfmt"MAP"|IMap_iter_->pp_print_stringfmt"ITER"|IMap_mem_->pp_print_stringfmt"MEM"|IMap_get_->pp_print_stringfmt"GET"|IMap_update_->pp_print_stringfmt"UPDATE"|IMap_get_and_update_->pp_print_stringfmt"GET_AND_UPDATE"|IMap_size_->pp_print_stringfmt"SIZE"|IEmpty_big_map_->pp_print_stringfmt"EMPTY_BIG_MAP"|IBig_map_mem_->pp_print_stringfmt"MEM"|IBig_map_get_->pp_print_stringfmt"GET"|IBig_map_update_->pp_print_stringfmt"UPDATE"|IBig_map_get_and_update_->pp_print_stringfmt"GET_AND_UPDATE"|IConcat_string_->pp_print_stringfmt"CONCAT"|IConcat_string_pair_->pp_print_stringfmt"CONCAT"|ISlice_string_->pp_print_stringfmt"SLICE"|IString_size_->pp_print_stringfmt"SIZE"|IConcat_bytes_->pp_print_stringfmt"CONCAT"|IConcat_bytes_pair_->pp_print_stringfmt"CONCAT"|ISlice_bytes_->pp_print_stringfmt"SLICE"|IBytes_size_->pp_print_stringfmt"SIZE"|IAdd_seconds_to_timestamp_->pp_print_stringfmt"ADD"|IAdd_timestamp_to_seconds_->pp_print_stringfmt"ADD"|ISub_timestamp_seconds_->pp_print_stringfmt"SUB"|IDiff_timestamps_->pp_print_stringfmt"DIFF"|IAdd_tez_->pp_print_stringfmt"ADD"|ISub_tez_->pp_print_stringfmt"SUB_MUTEZ"|ISub_tez_legacy_->pp_print_stringfmt"SUB"|IMul_teznat_|IMul_nattez_->pp_print_stringfmt"MUL"|IEdiv_teznat_->pp_print_stringfmt"EDIV"|IEdiv_tez_->pp_print_stringfmt"EDIV"|IOr_->pp_print_stringfmt"OR"|IAnd_->pp_print_stringfmt"AND"|IXor_->pp_print_stringfmt"XOR"|INot_->pp_print_stringfmt"NOT"|IIs_nat_->pp_print_stringfmt"ISNAT"|INeg_->pp_print_stringfmt"NEG"|IAbs_int_->pp_print_stringfmt"ABS"|IInt_nat_->pp_print_stringfmt"INT"|IAdd_int_|IAdd_nat_->pp_print_stringfmt"ADD"|ISub_int_->pp_print_stringfmt"SUB"|IMul_int_|IMul_nat_->pp_print_stringfmt"MUL"|IEdiv_int_|IEdiv_nat_->pp_print_stringfmt"EDIV"|ILsl_nat_->pp_print_stringfmt"LSL"|ILsr_nat_->pp_print_stringfmt"LSR"|IOr_nat_->pp_print_stringfmt"OR"|IAnd_nat_->pp_print_stringfmt"AND"|IAnd_int_nat_->pp_print_stringfmt"AND"|IXor_nat_->pp_print_stringfmt"XOR"|INot_int_->pp_print_stringfmt"NOT"|IIf_->pp_print_stringfmt"IF"|ILoop_->pp_print_stringfmt"LOOP"|ILoop_left_->pp_print_stringfmt"LOOP_LEFT"|IDip_->pp_print_stringfmt"DIP"|IExec_->pp_print_stringfmt"EXEC"|IApply_->pp_print_stringfmt"APPLY"|ILambda_->pp_print_stringfmt"LAMBDA"|IFailwith_->pp_print_stringfmt"FAILWITH"|ICompare_->pp_print_stringfmt"COMPARE"|IEq_->pp_print_stringfmt"EQ"|INeq_->pp_print_stringfmt"NEQ"|ILt_->pp_print_stringfmt"LT"|IGt_->pp_print_stringfmt"GT"|ILe_->pp_print_stringfmt"LE"|IGe_->pp_print_stringfmt"GE"|IAddress_->pp_print_stringfmt"ADDRESS"|IContract_->pp_print_stringfmt"CONTACT"|IView_->pp_print_stringfmt"VIEW"|ITransfer_tokens_->pp_print_stringfmt"TRANSFER_TOKENS"|IImplicit_account_->pp_print_stringfmt"IMPLICIT_ACCOUNT"|ICreate_contract_->pp_print_stringfmt"CREATE_CONTRACT"|ISet_delegate_->pp_print_stringfmt"SET_DELEGATE"|INow_->pp_print_stringfmt"NOW"|IMin_block_time_->pp_print_stringfmt"MIN_BLOCK_TIME"|IBalance_->pp_print_stringfmt"BALANCE"|ILevel_->pp_print_stringfmt"LEVEL"|ICheck_signature_->pp_print_stringfmt"CHECK_SIGNATURE"|IHash_key_->pp_print_stringfmt"HASH_KEY"|IPack_->pp_print_stringfmt"PACK"|IBlake2b_->pp_print_stringfmt"BLAKE2B"|ISha3_->pp_print_stringfmt"SHA3"|ISha256_->pp_print_stringfmt"SHA256"|ISha512_->pp_print_stringfmt"SHA512"|IUnpack_->pp_print_stringfmt"UNPACK"|ISource_->pp_print_stringfmt"SOURCE"|ISender_->pp_print_stringfmt"SENDER"|ISelf_->pp_print_stringfmt"SELF"|ISelf_address_->pp_print_stringfmt"SELF_ADDRESS"|IAmount_->pp_print_stringfmt"AMOUNT"|ISapling_empty_state_->pp_print_stringfmt"SAPLING_EMPTY_STATE"|ISapling_verify_update_|ISapling_verify_update_deprecated_->pp_print_stringfmt"SAPLING_VERIFY_UPDATE"|IDig_->pp_print_stringfmt"DIG"|IDug_->pp_print_stringfmt"DUG"|IDipn_->pp_print_stringfmt"DIP"|IDropn_->pp_print_stringfmt"DROP"|IChainId_->pp_print_stringfmt"CHAIN_ID"|INever_->pp_print_stringfmt"NEVER"|IVoting_power_->pp_print_stringfmt"VOTING_POWER"|ITotal_voting_power_->pp_print_stringfmt"TOTAL_VOTING_POWER"|IKeccak_->pp_print_stringfmt"KECCAK"|IAdd_bls12_381_g1_|IAdd_bls12_381_g2_|IAdd_bls12_381_fr_->pp_print_stringfmt"ADD"|IMul_bls12_381_g1_|IMul_bls12_381_g2_|IMul_bls12_381_fr_|IMul_bls12_381_z_fr_|IMul_bls12_381_fr_z_->pp_print_stringfmt"MUL"|IInt_bls12_381_fr_->pp_print_stringfmt"INT"|INeg_bls12_381_g1_|INeg_bls12_381_g2_|INeg_bls12_381_fr_->pp_print_stringfmt"NEG"|IPairing_check_bls12_381_->pp_print_stringfmt"PAIRING_CHECK"|IComb_->pp_print_stringfmt"PAIR"|IUncomb_->pp_print_stringfmt"UNPAIR"|IComb_get_->pp_print_stringfmt"GET"|IComb_set_->pp_print_stringfmt"UPDATE"|IDup_n_->pp_print_stringfmt"DUP"|ITicket_->pp_print_stringfmt"TICKET"|IRead_ticket_->pp_print_stringfmt"READ_TICKET"|ISplit_ticket_->pp_print_stringfmt"SPLIT_TICKET"|IJoin_tickets_->pp_print_stringfmt"JOIN_TICKETS"|IOpen_chest_->pp_print_stringfmt"OPEN_CHEST"|IEmit_->pp_print_stringfmt"EMIT"|IHalt_->pp_print_stringfmt"[halt]"|ILog(_,_,_,_,instr)->Format.fprintffmt"log/%a"pp_instr_nameinstrletrun_operation_servicectxt()({shell;protocol_data=Operation_dataprotocol_data},chain_id)=(* this code is a duplicate of Apply without signature check *)letretcontents=(Operation_dataprotocol_data,Apply_results.Operation_metadata{contents})inletoperation:_operation={shell;protocol_data}inlethash=Operation.hash{shell;protocol_data}inletctxt=Origination_nonce.initctxthashinletpayload_producer=Tezos_crypto.Signature.V0.Public_key_hash.zeroinValidate_operation.TMP_for_plugin.precheck_manager__do_nothing_on_non_manager_opctxtchain_idprotocol_data.contentsSkip_signature_check>>=?funop_validated_stamp->matchprotocol_data.contentswith|Single(Manager_operation_)asop->Apply.apply_manager_operationctxtOptimized~payload_producerchain_id~mempool_mode:trueop_validated_stampop>|=?fun(_ctxt,result)->retresult|Cons(Manager_operation_,_)asop->Apply.apply_manager_operationctxtOptimized~payload_producerchain_id~mempool_mode:trueop_validated_stampop>|=?fun(_ctxt,result)->retresult|_->letpredecessor_level=matchAlpha_context.Level.predctxt(Alpha_context.Level.currentctxt)with|Somelevel->level|None->assertfalseinAlpha_context.Round.getctxt>>=?funpredecessor_round->Apply.apply_contents_listctxtchain_id(Partial_construction{predecessor_level;predecessor_round;grand_parent_round=Round.zero;})Optimized~payload_producerop_validated_stampoperationoperation.protocol_data.contents>|=?fun(_ctxt,result)->retresult(*
The execution of an operation depends on the state of the
cache. In particular, gas consumption is usually impacted by
cache hits and misses.
Unfortunately, the state of the cache is different between the
context at operation-creation time and the context when is
included in a block.
Therefore, the simulation tries to predict the state of the
cache in a [time_in_blocks] assumed to be close to the inclusion
time of the operation.
*)letsimulate_operation_servicectxt(_simulate_query:<successor_level:bool>)(blocks_before_activation,op,chain_id,time_in_blocks)=Cache.Admin.future_cache_expectationctxt~time_in_blocks?blocks_before_activation>>=?functxt->run_operation_servicectxt()(op,chain_id)letdefault_from_contextctxtget=function|None->getctxt|Somex->returnx(* A convenience type for return values of [ensure_contracts_exist] below. *)typerun_code_config={balance:Tez.t;self:Contract_hash.t;payer:Contract.t;source:Contract.t;}(* 4_000_000 ꜩ *)letdefault_balance=Tez.of_mutez_exn4_000_000_000_000Lletregister()=letoriginate_dummy_contractctxtscriptbalance=letctxt=Origination_nonce.initctxtOperation_hash.zeroinContract.fresh_contract_from_current_noncectxt>>?=fun(ctxt,dummy_contract_hash)->letdummy_contract=Contract.Originateddummy_contract_hashinContract.raw_originatectxt~prepaid_bootstrap_storage:falsedummy_contract_hash~script:(script,None)>>=?functxt->Token.transfer~origin:Simulationctxt`Minted(`Contractdummy_contract)balance>>=?fun(ctxt,_)->return(ctxt,dummy_contract_hash)inletconfigure_contractsctxtscriptbalance~src_opt~pay_opt~self_opt=(matchself_optwith|None->letbalance=Option.value~default:default_balancebalanceinoriginate_dummy_contractctxtscriptbalance>>=?fun(ctxt,addr)->return(ctxt,addr,balance)|Someaddr->default_from_contextctxt(func->Contract.get_balancec@@Contract.Originatedaddr)balance>>=?funbal->return(ctxt,addr,bal))>>=?fun(ctxt,self,balance)->letsource,payer=match(src_opt,pay_opt)with|None,None->letself=Contract.Originatedselfin(self,self)|Somec,None|None,Somec->(c,c)|Somesrc,Somepay->(src,pay)inreturn(ctxt,{balance;self;source;payer})inletscript_entrypoint_typectxtexprentrypoint=letctxt=Gas.set_unlimitedctxtinletlegacy=falseinletopenScript_ir_translatorinparse_toplevelctxt~legacyexpr>>=?fun({arg_type;_},ctxt)->Lwt.return(parse_parameter_ty_and_entrypointsctxt~legacyarg_type>>?fun(Ex_parameter_ty_and_entrypoints{arg_type;entrypoints},_)->Gas_monad.runctxt@@Script_ir_translator.find_entrypoint~error_details:(Informative())arg_typeentrypointsentrypoint>>?fun(r,_ctxt)->r>|?fun(Ex_ty_cstr{original_type_expr;_})->Micheline.strip_locationsoriginal_type_expr)inletscript_view_typectxtcontractexprview=letctxt=Gas.set_unlimitedctxtinletlegacy=falseinletopenScript_ir_translatorinparse_toplevelctxt~legacyexpr>>=?fun({views;_},_)->Lwt.return(Script_string.of_stringview>>?funview_name->matchScript_map.getview_nameviewswith|None->error(View_helpers.View_not_found(contract,view))|SomeScript_typed_ir.{input_ty;output_ty;_}->ok(input_ty,output_ty))inRegistration.register0~chunked:trueS.run_code(functxt()((code,storage,parameter,amount,balance,chain_id,src_opt,pay_opt,self_opt,entrypoint),(unparsing_mode,gas,now,level))->letunparsing_mode=Option.value~default:Readableunparsing_modeinletstorage=Script.lazy_exprstorageinletcode=Script.lazy_exprcodeinconfigure_contractsctxt{storage;code}balance~src_opt~pay_opt~self_opt>>=?fun(ctxt,{self;source;payer;balance})->letgas=matchgaswith|Somegas->gas|None->Constants.hard_gas_limit_per_operationctxtinletctxt=Gas.set_limitctxtgasinletnow=matchnowwithNone->Script_timestamp.nowctxt|Somet->tinletlevel=matchlevelwith|None->(Level.currentctxt).level|>Raw_level.to_int32|>Script_int.of_int32|>Script_int.abs|Somez->zinletstep_constants=letopenScript_interpreterin{source;payer;self;amount;balance;chain_id;now;level}inScript_interpreter.executectxtunparsing_modestep_constants~cached_script:None~script:{storage;code}~entrypoint~parameter~internal:true>|=?fun({script=_;code_size=_;Script_interpreter.storage;operations;lazy_storage_diff;ticket_diffs=_;},_)->(storage,Apply_internal_results.contents_of_packed_internal_operationsoperations,lazy_storage_diff));Registration.register0~chunked:trueS.trace_code(functxt()((code,storage,parameter,amount,balance,chain_id,src_opt,pay_opt,self_opt,entrypoint),(unparsing_mode,gas,now,level))->letunparsing_mode=Option.value~default:Readableunparsing_modeinletstorage=Script.lazy_exprstorageinletcode=Script.lazy_exprcodeinconfigure_contractsctxt{storage;code}balance~src_opt~pay_opt~self_opt>>=?fun(ctxt,{self;source;payer;balance})->letgas=matchgaswith|Somegas->gas|None->Constants.hard_gas_limit_per_operationctxtinletctxt=Gas.set_limitctxtgasinletnow=matchnowwithNone->Script_timestamp.nowctxt|Somet->tinletlevel=matchlevelwith|None->(Level.currentctxt).level|>Raw_level.to_int32|>Script_int.of_int32|>Script_int.abs|Somez->zinletstep_constants=letopenScript_interpreterin{source;payer;self;amount;balance;chain_id;now;level}inletmoduleUnparsing_mode=structletunparsing_mode=unparsing_modeendinletmoduleInterp=Traced_interpreter(Unparsing_mode)inInterp.executectxtstep_constants~script:{storage;code}~entrypoint~parameter>|=?fun(({script=_;code_size=_;Script_interpreter.storage;operations;lazy_storage_diff;ticket_diffs=_;},_ctxt),trace)->(storage,Apply_internal_results.contents_of_packed_internal_operationsoperations,trace,lazy_storage_diff));Registration.register0~chunked:trueS.run_tzip4_view(functxt()(contract_hash,entrypoint,input,chain_id,source,payer,gas,unparsing_mode,now,level)->Contract.get_scriptctxtcontract_hash>>=?fun(ctxt,script_opt)->Option.fold~some:ok~none:(errorView_helpers.Viewed_contract_has_no_script)script_opt>>?=funscript->Script_repr.(force_decodescript.code)>>?=fundecoded_script->script_entrypoint_typectxtdecoded_scriptentrypoint>>=?funview_ty->View_helpers.extract_view_output_typeentrypointview_ty>>?=funty->letcontract=Contract.Originatedcontract_hashinContract.get_balancectxtcontract>>=?funbalance->Error_monad.traceView_helpers.View_callback_origination_failed@@originate_dummy_contractctxt(View_helpers.make_tzip4_viewer_scriptty)Tez.zero>>=?fun(ctxt,viewer_contract)->letsource,payer=match(source,payer)with|Somesource,Somepayer->(source,payer)|Somesource,None->(source,source)|None,Somepayer->(payer,payer)|None,None->(contract,contract)inletgas=Option.value~default:(Constants.hard_gas_limit_per_operationctxt)gasinletctxt=Gas.set_limitctxtgasinletnow=matchnowwithNone->Script_timestamp.nowctxt|Somet->tinletlevel=matchlevelwith|None->(Level.currentctxt).level|>Raw_level.to_int32|>Script_int.of_int32|>Script_int.abs|Somez->zinletstep_constants=letopenScript_interpreterin{source;payer;self=contract_hash;amount=Tez.zero;balance;chain_id;now;level;}inletparameter=View_helpers.make_view_parameter(Micheline.rootinput)(Contract.Originatedviewer_contract)inScript_interpreter.executectxtunparsing_modestep_constants~script~cached_script:None~entrypoint~parameter~internal:true>>=?fun({Script_interpreter.operations;script=_;code_size=_;storage=_;lazy_storage_diff=_;ticket_diffs=_;},_ctxt)->Lwt.return(View_helpers.extract_parameter_from_operationsentrypointoperationsviewer_contract));Registration.register0~chunked:trueS.run_script_view(functxt()((contract_hash,view,input,unlimited_gas,chain_id,source,payer,gas,unparsing_mode,now),level)->Contract.get_scriptctxtcontract_hash>>=?fun(ctxt,script_opt)->Option.fold~some:ok~none:(Error_monad.errorView_helpers.Viewed_contract_has_no_script)script_opt>>?=funscript->Script_repr.(force_decodescript.code)>>?=fundecoded_script->letcontract=Contract.Originatedcontract_hashinscript_view_typectxtcontract_hashdecoded_scriptview>>=?fun(input_ty,output_ty)->Contract.get_balancectxtcontract>>=?funbalance->letsource,payer=match(source,payer)with|Somesource,Somepayer->(source,payer)|Somesource,None->(source,source)|None,Somepayer->(payer,payer)|None,None->(contract,contract)inletnow=matchnowwithNone->Script_timestamp.nowctxt|Somet->tin(* Using [Gas.set_unlimited] won't work, since the interpreter doesn't
use this mode (see !4034#note_774734253) and still consumes gas.
Our best shot to emulate this is to use the maximum amount of
milligas possible which is represented by [2^62 - 1] according to
[Saturation_repr.saturated], which is [max_int]. *)letmax_gas=Gas.fp_of_milligas_intmax_intinletgas=Option.value~default:(Constants.hard_gas_limit_per_operationctxt)gasinletctxt=ifunlimited_gasthenGas.set_limitctxtmax_gaselseGas.set_limitctxtgasinletlevel=Option.valuelevel~default:((Level.currentctxt).level|>Raw_level.to_int32|>Script_int.of_int32|>Script_int.abs)inletstep_constants={Script_interpreter.source;payer;self=contract_hash;amount=Tez.zero;balance;chain_id;now;level;}inletviewer_script=View_helpers.make_michelson_viewer_scriptcontractviewinputinput_tyoutput_tyinletparameter=Micheline.(strip_locations(Prim(0,Script.D_Unit,[],[])))inScript_interpreter.executectxtunparsing_modestep_constants~script:viewer_script~cached_script:None~entrypoint:Entrypoint.default~parameter~internal:true>>=?fun({Script_interpreter.operations=_;script=_;code_size=_;storage;lazy_storage_diff=_;ticket_diffs=_;},_ctxt)->View_helpers.extract_value_from_storagestorage>>?=funvalue->return(Micheline.strip_locationsvalue));Registration.register0~chunked:falseS.typecheck_code(functxt()(expr,maybe_gas,legacy,show_types)->letlegacy=Option.value~default:falselegacyinletshow_types=Option.value~default:trueshow_typesinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasinScript_ir_translator.typecheck_code~legacy~show_typesctxtexpr>|=?fun(res,ctxt)->(res,Gas.levelctxt));Registration.register0~chunked:falseS.script_size(functxt()(expr,storage,maybe_gas,legacy)->letlegacy=Option.value~default:falselegacyinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasinletcode=Script.lazy_exprexprinScript_ir_translator.parse_code~legacyctxt~code>>=?fun(Ex_code(Code{code;arg_type;storage_type;views;entrypoints;code_size;}),ctxt)->Script_ir_translator.parse_data~legacy~allow_forged:truectxtstorage_type(Micheline.rootstorage)>>=?fun(storage,_)->letscript=Script_ir_translator.Ex_script(Script{code;arg_type;storage_type;views;entrypoints;code_size;storage;})inletsize,cost=Script_ir_translator.script_sizescriptinGas.consumectxtcost>>?=fun_ctxt->return@@size);Registration.register0~chunked:falseS.typecheck_data(functxt()(data,ty,maybe_gas,legacy)->letlegacy=Option.value~default:falselegacyinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasintypecheck_data~legacyctxt(data,ty)>|=?functxt->Gas.levelctxt);Registration.register0~chunked:trueS.pack_data(functxt()(expr,typ,maybe_gas)->letopenScript_ir_translatorinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasinparse_packable_tyctxt~legacy:true(Micheline.roottyp)>>?=fun(Ex_tytyp,ctxt)->parse_datactxt~legacy:true~allow_forged:truetyp(Micheline.rootexpr)>>=?fun(data,ctxt)->Script_ir_translator.pack_datactxttypdata>|=?fun(bytes,ctxt)->(bytes,Gas.levelctxt));Registration.register0~chunked:trueS.normalize_data(functxt()(expr,typ,unparsing_mode,legacy)->letopenScript_ir_translatorinletlegacy=Option.value~default:falselegacyinletctxt=Gas.set_unlimitedctxtinScript_ir_translator.parse_any_tyctxt~legacy(Micheline.roottyp)>>?=fun(Ex_tytyp,ctxt)->parse_datactxt~legacy~allow_forged:truetyp(Micheline.rootexpr)>>=?fun(data,ctxt)->Script_ir_translator.unparse_datactxtunparsing_modetypdata>|=?fun(normalized,_ctxt)->Micheline.strip_locationsnormalized);Registration.register0~chunked:trueS.normalize_script(functxt()(script,unparsing_mode)->letctxt=Gas.set_unlimitedctxtinScript_ir_translator.unparse_codectxtunparsing_mode(Micheline.rootscript)>|=?fun(normalized,_ctxt)->Micheline.strip_locationsnormalized);Registration.register0~chunked:trueS.normalize_type(functxt()typ->letopenScript_ir_translatorinletctxt=Gas.set_unlimitedctxtin(* Unfortunately, Script_ir_translator.parse_any_ty is not exported *)Script_ir_translator.parse_tyctxt~legacy:true~allow_lazy_storage:true~allow_operation:true~allow_contract:true~allow_ticket:true(Micheline.roottyp)>>?=fun(Ex_tytyp,_ctxt)->letnormalized=Unparse_types.unparse_ty~loc:()typinreturn@@Micheline.strip_locationsnormalized);Registration.register0~chunked:trueS.run_operationrun_operation_service;Registration.register0_successor_level~chunked:trueS.simulate_operationsimulate_operation_service;Registration.register0~chunked:trueS.entrypoint_type(functxt()(expr,entrypoint)->script_entrypoint_typectxtexprentrypoint);Registration.register0~chunked:trueS.list_entrypoints(functxt()expr->letctxt=Gas.set_unlimitedctxtinletlegacy=falseinletopenScript_ir_translatorinparse_toplevel~legacyctxtexpr>>=?fun({arg_type;_},ctxt)->Lwt.return(parse_parameter_ty_and_entrypointsctxt~legacyarg_type>|?fun(Ex_parameter_ty_and_entrypoints{arg_type;entrypoints},_)->letunreachable_entrypoint,map=Script_ir_translator.list_entrypoints_uncarbonatedarg_typeentrypointsin(unreachable_entrypoint,Entrypoint.Map.fold(funentry(_ex_ty,original_type_expr)acc->(Entrypoint.to_stringentry,Micheline.strip_locationsoriginal_type_expr)::acc)map[])))letrun_code?unparsing_mode?gas?(entrypoint=Entrypoint.default)?balance~script~storage~input~amount~chain_id~source~payer~self~now~levelctxtblock=RPC_context.make_call0S.run_codectxtblock()((script,storage,input,amount,balance,chain_id,source,payer,self,entrypoint),(unparsing_mode,gas,now,level))lettrace_code?unparsing_mode?gas?(entrypoint=Entrypoint.default)?balance~script~storage~input~amount~chain_id~source~payer~self~now~levelctxtblock=RPC_context.make_call0S.trace_codectxtblock()((script,storage,input,amount,balance,chain_id,source,payer,self,entrypoint),(unparsing_mode,gas,now,level))letrun_tzip4_view?gas~contract~entrypoint~input~chain_id~now~level?source?payer~unparsing_modectxtblock=RPC_context.make_call0S.run_tzip4_viewctxtblock()(contract,entrypoint,input,chain_id,source,payer,gas,unparsing_mode,now,level)(** [run_script_view] is an helper function to call the corresponding
RPC. [unlimited_gas] is set to [false] by default. *)letrun_script_view?gas~contract~view~input?(unlimited_gas=false)~chain_id~now~level?source?payer~unparsing_modectxtblock=RPC_context.make_call0S.run_script_viewctxtblock()((contract,view,input,unlimited_gas,chain_id,source,payer,gas,unparsing_mode,now),level)lettypecheck_code?gas?legacy~script?show_typesctxtblock=RPC_context.make_call0S.typecheck_codectxtblock()(script,gas,legacy,show_types)letscript_size?gas?legacy~script~storagectxtblock=RPC_context.make_call0S.script_sizectxtblock()(script,storage,gas,legacy)lettypecheck_data?gas?legacy~data~tyctxtblock=RPC_context.make_call0S.typecheck_datactxtblock()(data,ty,gas,legacy)letpack_data?gas~data~tyctxtblock=RPC_context.make_call0S.pack_datactxtblock()(data,ty,gas)letnormalize_data?legacy~data~ty~unparsing_modectxtblock=RPC_context.make_call0S.normalize_datactxtblock()(data,ty,unparsing_mode,legacy)letnormalize_script~script~unparsing_modectxtblock=RPC_context.make_call0S.normalize_scriptctxtblock()(script,unparsing_mode)letnormalize_type~tyctxtblock=RPC_context.make_call0S.normalize_typectxtblock()tyletrun_operation~op~chain_idctxtblock=RPC_context.make_call0S.run_operationctxtblock()(op,chain_id)letsimulate_operation~op~chain_id~latency?(successor_level=false)?blocks_before_activationctxtblock=RPC_context.make_call0S.simulate_operationctxtblock(objectmethodsuccessor_level=successor_levelend)(blocks_before_activation,op,chain_id,latency)letentrypoint_type~script~entrypointctxtblock=RPC_context.make_call0S.entrypoint_typectxtblock()(script,entrypoint)letlist_entrypointsctxtblock~script=RPC_context.make_call0S.list_entrypointsctxtblock()scriptendmoduleContract=structmoduleS=structletpath=(RPC_path.(open_root/"context"/"contracts"):RPC_context.tRPC_path.context)letget_storage_normalized=letopenData_encodinginRPC_service.post_service~description:"Access the data of the contract and normalize it using the \
requested unparsing mode."~input:(obj1(req"unparsing_mode"unparsing_mode_encoding))~query:RPC_query.empty~output:(optionScript.expr_encoding)RPC_path.(path/:Contract.rpc_arg/"storage"/"normalized")letget_script_normalized=letopenData_encodinginRPC_service.post_service~description:"Access the script of the contract and normalize it using the \
requested unparsing mode."~input:(obj2(req"unparsing_mode"unparsing_mode_encoding)(dft"normalize_types"boolfalse))~query:RPC_query.empty~output:(optionScript.encoding)RPC_path.(path/:Contract.rpc_arg/"script"/"normalized")endletregister()=(* Patched RPC: get_storage *)Registration.register1~chunked:trueS.get_storage_normalized(functxtcontract()unparsing_mode->matchcontractwith|Implicit_->return_none|Originatedcontract->(Contract.get_scriptctxtcontract>>=?fun(ctxt,script)->matchscriptwith|None->return_none|Somescript->letctxt=Gas.set_unlimitedctxtinletopenScript_ir_translatorinparse_scriptctxt~legacy:true~allow_forged_in_storage:truescript>>=?fun(Ex_script(Script{storage;storage_type;_}),ctxt)->unparse_datactxtunparsing_modestorage_typestorage>|=?fun(storage,_ctxt)->Some(Micheline.strip_locationsstorage)));(* Patched RPC: get_script *)Registration.register1~chunked:trueS.get_script_normalized(functxtcontract()(unparsing_mode,normalize_types)->matchcontractwith|Implicit_->return_none|Originatedcontract->(Contract.get_scriptctxtcontract>>=?fun(ctxt,script)->matchscriptwith|None->return_none|Somescript->letctxt=Gas.set_unlimitedctxtinScript_ir_translator.parse_and_unparse_script_unaccountedctxt~legacy:true~allow_forged_in_storage:trueunparsing_mode~normalize_typesscript>>=?fun(script,_ctxt)->return_somescript))letget_storage_normalizedctxtblock~contract~unparsing_mode=RPC_context.make_call1S.get_storage_normalizedctxtblock(Contract.Originatedcontract)()unparsing_modeletget_script_normalizedctxtblock~contract~unparsing_mode~normalize_types=RPC_context.make_call1S.get_script_normalizedctxtblock(Contract.Originatedcontract)()(unparsing_mode,normalize_types)endmoduleBig_map=structmoduleS=structletpath=(RPC_path.(open_root/"context"/"big_maps"):RPC_context.tRPC_path.context)letbig_map_get_normalized=letopenData_encodinginRPC_service.post_service~description:"Access the value associated with a key in a big map, normalize the \
output using the requested unparsing mode."~query:RPC_query.empty~input:(obj1(req"unparsing_mode"unparsing_mode_encoding))~output:Script.expr_encodingRPC_path.(path/:Big_map.Id.rpc_arg/:Script_expr_hash.rpc_arg/"normalized")endletregister()=Registration.register2~chunked:trueS.big_map_get_normalized(functxtidkey()unparsing_mode->letopenScript_ir_translatorinletctxt=Gas.set_unlimitedctxtinBig_map.existsctxtid>>=?fun(ctxt,types)->matchtypeswith|None->raiseNot_found|Some(_,value_type)->(parse_big_map_value_tyctxt~legacy:true(Micheline.rootvalue_type)>>?=fun(Ex_tyvalue_type,ctxt)->Big_map.get_optctxtidkey>>=?fun(_ctxt,value)->matchvaluewith|None->raiseNot_found|Somevalue->parse_datactxt~legacy:true~allow_forged:truevalue_type(Micheline.rootvalue)>>=?fun(value,ctxt)->unparse_datactxtunparsing_modevalue_typevalue>|=?fun(value,_ctxt)->Micheline.strip_locationsvalue))letbig_map_get_normalizedctxtblockidkey~unparsing_mode=RPC_context.make_call2S.big_map_get_normalizedctxtblockidkey()unparsing_modeendmoduleSc_rollup=structopenData_encodingmoduleS=structletpath:RPC_context.tRPC_path.context=RPC_path.(open_root/"context"/"sc_rollup")letkind=RPC_service.get_service~description:"Kind of smart-contract rollup"~query:RPC_query.empty~output:Sc_rollup.Kind.encodingRPC_path.(path/:Sc_rollup.Address.rpc_arg/"kind")letboot_sector=RPC_service.get_service~description:"Boot sector of smart-contract rollup"~query:RPC_query.empty~output:Data_encoding.stringRPC_path.(path/:Sc_rollup.Address.rpc_arg/"boot_sector")letinbox=RPC_service.get_service~description:"Inbox for a smart-contract rollup"~query:RPC_query.empty~output:Sc_rollup.Inbox.encodingRPC_path.(path/:Sc_rollup.Address.rpc_arg/"inbox")letinitial_level=RPC_service.get_service~description:"Initial level for a smart-contract rollup"~query:RPC_query.empty~output:Raw_level.encodingRPC_path.(path/:Sc_rollup.Address.rpc_arg/"initial_level")letlast_cemented_commitment_hash_with_level=RPC_service.get_service~description:"Level and hash of the last cemented commitment for a smart-contract \
rollup"~query:RPC_query.empty~output:(obj2(req"hash"Sc_rollup.Commitment.Hash.encoding)(req"level"Raw_level.encoding))RPC_path.(path/:Sc_rollup.Address.rpc_arg/"last_cemented_commitment_hash_with_level")letcommitment=RPC_service.get_service~description:"Commitment for a smart contract rollup from its hash"~query:RPC_query.empty~output:Sc_rollup.Commitment.encodingRPC_path.(path/:Sc_rollup.Address.rpc_arg/"commitment"/:Sc_rollup.Commitment.Hash.rpc_arg)letdal_slot_subscriptions=RPC_service.get_service~description:"List of slot indices to which a rollup is subscribed to at a given \
level"~query:RPC_query.empty~output:(Data_encoding.listDal.Slot_index.encoding)RPC_path.(path/:Sc_rollup.Address.rpc_arg/"dal_slot_subscriptions"/:Raw_level.rpc_arg)letroot=RPC_service.get_service~description:"List of all originated smart contract rollups"~query:RPC_query.empty~output:(Data_encoding.listSc_rollup.Address.encoding)pathendletkindctxtblocksc_rollup_address=RPC_context.make_call1S.kindctxtblocksc_rollup_address()letregister_inbox()=Registration.register1~chunked:trueS.inbox(functxtrollup()()->Stdlib.Format.eprintf"@[Context level at RPC time at %a@]@."Level.pp(Level.currentctxt);Sc_rollup.Inbox.inboxctxtrollup>>=?fun(inbox,_ctxt)->returninbox)letregister_kind()=Registration.opt_register1~chunked:trueS.kind@@functxtaddress()()->Alpha_context.Sc_rollup.kindctxtaddress(* TODO: https://gitlab.com/tezos/tezos/-/issues/2688 *)letregister_initial_level()=Registration.register1~chunked:trueS.initial_level@@functxtaddress()()->Alpha_context.Sc_rollup.initial_levelctxtaddressletregister_boot_sector()=Registration.register1~chunked:trueS.boot_sector@@functxtaddress()()->Alpha_context.Sc_rollup.get_boot_sectorctxtaddressletregister_last_cemented_commitment_hash_with_level()=Registration.register1~chunked:falseS.last_cemented_commitment_hash_with_level@@functxtaddress()()->letopenLwt_tzresult_syntaxinlet+last_cemented_commitment,level,_ctxt=Alpha_context.Sc_rollup.Commitment.last_cemented_commitment_hash_with_levelctxtaddressin(last_cemented_commitment,level)letregister_commitment()=Registration.register2~chunked:falseS.commitment@@functxtaddresscommitment_hash()()->letopenLwt_result_syntaxinlet+commitment,_=Alpha_context.Sc_rollup.Commitment.get_commitmentctxtaddresscommitment_hashincommitmentletregister_dal_slot_subscriptions()=Registration.register2~chunked:falseS.dal_slot_subscriptions@@functxtaddresslevel()()->Alpha_context.Sc_rollup.Dal_slot.subscribed_slot_indicesctxtaddresslevelletregister_root()=Registration.register0~chunked:trueS.root(funcontext()()->Sc_rollup.listcontext)letregister()=register_kind();register_inbox();register_initial_level();register_boot_sector();register_last_cemented_commitment_hash_with_level();register_commitment();register_dal_slot_subscriptions();register_root()letlistctxtblock=RPC_context.make_call0S.rootctxtblock()()letinitial_levelctxtblocksc_rollup_address=RPC_context.make_call1S.initial_levelctxtblocksc_rollup_address()()letlast_cemented_commitment_hash_with_levelctxtblocksc_rollup_address=RPC_context.make_call1S.last_cemented_commitment_hash_with_levelctxtblocksc_rollup_address()()letdal_slot_subscriptionsctxtblocksc_rollup_addresslevel=RPC_context.make_call2S.dal_slot_subscriptionsctxtblocksc_rollup_addresslevel()()letboot_sectorctxtblocksc_rollup_address=RPC_context.make_call1S.boot_sectorctxtblocksc_rollup_address()()endmoduleTx_rollup=structopenData_encodingmoduleS=structletpath:RPC_context.tRPC_path.context=RPC_path.(open_root/"context"/"tx_rollup")lethas_bond=RPC_service.get_service~description:"Returns true if the public key hash already deposited a bond for \
the given rollup"~query:RPC_query.empty~output:boolRPC_path.(path/:Tx_rollup.rpc_arg/"has_bond"/:Signature.Public_key_hash.rpc_arg)endletregister_has_bond()=Registration.register2~chunked:falseS.has_bond(functxtrollupoperator()()->Tx_rollup_commitment.has_bondctxtrollupoperator>>=?fun(_ctxt,has_bond)->returnhas_bond)letregister()=register_has_bond()lethas_bondctxtblockrollupoperator=RPC_context.make_call2S.has_bondctxtblockrollupoperator()()endmoduleForge=structmoduleS=structopenData_encodingletpath=RPC_path.(path/"forge")letoperations=RPC_service.post_service~description:"Forge an operation"~query:RPC_query.empty~input:Operation.unsigned_encoding~output:bytesRPC_path.(path/"operations")letempty_proof_of_work_nonce=Bytes.makeConstants_repr.proof_of_work_nonce_size'\000'letprotocol_data=RPC_service.post_service~description:"Forge the protocol-specific part of a block header"~query:RPC_query.empty~input:(obj5(req"payload_hash"Block_payload_hash.encoding)(req"payload_round"Round.encoding)(opt"nonce_hash"Nonce_hash.encoding)(dft"proof_of_work_nonce"(Fixed.bytesAlpha_context.Constants.proof_of_work_nonce_size)empty_proof_of_work_nonce)Liquidity_baking.(dft"liquidity_baking_toggle_vote"liquidity_baking_toggle_vote_encodingLB_pass))~output:(obj1(req"protocol_data"bytes))RPC_path.(path/"protocol_data")moduleTx_rollup=structopenData_encodingletpath=RPC_path.(path/"tx_rollup")moduleInbox=structletpath=RPC_path.(path/"inbox")letmessage_hash=RPC_service.post_service~description:"Compute the hash of a message"~query:RPC_query.empty~input:(obj1(req"message"Tx_rollup_message.encoding))~output:(obj1(req"hash"Tx_rollup_message_hash.encoding))RPC_path.(path/"message_hash")letmerkle_tree_hash=RPC_service.post_service~description:"Compute the merkle tree hash of an inbox"~query:RPC_query.empty~input:(obj1(req"message_hashes"(listTx_rollup_message_hash.encoding)))~output:(obj1(req"hash"Tx_rollup_inbox.Merkle.root_encoding))RPC_path.(path/"merkle_tree_hash")letmerkle_tree_path=RPC_service.post_service~description:"Compute a path of an inbox message in a merkle tree"~query:RPC_query.empty~input:(obj2(req"message_hashes"(listTx_rollup_message_hash.encoding))(req"position"int16))~output:(obj1(req"path"Tx_rollup_inbox.Merkle.path_encoding))RPC_path.(path/"merkle_tree_path")endmoduleCommitment=structletpath=RPC_path.(path/"commitment")letmerkle_tree_hash=RPC_service.post_service~description:"Compute the merkle tree hash of a commitment"~query:RPC_query.empty~input:(obj1(req"message_result_hashes"(listTx_rollup_message_result_hash.encoding)))~output:(obj1(req"hash"Tx_rollup_commitment.Merkle_hash.encoding))RPC_path.(path/"merkle_tree_hash")letmerkle_tree_path=RPC_service.post_service~description:"Compute a path of a message result hash in the commitment \
merkle tree"~query:RPC_query.empty~input:(obj2(req"message_result_hashes"(listTx_rollup_message_result_hash.encoding))(req"position"int16))~output:(obj1(req"path"Tx_rollup_commitment.Merkle.path_encoding))RPC_path.(path/"merkle_tree_path")letmessage_result_hash=RPC_service.post_service~description:"Compute the message result hash"~query:RPC_query.empty~input:Tx_rollup_message_result.encoding~output:(obj1(req"hash"Tx_rollup_message_result_hash.encoding))RPC_path.(path/"message_result_hash")endmoduleWithdraw=structletpath=RPC_path.(path/"withdraw")letwithdraw_list_hash=RPC_service.post_service~description:"Compute the hash of a withdraw list"~query:RPC_query.empty~input:(obj1(req"withdraw_list"(listTx_rollup_withdraw.encoding)))~output:(obj1(req"hash"Tx_rollup_withdraw_list_hash.encoding))RPC_path.(path/"withdraw_list_hash")endendendletregister()=Registration.register0_noctxt~chunked:trueS.operations(fun()(shell,proto)->return(Data_encoding.Binary.to_bytes_exnOperation.unsigned_encoding(shell,proto)));Registration.register0_noctxt~chunked:trueS.protocol_data(fun()(payload_hash,payload_round,seed_nonce_hash,proof_of_work_nonce,liquidity_baking_toggle_vote)->return(Data_encoding.Binary.to_bytes_exnBlock_header.contents_encoding{payload_hash;payload_round;seed_nonce_hash;proof_of_work_nonce;liquidity_baking_toggle_vote;}));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Inbox.message_hash(fun()message->return(Tx_rollup_message_hash.hash_uncarbonatedmessage));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Inbox.merkle_tree_hash(fun()message_hashes->return(Tx_rollup_inbox.Merkle.merklize_listmessage_hashes));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Inbox.merkle_tree_path(fun()(message_hashes,position)->Lwt.return(Tx_rollup_inbox.Merkle.compute_pathmessage_hashesposition));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Commitment.merkle_tree_hash(fun()message_result_hashes->letopenTx_rollup_commitment.Merkleinlettree=List.fold_leftsnocnilmessage_result_hashesinreturn(roottree));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Commitment.merkle_tree_path(fun()(message_result_hashes,position)->letopenTx_rollup_commitment.Merkleinlettree=List.fold_leftsnocnilmessage_result_hashesinLwt.return(compute_pathtreeposition));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Commitment.message_result_hash(fun()message_result->return(Tx_rollup_message_result_hash.hash_uncarbonatedmessage_result));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Withdraw.withdraw_list_hash(fun()withdrawals->return(Tx_rollup_withdraw_list_hash.hash_uncarbonatedwithdrawals))moduleManager=structlet[@coq_axiom_with_reason"cast on e"]operationsctxtblock~branch~source?sourcePubKey~counter~fee~gas_limit~storage_limitoperations=Contract_services.manager_keyctxtblocksource>>=function|Error_ase->Lwt.returne|Okrevealed->letops=List.map(fun(Manageroperation)->Contents(Manager_operation{source;counter;operation;fee;gas_limit;storage_limit}))operationsinletops=match(sourcePubKey,revealed)with|None,_|_,Some_->ops|Somepk,None->letoperation=RevealpkinContents(Manager_operation{source;counter;operation;fee;gas_limit;storage_limit})::opsinEnvironment.wrap_tzresult@@Operation.of_listops>>?=funops->RPC_context.make_call0S.operationsctxtblock()({branch},ops)letrevealctxtblock~branch~source~sourcePubKey~counter~fee()=operationsctxtblock~branch~source~sourcePubKey~counter~fee~gas_limit:Gas.Arith.zero~storage_limit:Z.zero[]lettransactionctxtblock~branch~source?sourcePubKey~counter~amount~destination?(entrypoint=Entrypoint.default)?parameters~gas_limit~storage_limit~fee()=letparameters=Option.fold~some:Script.lazy_expr~none:Script.unit_parameterparametersinoperationsctxtblock~branch~source?sourcePubKey~counter~fee~gas_limit~storage_limit[Manager(Transaction{amount;parameters;destination;entrypoint})]letoriginationctxtblock~branch~source?sourcePubKey~counter~balance?delegatePubKey~script~gas_limit~storage_limit~fee()=operationsctxtblock~branch~source?sourcePubKey~counter~fee~gas_limit~storage_limit[Manager(Origination{delegate=delegatePubKey;script;credit=balance});]letdelegationctxtblock~branch~source?sourcePubKey~counter~feedelegate=operationsctxtblock~branch~source?sourcePubKey~counter~fee~gas_limit:Gas.Arith.zero~storage_limit:Z.zero[Manager(Delegationdelegate)]endletoperationctxtblock~branchoperation=RPC_context.make_call0S.operationsctxtblock()({branch},Contents_list(Singleoperation))letendorsementctxtb~branch~consensus_content()=operationctxtb~branch(Endorsementconsensus_content)letproposalsctxtb~branch~source~period~proposals()=operationctxtb~branch(Proposals{source;period;proposals})letballotctxtb~branch~source~period~proposal~ballot()=operationctxtb~branch(Ballot{source;period;proposal;ballot})letfailing_noopctxtb~branch~message()=operationctxtb~branch(Failing_noopmessage)letseed_nonce_revelationctxtblock~branch~level~nonce()=operationctxtblock~branch(Seed_nonce_revelation{level;nonce})letvdf_revelationctxtblock~branch~solution()=operationctxtblock~branch(Vdf_revelation{solution})letdouble_baking_evidencectxtblock~branch~bh1~bh2()=operationctxtblock~branch(Double_baking_evidence{bh1;bh2})letdouble_endorsement_evidencectxtblock~branch~op1~op2()=operationctxtblock~branch(Double_endorsement_evidence{op1;op2})letdouble_preendorsement_evidencectxtblock~branch~op1~op2()=operationctxtblock~branch(Double_preendorsement_evidence{op1;op2})letempty_proof_of_work_nonce=Bytes.makeConstants_repr.proof_of_work_nonce_size'\000'letprotocol_datactxtblock?(payload_hash=Block_payload_hash.zero)?(payload_round=Round.zero)?seed_nonce_hash?(proof_of_work_nonce=empty_proof_of_work_nonce)~liquidity_baking_toggle_vote()=RPC_context.make_call0S.protocol_datactxtblock()(payload_hash,payload_round,seed_nonce_hash,proof_of_work_nonce,liquidity_baking_toggle_vote)endmoduleParse=structmoduleS=structopenData_encodingletpath=RPC_path.(path/"parse")letoperations=RPC_service.post_service~description:"Parse operations"~query:RPC_query.empty~input:(obj2(req"operations"(list(dynamic_sizeOperation.raw_encoding)))(opt"check_signature"bool))~output:(list(dynamic_sizeOperation.encoding))RPC_path.(path/"operations")letblock=RPC_service.post_service~description:"Parse a block"~query:RPC_query.empty~input:Block_header.raw_encoding~output:Block_header.protocol_data_encodingRPC_path.(path/"block")endletparse_protocol_dataprotocol_data=matchData_encoding.Binary.of_bytes_optBlock_header.protocol_data_encodingprotocol_datawith|None->Stdlib.failwith"Cant_parse_protocol_data"|Someprotocol_data->protocol_dataletregister()=Registration.register0~chunked:trueS.operations(fun_ctxt()(operations,check)->List.map_es(funraw->parse_operationraw>>?=funop->(matchcheckwith|Sometrue->return_unit(* FIXME *)(* I.check_signature ctxt *)(* op.protocol_data.signature op.shell op.protocol_data.contents *)|Somefalse|None->return_unit)>|=?fun()->op)operations);Registration.register0_noctxt~chunked:falseS.block(fun()raw_block->return@@parse_protocol_dataraw_block.protocol_data)letoperationsctxtblock?checkoperations=RPC_context.make_call0S.operationsctxtblock()(operations,check)letblockctxtblockshellprotocol_data=RPC_context.make_call0S.blockctxtblock()({shell;protocol_data}:Block_header.raw)end(* Compute the estimated starting time of a [round] at a future
[level], given the head's level [current_level], timestamp
[current_timestamp], and round [current_round]. Assumes blocks at
intermediate levels are produced at round 0. *)letestimated_timeround_durations~current_level~current_round~current_timestamp~level~round=ifLevel.(level<=current_level)thenResult.return_noneelseRound.timestamp_of_roundround_durations~round~predecessor_timestamp:current_timestamp~predecessor_round:current_round>>?funround_start_at_next_level->letstep=Round.round_durationround_durationsRound.zeroinletdiff=Level.difflevelcurrent_levelinPeriod.mult(Int32.preddiff)step>>?fundelay->Timestamp.(round_start_at_next_level+?delay)>>?funtimestamp->Result.return_sometimestampletrequested_levels~default_levelctxtcycleslevels=match(levels,cycles)with|[],[]->[default_level]|levels,cycles->(* explicitly fail when requested levels or cycle are in the past...
or too far in the future...
TODO: https://gitlab.com/tezos/tezos/-/issues/2335
this old comment (from version Alpha) conflicts with
the specification of the RPCs that use this code.
*)List.sort_uniqLevel.compare(List.rev_append(List.rev_map(Level.from_rawctxt)levels)(List.concat_map(Level.levels_in_cyclectxt)cycles))moduleBaking_rights=structtypet={level:Raw_level.t;delegate:Tezos_crypto.Signature.V0.Public_key_hash.t;round:Round.t;timestamp:Timestamp.toption;}letencoding=letopenData_encodinginconv(fun{level;delegate;round;timestamp}->(level,delegate,round,timestamp))(fun(level,delegate,round,timestamp)->{level;delegate;round;timestamp})(obj4(req"level"Raw_level.encoding)(req"delegate"Tezos_crypto.Signature.V0.Public_key_hash.encoding)(req"round"Round.encoding)(opt"estimated_time"Timestamp.encoding))letdefault_max_round=64moduleS=structopenData_encodingletpath=RPC_path.(open_root/"helpers"/"baking_rights")typebaking_rights_query={levels:Raw_level.tlist;cycle:Cycle.toption;delegates:Tezos_crypto.Signature.V0.Public_key_hash.tlist;max_round:intoption;all:bool;}letbaking_rights_query=letopenRPC_queryinquery(funlevelscycledelegatesmax_roundall->{levels;cycle;delegates;max_round;all})|+multi_field"level"Raw_level.rpc_arg(funt->t.levels)|+opt_field"cycle"Cycle.rpc_arg(funt->t.cycle)|+multi_field"delegate"Signature.Public_key_hash.rpc_arg(funt->t.delegates)|+opt_field"max_round"RPC_arg.uint(funt->t.max_round)|+flag"all"(funt->t.all)|>sealletbaking_rights=RPC_service.get_service~description:(Format.sprintf"Retrieves the list of delegates allowed to bake a block.\n\
By default, it gives the best baking opportunities (in terms of \
rounds) for bakers that have at least one opportunity below the \
%dth round for the next block.\n\
Parameters `level` and `cycle` can be used to specify the \
(valid) level(s) in the past or future at which the baking \
rights have to be returned.\n\
Parameter `delegate` can be used to restrict the results to the \
given delegates. If parameter `all` is set, all the baking \
opportunities for each baker at each level are returned, instead \
of just the first one.\n\
Returns the list of baking opportunities up to round %d. Also \
returns the minimal timestamps that correspond to these \
opportunities. The timestamps are omitted for levels in the \
past, and are only estimates for levels higher that the next \
block's, based on the hypothesis that all predecessor blocks \
were baked at the first round."default_max_rounddefault_max_round)~query:baking_rights_query~output:(listencoding)pathendletbaking_rights_at_levelctxtmax_roundlevel=Round.getctxt>>=?funcurrent_round->letcurrent_level=Level.currentctxtinletcurrent_timestamp=Timestamp.currentctxtinletround_durations=Alpha_context.Constants.round_durationsctxtinletrecloopctxtaccround=ifRound.(round>max_round)then(* returns the ctxt with an updated cache of slot holders *)return(ctxt,List.revacc)elseStake_distribution.baking_rights_ownerctxtlevel~round>>=?fun(ctxt,_slot,(_,delegate))->estimated_timeround_durations~current_level~current_round~current_timestamp~level~round>>?=funtimestamp->letacc={level=level.level;delegate;round;timestamp}::accinloopctxtacc(Round.succround)inloopctxt[]Round.zeroletremove_duplicated_delegatesrights=List.rev@@fst@@List.fold_left(fun(acc,previous)r->ifTezos_crypto.Signature.V0.Public_key_hash.Set.exists(Tezos_crypto.Signature.V0.Public_key_hash.equalr.delegate)previousthen(acc,previous)else(r::acc,Tezos_crypto.Signature.V0.Public_key_hash.Set.addr.delegateprevious))([],Tezos_crypto.Signature.V0.Public_key_hash.Set.empty)rightsletregister()=Registration.register0~chunked:trueS.baking_rights(functxtq()->letcycles=matchq.cyclewithNone->[]|Somecycle->[cycle]inletlevels=requested_levels~default_level:(Level.succctxt(Level.currentctxt))ctxtcyclesq.levelsinRound.of_int(matchq.max_roundwith|None->default_max_round|Somemax_round->Compare.Int.minmax_round(Constants.consensus_committee_sizectxt))>>?=funmax_round->List.fold_left_map_es(functxtl->baking_rights_at_levelctxtmax_roundl)ctxtlevels>|=?fun(_ctxt,rights)->letrights=ifq.allthenList.concatrightselseList.concat_mapremove_duplicated_delegatesrightsinmatchq.delegateswith|[]->rights|_::_asdelegates->letis_requestedp=List.exists(Tezos_crypto.Signature.V0.Public_key_hash.equalp.delegate)delegatesinList.filteris_requestedrights)letgetctxt?(levels=[])?cycle?(delegates=[])?(all=false)?max_roundblock=RPC_context.make_call0S.baking_rightsctxtblock{levels;cycle;delegates;max_round;all}()endmoduleEndorsing_rights=structtypedelegate_rights={delegate:Tezos_crypto.Signature.V0.Public_key_hash.t;first_slot:Slot.t;endorsing_power:int;}typet={level:Raw_level.t;delegates_rights:delegate_rightslist;estimated_time:Time.toption;}letdelegate_rights_encoding=letopenData_encodinginconv(fun{delegate;first_slot;endorsing_power}->(delegate,first_slot,endorsing_power))(fun(delegate,first_slot,endorsing_power)->{delegate;first_slot;endorsing_power})(obj3(req"delegate"Tezos_crypto.Signature.V0.Public_key_hash.encoding)(req"first_slot"Slot.encoding)(req"endorsing_power"uint16))letencoding=letopenData_encodinginconv(fun{level;delegates_rights;estimated_time}->(level,delegates_rights,estimated_time))(fun(level,delegates_rights,estimated_time)->{level;delegates_rights;estimated_time})(obj3(req"level"Raw_level.encoding)(req"delegates"(listdelegate_rights_encoding))(opt"estimated_time"Timestamp.encoding))moduleS=structopenData_encodingletpath=RPC_path.(path/"endorsing_rights")typeendorsing_rights_query={levels:Raw_level.tlist;cycle:Cycle.toption;delegates:Tezos_crypto.Signature.V0.Public_key_hash.tlist;}letendorsing_rights_query=letopenRPC_queryinquery(funlevelscycledelegates->{levels;cycle;delegates})|+multi_field"level"Raw_level.rpc_arg(funt->t.levels)|+opt_field"cycle"Cycle.rpc_arg(funt->t.cycle)|+multi_field"delegate"Signature.Public_key_hash.rpc_arg(funt->t.delegates)|>sealletendorsing_rights=RPC_service.get_service~description:"Retrieves the delegates allowed to endorse a block.\n\
By default, it gives the endorsing power for delegates that have at \
least one endorsing slot for the next block.\n\
Parameters `level` and `cycle` can be used to specify the (valid) \
level(s) in the past or future at which the endorsing rights have \
to be returned. Parameter `delegate` can be used to restrict the \
results to the given delegates.\n\
Returns the smallest endorsing slots and the endorsing power. Also \
returns the minimal timestamp that corresponds to endorsing at the \
given level. The timestamps are omitted for levels in the past, and \
are only estimates for levels higher that the next block's, based \
on the hypothesis that all predecessor blocks were baked at the \
first round."~query:endorsing_rights_query~output:(listencoding)pathendletendorsing_rights_at_levelctxtlevel=Baking.endorsing_rights_by_first_slotctxtlevel>>=?fun(ctxt,rights)->Round.getctxt>>=?funcurrent_round->letcurrent_level=Level.currentctxtinletcurrent_timestamp=Timestamp.currentctxtinletround_durations=Alpha_context.Constants.round_durationsctxtinestimated_timeround_durations~current_level~current_round~current_timestamp~level~round:Round.zero>>?=funestimated_time->letrights=Slot.Map.fold(funfirst_slot(_pk,delegate,endorsing_power)acc->{delegate;first_slot;endorsing_power}::acc)rights[]in(* returns the ctxt with an updated cache of slot holders *)return(ctxt,{level=level.level;delegates_rights=rights;estimated_time})letregister()=Registration.register0~chunked:trueS.endorsing_rights(functxtq()->letcycles=matchq.cyclewithNone->[]|Somecycle->[cycle]inletlevels=requested_levels~default_level:(Level.currentctxt)ctxtcyclesq.levelsinList.fold_left_map_esendorsing_rights_at_levelctxtlevels>|=?fun(_ctxt,rights_per_level)->matchq.delegateswith|[]->rights_per_level|_::_asdelegates->List.filter_map(funrights_at_level->letis_requestedp=List.exists(Tezos_crypto.Signature.V0.Public_key_hash.equalp.delegate)delegatesinmatchList.filteris_requestedrights_at_level.delegates_rightswith|[]->None|delegates_rights->Some{rights_at_levelwithdelegates_rights})rights_per_level)letgetctxt?(levels=[])?cycle?(delegates=[])block=RPC_context.make_call0S.endorsing_rightsctxtblock{levels;cycle;delegates}()endmoduleValidators=structtypet={level:Raw_level.t;delegate:Tezos_crypto.Signature.V0.Public_key_hash.t;slots:Slot.tlist;}letencoding=letopenData_encodinginconv(fun{level;delegate;slots}->(level,delegate,slots))(fun(level,delegate,slots)->{level;delegate;slots})(obj3(req"level"Raw_level.encoding)(req"delegate"Tezos_crypto.Signature.V0.Public_key_hash.encoding)(req"slots"(listSlot.encoding)))moduleS=structopenData_encodingletpath=RPC_path.(path/"validators")typevalidators_query={levels:Raw_level.tlist;delegates:Tezos_crypto.Signature.V0.Public_key_hash.tlist;}letvalidators_query=letopenRPC_queryinquery(funlevelsdelegates->{levels;delegates})|+multi_field"level"Raw_level.rpc_arg(funt->t.levels)|+multi_field"delegate"Signature.Public_key_hash.rpc_arg(funt->t.delegates)|>sealletvalidators=RPC_service.get_service~description:"Retrieves the level, the endorsement slots and the public key hash \
of each delegate allowed to endorse a block.\n\
By default, it provides this information for the next level.\n\
Parameter `level` can be used to specify the (valid) level(s) in \
the past or future at which the endorsement rights have to be \
returned. Parameter `delegate` can be used to restrict the results \
to the given delegates.\n"~query:validators_query~output:(listencoding)pathendletadd_endorsing_slots_at_level(ctxt,acc)level=Baking.endorsing_rightsctxtlevel>|=?fun(ctxt,rights)->(ctxt,Signature.Public_key_hash.Map.fold(fundelegateslotsacc->{level=level.level;delegate;slots}::acc)(rights:>Slot.tlistSignature.Public_key_hash.Map.t)acc)letregister()=Registration.register0~chunked:trueS.validators(functxtq()->letlevels=requested_levels~default_level:(Level.currentctxt)ctxt[]q.levelsinList.fold_left_esadd_endorsing_slots_at_level(ctxt,[])(List.revlevels)>|=?fun(_ctxt,rights)->matchq.delegateswith|[]->rights|_::_asdelegates->letis_requestedp=List.exists(Tezos_crypto.Signature.V0.Public_key_hash.equalp.delegate)delegatesinList.filteris_requestedrights)letgetctxt?(levels=[])?(delegates=[])block=RPC_context.make_call0S.validatorsctxtblock{levels;delegates}()endmoduleS=structopenData_encodingtypelevel_query={offset:int32}letlevel_query:level_queryRPC_query.t=letopenRPC_queryinquery(funoffset->{offset})|+field"offset"RPC_arg.int320l(funt->t.offset)|>sealletcurrent_level=RPC_service.get_service~description:"Returns the level of the interrogated block, or the one of a block \
located `offset` blocks after it in the chain. For instance, the next \
block if `offset` is 1. The offset cannot be negative."~query:level_query~output:Level.encodingRPC_path.(path/"current_level")letlevels_in_current_cycle=RPC_service.get_service~description:"Levels of a cycle"~query:level_query~output:(obj2(req"first"Raw_level.encoding)(req"last"Raw_level.encoding))RPC_path.(path/"levels_in_current_cycle")letround=RPC_service.get_service~description:"Returns the round of the interrogated block, or the one of a block \
located `offset` blocks after in the chain (or before when negative). \
For instance, the next block if `offset` is 1."~query:RPC_query.empty~output:Round.encodingRPC_path.(path/"round")endtypeEnvironment.Error_monad.error+=Negative_level_offsetlet()=Environment.Error_monad.register_error_kind`Permanent~id:"negative_level_offset"~title:"The specified level offset is negative"~description:"The specified level offset is negative"~pp:(funppf()->Format.fprintfppf"The specified level offset should be positive.")Data_encoding.unit(functionNegative_level_offset->Some()|_->None)(fun()->Negative_level_offset)letregister()=Scripts.register();Forge.register();Parse.register();Contract.register();Big_map.register();Baking_rights.register();Endorsing_rights.register();Validators.register();Sc_rollup.register();Tx_rollup.register();Registration.register0~chunked:falseS.current_level(functxtq()->ifq.offset<0lthenfailNegative_level_offsetelseLwt.return(Level.from_raw_with_offsetctxt~offset:q.offset(Level.currentctxt).level));Registration.opt_register0~chunked:trueS.levels_in_current_cycle(functxtq()->letrev_levels=Level.levels_in_current_cyclectxt~offset:q.offset()inmatchrev_levelswith|[]->return_none|[level]->return(Some(level.level,level.level))|last::default_first::rest->(* The [rev_levels] list is reversed, the last level is the head *)letfirst=List.lastdefault_firstrestinreturn(Some(first.level,last.level)));Registration.register0~chunked:falseS.round(functxt()()->Round.getctxt)letcurrent_levelctxt?(offset=0l)block=RPC_context.make_call0S.current_levelctxtblock{offset}()letlevels_in_current_cyclectxt?(offset=0l)block=RPC_context.make_call0S.levels_in_current_cyclectxtblock{offset}()letrpc_services=register();RPC_directory.mergerpc_services!Registration.patched_services