123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2021 Nomadic Labs, <contact@nomadic-labs.com> *)(* Copyright (c) 2022 Trili Tech, <contact@trili.tech> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)typemode=Observer|Accuser|Batcher|Maintenance|Operator|Customtypepurpose=Publish|Add_messages|Cement|Timeout|Refuteletpurposes=[Publish;Add_messages;Cement;Timeout;Refute]moduleOperator_purpose_map=Map.Make(structtypet=purposeletcompare=Stdlib.compareend)typeoperators=Signature.Public_key_hash.tOperator_purpose_map.ttypefee_parameters=Injector_sigs.fee_parameterOperator_purpose_map.ttypebatcher={simulate:bool;min_batch_elements:int;min_batch_size:int;max_batch_elements:int;max_batch_size:intoption;}typeinjector={retention_period:int;attempts:int;injection_ttl:int}typet={sc_rollup_address:Tezos_crypto.Hashed.Smart_rollup_address.t;boot_sector_file:stringoption;sc_rollup_node_operators:operators;rpc_addr:string;rpc_port:int;metrics_addr:stringoption;reconnection_delay:float;fee_parameters:fee_parameters;mode:mode;loser_mode:Loser_mode.t;dal_node_endpoint:Uri.toption;dac_observer_endpoint:Uri.toption;dac_timeout:Z.toption;batcher:batcher;injector:injector;l2_blocks_cache_size:int;log_kernel_debug:bool;}typeerror+=|Missing_mode_operatorsof{mode:string;missing_operators:stringlist}let()=register_error_kind~id:"sc_rollup.node.missing_mode_operators"~title:"Missing operators for the chosen mode"~description:"Missing operators for the chosen mode."~pp:(funppf(mode,missing_operators)->Format.fprintfppf"@[<hov>Missing operators %a for mode %s.@]"(Format.pp_print_list~pp_sep:(funppf()->Format.fprintfppf",@ ")Format.pp_print_string)missing_operatorsmode)`PermanentData_encoding.(obj2(req"mode"string)(req"missing_operators"(liststring)))(function|Missing_mode_operators{mode;missing_operators}->Some(mode,missing_operators)|_->None)(fun(mode,missing_operators)->Missing_mode_operators{mode;missing_operators})letdefault_data_dir=Filename.concat(Sys.getenv"HOME")".tezos-smart-rollup-node"letstorage_dir="storage"letcontext_dir="context"letdefault_storage_dirdata_dir=Filename.concatdata_dirstorage_dirletdefault_context_dirdata_dir=Filename.concatdata_dircontext_dirletconfig_filename~data_dir=Filename.concatdata_dir"config.json"letdefault_rpc_addr="127.0.0.1"letdefault_rpc_port=8932letdefault_metrics_port=9933letdefault_reconnection_delay=2.0(* seconds *)letmutezmutez={Injector_sigs.mutez}lettezt=mutezInt64.(mul(of_intt)1_000_000L)(* Copied from src/proto_alpha/lib_plugin/mempool.ml *)letdefault_minimal_fees=mutez100Lletdefault_minimal_nanotez_per_gas_unit=Q.of_int100letdefault_minimal_nanotez_per_byte=Q.of_int1000letdefault_force_low_fee=falseletdefault_fee_cap=tez1letdefault_burn_cap=mutez0L(* The below default fee and burn limits are computed by taking into account
the worst fee found in the tests for the rollup node.
We take as base the cost of commitment cementation, which is 719 mutez in fees:
- Commitment publishing is 1.37 times more expensive.
- Message submission is 0.7 times more expensive, so cheaper but it depends on
the size of the message.
- For refutation games:
- Open is 1.55 times more expensive.
- Dissection move is 2.31 times more expensive.
- Proof move is 1.47 times more expensive but depends on the size of the proof.
- Timeout move is 1.34 times more expensive.
We set a fee limit of 1 tz for cementation (instead of 719 mutez) which
should be plenty enough even if the gas price or gas consumption
increases. We adjust the other limits in proportion.
*)letdefault_fee=function|Cement->tez1|Publish->tez2|Add_messages->(* We keep this limit even though it depends on the size of the message
because the rollup node pays the fees for messages submitted by the
**users**. *)tez1|Timeout->tez2|Refute->(* Should be 3 based on comment above but we want to make sure we inject
refutation moves even if the proof is large. The stake is high (we can
lose the 10k deposit or we can get the reward). *)tez5letdefault_burn=function|Publish->(* The first commitment can store data. *)tez1|Add_messages->tez0|Cement->tez0|Timeout->tez0|Refute->(* A refutation move can store data, e.g. opening a game. *)tez1letdefault_fee_parameter?purpose()=letfee_cap,burn_cap=matchpurposewith|None->(default_fee_cap,default_burn_cap)|Somepurpose->(default_feepurpose,default_burnpurpose)in{Injector_sigs.minimal_fees=default_minimal_fees;minimal_nanotez_per_byte=default_minimal_nanotez_per_byte;minimal_nanotez_per_gas_unit=default_minimal_nanotez_per_gas_unit;force_low_fee=default_force_low_fee;fee_cap;burn_cap;}letdefault_fee_parameters=List.fold_left(funaccpurpose->Operator_purpose_map.addpurpose(default_fee_parameter~purpose())acc)Operator_purpose_map.emptypurposesletdefault_batcher_simulate=trueletdefault_batcher_min_batch_elements=10letdefault_batcher_min_batch_size=10letdefault_batcher_max_batch_elements=max_intletdefault_batcher={simulate=default_batcher_simulate;min_batch_elements=default_batcher_min_batch_elements;min_batch_size=default_batcher_min_batch_size;max_batch_elements=default_batcher_max_batch_elements;max_batch_size=None;}letdefault_injector={retention_period=2048;attempts=100;injection_ttl=120}letmax_injector_retention_period=5*8192(* Preserved cycles (5) for mainnet *)letdefault_l2_blocks_cache_size=64letstring_of_purpose=function|Publish->"publish"|Add_messages->"add_messages"|Cement->"cement"|Timeout->"timeout"|Refute->"refute"letpurpose_of_string=function|"publish"->SomePublish|"add_messages"->SomeAdd_messages|"cement"->SomeCement|"timeout"->SomeTimeout|"refute"->SomeRefute|_->Noneletpurpose_of_string_exns=matchpurpose_of_stringswith|Somep->p|None->invalid_arg("purpose_of_string "^s)letadd_fallbacksmapfallbacks=List.fold_left(funmap(missing_purpose,fallback_purpose)->ifOperator_purpose_map.memmissing_purposemapthen(* No missing purpose, don't fallback *)mapelsematchOperator_purpose_map.findfallback_purposemapwith|None->(* Nothing to fallback on *)map|Someoperator->Operator_purpose_map.addmissing_purposeoperatormap)mapfallbacksletmake_purpose_map~defaultbindings=letmap=Operator_purpose_map.of_seq@@List.to_seqbindingsinletmap=add_fallbacksmap[(Timeout,Refute)]inmatchdefaultwith|None->map|Somedefault->List.fold_left(funmappurpose->ifOperator_purpose_map.mempurposemapthenmapelseOperator_purpose_map.addpurposedefaultmap)mappurposesletoperator_purpose_map_encodingencoding=letopenData_encodinginletschema=letopenJson_schemainletv_schemap=Data_encoding.Json.schema(encodingp)inletv_schema_rp=root(v_schemap)inletkind=Object{properties=List.map(funpurpose->(string_of_purposepurpose,v_schema_rpurpose,false,None))purposes;pattern_properties=[];additional_properties=None;min_properties=0;max_properties=None;schema_dependencies=[];property_dependencies=[];}inupdate(elementkind)(v_schemaPublish(* Dummy for definitions *))inconv~schema(funmap->letfields=Operator_purpose_map.bindingsmap|>List.map(fun(p,v)->(string_of_purposep,Data_encoding.Json.construct(encodingp)v))in`Ofields)(function|`Ofields->List.map(fun(p,v)->letpurpose=purpose_of_string_exnpin(purpose,Data_encoding.Json.destruct(encodingpurpose)v))fields|>List.to_seq|>Operator_purpose_map.of_seq|_->assertfalse)Data_encoding.Json.encodingletoperators_encoding=operator_purpose_map_encoding(fun_->Signature.Public_key_hash.encoding)(* Encoding for Tez amounts, replicated from mempool. *)lettez_encoding=letopenData_encodinginletdecode{Injector_sigs.mutez}=Z.of_int64mutezinletencode=Json.wrap_error(funi->{Injector_sigs.mutez=Z.to_int64i})inData_encoding.def"mutez"~title:"A millionth of a tez"~description:"One million mutez make a tez (1 tez = 1e6 mutez)"(convdecodeencoden)(* Encoding for nano-Tez amounts, replicated from mempool. *)letnanotez_encoding=letopenData_encodingindef"nanotez"~title:"A thousandth of a mutez"~description:"One thousand nanotez make a mutez (1 tez = 1e9 nanotez)"(conv(funq->(q.Q.num,q.Q.den))(fun(num,den)->{Q.num;den})(tup2zz))letfee_parameter_encodingpurpose=letopenData_encodinginconv(fun{Injector_sigs.minimal_fees;minimal_nanotez_per_byte;minimal_nanotez_per_gas_unit;force_low_fee;fee_cap;burn_cap;}->(minimal_fees,minimal_nanotez_per_byte,minimal_nanotez_per_gas_unit,force_low_fee,fee_cap,burn_cap))(fun(minimal_fees,minimal_nanotez_per_byte,minimal_nanotez_per_gas_unit,force_low_fee,fee_cap,burn_cap)->{minimal_fees;minimal_nanotez_per_byte;minimal_nanotez_per_gas_unit;force_low_fee;fee_cap;burn_cap;})(obj6(dft"minimal-fees"~description:"Exclude operations with lower fees"tez_encodingdefault_minimal_fees)(dft"minimal-nanotez-per-byte"~description:"Exclude operations with lower fees per byte"nanotez_encodingdefault_minimal_nanotez_per_byte)(dft"minimal-nanotez-per-gas-unit"~description:"Exclude operations with lower gas fees"nanotez_encodingdefault_minimal_nanotez_per_gas_unit)(dft"force-low-fee"~description:"Don't check that the fee is lower than the estimated default"booldefault_force_low_fee)(dft"fee-cap"~description:"The fee cap"tez_encoding(default_feepurpose))(dft"burn-cap"~description:"The burn cap"tez_encoding(default_burnpurpose)))letfee_parameters_encoding=operator_purpose_map_encodingfee_parameter_encodingletmodes=[Observer;Batcher;Maintenance;Operator;Custom]letstring_of_mode=function|Observer->"observer"|Accuser->"accuser"|Batcher->"batcher"|Maintenance->"maintenance"|Operator->"operator"|Custom->"custom"letmode_of_string=function|"observer"->OkObserver|"accuser"->OkAccuser|"batcher"->OkBatcher|"maintenance"->OkMaintenance|"operator"->OkOperator|"custom"->OkCustom|_->Error[Exn(Failure"Invalid mode")]letdescription_of_mode=function|Observer->"Only follows the chain, reconstructs and interprets inboxes"|Accuser->"Only publishes commitments for conflicts and play refutation games"|Batcher->"Accepts transactions in its queue and batches them on the L1"|Maintenance->"Follows the chain and publishes commitments, cement and refute"|Operator->"Equivalent to maintenance + batcher"|Custom->"In this mode, only operations that have a corresponding operator/signer \
are injected"letmode_encoding=Data_encoding.string_enum[("observer",Observer);("accuser",Accuser);("batcher",Batcher);("maintenance",Maintenance);("operator",Operator);("custom",Custom);]letbatcher_encoding=letopenData_encodinginconv_with_guard(fun{simulate;min_batch_elements;min_batch_size;max_batch_elements;max_batch_size;}->(simulate,min_batch_elements,min_batch_size,max_batch_elements,max_batch_size))(fun(simulate,min_batch_elements,min_batch_size,max_batch_elements,max_batch_size)->letopenResult_syntaxinleterror_whencs=ifcthenErrorselsereturn_unitinlet*()=error_when(min_batch_size<=0)"min_batch_size must be positive"inlet*()=matchmax_batch_sizewith|Somemwhenm<min_batch_size->Error"max_batch_size must be greater than min_batch_size"|_->return_unitinlet*()=error_when(min_batch_elements<=0)"min_batch_size must be positive"inlet+()=error_when(max_batch_elements<min_batch_elements)"max_batch_elements must be greater than min_batch_elements"in{simulate;min_batch_elements;min_batch_size;max_batch_elements;max_batch_size;})@@obj5(dft"simulate"booldefault_batcher_simulate)(dft"min_batch_elements"int31default_batcher_min_batch_elements)(dft"min_batch_size"int31default_batcher_min_batch_size)(dft"max_batch_elements"int31default_batcher_max_batch_elements)(opt"max_batch_size"int31)letinjector_encoding:injectorData_encoding.t=letopenData_encodinginconv(fun{retention_period;attempts;injection_ttl}->(retention_period,attempts,injection_ttl))(fun(retention_period,attempts,injection_ttl)->ifretention_period>max_injector_retention_periodthenFormat.ksprintfStdlib.failwith"injector.retention_period should be smaller than %d"max_injector_retention_period;ifinjection_ttl<1thenStdlib.failwith"injector.injection_ttl should be at least 1";{retention_period;attempts;injection_ttl})@@obj3(dft"retention_period"uint16default_injector.retention_period)(dft"attempts"uint16default_injector.attempts)(dft"injection_ttl"uint16default_injector.injection_ttl)letencoding:tData_encoding.t=letopenData_encodinginconv(fun{sc_rollup_address;boot_sector_file;sc_rollup_node_operators;rpc_addr;rpc_port;metrics_addr;reconnection_delay;fee_parameters;mode;loser_mode;dal_node_endpoint;dac_observer_endpoint;dac_timeout;batcher;injector;l2_blocks_cache_size;log_kernel_debug;}->((sc_rollup_address,boot_sector_file,sc_rollup_node_operators,rpc_addr,rpc_port,metrics_addr,reconnection_delay,fee_parameters,mode,loser_mode),(dal_node_endpoint,dac_observer_endpoint,dac_timeout,batcher,injector,l2_blocks_cache_size,log_kernel_debug)))(fun((sc_rollup_address,boot_sector_file,sc_rollup_node_operators,rpc_addr,rpc_port,metrics_addr,reconnection_delay,fee_parameters,mode,loser_mode),(dal_node_endpoint,dac_observer_endpoint,dac_timeout,batcher,injector,l2_blocks_cache_size,log_kernel_debug))->{sc_rollup_address;boot_sector_file;sc_rollup_node_operators;rpc_addr;rpc_port;metrics_addr;reconnection_delay;fee_parameters;mode;loser_mode;dal_node_endpoint;dac_observer_endpoint;dac_timeout;batcher;injector;l2_blocks_cache_size;log_kernel_debug;})(merge_objs(obj10(req"smart-rollup-address"~description:"Smart rollup address"Tezos_crypto.Hashed.Smart_rollup_address.encoding)(opt"boot-sector"~description:"Boot sector"string)(req"smart-rollup-node-operator"~description:"Operators that sign operations of the smart rollup, by purpose"operators_encoding)(dft"rpc-addr"~description:"RPC address"stringdefault_rpc_addr)(dft"rpc-port"~description:"RPC port"uint16default_rpc_port)(opt"metrics-addr"~description:"Metrics address"string)(dft"reconnection_delay"~description:"The reconnection (to the tezos node) delay in seconds"floatdefault_reconnection_delay)(dft"fee-parameters"~description:"The fee parameters for each purpose used when injecting \
operations in L1"fee_parameters_encodingdefault_fee_parameters)(req~description:"The mode for this rollup node""mode"mode_encoding)(dft"loser-mode"~description:"If enabled, the rollup node will issue wrong commitments (for \
test only!)"Loser_mode.encodingLoser_mode.no_failures))(obj7(opt"DAL node endpoint"Tezos_rpc.Encoding.uri_encoding)(opt"dac-observer-client"Tezos_rpc.Encoding.uri_encoding)(opt"dac-timeout"Data_encoding.z)(dft"batcher"batcher_encodingdefault_batcher)(dft"injector"injector_encodingdefault_injector)(dft"l2_blocks_cache_size"int31default_l2_blocks_cache_size)(dft"log-kernel-debug"Data_encoding.boolfalse)))letcheck_modeconfig=letopenResult_syntaxinletcheck_purposespurposes=letmissing_operators=List.filter(funp->not(Operator_purpose_map.mempconfig.sc_rollup_node_operators))purposesinifmissing_operators<>[]thenletmode=string_of_modeconfig.modeinletmissing_operators=List.mapstring_of_purposemissing_operatorsintzfail(Missing_mode_operators{mode;missing_operators})elsereturn_unitinletnarrow_purposespurposes=let+()=check_purposespurposesinletsc_rollup_node_operators=Operator_purpose_map.filter(funop_purpose_->List.mem~equal:Stdlib.(=)op_purposepurposes)config.sc_rollup_node_operatorsin{configwithsc_rollup_node_operators}inmatchconfig.modewith|Observer->narrow_purposes[]|Batcher->narrow_purposes[Add_messages]|Accuser->narrow_purposes[Publish;Refute]|Maintenance->narrow_purposes[Publish;Cement;Refute]|Operator->narrow_purposes[Publish;Cement;Add_messages;Refute]|Custom->returnconfigletrefutation_player_buffer_levels=5letloser_warning_messageconfig=ifconfig.loser_mode<>Loser_mode.no_failuresthenFormat.printf{|
************ WARNING *************
This rollup node is in loser mode.
This should be used for test only!
************ WARNING *************
|}letsave~force~data_dirconfig=loser_warning_messageconfig;letopenLwt_result_syntaxinletjson=Data_encoding.Json.constructencodingconfiginletconfig_file=config_filename~data_dirinlet*!exists=Lwt_unix.file_existsconfig_fileinifexists&¬forcethenfailwith"Configuration file %S already exists. Use --force to overwrite."config_fileelselet*!()=Lwt_utils_unix.create_dirdata_dirinLwt_utils_unix.Json.write_fileconfig_filejsonletload~data_dir=letopenLwt_result_syntaxinlet+json=Lwt_utils_unix.Json.read_file(config_filename~data_dir)inletconfig=Data_encoding.Json.destructencodingjsoninloser_warning_messageconfig;config