123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.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. *)(* *)(*****************************************************************************)typeparameters=Dal.parameters={redundancy_factor:int;page_size:int;slot_size:int;number_of_shards:int;}letparameters_encoding=Dal.parameters_encodingmoduleCommitment=struct(* DAL/FIXME https://gitlab.com/tezos/tezos/-/issues/3389
It is not clear whether the size of the slot associated to the
commitment should be given here. *)typet=Dal.commitmentletequal=Dal.Commitment.equalletencoding=Dal.Commitment.encodingletpp=Dal.Commitment.ppletzero=Dal.Commitment.zeroendmoduleCommitment_proof=structtypet=Dal.commitment_proofletencoding=Dal.Commitment_proof.encodingletzero=Dal.Commitment_proof.zeroendmoduleIndex=structtypet=intletmax_value=255letencoding=Data_encoding.uint8letpp=Format.pp_print_intletzero=0letof_intslot_index=ifCompare.Int.(slot_index<=max_value&&slot_index>=zero)thenSomeslot_indexelseNoneletto_intslot_index=slot_index[@@ocaml.inlinealways]letcompare=Compare.Int.compareletequal=Compare.Int.equalendmoduleHeader=structtypeid={published_level:Raw_level_repr.t;index:Index.t}typet={id:id;commitment:Commitment.t}typeoperation={header:t;proof:Commitment_proof.t}letslot_id_equal{published_level;index}s2=Raw_level_repr.equalpublished_levels2.published_level&&Index.equalindexs2.indexletequal{id;commitment}s2=slot_id_equalids2.id&&Commitment.equalcommitments2.commitmentletcompare_slot_id{published_level;index}s2=letc=Raw_level_repr.comparepublished_levels2.published_levelinifCompare.Int.(c<>0)thencelseIndex.compareindexs2.indexletzero_id={(* We don't expect to have any published slot at level
Raw_level_repr.root. *)published_level=Raw_level_repr.root;index=Index.zero;}letzero={id=zero_id;commitment=Commitment.zero}letid_encoding=letopenData_encodinginconv(fun{published_level;index}->(published_level,index))(fun(published_level,index)->{published_level;index})(obj2(req"level"Raw_level_repr.encoding)(req"index"Data_encoding.uint8))letencoding=letopenData_encodinginconv(fun{id;commitment}->(id,commitment))(fun(id,commitment)->{id;commitment})(merge_objsid_encoding(obj1(req"commitment"Commitment.encoding)))letoperation_encoding=letopenData_encodinginconv(fun{header={id;commitment};proof}->(id,(commitment,proof)))(fun(id,(commitment,proof))->{header={id;commitment};proof})(merge_objsid_encoding(obj2(req"commitment" Commitment.encoding)(req"commitment_proof"Commitment_proof.encoding)))letpp_idfmt{published_level;index}=Format.fprintffmt"published_level: %a, index: %a"Raw_level_repr.pppublished_levelFormat.pp_print_intindexletppfmt{id;commitment=c}=Format.fprintffmt"id:(%a), commitment: %a"pp_ididCommitment.ppctypeerror+=Dal_commitment_proof_errorofstringlet()=letopenData_encodinginregister_error_kind`Permanent~id:"dal_slot_repr.dal_commitment_proof_error"~title:"Dal commitment proof error"~description:"Error occurred during Dal commitment proof validation"~pp:(funppfe->Format.fprintfppf"Dal commitment proof error: %s"e)(obj1(req"error"(stringPlain)))(functionDal_commitment_proof_errore->Somee|_->None)(fune->Dal_commitment_proof_errore)letverify_commitmentdal_params{header={commitment;_};proof}=letopenResult_syntaxinlet*dal=matchDal.makedal_paramswith|Okdal->returndal|Error(`Fails)->error(Dal_commitment_proof_errors)inreturn@@Dal.verify_commitmentdalcommitmentproofendmoduleSlot_index=IndexmodulePage=structtypecontent=Bytes.ttypeslot_index=Index.tletpages_per_slot=Dal.pages_per_slotmoduleIndex=structtypet=intletzero=0letencoding=Data_encoding.int16letpp=Format.pp_print_intletcompare=Compare.Int.compareletequal=Compare.Int.equalendtypet={slot_id:Header.id;page_index:Index.t}typeproof=Dal.page_proofletencoding=letopenData_encodinginconv(fun{slot_id={published_level;index};page_index}->(published_level,index,page_index))(fun(published_level,index,page_index)->{slot_id={published_level;index};page_index})(obj3(req"published_level"Raw_level_repr.encoding)(req"slot_index"Slot_index.encoding)(req"page_index"Index.encoding))letequal{slot_id;page_index}p=Header.slot_id_equalslot_idp.slot_id&&Index.equalpage_indexp.page_indexletproof_encoding=Dal.page_proof_encodingletcontent_encoding=Data_encoding.(bytesHex)letppfmt{slot_id={published_level;index};page_index}=Format.fprintffmt"(published_level: %a, slot_index: %a, page_index: %a)"Raw_level_repr.pppublished_levelSlot_index.ppindexIndex.pppage_indexletpp_prooffmtproof=Data_encoding.Json.ppfmt(Data_encoding.Json.constructproof_encodingproof)endmoduleSlot_market=struct(* DAL/FIXME https://gitlab.com/tezos/tezos/-/issues/3108
Think harder about this data structure and whether it can be
optimized. *)moduleSlot_index_map=Map.Make(Index)typet={length:int;slot_headers:Header.tSlot_index_map.t}letinit~length=ifCompare.Int.(length<0)theninvalid_arg"Dal_slot_repr.Slot_market.init: length cannot be negative";letslot_headers=Slot_index_map.emptyin{length;slot_headers}letlength{length;_}=lengthletregistertnew_slot_header=letopenHeaderinifnotCompare.Int.(0<=new_slot_header.id.index&&new_slot_header.id.index<t.length)thenNoneelselethas_changed=reffalseinletupdate=function|None->has_changed:=true;Somenew_slot_header|Somex->Somexinletslot_headers=Slot_index_map.updatenew_slot_header.id.indexupdatet.slot_headersinlett={twithslot_headers}inSome(t,!has_changed)letcandidatest=t.slot_headers|>Slot_index_map.to_seq|>Seq.mapsnd|>List.of_seqendmoduleHistory=struct(* History is represented via a skip list. The content of the cell
is the hash of a merkle proof. *)(* A leaf of the merkle tree is a slot. *)moduleLeaf=structtypet=Header.tletto_bytes=Data_encoding.Binary.to_bytes_exnHeader.encodingendmoduleContent_prefix=structlet(_prefix:string)="dash1"(* 32 *)letb58check_prefix="\002\224\072\094\219"(* dash1(55) *)letsize=Some32letname="dal_skip_list_content"lettitle="A hash to represent the content of a cell in the skip list"endmoduleContent_hash=Blake2B.Make(Base58)(Content_prefix)moduleMerkle_list=Merkle_list.Make(Leaf)(Content_hash)(* Pointers of the skip lists are used to encode the content and the
backpointers. *)modulePointer_prefix=structlet(_prefix:string)="dask1"(* 32 *)letb58check_prefix="\002\224\072\115\035"(* dask1(55) *)letsize=Some32letname="dal_skip_list_pointer"lettitle="A hash that represents the skip list pointers"endmodulePointer_hash=Blake2B.Make(Base58)(Pointer_prefix)moduleSkip_list_parameters=structletbasis=4endtypeerror+=Add_element_in_slots_skip_list_violates_orderinglet()=register_error_kind`Temporary~id:"Dal_slot_repr.add_element_in_slots_skip_list_violates_ordering"~title:"Add an element in slots skip list that violates ordering"~description:"Attempting to add an element on top of the Dal confirmed slots skip \
list that violates the ordering."Data_encoding.unit(function|Add_element_in_slots_skip_list_violates_ordering->Some()|_->None)(fun()->Add_element_in_slots_skip_list_violates_ordering)moduleSkip_list=structincludeSkip_list_repr.Make(Skip_list_parameters)(** All confirmed DAL slots will be stored in a skip list, where only the
last cell is remembered in the L1 context. The skip list is used in
the proof phase of a refutation game to verify whether a given slot
exists (i.e., confirmed) or not in the skip list. The skip list is
supposed to be sorted, as its 'search' function explicitly uses a given
`compare` function during the list traversal to quickly (in log(size))
reach the target if any.
In our case, we will store one slot per cell in the skip list and
maintain that the list is well sorted (and without redundancy) w.r.t.
the [compare_slot_id] function.
Below, we redefine the [next] function (that allows adding elements
on top of the list) to enforce that the constructed skip list is
well-sorted. We also define a wrapper around the search function to
guarantee that it can only be called with the adequate compare function.
*)letnext~prev_cell~prev_cell_ptrelt=letopenResult_syntaxinlet*()=error_when(Compare.Int.(<=)(Header.compare_slot_idelt.Header.id(contentprev_cell).Header.id)0)Add_element_in_slots_skip_list_violates_orderinginreturn@@next~prev_cell~prev_cell_ptreltletsearch~deref~cell~target_id=Lwt.search~deref~cell~compare:(funslot->Header.compare_slot_idslot.Header.idtarget_id)endmoduleV1=struct(* The content of a cell is the hash of all the slot commitments
represented as a merkle list. *)(* TODO/DAL: https://gitlab.com/tezos/tezos/-/issues/3765
Decide how to store attested slots in the skip list's content. *)typecontent=Header.t(* A pointer to a cell is the hash of its content and all the back
pointers. *)typehash=Pointer_hash.ttypehistory=(content,hash)Skip_list.celltypet=historylethistory_encoding=Skip_list.encodingPointer_hash.encodingHeader.encodingletequal_history:history->history->bool=Skip_list.equalPointer_hash.equalHeader.equalletencoding=history_encodingletequal:t->t->bool=equal_historyletgenesis:t=Skip_list.genesisHeader.zerolethashcell=letcurrent_slot=Skip_list.contentcellinletback_pointers_hashes=Skip_list.back_pointerscellinData_encoding.Binary.to_bytes_exnHeader.encodingcurrent_slot::List.mapPointer_hash.to_bytesback_pointers_hashes|>Pointer_hash.hash_bytesletpp_historyfmt(history:history)=lethistory_hash=hashhistoryinFormat.fprintffmt"@[hash : %a@;%a@]"Pointer_hash.pphistory_hash(Skip_list.pp~pp_content:Header.pp~pp_ptr:Pointer_hash.pp)historymoduleHistory_cache=Bounded_history_repr.Make(structletname="dal_slots_cache"end)(Pointer_hash)(structtypet=historyletencoding=history_encodingletpp=pp_historyletequal=equal_historyend)letadd_confirmed_slot_header(t,cache)slot_header=letopenResult_syntaxinletprev_cell_ptr=hashtinlet*cache=History_cache.rememberprev_cell_ptrtcacheinlet*new_cell=Skip_list.next~prev_cell:t~prev_cell_ptrslot_headerinreturn(new_cell,cache)letadd_confirmed_slot_headers(t:t)cacheslot_headers=List.fold_left_eadd_confirmed_slot_header(t,cache)slot_headersletadd_confirmed_slot_headers_no_cache=letno_cache=History_cache.empty~capacity:0Linfuntslots->List.fold_left_eadd_confirmed_slot_header(t,no_cache)slots>|?fst(* Dal proofs section *)(** An inclusion proof, for a page ID, is a list of the slots' history
skip list's cells that encodes a minimal path:
- from a starting cell, which serves as a reference. It is usually called
'snapshot' below,
- to a final cell, that is either the exact target cell in case the slot
of the page is confirmed, or a cell whose slot ID is the smallest
that directly follows the page's slot id, in case the target slot
is not confirmed.
Using the starting cell as a trustable starting point (i.e. maintained
and provided by L1), and combined with the extra information stored in
the {!proof} type below, one can verify if a slot (and then a page of
that slot) is confirmed on L1 or not. *)typeinclusion_proof=historylist(** (See the documentation in the mli file to understand what we want to
prove in game refutation involving Dal and why.)
A Dal proof is an algebraic datatype with two cases, where we basically
prove that a Dal page is confirmed on L1 or not. Being 'not confirmed'
here includes the case where the slot's header is not published and the
case where the slot's header is published, but the endorsers didn't
confirm the availability of its data.
To produce a proof representation for a page (see function {!produce_proof_repr}
below), we assume given:
- [page_id], identifies the page;
- [slots_history], a current/recent cell of the slots history skip list.
Typically, it should be the skip list cell snapshotted when starting the
refutation game;
- [history_cache], a sufficiently large slots history cache, to navigate
back through the successive cells of the skip list. Typically,
the cache should at least contain the cell whose slot ID is [page_id.slot_id]
in case the page is confirmed, or the cell whose slot ID is immediately
after [page_id.slot_id] in case of an unconfirmed page. Indeed,
inclusion proofs encode paths through skip lists' cells where the head
is the reference/snapshot cell and the last element is the target slot
in or the nearest upper slot (w.r.t [page_id]'s slot id and to
skip list elements ordering) ;
- [page_info], that provides the page's information (the content and
the slot membership proof) for page_id. In case the page is supposed
to be confirmed, this argument should contain the page's content and
the proof that the page is part of the (confirmed) slot whose ID is
given in [page_id]. In case we want to show that the page is not confirmed,
the value [page_info] should be [None].
[dal_parameters] is used when verifying that/if the page is part of
the candidate slot (if any).
*)typeproof_repr=|Page_confirmedof{target_cell:history;(** [target_cell] is a cell whose content contains the slot to
which the page belongs to. *)inc_proof:inclusion_proof;(** [inc_proof] is a (minimal) path in the skip list that proves
cells inclusion. The head of the list is the [slots_history]
provided to produce the proof. The last cell's content is
the slot containing the page identified by [page_id],
that is: [target_cell]. *)page_data:Page.content;(** [page_data] is the content of the page. *)page_proof:Page.proof;(** [page_proof] is the proof that the page whose content is
[page_data] is actually the [page_id.page_index]th page of
the slot stored in [target_cell] and identified by
page_id.slot_id. *)}(** The case where the slot's page is confirmed/attested on L1. *)|Page_unconfirmedof{prev_cell:history;(** [prev_cell] is the cell of the skip list containing a
(confirmed) slot, and whose ID is the biggest (w.r.t. to skip
list elements ordering), but smaller than [page_id.slot_id]. *)next_cell_opt:historyoption;(** [next_cell_opt] is the cell that immediately follows [prev_cell]
in the skip list, if [prev_cell] is not the latest element in
the list. Otherwise, it's set to [None]. *)next_inc_proof:inclusion_proof;(** [inc_proof] is a (minimal) path in the skip list that proves
cells inclusion. In case, [next_cell_opt] contains some cell
'next_cell', the head of the list is the [slots_history]
provided to produce the proof, and the last cell is
'next_cell'. In case [next_cell_opt] is [None], the list is
empty.
We maintain the following invariant in case the inclusion
proof is not empty:
```
(content next_cell).id > page_id.slot_id > (content prev_cell).id AND
hash prev_cell = back_pointer next_cell 0 AND
Some next_cell = next_cell_opt AND
head next_inc_proof = slots_history
```
Said differently, `next_cell` and `prev_cell` are two consecutive
cells of the skip list whose contents' IDs surround the page's
slot ID. Moreover, the head of the list should be equal to
the initial (snapshotted) slots_history skip list.
The case of an empty inclusion proof happens when the inputs
are such that: `page_id.slot_id > (content slots_history).id`.
The returned proof statement implies the following property in this case:
```
next_cell_opt = None AND prev_cell = slots_history
```
*)}(** The case where the slot's page doesn't exist or is not
confirmed on L1. *)letproof_repr_encoding=letopenData_encodinginletcase_page_confirmed=case~title:"confirmed dal page proof representation"(Tag0)(obj5(req"kind"(constant"confirmed"))(req"target_cell"history_encoding)(req"inc_proof"(listhistory_encoding))(req"page_data"(bytesHex))(req"page_proof"Page.proof_encoding))(function|Page_confirmed{target_cell;inc_proof;page_data;page_proof}->Some((),target_cell,inc_proof,page_data,page_proof)|_->None)(fun((),target_cell,inc_proof,page_data,page_proof)->Page_confirmed{target_cell;inc_proof;page_data;page_proof})andcase_page_unconfirmed=case~title:"unconfirmed dal page proof representation"(Tag1)(obj4(req"kind"(constant"unconfirmed"))(req"prev_cell"history_encoding)(req"next_cell_opt"(optionhistory_encoding))(req"next_inc_proof"(listhistory_encoding)))(function|Page_unconfirmed{prev_cell;next_cell_opt;next_inc_proof}->Some((),prev_cell,next_cell_opt,next_inc_proof)|_->None)(fun((),prev_cell,next_cell_opt,next_inc_proof)->Page_unconfirmed{prev_cell;next_cell_opt;next_inc_proof})inunion[case_page_confirmed;case_page_unconfirmed](** Proof's type is set to bytes and not a structural datatype because
when a proof appears in a tezos operation or in an rpc, a user can not
reasonably understand the proof, thus it eases the work of people decoding
the proof by only supporting bytes and not the whole structured proof. *)typeproof=bytes(** DAL/FIXME: https://gitlab.com/tezos/tezos/-/issues/4084
DAL proof's encoding should be bounded *)letproof_encoding=Data_encoding.(bytesHex)typeerror+=Dal_invalid_proof_serializationlet()=register_error_kind`Permanent~id:"Dal_slot_repr.invalid_proof_serialization"~title:"Dal invalid proof serialization"~description:"Error occured during dal proof serialization"Data_encoding.unit(functionDal_invalid_proof_serialization->Some()|_->None)(fun()->Dal_invalid_proof_serialization)letserialize_proofproof=matchData_encoding.Binary.to_bytes_optproof_repr_encodingproofwith|None->errorDal_invalid_proof_serialization|Someserialized_proof->okserialized_prooftypeerror+=Dal_invalid_proof_deserializationlet()=register_error_kind`Permanent~id:"Dal_slot_repr.invalid_proof_deserialization"~title:"Dal invalid proof deserialization"~description:"Error occured during dal proof deserialization"Data_encoding.unit(functionDal_invalid_proof_deserialization->Some()|_->None)(fun()->Dal_invalid_proof_deserialization)letdeserialize_proofproof=matchData_encoding.Binary.of_bytes_optproof_repr_encodingproofwith|None->errorDal_invalid_proof_deserialization|Somedeserialized_proof->okdeserialized_proofletpp_inclusion_proof=Format.pp_print_listpp_historyletpp_history_opt=Format.pp_print_optionpp_historyletpp_proof~serializedfmtp=ifserializedthenFormat.pp_print_stringfmt(Bytes.to_stringp)elsematchdeserialize_proofpwith|Errormsg->Error_monad.pp_tracefmtmsg|Okproof->(matchproofwith|Page_confirmed{target_cell;inc_proof;page_data;page_proof}->Format.fprintffmt"Page_confirmed (target_cell=%a, data=%s,@ \
inc_proof:[size=%d |@ path=%a]@ page_proof:%a)"pp_historytarget_cell(Bytes.to_stringpage_data)(List.lengthinc_proof)pp_inclusion_proofinc_proofPage.pp_proofpage_proof|Page_unconfirmed{prev_cell;next_cell_opt;next_inc_proof}->Format.fprintffmt"Page_unconfirmed (prev_cell = %a | next_cell = %a | \
prev_inc_proof:[size=%d@ | path=%a])"pp_historyprev_cellpp_history_optnext_cell_opt(List.lengthnext_inc_proof)pp_inclusion_proofnext_inc_proof)typeerror+=|Dal_proof_errorofstring|Unexpected_page_sizeof{expected_size:int;page_size:int}let()=letopenData_encodinginregister_error_kind`Permanent~id:"dal_slot_repr.slots_history.dal_proof_error"~title:"Dal proof error"~description:"Error occurred during Dal proof production or validation"~pp:(funppfe->Format.fprintfppf"Dal proof error: %s"e)(obj1(req"error"(stringPlain)))(functionDal_proof_errore->Somee|_->None)(fune->Dal_proof_errore)let()=letopenData_encodinginregister_error_kind`Permanent~id:"dal_slot_repr.slots_history.unexpected_page_size"~title:"Unexpected page size"~description:"The size of the given page content doesn't match the expected one."~pp:(funppf(expected,size)->Format.fprintfppf"The size of a Dal page is expected to be %d bytes. The given one \
has %d"expectedsize)(obj2(req"expected_size"int16)(req"page_size"int16))(function|Unexpected_page_size{expected_size;page_size}->Some(expected_size,page_size)|_->None)(fun(expected_size,page_size)->Unexpected_page_size{expected_size;page_size})letdal_proof_errorreason=Dal_proof_errorreasonletproof_errorreason=error@@dal_proof_errorreasonletcheck_page_proofdal_paramsproofdata({Page.page_index;_}aspid)commitment=letopenResult_syntaxinlet*dal=matchDal.makedal_paramswith|Okdal->returndal|Error(`Fails)->proof_errorsinletfail_with_error_msgwhat=Format.kasprintfproof_error"%s (page id=%a)."whatPage.pppidinmatchDal.verify_pagedalcommitment~page_indexdataproofwith|Oktrue->return()|Okfalse->fail_with_error_msg"Wrong page content for the given page index and slot commitment"|Error`Segment_index_out_of_range->fail_with_error_msg"Segment_index_out_of_range"|Error`Page_length_mismatch->tzfail@@Unexpected_page_size{expected_size=dal_params.page_size;page_size=Bytes.lengthdata;}letproduce_proof_reprdal_paramspage_id~page_info~get_historyslots_hist=letopenLwt_result_syntaxinletPage.{slot_id;page_index=_}=page_idin(* We search for a slot whose ID is equal to target_id. *)let*!search_result=Skip_list.search~deref:get_history~target_id:slot_id~cell:slots_histinmatch(page_info,search_result.Skip_list.last_cell)with|_,Deref_returned_none->tzfail@@dal_proof_error"Skip_list.search returned 'Deref_returned_none': Slots history \
cache is ill-formed or has too few entries."|_,No_exact_or_lower_ptr->tzfail@@dal_proof_error"Skip_list.search returned 'No_exact_or_lower_ptr', while it is \
initialized with a min elt (slot zero)."|Some(page_data,page_proof),Foundtarget_cell->(* The slot to which the page is supposed to belong is found. *)letHeader.{id;commitment}=Skip_list.contenttarget_cellin(* We check that the slot is not the dummy slot. *)let*?()=error_whenCompare.Int.(Header.compare_slot_ididHeader.zero.id=0)(dal_proof_error"Skip_list.search returned 'Found <zero_slot>': No existence \
proof should be constructed with the slot zero.")inlet*?()=check_page_proofdal_paramspage_proofpage_datapage_idcommitmentinletinc_proof=List.revsearch_result.Skip_list.rev_pathinlet*?()=error_when(List.is_emptyinc_proof)(dal_proof_error"The inclusion proof cannot be empty")in(* All checks succeeded. We return a `Page_confirmed` proof. *)return(Page_confirmed{inc_proof;target_cell;page_data;page_proof},Somepage_data)|None,Nearest{lower=prev_cell;upper=next_cell_opt}->(* There is no previously confirmed slot in the skip list whose ID
corresponds to the {published_level; slot_index} information
given in [page_id]. But, `search` returned a skip list [prev_cell]
(and possibly [next_cell_opt]) such that:
- the ID of [prev_cell]'s slot is the biggest immediately smaller than
the page's information {published_level; slot_index}
- if not equal to [None], the ID of [next_cell_opt]'s slot is the smallest
immediately bigger than the page's slot id `slot_id`.
- if [next_cell_opt] is [None] then, [prev_cell] should be equal to
the given history_proof cell. *)let*next_inc_proof=matchsearch_result.Skip_list.rev_pathwith|[]->assertfalse(* Not reachable *)|prev::rev_next_inc_proof->let*?()=error_unless(equal_historyprevprev_cell)(dal_proof_error"Internal error: search's Nearest result is \
inconsistent.")inreturn@@List.revrev_next_inc_proofinreturn(Page_unconfirmed{prev_cell;next_cell_opt;next_inc_proof},None)|None,Found_->tzfail@@dal_proof_error"The page ID's slot is confirmed, but no page content and proof \
are provided."|Some_,Nearest_->tzfail@@dal_proof_error"The page ID's slot is not confirmed, but page content and \
proof are provided."letproduce_proofdal_paramspage_id~page_info~get_historyslots_hist=letopenLwt_result_syntaxinlet*proof_repr,page_data=produce_proof_reprdal_paramspage_id~page_info~get_historyslots_histinlet*?serialized_proof=serialize_proofproof_reprinreturn(serialized_proof,page_data)(* Given a starting cell [snapshot] and a (final) [target], this function
checks that the provided [inc_proof] encodes a minimal path from
[snapshot] to [target]. *)letverify_inclusion_proofinc_proof~src:snapshot~dest:target=letassoc=List.map(func->(hashc,c))inc_proofinletpath=List.splitassoc|>fstinletderef=letopenMap.Make(Pointer_hash)inletmap=of_seq(List.to_seqassoc)infunptr->find_optptrmapinletsnapshot_ptr=hashsnapshotinlettarget_ptr=hashtargetinerror_unless(Skip_list.valid_back_path~equal_ptr:Pointer_hash.equal~deref~cell_ptr:snapshot_ptr~target_ptrpath)(dal_proof_error"verify_proof_repr: invalid inclusion Dal proof.")letverify_proof_reprdal_paramspage_idsnapshotproof=letopenResult_syntaxinletPage.{slot_id;page_index=_}=page_idinmatchproofwith|Page_confirmed{target_cell;page_data;page_proof;inc_proof}->(* If the page is supposed to be confirmed, the last cell in
[inc_proof] should store the slot of the page. *)letHeader.{id;commitment}=Skip_list.contenttarget_cellinlet*()=error_whenCompare.Int.(Header.compare_slot_ididHeader.zero.id=0)(dal_proof_error"verify_proof_repr: cannot construct a confirmation page \
proof with 'zero' as target slot.")inlet*()=verify_inclusion_proofinc_proof~src:snapshot~dest:target_cellin(* We check that the page indeed belongs to the target slot at the
given page index. *)let*()=check_page_proofdal_paramspage_proofpage_datapage_idcommitmentin(* If all checks succeed, we return the data/content of the page. *)return_somepage_data|Page_unconfirmed{prev_cell;next_cell_opt;next_inc_proof}->(* The page's slot is supposed to be unconfirmed. *)let(<)ab=Compare.Int.(Header.compare_slot_idab<0)in(* We retrieve the last cell of the inclusion proof to be able to
call {!verify_inclusion_proof}. We also do some well-formedness on
the shape of the inclusion proof (see the case [Page_unconfirmed]
of type {!proof}). *)let*()=matchnext_cell_optwith|None->let*()=error_unless(List.is_emptynext_inc_proof)(dal_proof_error"verify_proof_repr: invalid next_inc_proof")in(* In case the inclusion proof has no elements, we check that:
- the prev_cell slot's id is smaller than the unconfirmed slot's ID
- the snapshot is equal to the [prev_cell] skip list.
This way, and since the skip list is sorted wrt.
{!compare_slot_id}, we are sure that the skip list whose head
is [snapshot] = [prev_cell] cannot contain a slot whose ID is
[slot_id]. *)error_unless((Skip_list.contentprev_cell).id<slot_id&&equal_historysnapshotprev_cell)(dal_proof_error"verify_proof_repr: invalid next_inc_proof")|Somenext_cell->(* In case the inclusion proof has at least one element,
we check that:
- the [prev_cell] slot's id is smaller than [slot_id]
- the [next_cell] slot's id is greater than [slot_id]
- the [next_cell] cell is a direct successor of the
[prev_cell] cell.
- the [next_cell] cell is a predecessor of [snapshot]
Since the skip list is sorted wrt. {!compare_slot_id}, and
if the call to {!verify_inclusion_proof} succeeds, we are
sure that the skip list whose head is [snapshot] cannot
contain a slot whose ID is [slot_id]. *)let*()=error_unless((Skip_list.contentprev_cell).id<slot_id&&slot_id<(Skip_list.contentnext_cell).id&&letprev_cell_pointer=Skip_list.back_pointernext_cell0inmatchprev_cell_pointerwith|None->false|Someprev_ptr->Pointer_hash.equalprev_ptr(hashprev_cell))(dal_proof_error"verify_proof_repr: invalid next_inc_proof")inverify_inclusion_proofnext_inc_proof~src:snapshot~dest:next_cellinreturn_noneletverify_proofdal_paramspage_idsnapshotserialized_proof=letopenResult_syntaxinlet*proof_repr=deserialize_proofserialized_proofinverify_proof_reprdal_paramspage_idsnapshotproof_reprmoduleInternal_for_tests=structletcontent=Skip_list.contentletproof_statement_isserialized_proofexpected=matchdeserialize_proofserialized_proofwith|Error_->false|Okproof->(match(expected,proof)with|`Confirmed,Page_confirmed_|`Unconfirmed,Page_unconfirmed_->true|_->false)endendincludeV1end