package tezos-client-alpha

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file client_proto_programs_commands.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
(*****************************************************************************)
(*                                                                           *)
(* Open Source License                                                       *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com>     *)
(* Copyright (c) 2019 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.                                                 *)
(*                                                                           *)
(*****************************************************************************)

open Protocol

let group =
  {
    Tezos_clic.name = "scripts";
    title = "Commands for managing the library of known scripts";
  }

open Tezos_micheline
open Client_proto_programs
open Client_proto_args
open Client_proto_contracts

let commands () =
  let open Tezos_clic in
  let show_types_switch =
    switch
      ~long:"details"
      ~short:'v'
      ~doc:"show the types of each instruction"
      ()
  in
  let emacs_mode_switch =
    switch
      ~long:"emacs"
      ?short:None
      ~doc:"output in `michelson-mode.el` compatible format"
      ()
  in
  let trace_stack_switch =
    switch ~long:"trace-stack" ~doc:"show the stack after each step" ()
  in
  let zero_loc_switch =
    switch ~short:'z' ~long:"zero-loc" ~doc:"replace location with \"0\"" ()
  in
  let legacy_switch =
    switch
      ~long:"legacy"
      ~doc:"typecheck in legacy mode as if the data was taken from the chain"
      ()
  in
  let amount_arg =
    Client_proto_args.tez_arg
      ~parameter:"amount"
      ~doc:"amount of the transfer in \xEA\x9C\xA9"
      ~default:"0.05"
  in
  let source_arg =
    ContractAlias.destination_arg
      ~name:"source"
      ~doc:"name of the source (i.e. SENDER) contract for the transaction"
      ()
  in
  let payer_arg =
    Client_keys.Public_key_hash.source_arg
      ~long:"payer"
      ~doc:"name of the payer (i.e. SOURCE) contract for the transaction"
      ()
  in
  let self_arg =
    OriginatedContractAlias.destination_arg
      ~name:"self-address"
      ~doc:"address of the contract (i.e. SELF_ADDRESS) for the transaction"
      ()
  in
  let balance_arg =
    Client_proto_args.tez_opt_arg
      ~parameter:"balance"
      ~doc:"balance of run contract in \xEA\x9C\xA9"
  in
  let now_arg = Client_proto_args.now_arg in
  let level_arg = Client_proto_args.level_arg in
  let resolve_max_gas cctxt block =
    let open Lwt_result_syntax in
    function
    | None ->
        let* {parametric = {hard_gas_limit_per_operation; _}; _} =
          Alpha_services.Constants.all cctxt (cctxt#chain, block)
        in
        return hard_gas_limit_per_operation
    | Some gas -> return gas
  in
  let parse_expr expr =
    Lwt.return @@ Micheline_parser.no_parsing_error
    @@ Michelson_v1_parser.parse_expression expr
  in
  let data_type_arg =
    arg
      ~doc:"the given data will be type-checked against this type"
      ~short:'t'
      ~long:"type"
      ~placeholder:"unit"
      data_parameter
  in
  let bytes_parameter ~name ~desc =
    param ~name ~desc Client_proto_args.bytes_parameter
  in
  let signature_parameter =
    parameter (fun (cctxt : #Client_context.full) s ->
        match Signature.of_b58check_opt s with
        | Some s -> Lwt_result_syntax.return s
        | None -> cctxt#error "Not given a valid signature")
  in
  let convert_input_format_param =
    let open Lwt_result_syntax in
    param
      ~name:"input_format"
      ~desc:"format of the input for conversion"
      (parameter
         ~autocomplete:(fun _ -> return ["michelson"; "json"; "binary"])
         (fun (cctxt : #Client_context.full) s ->
           match String.lowercase_ascii s with
           | "michelson" -> return `Michelson
           | "json" -> return `JSON
           | "binary" -> return `Binary
           | _ ->
               cctxt#error
                 "invalid input format, expecting one of \"michelson\", \
                  \"json\" or \"binary\"."))
  in
  let convert_output_format_param =
    let open Lwt_result_syntax in
    param
      ~name:"output_format"
      ~desc:"format of the conversion output"
      (parameter
         ~autocomplete:(fun _ ->
           return ["michelson"; "json"; "binary"; "ocaml"])
         (fun (cctxt : #Client_context.full) s ->
           match String.lowercase_ascii s with
           | "michelson" -> return `Michelson
           | "json" -> return `JSON
           | "binary" -> return `Binary
           | "ocaml" -> return `OCaml
           | _ ->
               cctxt#error
                 "invalid output format, expecting one of \"michelson\", \
                  \"json\", \"binary\" or \"ocaml\"."))
  in
  let file_or_literal_with_origin_param () =
    param
      ~name:"source"
      ~desc:"literal or a path to a file"
      (Client_proto_args.file_or_text_with_origin_parameter
         ~from_text:(fun _cctxt s -> Lwt_result_syntax.return s)
         ())
  in
  let file_or_literal_param () =
    param
      ~name:"source"
      ~desc:"literal or a path to a file"
      (Client_proto_args.file_or_text_parameter
         ~from_text:(fun _cctx s -> Lwt_result_syntax.return s)
         ())
  in
  let handle_parsing_error label (cctxt : Protocol_client_context.full)
      (emacs_mode, no_print_source) program body =
    let open Lwt_result_syntax in
    match program with
    | program, [] -> body program
    | res_with_errors when emacs_mode ->
        let*! () =
          cctxt#message
            "(@[<v 0>(%s . ())@ (errors . %a)@])"
            label
            Michelson_v1_emacs.report_errors
            res_with_errors
        in
        return_unit
    | parsed, errors ->
        let*! () =
          cctxt#message
            "%a"
            (fun ppf () ->
              Michelson_v1_error_reporter.report_errors
                ~details:(not no_print_source)
                ~parsed
                ~show_source:(not no_print_source)
                ppf
                errors)
            ()
        in
        cctxt#error "syntax error in program"
  in
  [
    command
      ~group
      ~desc:"Lists all scripts in the library."
      no_options
      (fixed ["list"; "known"; "scripts"])
      (fun () (cctxt : Protocol_client_context.full) ->
        let open Lwt_result_syntax in
        let* list = Program.load cctxt in
        let*! () = List.iter_s (fun (n, _) -> cctxt#message "%s" n) list in
        return_unit);
    command
      ~group
      ~desc:"Add a script to the library."
      (args1 (Program.force_switch ()))
      (prefixes ["remember"; "script"]
      @@ Program.fresh_alias_param @@ Program.source_param @@ stop)
      (fun force name hash cctxt ->
        let open Lwt_result_syntax in
        let* name = Program.of_fresh cctxt force name in
        Program.add ~force cctxt name hash);
    command
      ~group
      ~desc:"Remove a script from the library."
      no_options
      (prefixes ["forget"; "script"] @@ Program.alias_param @@ stop)
      (fun () (name, _) cctxt -> Program.del cctxt name);
    command
      ~group
      ~desc:"Display a script from the library."
      no_options
      (prefixes ["show"; "known"; "script"] @@ Program.alias_param @@ stop)
      (fun () (_, program) (cctxt : Protocol_client_context.full) ->
        let open Lwt_result_syntax in
        let* source = Program.to_source program in
        let*! () = cctxt#message "%s\n" source in
        return_unit);
    command
      ~group
      ~desc:"Ask the node to run a script."
      (args12
         trace_stack_switch
         amount_arg
         balance_arg
         source_arg
         payer_arg
         self_arg
         no_print_source_flag
         run_gas_limit_arg
         entrypoint_arg
         (unparsing_mode_arg ~default:"Readable")
         now_arg
         level_arg)
      (prefixes ["run"; "script"]
      @@ Program.source_param
      @@ prefixes ["on"; "storage"]
      @@ param ~name:"storage" ~desc:"the storage data" data_parameter
      @@ prefixes ["and"; "input"]
      @@ param ~name:"input" ~desc:"the input data" data_parameter
      @@ stop)
      (fun ( trace_exec,
             amount,
             balance,
             sender,
             payer,
             self,
             no_print_source,
             gas,
             entrypoint,
             unparsing_mode,
             now,
             level )
           program
           storage
           input
           cctxt ->
        let open Lwt_result_syntax in
        let*? program = Micheline_parser.no_parsing_error program in
        let show_source = not no_print_source in
        if trace_exec then
          let*! res =
            trace
              cctxt
              ~chain:cctxt#chain
              ~block:cctxt#block
              {
                amount = Some amount;
                balance;
                program;
                storage;
                shared_params =
                  {input; unparsing_mode; now; level; sender; payer; gas};
                entrypoint;
                self;
              }
          in
          print_trace_result cctxt ~show_source ~parsed:program res
        else
          let*! res =
            run
              cctxt
              ~chain:cctxt#chain
              ~block:cctxt#block
              {
                amount = Some amount;
                balance;
                program;
                storage;
                shared_params =
                  {input; unparsing_mode; now; level; sender; payer; gas};
                entrypoint;
                self;
              }
          in
          print_run_result cctxt ~show_source ~parsed:program res);
    command
      ~group
      ~desc:"Ask the node to compute the size of a script."
      (args4
         emacs_mode_switch
         no_print_source_flag
         run_gas_limit_arg
         legacy_switch)
      (prefixes ["compute"; "size"; "for"; "script"]
      @@ Program.source_param
      @@ prefixes ["on"; "storage"]
      @@ param ~name:"storage" ~desc:"the storage data" data_parameter
      @@ stop)
      (fun (emacs_mode, no_print_source, original_gas, legacy)
           program
           storage
           cctxt ->
        let open Lwt_result_syntax in
        let setup = (emacs_mode, no_print_source) in
        let* original_gas = resolve_max_gas cctxt cctxt#block original_gas in
        handle_parsing_error "size" cctxt setup program @@ fun program ->
        let* code_size =
          script_size
            cctxt
            ~chain:cctxt#chain
            ~block:cctxt#block
            ~gas:original_gas
            ~legacy
            ~program
            ~storage
            ()
        in
        let*! () = cctxt#message "%d" code_size in
        return_unit);
    command
      ~group
      ~desc:"Ask the node to typecheck a script."
      (args5
         show_types_switch
         emacs_mode_switch
         no_print_source_flag
         run_gas_limit_arg
         legacy_switch)
      (prefixes ["typecheck"; "script"] @@ Program.source_param @@ stop)
      (fun (show_types, emacs_mode, no_print_source, original_gas, legacy)
           program
           cctxt ->
        let open Lwt_result_syntax in
        let setup = (emacs_mode, no_print_source) in
        handle_parsing_error "types" cctxt setup program @@ fun program ->
        let* original_gas = resolve_max_gas cctxt cctxt#block original_gas in
        let*! res =
          typecheck_program
            cctxt
            ~chain:cctxt#chain
            ~block:cctxt#block
            ~gas:original_gas
            ~legacy
            ~show_types
            program
        in
        print_typecheck_result
          ~emacs:emacs_mode
          ~show_types
          ~print_source_on_error:(not no_print_source)
          program
          res
          cctxt);
    command
      ~group
      ~desc:"Ask the node to typecheck a data expression."
      (args3 no_print_source_flag run_gas_limit_arg legacy_switch)
      (prefixes ["typecheck"; "data"]
      @@ param ~name:"data" ~desc:"the data to typecheck" data_parameter
      @@ prefixes ["against"; "type"]
      @@ param ~name:"type" ~desc:"the expected type" data_parameter
      @@ stop)
      (fun (no_print_source, custom_gas, legacy) data ty cctxt ->
        let open Lwt_result_syntax in
        let* original_gas = resolve_max_gas cctxt cctxt#block custom_gas in
        let*! r =
          Client_proto_programs.typecheck_data
            cctxt
            ~chain:cctxt#chain
            ~block:cctxt#block
            ~gas:original_gas
            ~legacy
            ~data
            ~ty
            ()
        in
        match r with
        | Ok gas ->
            let*! () =
              cctxt#message
                "@[<v 0>Well typed@,Gas remaining: %a@]"
                Alpha_context.Gas.pp
                gas
            in
            return_unit
        | Error errs ->
            let*! () =
              cctxt#warning
                "%a"
                (Michelson_v1_error_reporter.report_errors
                   ~details:false
                   ~show_source:(not no_print_source)
                   ?parsed:None)
                errs
            in
            cctxt#error "ill-typed data");
    command
      ~group
      ~desc:
        "Ask the node to pack a data expression.\n\
         The returned hash is the same as what Michelson instruction `PACK` \
         would have produced.\n\
         Also displays the result of hashing this packed data with `BLAKE2B`, \
         `SHA256` or `SHA512` instruction."
      (args2 run_gas_limit_arg (Tezos_clic_unix.Scriptable.clic_arg ()))
      (prefixes ["hash"; "data"]
      @@ param ~name:"data" ~desc:"the data to hash" data_parameter
      @@ prefixes ["of"; "type"]
      @@ param ~name:"type" ~desc:"type of the data" data_parameter
      @@ stop)
      (fun (custom_gas, scriptable) data typ cctxt ->
        let open Lwt_result_syntax in
        let* original_gas = resolve_max_gas cctxt cctxt#block custom_gas in
        let*! r =
          Plugin.RPC.Scripts.pack_data
            cctxt
            (cctxt#chain, cctxt#block)
            ~gas:original_gas
            ~data:data.expanded
            ~ty:typ.expanded
        in
        match r with
        | Ok (bytes, remaining_gas) ->
            let hash = Script_expr_hash.hash_bytes [bytes] in
            let name_value_rows =
              Format.
                [
                  ( "Raw packed data",
                    asprintf "0x%a" Hex.pp (Hex.of_bytes bytes) );
                  ( "Script-expression-ID-Hash",
                    asprintf "%a" Script_expr_hash.pp hash );
                  ( "Raw Script-expression-ID-Hash",
                    asprintf
                      "0x%a"
                      Hex.pp
                      (Hex.of_bytes (Script_expr_hash.to_bytes hash)) );
                  ( "Ledger Blake2b hash",
                    Tezos_crypto.Base58.raw_encode
                      Tezos_crypto.Blake2B.(hash_bytes [bytes] |> to_string) );
                  ( "Raw Sha256 hash",
                    asprintf
                      "0x%a"
                      Hex.pp
                      (Hex.of_bytes (Environment.Raw_hashes.sha256 bytes)) );
                  ( "Raw Sha512 hash",
                    asprintf
                      "0x%a"
                      Hex.pp
                      (Hex.of_bytes (Environment.Raw_hashes.sha512 bytes)) );
                  ( "Gas remaining",
                    asprintf "%a" Alpha_context.Gas.pp remaining_gas );
                ]
            in
            Tezos_clic_unix.Scriptable.output
              scriptable
              ~for_human:(fun () ->
                let*! () =
                  List.iter_s
                    (fun (name, value) -> cctxt#message "%s: %s" name value)
                    name_value_rows
                in
                return_unit)
              ~for_script:(fun () ->
                name_value_rows |> List.map (fun (name, value) -> [name; value]))
        | Error errs ->
            let*! () =
              cctxt#warning
                "%a"
                (Michelson_v1_error_reporter.report_errors
                   ~details:false
                   ~show_source:false
                   ?parsed:None)
                errs
            in
            cctxt#error "ill-formed data");
    command
      ~group
      ~desc:"Ask the node to hash a Michelson script with `BLAKE2B`."
      (args3
         enforce_indentation_flag
         display_names_flag
         (Tezos_clic_unix.Scriptable.clic_arg ()))
      (prefixes ["hash"; "script"]
      @@ seq_of_param
      @@ file_or_literal_with_origin_param ())
      (fun (check, display_names, scriptable)
           expr_strings
           (cctxt : Protocol_client_context.full) ->
        let open Lwt_result_syntax in
        match expr_strings with
        | [] ->
            let*! () =
              cctxt#warning "No scripts were specified on the command line"
            in
            return_unit
        | _ :: _ ->
            let* hash_name_rows =
              List.mapi_ep
                (fun i content_with_origin ->
                  let expr_string =
                    Client_proto_args.content_of_file_or_text
                      content_with_origin
                  in
                  let program =
                    Michelson_v1_parser.parse_toplevel ~check expr_string
                  in
                  let*? program = Micheline_parser.no_parsing_error program in
                  let code = program.expanded in
                  let bytes =
                    Data_encoding.Binary.to_bytes_exn
                      Alpha_context.Script.expr_encoding
                      code
                  in
                  let hash =
                    Format.asprintf
                      "%a"
                      Script_expr_hash.pp
                      (Script_expr_hash.hash_bytes [bytes])
                  in
                  let name =
                    match content_with_origin with
                    | Client_proto_args.File {path; _} -> path
                    | Text _ -> "Literal script " ^ string_of_int (i + 1)
                  in
                  return (hash, name))
                expr_strings
            in
            Tezos_clic_unix.Scriptable.output
              scriptable
              ~for_human:(fun () ->
                let*! () =
                  List.iter_s
                    (fun (hash, name) ->
                      if display_names then cctxt#answer "%s\t%s" hash name
                      else cctxt#answer "%s" hash)
                    hash_name_rows
                in
                return_unit)
              ~for_script:(fun () ->
                List.map
                  (fun (hash, name) ->
                    if display_names then [hash; name] else [hash])
                  hash_name_rows));
    command
      ~group
      ~desc:
        "Parse a byte sequence (in hexadecimal notation) as a data expression, \
         as per Michelson instruction `UNPACK`."
      no_options
      (prefixes ["unpack"; "michelson"; "data"]
      @@ bytes_parameter ~name:"bytes" ~desc:"the packed data to parse"
      @@ stop)
      (fun () bytes cctxt ->
        let open Lwt_result_syntax in
        let* () =
          if Bytes.get bytes 0 != '\005' then
            cctxt#error
              "Not a piece of packed Michelson data (must start with `0x05`)"
          else return_unit
        in
        (* Remove first byte *)
        let bytes = Bytes.sub bytes 1 (Bytes.length bytes - 1) in
        match
          Data_encoding.Binary.of_bytes_opt
            Alpha_context.Script.expr_encoding
            bytes
        with
        | None -> cctxt#error "Could not decode bytes"
        | Some expr ->
            let*! () =
              cctxt#message "%a" Michelson_v1_printer.print_expr_unwrapped expr
            in
            return_unit);
    command
      ~group
      ~desc:"Ask the node to normalize a script."
      (args1 (unparsing_mode_arg ~default:"Readable"))
      (prefixes ["normalize"; "script"] @@ Program.source_param @@ stop)
      (fun unparsing_mode program cctxt ->
        let open Lwt_result_syntax in
        let*? program = Micheline_parser.no_parsing_error program in
        let*! r =
          Plugin.RPC.Scripts.normalize_script
            cctxt
            (cctxt#chain, cctxt#block)
            ~script:program.expanded
            ~unparsing_mode
        in
        match r with
        | Ok program ->
            let*! () =
              cctxt#message
                "%a"
                (fun ppf () : unit ->
                  Michelson_v1_printer.print_expr_unwrapped ppf program)
                ()
            in
            return_unit
        | Error errs ->
            let*! () =
              cctxt#warning
                "%a"
                (Michelson_v1_error_reporter.report_errors
                   ~details:false
                   ~show_source:false
                   ?parsed:None)
                errs
            in
            cctxt#error "ill-typed script");
    command
      ~group
      ~desc:"Ask the node to normalize a data expression."
      (args2 (unparsing_mode_arg ~default:"Readable") legacy_switch)
      (prefixes ["normalize"; "data"]
      @@ param
           ~name:"data"
           ~desc:"the data expression to normalize"
           data_parameter
      @@ prefixes ["of"; "type"]
      @@ param ~name:"type" ~desc:"type of the data expression" data_parameter
      @@ stop)
      (fun (unparsing_mode, legacy) data typ cctxt ->
        let open Lwt_result_syntax in
        let*! r =
          Plugin.RPC.Scripts.normalize_data
            cctxt
            (cctxt#chain, cctxt#block)
            ~legacy
            ~data:data.expanded
            ~ty:typ.expanded
            ~unparsing_mode
        in
        match r with
        | Ok expr ->
            let*! () =
              cctxt#message "%a" Michelson_v1_printer.print_expr_unwrapped expr
            in
            return_unit
        | Error errs ->
            let*! () =
              cctxt#warning
                "%a"
                (Michelson_v1_error_reporter.report_errors
                   ~details:false
                   ~show_source:false
                   ?parsed:None)
                errs
            in
            cctxt#error "ill-typed data expression");
    command
      ~group
      ~desc:"Ask the node to normalize a typed Michelson stack."
      (args2 (unparsing_mode_arg ~default:"Readable") legacy_switch)
      (prefixes ["normalize"; "stack"]
      @@ param
           ~name:"stack"
           ~desc:
             "the stack to normalize, in the following format: {Stack_elt \
              <ty_1> <val_1>; ...; Stack_elt <ty_n> <val_n>}, where each \
              <val_i> is a Michelson value of type <ty_i>. The topmost element \
              of the stack is <val_1>."
           micheline_parameter
      @@ stop)
      (fun (unparsing_mode, legacy) (stack, source) cctxt ->
        let open Lwt_result_syntax in
        let*? stack = Michelson_v1_stack.parse_stack ~source stack in
        let*! r =
          Plugin.RPC.Scripts.normalize_stack
            cctxt
            (cctxt#chain, cctxt#block)
            ~legacy
            ~stack
            ~unparsing_mode
        in
        match r with
        | Ok expr ->
            let*! () =
              cctxt#message "%a" Michelson_v1_printer.print_typed_stack expr
            in
            return_unit
        | Error errs ->
            let*! () =
              cctxt#warning
                "%a"
                (Michelson_v1_error_reporter.report_errors
                   ~details:false
                   ~show_source:false
                   ?parsed:None)
                errs
            in
            cctxt#error "ill-typed stack");
    command
      ~group
      ~desc:"Ask the node to normalize a type."
      no_options
      (prefixes ["normalize"; "type"]
      @@ param
           ~name:"typ"
           ~desc:"the Michelson type to normalize"
           data_parameter
      @@ stop)
      (fun () typ cctxt ->
        let open Lwt_result_syntax in
        let*! r =
          Plugin.RPC.Scripts.normalize_type
            cctxt
            (cctxt#chain, cctxt#block)
            ~ty:typ.expanded
        in
        match r with
        | Ok expr ->
            let*! () =
              cctxt#message "%a" Michelson_v1_printer.print_expr_unwrapped expr
            in
            return_unit
        | Error errs ->
            let*! () =
              cctxt#warning
                "%a"
                (Michelson_v1_error_reporter.report_errors
                   ~details:false
                   ~show_source:false
                   ?parsed:None)
                errs
            in
            cctxt#error "ill-formed type");
    command
      ~group
      ~desc:
        "Sign a raw sequence of bytes and display it using the format expected \
         by Michelson instruction `CHECK_SIGNATURE`."
      no_options
      (prefixes ["sign"; "bytes"]
      @@ bytes_parameter ~name:"data" ~desc:"the raw data to sign"
      @@ prefixes ["for"] @@ Client_keys.Secret_key.source_param @@ stop)
      (fun () bytes sk cctxt ->
        let open Lwt_result_syntax in
        let* signature = Client_keys.sign cctxt sk bytes in
        let*! () = cctxt#message "Signature: %a" Signature.pp signature in
        return_unit);
    command
      ~group
      ~desc:
        "Check the signature of a byte sequence as per Michelson instruction \
         `CHECK_SIGNATURE`."
      (args1 (switch ~doc:"Use only exit codes" ~short:'q' ~long:"quiet" ()))
      (prefixes ["check"; "that"; "bytes"]
      @@ bytes_parameter ~name:"bytes" ~desc:"the signed data"
      @@ prefixes ["were"; "signed"; "by"]
      @@ Client_keys.Public_key.alias_param ~name:"key"
      @@ prefixes ["to"; "produce"]
      @@ param
           ~name:"signature"
           ~desc:"the signature to check"
           signature_parameter
      @@ stop)
      (fun quiet
           bytes
           (_, (key_locator, _))
           signature
           (cctxt : #Protocol_client_context.full) ->
        let open Lwt_result_syntax in
        let* check = Client_keys.check key_locator signature bytes in
        if check then
          if quiet then return_unit
          else
            let*! () = cctxt#message "Signature check successful." in
            return_unit
        else cctxt#error "invalid signature");
    command
      ~group
      ~desc:"Ask the type of an entrypoint of a script."
      (args2 emacs_mode_switch no_print_source_flag)
      (prefixes ["get"; "script"; "entrypoint"; "type"; "of"]
      @@ param
           ~name:"entrypoint"
           ~desc:"the entrypoint to describe"
           entrypoint_parameter
      @@ prefixes ["for"] @@ Program.source_param @@ stop)
      (fun ((emacs_mode, no_print_source) as setup) entrypoint program cctxt ->
        let open Lwt_syntax in
        handle_parsing_error "entrypoint" cctxt setup program @@ fun program ->
        let* entrypoint_type =
          entrypoint_type
            cctxt
            ~chain:cctxt#chain
            ~block:cctxt#block
            program
            ~entrypoint
        in
        print_entrypoint_type
          ~emacs:emacs_mode
          ~show_source:(not no_print_source)
          ~parsed:program
          ~entrypoint
          cctxt
          entrypoint_type);
    command
      ~group
      ~desc:"Ask the node to list the entrypoints of a script."
      (args2 emacs_mode_switch no_print_source_flag)
      (prefixes ["get"; "script"; "entrypoints"; "for"]
      @@ Program.source_param @@ stop)
      (fun ((emacs_mode, no_print_source) as setup) program cctxt ->
        let open Lwt_syntax in
        handle_parsing_error "entrypoints" cctxt setup program @@ fun program ->
        let* entrypoints =
          list_entrypoints cctxt ~chain:cctxt#chain ~block:cctxt#block program
        in
        print_entrypoints_list
          ~emacs:emacs_mode
          ~show_source:(not no_print_source)
          ~parsed:program
          cctxt
          entrypoints);
    command
      ~group
      ~desc:
        "Ask the node to list the unreachable paths in a script's parameter \
         type."
      (args2 emacs_mode_switch no_print_source_flag)
      (prefixes ["get"; "script"; "unreachable"; "paths"; "for"]
      @@ Program.source_param @@ stop)
      (fun ((emacs_mode, no_print_source) as setup) program cctxt ->
        let open Lwt_syntax in
        handle_parsing_error "entrypoints" cctxt setup program @@ fun program ->
        let* entrypoints =
          list_unreachables cctxt ~chain:cctxt#chain ~block:cctxt#block program
        in
        print_unreachables
          ~emacs:emacs_mode
          ~show_source:(not no_print_source)
          ~parsed:program
          cctxt
          entrypoints);
    command
      ~group
      ~desc:"Ask the node to expand the Michelson macros in a script."
      no_options
      (prefixes ["expand"; "macros"; "in"] @@ Program.source_param @@ stop)
      (fun () program (cctxt : Protocol_client_context.full) ->
        let open Lwt_result_syntax in
        let*? program = Micheline_parser.no_parsing_error program in
        let*! () =
          cctxt#message
            "%a"
            (fun ppf () : unit ->
              Michelson_v1_printer.print_expr_unwrapped ppf program.expanded)
            ()
        in
        return_unit);
    command
      ~desc:
        "Conversion of Michelson script from Micheline, JSON or binary to \
         Micheline, JSON, binary or OCaml"
      (args3 zero_loc_switch legacy_switch enforce_indentation_flag)
      (prefixes ["convert"; "script"]
      @@ file_or_literal_param () @@ prefix "from" @@ convert_input_format_param
      @@ prefix "to" @@ convert_output_format_param @@ stop)
      (fun (zero_loc, legacy, check)
           expr_string
           from_format
           to_format
           (cctxt : Protocol_client_context.full) ->
        let open Lwt_result_syntax in
        let* (expression : Alpha_context.Script.expr) =
          match from_format with
          | `Michelson ->
              let program =
                Michelson_v1_parser.parse_toplevel ~check expr_string
              in
              let*? program = Micheline_parser.no_parsing_error program in
              let* () =
                let*! r =
                  typecheck_program
                    cctxt
                    ~chain:cctxt#chain
                    ~block:cctxt#block
                    ~legacy
                    ~show_types:true
                    program
                in
                match r with
                | Error _ as res ->
                    print_typecheck_result
                      ~emacs:false
                      ~show_types:true
                      ~print_source_on_error:true
                      program
                      res
                      cctxt
                | Ok _ -> return_unit
              in
              return program.expanded
          | `JSON -> (
              match Data_encoding.Json.from_string expr_string with
              | Error err -> cctxt#error "%s" err
              | Ok json ->
                  safe_decode_json
                    ~name:"script"
                    cctxt
                    Alpha_context.Script.expr_encoding
                    json)
          | `Binary -> (
              let* bytes = bytes_of_prefixed_string cctxt expr_string in
              match
                Data_encoding.Binary.of_bytes_opt
                  Alpha_context.Script.expr_encoding
                  bytes
              with
              | None -> cctxt#error "Could not decode bytes"
              | Some expr -> return expr)
        in
        let output =
          match to_format with
          | `Michelson ->
              Micheline_printer.printable
                Michelson_v1_primitives.string_of_prim
                expression
              |> Format.asprintf "%a" Micheline_printer.print_expr
          | `JSON ->
              Data_encoding.Json.(
                construct Alpha_context.Script.expr_encoding expression
                |> to_string)
          | `Binary ->
              Format.asprintf
                "0x%s"
                (Data_encoding.Binary.(
                   to_bytes_exn Alpha_context.Script.expr_encoding expression)
                |> Hex.of_bytes |> Hex.show)
          | `OCaml ->
              Michelson_v1_printer.micheline_string_of_expression
                ~zero_loc
                expression
        in
        let*! () = cctxt#message "%s" output in
        return_unit);
    command
      ~desc:
        "Conversion of Micheline expression from Micheline, JSON or binary to \
         Micheline, JSON, binary or OCaml"
      (args2 zero_loc_switch data_type_arg)
      (prefixes ["convert"; "data"]
      @@ file_or_literal_param () @@ prefix "from" @@ convert_input_format_param
      @@ prefix "to" @@ convert_output_format_param @@ stop)
      (fun (zero_loc, data_ty)
           data_string
           from_format
           to_format
           (cctxt : Protocol_client_context.full) ->
        let open Lwt_result_syntax in
        let micheline_of_expr expr =
          Micheline_printer.printable
            Michelson_v1_primitives.string_of_prim
            expr
          |> Format.asprintf "%a" Micheline_printer.print_expr
        in
        let typecheck_parsed ~data ~ty =
          let*! r =
            Client_proto_programs.typecheck_data
              cctxt
              ~chain:cctxt#chain
              ~block:cctxt#block
              ~data
              ~ty
              ()
          in
          match r with
          | Error errs ->
              cctxt#error
                "%a"
                (Michelson_v1_error_reporter.report_errors
                   ~details:false
                   ~show_source:false
                   ?parsed:None)
                errs
          | Ok _gas -> return data.expanded
        in
        let typecheck_expr ~expr ~ty =
          let data_string = micheline_of_expr expr in
          let* data = parse_expr data_string in
          typecheck_parsed ~data ~ty
        in
        let* (expression : Alpha_context.Script.expr) =
          match from_format with
          | `Michelson -> (
              let* data = parse_expr data_string in
              match data_ty with
              | Some ty -> typecheck_parsed ~data ~ty
              | None -> return data.expanded)
          | `JSON -> (
              match Data_encoding.Json.from_string data_string with
              | Error err -> cctxt#error "%s" err
              | Ok json -> (
                  let* expr =
                    safe_decode_json
                      ~name:"script"
                      cctxt
                      Alpha_context.Script.expr_encoding
                      json
                  in
                  match data_ty with
                  | None -> return expr
                  | Some ty -> typecheck_expr ~expr ~ty))
          | `Binary -> (
              let* bytes = bytes_of_prefixed_string cctxt data_string in
              match
                Data_encoding.Binary.of_bytes_opt
                  Alpha_context.Script.expr_encoding
                  bytes
              with
              | None -> cctxt#error "Could not decode bytes"
              | Some expr -> (
                  match data_ty with
                  | None -> return expr
                  | Some ty -> typecheck_expr ~expr ~ty))
        in
        let output =
          match to_format with
          | `Michelson -> micheline_of_expr expression
          | `JSON ->
              Data_encoding.Json.(
                construct Alpha_context.Script.expr_encoding expression
                |> to_string)
          | `Binary ->
              Format.asprintf
                "0x%s"
                (Data_encoding.Binary.(
                   to_bytes_exn Alpha_context.Script.expr_encoding expression)
                |> Hex.of_bytes |> Hex.show)
          | `OCaml ->
              Michelson_v1_printer.micheline_string_of_expression
                ~zero_loc
                expression
        in
        let*! () = cctxt#message "%s" output in
        return_unit);
    command
      ~group
      ~desc:"Ask the node to run a TZIP-4 view."
      (args6
         source_arg
         payer_arg
         run_gas_limit_arg
         (unparsing_mode_arg ~default:"Readable")
         now_arg
         level_arg)
      (prefixes ["run"; "tzip4"; "view"]
      @@ param
           ~name:"entrypoint"
           ~desc:"the name of the view"
           entrypoint_parameter
      @@ prefixes ["on"; "contract"]
      @@ OriginatedContractAlias.destination_param
           ~name:"contract"
           ~desc:"viewed contract"
      @@ prefixes ["with"; "input"]
      @@ param ~name:"input" ~desc:"the input data" data_parameter
      @@ stop)
      (fun (sender, payer, gas, unparsing_mode, now, level)
           entrypoint
           contract
           input
           cctxt ->
        let open Lwt_syntax in
        let* res =
          Client_proto_programs.run_view
            cctxt
            ~chain:cctxt#chain
            ~block:cctxt#block
            {
              shared_params =
                {input; unparsing_mode; now; level; sender; payer; gas};
              contract;
              entrypoint;
            }
        in
        print_view_result cctxt res);
    command
      ~group
      ~desc:"Ask the node to run a Michelson view with Unit as input."
      (args7
         source_arg
         payer_arg
         run_gas_limit_arg
         unlimited_gas_arg
         (unparsing_mode_arg ~default:"Readable")
         now_arg
         level_arg)
      (prefixes ["run"; "view"]
      @@ param ~name:"view" ~desc:"the name of the view" string_parameter
      @@ prefixes ["on"; "contract"]
      @@ OriginatedContractAlias.destination_param
           ~name:"contract"
           ~desc:"the contract containing the view"
      @@ stop)
      (fun (sender, payer, gas, unlimited_gas, unparsing_mode, now, level)
           view
           contract
           cctxt ->
        let open Lwt_result_syntax in
        let*? input =
          Micheline_parser.no_parsing_error
          @@ Michelson_v1_parser.parse_expression "Unit"
        in
        let*! res =
          Client_proto_programs.run_script_view
            cctxt
            ~chain:cctxt#chain
            ~block:cctxt#block
            {
              shared_params =
                {input; unparsing_mode; now; level; sender; payer; gas};
              contract;
              view;
              unlimited_gas;
            }
        in
        print_view_result cctxt res);
    command
      ~group
      ~desc:"Ask the node to run a Michelson view."
      (args7
         source_arg
         payer_arg
         run_gas_limit_arg
         unlimited_gas_arg
         (unparsing_mode_arg ~default:"Readable")
         now_arg
         level_arg)
      (prefixes ["run"; "view"]
      @@ param ~name:"view" ~desc:"the name of the view" string_parameter
      @@ prefixes ["on"; "contract"]
      @@ OriginatedContractAlias.destination_param
           ~name:"contract"
           ~desc:"the contract containing the view"
      @@ prefixes ["with"; "input"]
      @@ param
           ~name:"input"
           ~desc:"the argument provided to the view"
           data_parameter
      @@ stop)
      (fun (sender, payer, gas, unlimited_gas, unparsing_mode, now, level)
           view
           contract
           input
           cctxt ->
        let open Lwt_syntax in
        let* res =
          Client_proto_programs.run_script_view
            cctxt
            ~chain:cctxt#chain
            ~block:cctxt#block
            {
              shared_params =
                {input; unparsing_mode; now; level; sender; payer; gas};
              contract;
              view;
              unlimited_gas;
            }
        in
        print_view_result cctxt res);
  ]
OCaml

Innovation. Community. Security.