123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *)(* Copyright (c) 2022 TriliTech <contact@trili.tech> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)openSc_rollup_errorsmoduleStore=Storage.Sc_rollupmoduleCommitment=Sc_rollup_commitment_reprmoduleCommitment_storage=Sc_rollup_commitment_storagemoduleCommitment_hash=Commitment.HashmoduleStake_storage=Sc_rollup_stake_storagetypepoint={commitment:Sc_rollup_commitment_repr.t;hash:Commitment_hash.t;}typeconflict_point=point*point(** TODO: #2902 replace with protocol constant and consider good value. *)lettimeout_period_in_blocks=500lettimeout_levelctxt=letlevel=Raw_context.current_levelctxtinRaw_level_repr.addlevel.leveltimeout_period_in_blocks(** [goto_inbox_level ctxt rollup inbox_level commit] Follows the predecessors of [commit] until it
arrives at the exact [inbox_level]. The result is the commit hash at the given inbox level. *)letgoto_inbox_levelctxtrollupinbox_levelcommit=letopenLwt_tzresult_syntaxinletrecgoctxtcommit=let*info,ctxt=Commitment_storage.get_commitment_unsafectxtrollupcommitinifRaw_level_repr.(info.Commitment.inbox_level<=inbox_level)then((* Assert that we're exactly at that level. If this isn't the case, we're most likely in a
situation where inbox levels are inconsistent. *)assert(Raw_level_repr.(info.inbox_level=inbox_level));return(commit,ctxt))else(go[@ocaml.tailcall])ctxtinfo.predecessoringoctxtcommitletget_conflict_pointctxtrollupstaker1staker2=letopenLwt_tzresult_syntaxin(* Ensure the LCC is set. *)let*lcc,ctxt=Commitment_storage.last_cemented_commitmentctxtrollupin(* Find out on which commitments the competitors are staked. *)let*commit1,ctxt=Stake_storage.find_stakerctxtrollupstaker1inlet*commit2,ctxt=Stake_storage.find_stakerctxtrollupstaker2inlet*()=fail_whenCommitment_hash.((* If PVM is in pre-boot state, there might be stakes on the zero commitment. *)commit1=zero||commit2=zero(* If either commit is the LCC, that also means there can't be a conflict. *)||commit1=lcc||commit2=lcc)Sc_rollup_no_conflictinlet*commit1_info,ctxt=Commitment_storage.get_commitment_unsafectxtrollupcommit1inlet*commit2_info,ctxt=Commitment_storage.get_commitment_unsafectxtrollupcommit2in(* Make sure that both commits are at the same inbox level. In case they are not move the commit
that is farther ahead to the exact inbox level of the other.
We do this instead of an alternating traversal of either commit to ensure the we can detect
wonky inbox level increases. For example, if the inbox levels decrease in different intervals
between commits for either history, we risk going past the conflict point and accidentally
determined that the commits are not in conflict by joining at the same commit. *)lettarget_inbox_level=Raw_level_repr.mincommit1_info.inbox_levelcommit2_info.inbox_levelinlet*commit1,ctxt=goto_inbox_levelctxtrolluptarget_inbox_levelcommit1inlet*commit2,ctxt=goto_inbox_levelctxtrolluptarget_inbox_levelcommit2in(* The inbox level of a commitment increases by a fixed amount over the preceding commitment.
We use this fact in the following to efficiently traverse both commitment histories towards
the conflict points. *)letrectraverse_in_parallelctxtcommit1commit2=(* We know that commit1 <> commit2 at the first call and during recursive calls
as well. *)let*commit1_info,ctxt=Commitment_storage.get_commitment_unsafectxtrollupcommit1inlet*commit2_info,ctxt=Commitment_storage.get_commitment_unsafectxtrollupcommit2in(* This assert should hold because:
- We call function [traverse_in_parallel] with two initial commitments
whose levels are equal to [target_inbox_level],
- In recursive calls, the commitments are replaced by their respective
predecessors, and we know that successive commitments in a branch are
spaced by [sc_rollup_commitment_period_in_blocks] *)assert(Raw_level_repr.(commit1_info.inbox_level=commit2_info.inbox_level));ifCommitment_hash.(commit1_info.predecessor=commit2_info.predecessor)then(* Same predecessor means we've found the conflict points. *)return(({hash=commit1;commitment=commit1_info},{hash=commit2;commitment=commit2_info}),ctxt)else(* Different predecessors means they run in parallel. *)(traverse_in_parallel[@ocaml.tailcall])ctxtcommit1_info.predecessorcommit2_info.predecessorinlet*()=fail_when(* This case will most dominantly happen when either commit is part of the other's history.
It occurs when the commit that is farther ahead gets dereferenced to its predecessor often
enough to land at the other commit. *)Commitment_hash.(commit1=commit2)Sc_rollup_no_conflictintraverse_in_parallelctxtcommit1commit2letget_gamectxtrollupstakers=letopenLwt_tzresult_syntaxinlet*ctxt,game=Store.Game.find(ctxt,rollup)stakersinmatchgamewithSomeg->return(g,ctxt)|None->failSc_rollup_no_game(** [init_game ctxt rollup refuter defender] initialises the game or
if it already exists fails with `Sc_rollup_game_already_started`.
The game is created with `refuter` as the first player to move. The
initial state of the game will be obtained from the commitment pair
belonging to [defender] at the conflict point. See
[Sc_rollup_game_repr.initial] for documentation on how a pair of
commitments is turned into an initial game state.
This also deals with the other bits of data in the storage around
the game. It checks neither staker is already in a game (and also
marks them as in a game once the new game is created). The reason we
only allow a staker to play one game at a time is to keep the
end-of-game logic simple---this way, a game can't end suddenly in
the middle because one player lost their stake in another game, it
can only end due to it's own moves or timeouts.
It also initialises the timeout level to the current level plus
[timeout_period_in_blocks] (which will become a protocol constant
soon) to mark the block level at which it becomes possible for
anyone to end the game by timeout.
May fail with:
{ul
{li [Sc_rollup_does_not_exist] if [rollup] does not exist}
{li [Sc_rollup_no_conflict] if [refuter] is staked on an ancestor of
the commitment staked on by [defender], or vice versa}
{li [Sc_rollup_not_staked] if one of the [refuter] or [defender] is
not actually staked}
{li [Sc_rollup_staker_in_game] if one of the [refuter] or [defender]
is already playing a game}
} *)letinit_gamectxtrollup~refuter~defender=letopenLwt_tzresult_syntaxinletstakers=Sc_rollup_game_repr.Index.makerefuterdefenderinlet*ctxt,game=Store.Game.find(ctxt,rollup)stakersinmatchgamewith|Some_->failSc_rollup_game_already_started|None->let*ctxt,opp_1=Store.Opponent.find(ctxt,rollup)refuterinlet*ctxt,opp_2=Store.Opponent.find(ctxt,rollup)defenderinlet*_=match(opp_1,opp_2)with|None,None->return()|Some_refuter_opponent,None->fail(Sc_rollup_staker_in_game(`Refuterrefuter))|None,Some_defender_opponent->fail(Sc_rollup_staker_in_game(`Defenderdefender))|Some_refuter_opponent,Some_defender_opponent->fail(Sc_rollup_staker_in_game(`Both(refuter,defender)))inlet*(({hash=_refuter_commit;commitment=_info},{hash=_defender_commit;commitment=child_info}),ctxt)=get_conflict_pointctxtrolluprefuterdefenderinlet*parent_info,ctxt=Commitment_storage.get_commitment_unsafectxtrollupchild_info.predecessorinlet*ctxt,inbox=Store.Inbox.getctxtrollupinlet*kind=Store.PVM_kind.getctxtrollupinletgame=Sc_rollup_game_repr.initialinbox~pvm_name:(Sc_rollups.Kind.name_ofkind)~parent:parent_info~child:child_info~refuter~defenderinlet*ctxt,_=Store.Game.init(ctxt,rollup)stakersgameinlet*ctxt,_=Store.Game_timeout.init(ctxt,rollup)stakers(timeout_levelctxt)inlet*ctxt,_=Store.Opponent.init(ctxt,rollup)refuterdefenderinlet*ctxt,_=Store.Opponent.init(ctxt,rollup)defenderrefuterinreturn(game,ctxt)letgame_movectxtrollup~player~opponentrefutation~is_opening_move=letopenLwt_tzresult_syntaxinlet({alice;bob}asstakers:Sc_rollup_game_repr.Index.t)=Sc_rollup_game_repr.Index.makeplayeropponentinlet*game,ctxt=ifis_opening_movetheninit_gamectxtrollup~refuter:player~defender:opponentelseget_gamectxtrollupstakersinlet*()=fail_unless(letturn=matchgame.turnwithAlice->alice|Bob->bobinSc_rollup_repr.Staker.equalturnplayer)Sc_rollup_wrong_turninlet*move_result=Lwt.mapResult.ok@@Sc_rollup_game_repr.playgamerefutationinmatchmove_resultwith|Either.Leftoutcome->return(Someoutcome,ctxt)|Either.Rightnew_game->let*ctxt,_=Store.Game.update(ctxt,rollup)stakersnew_gameinlet*ctxt,_=Store.Game_timeout.update(ctxt,rollup)stakers(timeout_levelctxt)inreturn(None,ctxt)lettimeoutctxtrollupstakers=letopenLwt_tzresult_syntaxinletlevel=(Raw_context.current_levelctxt).levelinlet*ctxt,game=Store.Game.find(ctxt,rollup)stakersinmatchgamewith|None->failSc_rollup_no_game|Somegame->let*ctxt,timeout_level=Store.Game_timeout.get(ctxt,rollup)stakersinlet*()=fail_unlessRaw_level_repr.(level>timeout_level)Sc_rollup_timeout_level_not_reachedinreturn(Sc_rollup_game_repr.{loser=game.turn;reason=Timeout},ctxt)letapply_outcomectxtrollupstakers(outcome:Sc_rollup_game_repr.outcome)=letopenLwt_tzresult_syntaxinletlosing_staker=Sc_rollup_game_repr.Index.stakerstakersoutcome.loserinlet*ctxt,balance_updates=Stake_storage.remove_stakerctxtrolluplosing_stakerinlet*ctxt,_,_=Store.Game.remove(ctxt,rollup)stakersinlet*ctxt,_,_=Store.Game_timeout.remove(ctxt,rollup)stakersinlet*ctxt,_,_=Store.Opponent.remove(ctxt,rollup)stakers.aliceinlet*ctxt,_,_=Store.Opponent.remove(ctxt,rollup)stakers.bobinreturn(Sc_rollup_game_repr.Ended(outcome.reason,losing_staker),ctxt,balance_updates)moduleInternal_for_tests=structletget_conflict_point=get_conflict_pointend