123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Nomadic Development. <contact@tezcore.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. *)(* *)(*****************************************************************************)openProtocolopenAlpha_contexttypeEnvironment.Error_monad.error+=Cannot_parse_operation(* `Branch *)typeEnvironment.Error_monad.error+=Cannot_serialize_loglet()=Environment.Error_monad.register_error_kind`Branch~id:"operation.cannot_parse"~title:"Cannot parse operation"~description:"The operation is ill-formed or for another protocol version"~pp:(funppf()->Format.fprintfppf"The operation cannot be parsed")Data_encoding.unit(functionCannot_parse_operation->Some()|_->None)(fun()->Cannot_parse_operation);(* Cannot serialize log *)Environment.Error_monad.register_error_kind`Temporary~id:"michelson_v1.cannot_serialize_log"~title:"Not enough gas to serialize execution trace"~description:"Execution trace with stacks was to big to be serialized with the \
provided gas"Data_encoding.empty(functionCannot_serialize_log->Some()|_->None)(fun()->Cannot_serialize_log)moduleView_helpers=structopenTezos_michelinetypeEnvironment.Error_monad.error+=Viewed_contract_has_no_scripttypeEnvironment.Error_monad.error+=View_callback_origination_failedtypeEnvironment.Error_monad.error+=|Illformed_view_typeofstring*Script.exprtypeEnvironment.Error_monad.error+=|View_never_returnsofstring*Contract.ttypeEnvironment.Error_monad.error+=|View_unexpected_returnofstring*Contract.tlet()=Environment.Error_monad.register_error_kind`Permanent~id:"viewedContractHasNoScript"~title:"Viewed contract has no script"~description:"A view was called on a contract with no script."~pp:(funppf()->Format.fprintfppf"A view was called on a contract with no script.")Data_encoding.(unit)(functionViewed_contract_has_no_script->Some()|_->None)(fun()->Viewed_contract_has_no_script);Environment.Error_monad.register_error_kind`Permanent~id:"viewCallbackOriginationFailed"~title:"View callback origination failed"~description:"View callback origination failed"~pp:(funppf()->Format.fprintfppf"Error during origination of view callback contract.")Data_encoding.(unit)(functionView_callback_origination_failed->Some()|_->None)(fun()->View_callback_origination_failed);Environment.Error_monad.register_error_kind`Permanent~id:"illformedViewType"~title:"An entrypoint type is incompatible with TZIP-4 view type."~description:"An entrypoint type is incompatible with TZIP-4 view type."~pp:(funppf(entrypoint,typ)->Format.fprintfppf"The view %s has type %a, it is not compatible with a TZIP-4 view \
type."entrypointMicheline_printer.print_expr(Micheline_printer.printable(funx->x)(Michelson_v1_primitives.strings_of_primstyp)))Data_encoding.(obj2(req"entrypoint"string)(req"type"Script.expr_encoding))(functionIllformed_view_type(etp,exp)->Some(etp,exp)|_->None)(fun(etp,exp)->Illformed_view_type(etp,exp));Environment.Error_monad.register_error_kind`Permanent~id:"viewNeverReturns"~title:"A view never returned a transaction to the given callback contract"~description:"A view never initiated a transaction to the given callback contract."~pp:(funppf(entrypoint,callback)->Format.fprintfppf"The view %s never initiated a transaction to the given callback \
contract %a."entrypointContract.ppcallback)Data_encoding.(obj2(req"entrypoint"string)(req"callback"Contract.encoding))(functionView_never_returns(e,c)->Some(e,c)|_->None)(fun(e,c)->View_never_returns(e,c));Environment.Error_monad.register_error_kind`Permanent~id:"viewUnexpectedReturn"~title:"A view returned an unexpected list of operations"~description:"A view initiated a list of operations while the TZIP-4 standard \
expects only a transaction to the given callback contract."~pp:(funppf(entrypoint,callback)->Format.fprintfppf"The view %s initiated a list of operations while the TZIP-4 \
standard expects only a transaction to the given callback contract \
%a."entrypointContract.ppcallback)Data_encoding.(obj2(req"entrypoint"string)(req"callback"Contract.encoding))(functionView_never_returns(e,c)->Some(e,c)|_->None)(fun(e,c)->View_never_returns(e,c))(* This script is actually never run, its usage is to ensure a
contract that has the type `contract <ty>` is originated, which
will be required as callback of the view. *)letmake_viewer_scriptty:Script.t=letloc=0inletty=Micheline.roottyinletcode=Micheline.strip_locations@@Micheline.Seq(loc,[Micheline.Prim(loc,Script.K_parameter,[ty],[]);Micheline.Prim(loc,Script.K_storage,[Micheline.Prim(loc,Script.T_unit,[],[])],[]);Micheline.Prim(loc,Script.K_code,[Micheline.Prim(loc,Script.I_FAILWITH,[],[])],[]);])inletstorage=Micheline.strip_locations(Micheline.Prim(loc,Script.D_Unit,[],[]))in{code=Script.lazy_exprcode;storage=Script.lazy_exprstorage}letmake_view_parameterinputcallback=letloc=0inMicheline.strip_locations(Micheline.Prim(loc,Script.D_Pair,[input;Micheline.Bytes(loc,Data_encoding.Binary.to_bytes_exnContract.encodingcallback);],[]))letextract_view_output_typeentrypointty=matchMicheline.roottywith|Micheline.Prim(_,Script.T_pair,[_;Micheline.Prim(_,Script.T_contract,[ty],_)],_)->ok(Micheline.strip_locationsty)|_->Environment.Error_monad.error(Illformed_view_type(entrypoint,ty))(* 'view' entrypoints returns their value by calling a callback contract, thus
the expected result is a unique internal transaction to this callback. *)letextract_parameter_from_operationsentrypointoperationscallback=letunexpected_return=Environment.Error_monad.error@@View_unexpected_return(entrypoint,callback)inmatchoperationswith|[Internal_operation{operation=Transaction{destination;parameters;_};_};]whenContract.equaldestinationcallback->okparameters|[]->Environment.Error_monad.error(View_never_returns(entrypoint,callback))|_->unexpected_returnendmoduleRPC=structopenEnvironmentopenAlpha_contextopenEnvironment.Error_monadletparse_operation(op:Operation.raw)=matchData_encoding.Binary.of_bytesOperation.protocol_data_encodingop.protowith|Someprotocol_data->ok{shell=op.shell;protocol_data}|None->errorCannot_parse_operationletpath=RPC_path.(open_root/"helpers")moduleRegistration=structletpatched_services=ref(RPC_directory.empty:Updater.rpc_contextRPC_directory.t)letregister0_fullctxtsf=patched_services:=RPC_directory.register!patched_servicess(functxtqi->Services_registration.rpc_initctxt>>=?functxt->fctxtqi)letregister0sf=register0_fullctxts(fun{context;_}->fcontext)letregister0_noctxtsf=patched_services:=RPC_directory.register!patched_servicess(fun_qi->fqi)letopt_register0_fullctxtsf=patched_services:=RPC_directory.opt_register!patched_servicess(functxtqi->Services_registration.rpc_initctxt>>=?functxt->fctxtqi)letopt_register0sf=opt_register0_fullctxts(fun{context;_}->fcontext)letregister1_fullctxtsf=patched_services:=RPC_directory.register!patched_servicess(fun(ctxt,arg)qi->Services_registration.rpc_initctxt>>=?functxt->fctxtargqi)letregister1sf=register1_fullctxts(fun{context;_}x->fcontextx)letregister2_fullctxtsf=patched_services:=RPC_directory.register!patched_servicess(fun((ctxt,arg1),arg2)qi->Services_registration.rpc_initctxt>>=?functxt->fctxtarg1arg2qi)letregister2sf=register2_fullctxts(fun{context;_}a1a2qi->fcontexta1a2qi)endletunparsing_mode_encoding=letopenScript_ir_translatorinletopenData_encodinginunion~tag_size:`Uint8[case(Tag0)~title:"Readable"(constant"Readable")(function|Readable->Some()|Optimized|Optimized_legacy->None)(fun()->Readable);case(Tag1)~title:"Optimized"(constant"Optimized")(function|Optimized->Some()|Readable|Optimized_legacy->None)(fun()->Optimized);case(Tag2)~title:"Optimized_legacy"(constant"Optimized_legacy")(function|Optimized_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)(req"balance"Tez.encoding)(req"chain_id"Chain_id.encoding)(opt"source"Contract.encoding)(opt"payer"Contract.encoding)(opt"gas"Gas.Arith.z_integral_encoding)(dft"entrypoint"string"default"))(obj1(opt"unparsing_mode"unparsing_mode_encoding))letrun_code_output_encoding=conv(fun(storage,operations,lazy_storage_diff)->(storage,operations,lazy_storage_diff,lazy_storage_diff))(fun(storage,operations,legacy_lazy_storage_diff,lazy_storage_diff)->letlazy_storage_diff=Option.eitherlazy_storage_difflegacy_lazy_storage_diffin(storage,operations,lazy_storage_diff))(obj4(req"storage"Script.expr_encoding)(req"operations"(listOperation.internal_operation_encoding))(opt"big_map_diff"Lazy_storage.legacy_big_map_diff_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"(list(obj2(req"item"Script.expr_encoding)(opt"annot"string))))lettrace_code_output_encoding=conv(fun(storage,operations,trace,lazy_storage_diff)->(storage,operations,trace,lazy_storage_diff,lazy_storage_diff))(fun(storage,operations,trace,legacy_lazy_storage_diff,lazy_storage_diff)->letlazy_storage_diff=Option.eitherlazy_storage_difflegacy_lazy_storage_diffin(storage,operations,trace,lazy_storage_diff))(obj5(req"storage"Script.expr_encoding)(req"operations"(listOperation.internal_operation_encoding))(req"trace"trace_encoding)(opt"big_map_diff"Lazy_storage.legacy_big_map_diff_encoding)(opt"lazy_storage_diff"Lazy_storage.encoding))letrun_view_encoding=letopenData_encodinginobj8(req"contract"Contract.encoding)(req"entrypoint"string)(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)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")letrun_code_normalized=RPC_service.post_service~description:"Deprecated alias of the .../helpers/scripts/run_code RPC"~query:RPC_query.empty~input:run_code_input_encoding~output:run_code_output_encodingRPC_path.(path/"run_code"/"normalized")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")lettrace_code_normalized=RPC_service.post_service~description:"Deprecated alias of the .../helpers/scripts/trace_code RPC"~query:RPC_query.empty~input:trace_code_input_encoding~output:trace_code_output_encodingRPC_path.(path/"trace_code"/"normalized")letrun_view=RPC_service.post_service~description:"Simulate a call to a view following the TZIP-4 standard. See \
https://gitlab.com/tzip/tzip/-/blob/master/proposals/tzip-4/tzip-4.md#view-entrypoints."~input:run_view_encoding~output:(obj1(req"data"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"run_view")lettypecheck_code=RPC_service.post_service~description:"Typecheck a piece of code in the current context"~query:RPC_query.empty~input:(obj3(req"program"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"legacy"bool))~output:(obj2(req"type_map"Script_tc_errors_registration.type_map_enc)(req"gas"Gas.encoding))RPC_path.(path/"typecheck_code")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 without signature checks"~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")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"string"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.expr*stringoption)listtzresultLwt.t=function|Bot_t,(EmptyCell,EmptyCell)->return_nil|Item_t(ty,rest_ty,annot),(v,rest)->Script_ir_translator.unparse_datactxtUnparsing_mode.unparsing_modetyv>>=?fun(data,_ctxt)->unparse_stack(rest_ty,rest)>|=?funrest->letannot=matchScript_ir_annot.unparse_var_annotannotwith|[]->None|[a]->Somea|_->assertfalseinletdata=Micheline.strip_locationsdatain(data,annot)::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()=map_s(fun(Log(ctxt,loc,stack,stack_ty))->traceCannot_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~loggerctxtUnparsing_mode.unparsing_modestep_constants~script~entrypoint~parameter~internal:true>>=?fun{ctxt;storage;lazy_storage_diff;operations}->logger.get_log()>|=?funtrace->lettrace=Option.value~default:[]tracein({ctxt;storage;lazy_storage_diff;operations},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_parameter_tyctxt~legacy(Micheline.rootexp_ty))>>?=fun(Ex_tyexp_ty,ctxt)->trace_eval(fun()->Lwt.return(Script_ir_translator.serialize_ty_for_errorctxtexp_ty>|?fun(exp_ty,_ctxt)->Script_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)) *)openScript_ir_translatoropenMichelineopenMichelson_v1_primitivesopenScript_ir_annotopenScript_typed_irletrecunparse_comparable_ty:typea.acomparable_ty->Script.node=function|Unit_keytname->Prim(-1,T_unit,[],unparse_type_annottname)|Never_keytname->Prim(-1,T_never,[],unparse_type_annottname)|Int_keytname->Prim(-1,T_int,[],unparse_type_annottname)|Nat_keytname->Prim(-1,T_nat,[],unparse_type_annottname)|Signature_keytname->Prim(-1,T_signature,[],unparse_type_annottname)|String_keytname->Prim(-1,T_string,[],unparse_type_annottname)|Bytes_keytname->Prim(-1,T_bytes,[],unparse_type_annottname)|Mutez_keytname->Prim(-1,T_mutez,[],unparse_type_annottname)|Bool_keytname->Prim(-1,T_bool,[],unparse_type_annottname)|Key_hash_keytname->Prim(-1,T_key_hash,[],unparse_type_annottname)|Key_keytname->Prim(-1,T_key,[],unparse_type_annottname)|Timestamp_keytname->Prim(-1,T_timestamp,[],unparse_type_annottname)|Address_keytname->Prim(-1,T_address,[],unparse_type_annottname)|Chain_id_keytname->Prim(-1,T_chain_id,[],unparse_type_annottname)|Pair_key((l,al),(r,ar),pname)->lettl=add_field_annotalNone(unparse_comparable_tyl)inlettr=add_field_annotarNone(unparse_comparable_tyr)inPrim(-1,T_pair,[tl;tr],unparse_type_annotpname)|Union_key((l,al),(r,ar),tname)->lettl=add_field_annotalNone(unparse_comparable_tyl)inlettr=add_field_annotarNone(unparse_comparable_tyr)inPrim(-1,T_or,[tl;tr],unparse_type_annottname)|Option_key(t,tname)->Prim(-1,T_option,[unparse_comparable_tyt],unparse_type_annottname)letunparse_memo_sizememo_size=letz=Alpha_context.Sapling.Memo_size.unparse_to_zmemo_sizeinInt(-1,z)letrecunparse_ty:typea.aty->Script.node=funty->letreturn(name,args,annot)=Prim(-1,name,args,annot)inmatchtywith|Unit_ttname->return(T_unit,[],unparse_type_annottname)|Int_ttname->return(T_int,[],unparse_type_annottname)|Nat_ttname->return(T_nat,[],unparse_type_annottname)|Signature_ttname->return(T_signature,[],unparse_type_annottname)|String_ttname->return(T_string,[],unparse_type_annottname)|Bytes_ttname->return(T_bytes,[],unparse_type_annottname)|Mutez_ttname->return(T_mutez,[],unparse_type_annottname)|Bool_ttname->return(T_bool,[],unparse_type_annottname)|Key_hash_ttname->return(T_key_hash,[],unparse_type_annottname)|Key_ttname->return(T_key,[],unparse_type_annottname)|Timestamp_ttname->return(T_timestamp,[],unparse_type_annottname)|Address_ttname->return(T_address,[],unparse_type_annottname)|Operation_ttname->return(T_operation,[],unparse_type_annottname)|Chain_id_ttname->return(T_chain_id,[],unparse_type_annottname)|Never_ttname->return(T_never,[],unparse_type_annottname)|Bls12_381_g1_ttname->return(T_bls12_381_g1,[],unparse_type_annottname)|Bls12_381_g2_ttname->return(T_bls12_381_g2,[],unparse_type_annottname)|Bls12_381_fr_ttname->return(T_bls12_381_fr,[],unparse_type_annottname)|Contract_t(ut,tname)->lett=unparse_tyutinreturn(T_contract,[t],unparse_type_annottname)|Pair_t((utl,l_field,l_var),(utr,r_field,r_var),tname)->letannot=unparse_type_annottnameinletutl=unparse_tyutlinlettl=add_field_annotl_fieldl_varutlinletutr=unparse_tyutrinlettr=add_field_annotr_fieldr_varutrinreturn(T_pair,[tl;tr],annot)|Union_t((utl,l_field),(utr,r_field),tname)->letannot=unparse_type_annottnameinletutl=unparse_tyutlinlettl=add_field_annotl_fieldNoneutlinletutr=unparse_tyutrinlettr=add_field_annotr_fieldNoneutrinreturn(T_or,[tl;tr],annot)|Lambda_t(uta,utr,tname)->letta=unparse_tyutainlettr=unparse_tyutrinreturn(T_lambda,[ta;tr],unparse_type_annottname)|Option_t(ut,tname)->letannot=unparse_type_annottnameinletut=unparse_tyutinreturn(T_option,[ut],annot)|List_t(ut,tname)->lett=unparse_tyutinreturn(T_list,[t],unparse_type_annottname)|Ticket_t(ut,tname)->lett=unparse_comparable_tyutinreturn(T_ticket,[t],unparse_type_annottname)|Set_t(ut,tname)->lett=unparse_comparable_tyutinreturn(T_set,[t],unparse_type_annottname)|Map_t(uta,utr,tname)->letta=unparse_comparable_tyutainlettr=unparse_tyutrinreturn(T_map,[ta;tr],unparse_type_annottname)|Big_map_t(uta,utr,tname)->letta=unparse_comparable_tyutainlettr=unparse_tyutrinreturn(T_big_map,[ta;tr],unparse_type_annottname)|Sapling_transaction_t(memo_size,tname)->return(T_sapling_transaction,[unparse_memo_sizememo_size],unparse_type_annottname)|Sapling_state_t(memo_size,tname)->return(T_sapling_state,[unparse_memo_sizememo_size],unparse_type_annottname)endletregister()=letoriginate_dummy_contractctxtscriptbalance=letctxt=Contract.init_origination_noncectxtOperation_hash.zeroinLwt.return(Contract.fresh_contract_from_current_noncectxt)>>=?fun(ctxt,dummy_contract)->Contract.originatectxtdummy_contract~balance~delegate:None~script:(script,None)>>=?functxt->return(ctxt,dummy_contract)inletscript_entrypoint_typectxtexprentrypoint=letctxt=Gas.set_unlimitedctxtinletlegacy=falseinletopenScript_ir_translatorinLwt.return((parse_toplevel~legacyexpr>>?fun(arg_type,_,_,root_name)->parse_parameter_tyctxt~legacyarg_type>>?fun(Ex_tyarg_type,_)->Script_ir_translator.find_entrypoint~root_namearg_typeentrypoint)>>?fun(_f,Ex_tyty)->unparse_tyctxtty>|?fun(ty_node,_)->Micheline.strip_locationsty_node)inletrun_code_registrationctxt()((code,storage,parameter,amount,balance,chain_id,source,payer,gas,entrypoint),unparsing_mode)=letunparsing_mode=Option.value~default:Script_ir_translator.Readableunparsing_modeinletstorage=Script.lazy_exprstorageinletcode=Script.lazy_exprcodeinoriginate_dummy_contractctxt{storage;code}balance>>=?fun(ctxt,dummy_contract)->letsource,payer=match(source,payer)with|Somesource,Somepayer->(source,payer)|Somesource,None->(source,source)|None,Somepayer->(payer,payer)|None,None->(dummy_contract,dummy_contract)inletgas=matchgaswith|Somegas->gas|None->Constants.hard_gas_limit_per_operationctxtinletctxt=Gas.set_limitctxtgasinletstep_constants=letopenScript_interpreterin{source;payer;self=dummy_contract;amount;chain_id}inScript_interpreter.executectxtunparsing_modestep_constants~script:{storage;code}~entrypoint~parameter~internal:true>|=?fun{Script_interpreter.storage;operations;lazy_storage_diff;_}->(storage,operations,lazy_storage_diff)inRegistration.register0S.run_coderun_code_registration;Registration.register0S.run_code_normalizedrun_code_registration;lettrace_code_registrationctxt()((code,storage,parameter,amount,balance,chain_id,source,payer,gas,entrypoint),unparsing_mode)=letunparsing_mode=Option.value~default:Script_ir_translator.Readableunparsing_modeinletstorage=Script.lazy_exprstorageinletcode=Script.lazy_exprcodeinoriginate_dummy_contractctxt{storage;code}balance>>=?fun(ctxt,dummy_contract)->letsource,payer=match(source,payer)with|Somesource,Somepayer->(source,payer)|Somesource,None->(source,source)|None,Somepayer->(payer,payer)|None,None->(dummy_contract,dummy_contract)inletgas=matchgaswith|Somegas->gas|None->Constants.hard_gas_limit_per_operationctxtinletctxt=Gas.set_limitctxtgasinletstep_constants=letopenScript_interpreterin{source;payer;self=dummy_contract;amount;chain_id}inletmoduleUnparsing_mode=structletunparsing_mode=unparsing_modeendinletmoduleInterp=Traced_interpreter(Unparsing_mode)inInterp.executectxtstep_constants~script:{storage;code}~entrypoint~parameter>|=?fun({Script_interpreter.storage;operations;lazy_storage_diff;_},trace)->(storage,operations,trace,lazy_storage_diff)inRegistration.register0S.trace_codetrace_code_registration;Registration.register0S.trace_code_normalizedtrace_code_registration;Registration.register0S.run_view(functxt()(contract,entrypoint,input,chain_id,source,payer,gas,unparsing_mode)->Contract.get_scriptctxtcontract>>=?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->script_entrypoint_typectxtdecoded_scriptentrypoint>>=?funview_ty->View_helpers.extract_view_output_typeentrypointview_ty>>?=funty->Error_monad.traceView_helpers.View_callback_origination_failed@@originate_dummy_contractctxt(View_helpers.make_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_limitctxtgasinletstep_constants=letopenScript_interpreterin{source;payer;self=contract;amount=Tez.zero;chain_id}inletparameter=View_helpers.make_view_parameter(Micheline.rootinput)viewer_contractinScript_interpreter.executectxtunparsing_modestep_constants~script~entrypoint~parameter~internal:true>>=?fun{Script_interpreter.operations;_}->View_helpers.extract_parameter_from_operationsentrypointoperationsviewer_contract>>?=funparameter->Lwt.return(Script_repr.force_decodeparameter));Registration.register0S.typecheck_code(functxt()(expr,maybe_gas,legacy)->letlegacy=Option.value~default:falselegacyinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasinScript_ir_translator.typecheck_code~legacyctxtexpr>|=?fun(res,ctxt)->(res,Gas.levelctxt));Registration.register0S.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.register0S.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.register0S.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.register0S.normalize_script(functxt()(script,unparsing_mode)->letctxt=Gas.set_unlimitedctxtinScript_ir_translator.unparse_codectxtunparsing_mode(Micheline.rootscript)>|=?fun(normalized,_ctxt)->Micheline.strip_locationsnormalized);Registration.register0S.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_tytypinreturn@@Micheline.strip_locationsnormalized);Registration.register0S.run_operation(functxt()({shell;protocol_data=Operation_dataprotocol_data},chain_id)->(* this code is a duplicate of Apply without signature check *)letpartial_precheck_manager_contents(typekind)ctxt(op:kindKind.managercontents):contexttzresultLwt.t=let(Manager_operation{source;fee;counter;operation;gas_limit;storage_limit})=opinGas.consume_limit_in_blockctxtgas_limit>>?=functxt->letctxt=Gas.set_limitctxtgas_limitinFees.check_storage_limitctxt~storage_limit>>?=fun()->Contract.must_be_allocatedctxt(Contract.implicit_contractsource)>>=?fun()->Contract.check_counter_incrementctxtsourcecounter>>=?fun()->(matchoperationwith|Revealpk->Contract.reveal_manager_keyctxtsourcepk|Transaction{parameters;_}->(* Here the data comes already deserialized, so we need to fake the deserialization to mimic apply *)letarg_bytes=Data_encoding.Binary.to_bytes_exnScript.lazy_expr_encodingparametersinletarg=matchData_encoding.Binary.of_bytesScript.lazy_expr_encodingarg_byteswith|Somearg->arg|None->assertfalseinLwt.return@@record_traceApply.Gas_quota_exceeded_init_deserialize@@(* Fail if not enough gas for complete deserialization cost *)(Script.force_decode_in_contextctxtarg>|?fun(_arg,ctxt)->ctxt)|Origination{script;_}->(* Here the data comes already deserialized, so we need to fake the deserialization to mimic apply *)letscript_bytes=Data_encoding.Binary.to_bytes_exnScript.encodingscriptinletscript=matchData_encoding.Binary.of_bytesScript.encodingscript_byteswith|Somescript->script|None->assertfalseinLwt.return@@record_traceApply.Gas_quota_exceeded_init_deserialize@@(* Fail if not enough gas for complete deserialization cost *)(Script.force_decode_in_contextctxtscript.code>>?fun(_code,ctxt)->Script.force_decode_in_contextctxtscript.storage>|?fun(_storage,ctxt)->ctxt)|_->returnctxt)>>=?functxt->Contract.get_manager_keyctxtsource>>=?fun_public_key->(* signature check unplugged from here *)Contract.increment_counterctxtsource>>=?functxt->Contract.spendctxt(Contract.implicit_contractsource)feeinletrecpartial_precheck_manager_contents_list:typekind.Alpha_context.t->kindKind.managercontents_list->contexttzresultLwt.t=functxtcontents_list->matchcontents_listwith|Single(Manager_operation_asop)->partial_precheck_manager_contentsctxtop|Cons((Manager_operation_asop),rest)->partial_precheck_manager_contentsctxtop>>=?functxt->partial_precheck_manager_contents_listctxtrestinletretcontents=(Operation_dataprotocol_data,Apply_results.Operation_metadata{contents})inletoperation:_operation={shell;protocol_data}inlethash=Operation.hash{shell;protocol_data}inletctxt=Contract.init_origination_noncectxthashinletbaker=Tezos_crypto.Signature.V0.Public_key_hash.zeroinmatchprotocol_data.contentswith|Single(Manager_operation_)asop->partial_precheck_manager_contents_listctxtop>>=?functxt->Apply.apply_manager_contents_listctxtOptimizedbakerchain_idop>|=fun(_ctxt,result)->ok@@retresult|Cons(Manager_operation_,_)asop->partial_precheck_manager_contents_listctxtop>>=?functxt->Apply.apply_manager_contents_listctxtOptimizedbakerchain_idop>|=fun(_ctxt,result)->ok@@retresult|_->Apply.apply_contents_listctxtchain_idOptimizedshell.branchbakeroperationoperation.protocol_data.contents>|=?fun(_ctxt,result)->retresult);Registration.register0S.entrypoint_type(functxt()(expr,entrypoint)->script_entrypoint_typectxtexprentrypoint);Registration.register0S.list_entrypoints(functxt()expr->letctxt=Gas.set_unlimitedctxtinletlegacy=falseinletopenScript_ir_translatorinLwt.return(parse_toplevel~legacyexpr>>?fun(arg_type,_,_,root_name)->parse_parameter_tyctxt~legacyarg_type>>?fun(Ex_tyarg_type,_)->Script_ir_translator.list_entrypoints~root_namearg_typectxt>|?fun(unreachable_entrypoint,map)->(unreachable_entrypoint,Entrypoints_map.fold(funentry(_,ty)acc->(entry,Micheline.strip_locationsty)::acc)map[])))letrun_code?unparsing_mode?gas?(entrypoint="default")~script~storage~input~amount~balance~chain_id~source~payerctxtblock=RPC_context.make_call0S.run_codectxtblock()((script,storage,input,amount,balance,chain_id,source,payer,gas,entrypoint),unparsing_mode)lettrace_code?unparsing_mode?gas?(entrypoint="default")~script~storage~input~amount~balance~chain_id~source~payerctxtblock=RPC_context.make_call0S.trace_codectxtblock()((script,storage,input,amount,balance,chain_id,source,payer,gas,entrypoint),unparsing_mode)letrun_view?gas~contract~entrypoint~input~chain_id?source?payer~unparsing_modectxtblock=RPC_context.make_call0S.run_viewctxtblock()(contract,entrypoint,input,chain_id,source,payer,gas,unparsing_mode)lettypecheck_code?gas?legacy~scriptctxtblock=RPC_context.make_call0S.typecheck_codectxtblock()(script,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_scriptctxtblock~script~unparsing_mode=RPC_context.make_call0S.normalize_scriptctxtblock()(script,unparsing_mode)letnormalize_typectxtblock~ty=RPC_context.make_call0S.normalize_typectxtblock()tyletrun_operationctxtblock~op~chain_id=RPC_context.make_call0S.run_operationctxtblock()(op,chain_id)letentrypoint_typectxtblock~script~entrypoint=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:(obj1(req"unparsing_mode"unparsing_mode_encoding))~query:RPC_query.empty~output:(optionScript.encoding)RPC_path.(path/:Contract.rpc_arg/"script"/"normalized")endletregister()=(* Patched RPC: get_storage *)Registration.register1S.get_storage_normalized(functxtcontract()unparsing_mode->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_scriptscript,ctxt)->unparse_scriptctxtunparsing_modescript>>=?fun(script,ctxt)->Script.force_decode_in_contextctxtscript.storage>>?=fun(storage,_ctxt)->return_somestorage);(* Patched RPC: get_script *)Registration.register1S.get_script_normalized(functxtcontract()unparsing_mode->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_scriptscript,ctxt)->unparse_scriptctxtunparsing_modescript>>=?fun(script,_ctxt)->return_somescript)letget_storage_normalizedctxtblock~contract~unparsing_mode=RPC_context.make_call1S.get_storage_normalizedctxtblockcontract()unparsing_modeletget_script_normalizedctxtblock~contract~unparsing_mode=RPC_context.make_call1S.get_script_normalizedctxtblockcontract()unparsing_modeendmoduleBig_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.register2S.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_modeendmoduleForge=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:(obj4(req"priority"uint16)(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)(dft"liquidity_baking_escape_vote"boolfalse))~output:(obj1(req"protocol_data"bytes))RPC_path.(path/"protocol_data")endletregister()=Registration.register0_noctxtS.operations(fun()(shell,proto)->return(Data_encoding.Binary.to_bytes_exnOperation.unsigned_encoding(shell,proto)));Registration.register0_noctxtS.protocol_data(fun()(priority,seed_nonce_hash,proof_of_work_nonce,liquidity_baking_escape_vote)->return(Data_encoding.Binary.to_bytes_exnBlock_header.contents_encoding{priority;seed_nonce_hash;proof_of_work_nonce;liquidity_baking_escape_vote;}))moduleManager=structletoperationsctxtblock~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;})::opsinRPC_context.make_call0S.operationsctxtblock()({branch},Operation.of_listops)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="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;preorigination=None;});]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~level()=operationctxtb~branch(Endorsement{level})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})letdouble_baking_evidencectxtblock~branch~bh1~bh2()=operationctxtblock~branch(Double_baking_evidence{bh1;bh2})letdouble_endorsement_evidencectxtblock~branch~op1~op2~slot()=operationctxtblock~branch(Double_endorsement_evidence{op1;op2;slot})letempty_proof_of_work_nonce=Bytes.makeConstants_repr.proof_of_work_nonce_size'\000'letprotocol_datactxtblock~priority?seed_nonce_hash?(proof_of_work_nonce=empty_proof_of_work_nonce)~liquidity_baking_escape_vote()=RPC_context.make_call0S.protocol_datactxtblock()(priority,seed_nonce_hash,proof_of_work_nonce,liquidity_baking_escape_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_bytesBlock_header.protocol_data_encodingprotocol_datawith|None->Stdlib.failwith"Cant_parse_protocol_data"|Someprotocol_data->protocol_dataletregister()=Registration.register0S.operations(fun_ctxt()(operations,check)->map_s(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_noctxtS.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)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 in the chain (or before when \
negative). For instance, the next block if `offset` is 1."~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")endletregister()=Scripts.register();Forge.register();Parse.register();Contract.register();Big_map.register();Registration.register0S.current_level(functxtq()->Level.from_rawctxt~offset:q.offset(Level.currentctxt).level|>return);Registration.opt_register0S.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::(_::_asrest)->(* The [rev_levels] list is reversed, the last level is the head *)letfirst=List.hd(List.revrest)inreturn(Some(first.level,last.level)))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_servicesend