123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592(*****************************************************************************)(* *)(* 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. *)(* *)(*****************************************************************************)(** This module introduces the semantics of Proof-generating Virtual Machines.
A PVM defines an operational semantics for some computational model. The
specificity of PVMs, in comparison with standard virtual machines, is their
ability to generate and to validate a *compact* proof that a given atomic
execution step turned a given state into another one.
In the smart-contract rollups, PVMs are used for two purposes:
- They allow for the externalization of rollup execution by completely
specifying the operational semantics of a given rollup. This
standardization of the semantics gives a unique and executable source of
truth about the interpretation of smart-contract rollup inboxes, seen as a
transformation of a rollup state.
- They allow for the validation or refutation of a claim that the processing
of some messages led to a given new rollup state (given an actual source
of truth about the nature of these messages).
*)(** An input to a PVM is the [message_counter] element of an inbox at
a given [inbox_level] and contains a given [payload].
According the rollup management protocol, the payload must be obtained
through {!Sc_rollup_inbox_message_repr.serialize} which follows a documented
format.
*)typeinbox_message={inbox_level:Raw_level_repr.t;message_counter:Z.t;payload:Sc_rollup_inbox_message_repr.serialized;}typereveal_data=|Raw_dataofstring|MetadataofSc_rollup_metadata_repr.t|Dal_pageofDal_slot_repr.Page.contentoptiontypeinput=Inbox_messageofinbox_message|Revealofreveal_dataletpp_inbox_messagefmt{inbox_level;message_counter;_}=Format.fprintffmt"@[<v 2>level: %a@,message index: %a@]"Raw_level_repr.ppinbox_levelZ.pp_printmessage_counterletpp_reveal_datafmt=function|Raw_data_->Format.pp_print_stringfmt"raw data"|Metadatametadata->Sc_rollup_metadata_repr.ppfmtmetadata|Dal_pagecontent_opt->Format.pp_print_option~none:(funfmt()->Format.pp_print_stringfmt"<No_dal_data>")(funfmt_a->Format.fprintffmt"<Some_dal_data>")fmtcontent_optletpp_inputfmt=function|Inbox_messagemsg->Format.fprintffmt"@[<v 2>inbox message:@,%a@]"pp_inbox_messagemsg|Revealreveal->Format.fprintffmt"@[<v 2>reveal: %a@]"pp_reveal_datareveal(** [inbox_message_encoding] encoding value for {!inbox_message}. *)letinbox_message_encoding=letopenData_encodinginconv(fun{inbox_level;message_counter;payload}->(inbox_level,message_counter,(payload:>string)))(fun(inbox_level,message_counter,payload)->letpayload=Sc_rollup_inbox_message_repr.unsafe_of_stringpayloadin{inbox_level;message_counter;payload})(obj3(req"inbox_level"Raw_level_repr.encoding)(req"message_counter"n)(req"payload"(stringHex)))letreveal_data_encoding=letopenData_encodinginletkindname=req"reveal_data_kind"(constantname)inletcase_raw_data=case~title:"raw data"(Tag0)(obj2(kind"raw_data")(req"raw_data"(check_sizeConstants_repr.sc_rollup_message_size_limitVariable.(stringHex))))(functionRaw_datam->Some((),m)|_->None)(fun((),m)->Raw_datam)andcase_metadata=case~title:"metadata"(Tag1)(obj2(kind"metadata")(req"metadata"Sc_rollup_metadata_repr.encoding))(functionMetadatamd->Some((),md)|_->None)(fun((),md)->Metadatamd)inletcase_dal_page=case~title:"dal page"(Tag2)(obj2(kind"dal_page")(req"dal_page_content"(option(bytesHex))))(functionDal_pagep->Some((),p)|_->None)(fun((),p)->Dal_pagep)inunion[case_raw_data;case_metadata;case_dal_page]letinput_encoding=letopenData_encodinginletkindname=req"input_kind"(constantname)inletcase_inbox_message=case~title:"inbox msg"(Tag0)(obj2(kind"inbox_message")(req"inbox_message"inbox_message_encoding))(functionInbox_messagem->Some((),m)|_->None)(fun((),m)->Inbox_messagem)andcase_reveal_revelation=case~title:"reveal"(Tag1)(obj2(kind"reveal_revelation")(req"reveal_data"reveal_data_encoding))(functionReveald->Some((),d)|_->None)(fun((),d)->Reveald)inunion[case_inbox_message;case_reveal_revelation](** [input_equal i1 i2] return whether [i1] and [i2] are equal. *)letinbox_message_equalab=let{inbox_level;message_counter;payload}=ain(* To be robust to the addition of fields in [input] *)Raw_level_repr.equalinbox_levelb.inbox_level&&Z.equalmessage_counterb.message_counter&&String.equal(payload:>string)(b.payload:>string)letreveal_data_equalab=match(a,b)with|Raw_dataa,Raw_datab->String.equalab|Raw_data_,_->false|Metadataa,Metadatab->Sc_rollup_metadata_repr.equalab|Metadata_,_->false|Dal_pagea,Dal_pageb->Option.equalBytes.equalab|Dal_page_,_->falseletinput_equalab=match(a,b)with|Inbox_messagea,Inbox_messageb->inbox_message_equalab|Inbox_message_,_->false|Reveala,Revealb->reveal_data_equalab|Reveal_,_->falsemoduleInput_hash=Blake2B.Make(Base58)(structletname="Smart_rollup_input_hash"lettitle="A smart rollup input hash"letb58check_prefix="\001\118\125\135"(* "scd1(37)" decoded from base 58. *)letsize=Some20end)typereveal=|Reveal_raw_dataofSc_rollup_reveal_hash.t|Reveal_metadata|Request_dal_pageofDal_slot_repr.Page.tletreveal_encoding=letopenData_encodinginletkindname=req"reveal_kind"(constantname)inletcase_raw_data=case~title:"Reveal_raw_data"(Tag0)(obj2(kind"reveal_raw_data")(req"input_hash"Sc_rollup_reveal_hash.encoding))(functionReveal_raw_datas->Some((),s)|_->None)(fun((),s)->Reveal_raw_datas)andcase_metadata=case~title:"Reveal_metadata"(Tag1)(obj1(kind"reveal_metadata"))(functionReveal_metadata->Some()|_->None)(fun()->Reveal_metadata)inletcase_dal_page=case~title:"Request_dal_page"(Tag2)(obj2(kind"request_dal_page")(req"page_id"Dal_slot_repr.Page.encoding))(functionRequest_dal_pages->Some((),s)|_->None)(fun((),s)->Request_dal_pages)inunion[case_raw_data;case_metadata;case_dal_page](** [is_reveal_enabled] is the type of a predicate that tells if a kind of
reveal is activated at a certain block level. *)typeis_reveal_enabled=current_block_level:Raw_level_repr.t->reveal->boolletis_reveal_enabled_predicate(t:Constants_parametric_repr.sc_rollup_reveal_activation_level):is_reveal_enabled=fun~current_block_levelreveal->letactivation_level=matchrevealwith|Reveal_raw_datah->(matchSc_rollup_reveal_hash.scheme_of_hashhwith|Blake2B->t.raw_data.blake2B)|Reveal_metadata->t.metadata|Request_dal_page_->t.dal_pageinRaw_level_repr.(current_block_level>=activation_level)(** The PVM's current input expectations:
- [No_input_required] if the machine is busy and has no need for new input.
- [Initial] if the machine has never received an input so expects the very
first item in the inbox.
- [First_after (level, counter)] expects whatever comes next after that
position in the inbox.
- [Needs_metadata] if the machine needs the metadata to continue
its execution.
*)typeinput_request=|No_input_required|Initial|First_afterofRaw_level_repr.t*Z.t|Needs_revealofreveal(** [input_request_encoding] encoding value for {!input_request}. *)letinput_request_encoding=letopenData_encodinginletkindname=req"input_request_kind"(constantname)inunion~tag_size:`Uint8[case~title:"No_input_required"(Tag0)(obj1(kind"no_input_required"))(functionNo_input_required->Some()|_->None)(fun()->No_input_required);case~title:"Initial"(Tag1)(obj1(kind"initial"))(functionInitial->Some()|_->None)(fun()->Initial);case~title:"First_after"(Tag2)(obj3(kind"first_after")(req"level"Raw_level_repr.encoding)(req"counter"n))(function|First_after(level,counter)->Some((),level,counter)|_->None)(fun((),level,counter)->First_after(level,counter));case~title:"Needs_reveal"(Tag3)(obj2(kind"needs_reveal")(req"reveal"reveal_encoding))(functionNeeds_revealp->Some((),p)|_->None)(fun((),p)->Needs_revealp);]letpp_revealfmt=function|Reveal_raw_datahash->Sc_rollup_reveal_hash.ppfmthash|Reveal_metadata->Format.pp_print_stringfmt"Reveal metadata"|Request_dal_pageid->Dal_slot_repr.Page.ppfmtid(** [pp_input_request fmt i] pretty prints the given input [i] to the formatter
[fmt]. *)letpp_input_requestfmtrequest=matchrequestwith|No_input_required->Format.fprintffmt"No_input_required"|Initial->Format.fprintffmt"Initial"|First_after(l,n)->Format.fprintffmt"First_after (level = %a, counter = %a)"Raw_level_repr.pplZ.pp_printn|Needs_revealreveal->Format.fprintffmt"Needs reveal of %a"pp_revealrevealletreveal_equalp1p2=match(p1,p2)with|Reveal_raw_datah1,Reveal_raw_datah2->Sc_rollup_reveal_hash.equalh1h2|Reveal_raw_data_,_->false|Reveal_metadata,Reveal_metadata->true|Reveal_metadata,_->false|Request_dal_pagea,Request_dal_pageb->Dal_slot_repr.Page.equalab|Request_dal_page_,_->false(** [input_request_equal i1 i2] return whether [i1] and [i2] are equal. *)letinput_request_equalab=match(a,b)with|No_input_required,No_input_required->true|No_input_required,_->false|Initial,Initial->true|Initial,_->false|First_after(l,n),First_after(m,o)->Raw_level_repr.equallm&&Z.equalno|First_after_,_->false|Needs_revealp1,Needs_revealp2->reveal_equalp1p2|Needs_reveal_,_->false(** Type that describes output values. *)typeoutput={outbox_level:Raw_level_repr.t;(** The outbox level containing the message. The level corresponds to the
inbox level for which the message was produced. *)message_index:Z.t;(** The message index. *)message:Sc_rollup_outbox_message_repr.t;(** The message itself. *)}(** [output_encoding] encoding value for {!output}. *)letoutput_encoding=letopenData_encodinginconv(fun{outbox_level;message_index;message}->(outbox_level,message_index,message))(fun(outbox_level,message_index,message)->{outbox_level;message_index;message})(obj3(req"outbox_level"Raw_level_repr.encoding)(req"message_index"n)(req"message"Sc_rollup_outbox_message_repr.encoding))(** [pp_output fmt o] pretty prints the given output [o] to the formatter
[fmt]. *)letpp_outputfmt{outbox_level;message_index;message}=Format.fprintffmt"@[%a@;%a@;%a@;@]"Raw_level_repr.ppoutbox_levelZ.pp_printmessage_indexSc_rollup_outbox_message_repr.ppmessagemoduletypeS=sig(** The state of the PVM denotes a state of the rollup.
The life cycle of the PVM is as follows. It starts its execution
from an {!initial_state}. The initial state is specialized at
origination with a [boot_sector], using the
{!install_boot_sector} function. The resulting state is call the
“genesis” of the rollup.
Afterwards, we classify states into two categories: "internal
states" do not require any external information to be executed
while "input states" are waiting for some information from the
inbox to be executable. *)typestatevalpp:state->(Format.formatter->unit->unit)Lwt.t(** A [context] represents the executable environment needed by the state to
exist. Typically, the rollup node storage can be part of this context to
allow the PVM state to be persistent. *)typecontext(** A [hash] characterizes the contents of a state. *)typehash=Sc_rollup_repr.State_hash.t(** During interactive refutation games, a player may need to provide a proof
that a given execution step is valid. The PVM implementation is
responsible for ensuring that this proof type has the correct semantics.
A proof [p] has four parameters:
- [start_hash := proof_start_state p]
- [stop_hash := proof_stop_state p]
- [input_requested := proof_input_requested p]
- [input_given := proof_input_given p]
The following predicate must hold of a valid proof:
[exists start_state, stop_state.
(state_hash start_state == start_hash)
AND (Option.map state_hash stop_state == stop_hash)
AND (is_input_state start_state == input_requested)
AND (match (input_given, input_requested) with
| (None, No_input_required) -> eval start_state == stop_state
| (None, Initial) -> stop_state == None
| (None, First_after (l, n)) -> stop_state == None
| (Some input, No_input_required) -> true
| (Some input, Initial) ->
set_input input_given start_state == stop_state
| (Some input, First_after (l, n)) ->
set_input input_given start_state == stop_state)]
In natural language---the two hash parameters [start_hash] and [stop_hash]
must have actual [state] values (or possibly [None] in the case of
[stop_hash]) of which they are the hashes. The [input_requested] parameter
must be the correct request from the [start_hash], given according to
[is_input_state]. Finally there are four possibilities of [input_requested]
and [input_given].
- if no input is required, or given, the proof is a simple [eval]
step ;
- if input was required but not given, the [stop_hash] must be
[None] (the machine is blocked) ;
- if no input was required but some was given, this makes no sense
and it doesn't matter if the proof is valid or invalid (this
case will be ruled out by the inbox proof anyway) ;
- finally, if input was required and given, the proof is a
[set_input] step. *)typeproof(** [proof]s are embedded in L1 refutation game operations using
[proof_encoding]. Given that the size of L1 operations are limited, it is
of *critical* importance to make sure that no execution step of the PVM
can generate proofs that do not fit in L1 operations when encoded. If such
a proof existed, the rollup could get stuck. *)valproof_encoding:proofData_encoding.t(** [proof_start_state proof] returns the initial state hash of the [proof]
execution step. *)valproof_start_state:proof->hash(** [proof_stop_state proof] returns the final state hash of the [proof]
execution step. *)valproof_stop_state:proof->hash(** [state_hash state] returns a compressed representation of [state]. *)valstate_hash:state->hashLwt.t(** [initial_state ~empty] is the initial state of the PVM, before its
specialization with a given [boot_sector]. The initial state is built on
the [empty] state which must be provided. *)valinitial_state:empty:state->stateLwt.t(** [install_boot_sector state boot_sector] specializes the initial
[state] of a PVM using a dedicated [boot_sector], submitted at
the origination of the rollup. *)valinstall_boot_sector:state->string->stateLwt.t(** [is_input_state ~is_reveal_enabled state] returns the input expectations of the
[state]---does it need input, and if so, how far through the inbox
has it read so far? *)valis_input_state:is_reveal_enabled:is_reveal_enabled->state->input_requestLwt.t(** [set_input input state] sets [input] in [state] as the next
input to be processed. This must answer the [input_request]
from [is_input_state state]. *)valset_input:input->state->stateLwt.t(** [eval s0] returns a state [s1] resulting from the
execution of an atomic step of the rollup at state [s0]. *)valeval:state->stateLwt.t(** [verify_proof ~is_reveal_enabled input p] checks the proof [p] with input [input]
and returns the [input_request] before the evaluation of the proof. See the
doc-string for the [proof] type.
[verify_proof input p] fails when the proof is invalid in regards to the
given input. *)valverify_proof:is_reveal_enabled:is_reveal_enabled->inputoption->proof->input_requesttzresultLwt.t(** [produce_proof ctxt ~is_reveal_enabled input_given state] should return a [proof]
for the PVM step starting from [state], if possible. This may fail for
a few reasons:
- the [input_given] doesn't match the expectations of [state] ;
- the [context] for this instance of the PVM doesn't have access
to enough of the [state] to build the proof. *)valproduce_proof:context->is_reveal_enabled:is_reveal_enabled->inputoption->state->prooftzresultLwt.t(** The following type is inhabited by the proofs that a given [output]
is part of the outbox of a given [state]. *)typeoutput_proof(** [output_proof_encoding] encoding value for [output_proof]s. *)valoutput_proof_encoding:output_proofData_encoding.t(** [output_of_output_proof proof] returns the [output] that is referred to in
[proof]'s statement. *)valoutput_of_output_proof:output_proof->output(** [state_of_output_proof proof] returns the [state] hash that is referred to
in [proof]'s statement. *)valstate_of_output_proof:output_proof->hash(** [verify_output_proof output_proof] returns the [output_proof]'s output
iff the proof is a valid witness that its [output] is part of its
[state]'s outbox. *)valverify_output_proof:output_proof->outputtzresultLwt.t(** [produce_output_proof ctxt state output] returns a proof that witnesses
the fact that [output] is part of [state]'s outbox. *)valproduce_output_proof:context->state->output->(output_proof,error)resultLwt.t(** [check_dissection ~default_number_of_sections ~start_chunk
~stop_chunk chunks] fails if the dissection encoded by the list
[[start_chunk] @ chunks @ [stop_chunk]] does not satisfy the
properties expected by the PVM. *)valcheck_dissection:default_number_of_sections:int->start_chunk:Sc_rollup_dissection_chunk_repr.t->stop_chunk:Sc_rollup_dissection_chunk_repr.t->Sc_rollup_dissection_chunk_repr.tlist->unittzresult(** [get_current_level state] returns the current level of the [state],
returns [None] if it is not possible to compute the level. *)valget_current_level:state->Raw_level_repr.toptionLwt.tmoduleInternal_for_tests:sig(** [insert_failure state] corrupts the PVM state. This is used in
the loser mode of the rollup node. *)valinsert_failure:state->stateLwt.tendendmoduletypeGeneric_pvm_context_sig=sigmoduleTree:Context.TREEwithtypekey=stringlistandtypevalue=bytestypetree=Tree.treetypeproofvalproof_encoding:proofData_encoding.tvalproof_before:proof->Sc_rollup_repr.State_hash.tvalproof_after:proof->Sc_rollup_repr.State_hash.tvalverify_proof:proof->(tree->(tree*'a)Lwt.t)->(tree*'a)optionLwt.tvalproduce_proof:Tree.t->tree->(tree->(tree*'a)Lwt.t)->(proof*'a)optionLwt.tend