Library QedkConcrete.hostcopybounds

Native bounds for EXTCODECOPY

The offset and requested count come from the VM's checked conversion. The code-length premise makes length code - offset exact in OCaml's signed 63-bit int. The result contains at most the requested bytes; no exception-result value is used.
From Stdlib Require Import ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import RocqOfOCaml.Unreachable.StringBounds.
Require Import MonadVM.Host QedkConcrete.hostframe QedkConcrete.worldaccounts
  QedkConcrete.nativeindices.
Set Default Goal Selector "!".
Local Open Scope Z_scope.

Lemma copy_code_length {F : H.FArgs} addr offset count state :
  OCamlString.length (A.t.code (State.op_pointcaretlparenrparen
    (S.t.world_state state) (@W.account None addr))) < 2^62 →
  0 ≤ offset → 0 ≤ count →
  OCamlString.length (fst (@H.copy_code F addr offset count state)) ≤ count.
Proof.
  intros Hcode Hoffset Hcount.
  set (code := A.t.code (State.op_pointcaretlparenrparen
    (S.t.world_state state) (@W.account None addr))) in ×.
  unfold H.copy_code. cbn -[W.account Byte_string.Bytes.sub OCamlInt.sub].
  change (OCamlString.length (fst
    ((if Z.geb offset (OCamlString.length code) then
      fun s : S.t ⇒ (String.EmptyString, s)
     else fun s : S.t ⇒ (Byte_string.Bytes.sub (@H._rocq_fallback_copy_code_0 F) code offset
       (Z.min count (OCamlInt.sub (OCamlString.length code) offset)), s)) state)) ≤ count).
  destruct (Z.geb offset (OCamlString.length code)) eqn:Hguard.
  - change (0 ≤ count). exact Hcount.
  - rewrite Z.geb_leb in Hguard. apply Z.leb_gt in Hguard.
    unfold OCamlInt.sub. rewrite native_repr_small by lia.
    change (OCamlString.length
      (@OCamlString.sub (Opaque.legacy_witness (@H._rocq_fallback_copy_code_0 F))
        code offset (Z.min count (OCamlString.length code - offset))) ≤ count).
    rewrite StringBounds.sub_length_in_bounds.
    + apply Z.le_min_l.
    + exact Hoffset.
    + apply Z.min_glb; lia.
    + pose proof (Z.le_min_r count (OCamlString.length code - offset)). lia.
Qed.

Print Assumptions copy_code_length.