• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

MinaProtocol / mina / 749

30 Oct 2025 06:25PM UTC coverage: 33.517% (+1.2%) from 32.315%
749

push

buildkite

web-flow
Merge pull request #18037 from MinaProtocol/local-images

Replacing common images with ones in our repos

24488 of 73061 relevant lines covered (33.52%)

23563.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

22.08
/src/app/cli/src/cli_entrypoint/mina_cli_entrypoint.ml
1
open Core
2
open Async
3
open Mina_base
4
open Cli_lib
5
open Signature_lib
6
open Init
7
module YJ = Yojson.Safe
8

9
type mina_initialization =
10
  { mina : Mina_lib.t
11
  ; client_trustlist : Unix.Cidr.t list option
12
  ; rest_server_port : int
13
  ; limited_graphql_port : int option
14
  ; itn_graphql_port : int option
15
  }
16

17
(* keep this code in sync with Client.chain_id_inputs, Mina_commands.chain_id_inputs, and
18
   Daemon_rpcs.Chain_id_inputs
19
*)
20
let chain_id ~constraint_system_digests ~genesis_state_hash ~genesis_constants
21
    ~protocol_transaction_version ~protocol_network_version =
22
  (* if this changes, also change Mina_commands.chain_id_inputs *)
23
  let genesis_state_hash = State_hash.to_base58_check genesis_state_hash in
×
24
  let genesis_constants_hash = Genesis_constants.hash genesis_constants in
×
25
  let all_snark_keys =
×
26
    List.map constraint_system_digests ~f:(fun (_, digest) -> Md5.to_hex digest)
×
27
    |> String.concat ~sep:""
×
28
  in
29
  let version_digest v = Int.to_string v |> Md5.digest_string |> Md5.to_hex in
×
30
  let protocol_transaction_version_digest =
31
    version_digest protocol_transaction_version
32
  in
33
  let protocol_network_version_digest =
×
34
    version_digest protocol_network_version
35
  in
36
  let b2 =
×
37
    Blake2.digest_string
38
      ( genesis_state_hash ^ all_snark_keys ^ genesis_constants_hash
39
      ^ protocol_transaction_version_digest ^ protocol_network_version_digest )
40
  in
41
  Blake2.to_hex b2
×
42

43
let plugin_flag =
44
  if Node_config.plugins then
45
    let open Command.Param in
×
46
    flag "--load-plugin" ~aliases:[ "load-plugin" ] (listed string)
×
47
      ~doc:
48
        "PATH The path to load a .cmxs plugin from. May be passed multiple \
49
         times"
50
  else Command.Param.return []
135✔
51

52
module Chain_state_locations = struct
53
  (** The locations of the chain state in a daemon. These will be computed by
54
      [chain_state_locations] based on the runtime daemon config. By default,
55
      the [chain_state] will be located in the mina config directory and the
56
      other directories will be located in the [chain_state]. *)
57
  type t =
58
    { chain_state : string  (** The top-level chain state directory *)
59
    ; mina_net : string  (** Mina networking information *)
60
    ; trust : string  (** P2P trust information *)
61
    ; root : string  (** The root snarked ledgers *)
62
    ; genesis : string  (** The genesis ledgers *)
63
    ; frontier : string  (** The transition frontier *)
64
    ; epoch_ledger : string  (** The epoch ledger snapshots *)
65
    ; proof_cache : string  (** The proof cache *)
66
    ; zkapp_vk_cache : string  (** The zkApp vk cache *)
67
    ; snark_pool : string  (** The snark pool *)
68
    }
69

70
  (** Determine the locations of the chain state components based on the daemon
71
      runtime config *)
72
  let of_config ~conf_dir (config : Runtime_config.t) : t =
73
    (* TODO: post hard fork, we should not be ignoring this *)
74
    let _config = config in
×
75
    let chain_state = conf_dir in
76
    { chain_state
77
    ; mina_net = chain_state ^/ "mina_net2"
×
78
    ; trust = chain_state ^/ "trust"
×
79
    ; root = chain_state ^/ "root"
×
80
    ; genesis = chain_state ^/ "genesis"
×
81
    ; frontier = chain_state ^/ "frontier"
×
82
    ; epoch_ledger = chain_state
83
    ; proof_cache = chain_state ^/ "proof_cache"
×
84
    ; zkapp_vk_cache = chain_state ^/ "zkapp_vk_cache"
×
85
    ; snark_pool = chain_state ^/ "snark_pool"
×
86
    }
87
end
88

89
let load_config_files ~logger ~genesis_constants ~constraint_constants ~conf_dir
90
    ~genesis_dir ~cli_proof_level ~proof_level ~genesis_backing_type
91
    config_files =
92
  let%bind config_jsons =
93
    let config_files_paths =
94
      List.map config_files ~f:(fun (config_file, _) -> `String config_file)
×
95
    in
96
    [%log info] "Reading configuration files $config_files"
×
97
      ~metadata:[ ("config_files", `List config_files_paths) ] ;
98
    Deferred.List.filter_map config_files
×
99
      ~f:(fun (config_file, handle_missing) ->
100
        match%bind Genesis_ledger_helper.load_config_json config_file with
×
101
        | Ok config_json ->
×
102
            let%map config_json =
103
              Genesis_ledger_helper.upgrade_old_config ~logger config_file
×
104
                config_json
105
            in
106
            Some (config_file, config_json)
×
107
        | Error err -> (
×
108
            match handle_missing with
109
            | `Must_exist ->
×
110
                Mina_stdlib.Mina_user_error.raisef
111
                  ~where:"reading configuration file"
112
                  "The configuration file %s could not be read:\n%s" config_file
113
                  (Error.to_string_hum err)
×
114
            | `May_be_missing ->
×
115
                [%log warn] "Could not read configuration from $config_file"
×
116
                  ~metadata:
117
                    [ ("config_file", `String config_file)
118
                    ; ("error", Error_json.error_to_yojson err)
×
119
                    ] ;
120
                return None ) )
×
121
  in
122
  let config =
×
123
    List.fold ~init:Runtime_config.default config_jsons
124
      ~f:(fun config (config_file, config_json) ->
125
        match Runtime_config.of_yojson config_json with
×
126
        | Ok loaded_config ->
×
127
            Runtime_config.combine config loaded_config
128
        | Error err ->
×
129
            [%log fatal]
×
130
              "Could not parse configuration from $config_file: $error"
131
              ~metadata:
132
                [ ("config_file", `String config_file)
133
                ; ("config_json", config_json)
134
                ; ("error", `String err)
135
                ] ;
136
            failwithf "Could not parse configuration file: %s" err () )
×
137
  in
138
  let chain_state_locations =
×
139
    Chain_state_locations.of_config ~conf_dir config
140
  in
141
  let genesis_dir =
×
142
    Option.value ~default:chain_state_locations.genesis genesis_dir
143
  in
144
  let%bind precomputed_values =
145
    match%map
146
      Genesis_ledger_helper.init_from_config_file ~cli_proof_level ~genesis_dir
×
147
        ~logger ~genesis_constants ~constraint_constants ~proof_level
148
        ~genesis_backing_type config
149
    with
150
    | Ok (precomputed_values, _) ->
×
151
        precomputed_values
152
    | Error err ->
×
153
        let ( json_config
154
            , `Accounts_omitted
155
                ( `Genesis genesis_accounts_omitted
156
                , `Staking staking_accounts_omitted
157
                , `Next next_accounts_omitted ) ) =
158
          Runtime_config.to_yojson_without_accounts config
159
        in
160
        let append_accounts_omitted s =
×
161
          Option.value_map
×
162
            ~f:(fun i -> List.cons (s ^ "_accounts_omitted", `Int i))
×
163
            ~default:Fn.id
164
        in
165
        let metadata =
166
          append_accounts_omitted "genesis" genesis_accounts_omitted
167
          @@ append_accounts_omitted "staking" staking_accounts_omitted
×
168
          @@ append_accounts_omitted "next" next_accounts_omitted []
×
169
          @ [ ("config", json_config)
170
            ; ( "name"
171
              , `String
172
                  (Option.value ~default:"not provided"
×
173
                     (let%bind.Option ledger = config.ledger in
174
                      Option.first_some ledger.name ledger.hash ) ) )
×
175
            ; ("error", Error_json.error_to_yojson err)
×
176
            ]
177
        in
178
        [%log info]
×
179
          "Initializing with runtime configuration. Ledger source: $name"
180
          ~metadata ;
181
        Error.raise err
×
182
  in
183
  return (precomputed_values, config_jsons, config, chain_state_locations)
×
184

185
let setup_daemon logger ~itn_features ~default_snark_worker_fee =
186
  let open Command.Let_syntax in
270✔
187
  let open Cli_lib.Arg_type in
188
  let receiver_key_warning = Cli_lib.Default.receiver_key_warning in
189
  let%map_open conf_dir = Cli_lib.Flag.conf_dir
190
  and block_production_key =
191
    flag "--block-producer-key" ~aliases:[ "block-producer-key" ]
270✔
192
      ~doc:
193
        (sprintf
270✔
194
           "DEPRECATED: Use environment variable `MINA_BP_PRIVKEY` instead. \
195
            Private key file for the block producer. Providing this flag or \
196
            the environment variable will enable block production. You cannot \
197
            provide both `block-producer-key` and `block-producer-pubkey`. \
198
            (default: use environment variable `MINA_BP_PRIVKEY`, if provided, \
199
            or else don't produce any blocks) %s"
200
           receiver_key_warning )
201
      (optional string)
270✔
202
  and block_production_pubkey =
203
    flag "--block-producer-pubkey"
270✔
204
      ~aliases:[ "block-producer-pubkey" ]
205
      ~doc:
206
        (sprintf
270✔
207
           "PUBLICKEY Public key for the associated private key that is being \
208
            tracked by this daemon. You cannot provide both \
209
            `block-producer-key` (or `MINA_BP_PRIVKEY`) and \
210
            `block-producer-pubkey`. (default: don't produce blocks) %s"
211
           receiver_key_warning )
212
      (optional public_key_compressed)
270✔
213
  and block_production_password =
214
    flag "--block-producer-password"
270✔
215
      ~aliases:[ "block-producer-password" ]
216
      ~doc:
217
        "PASSWORD Password associated with the block-producer key. Setting \
218
         this is equivalent to setting the MINA_PRIVKEY_PASS environment \
219
         variable. Be careful when setting it in the commandline as it will \
220
         likely get tracked in your history. Mainly to be used from the \
221
         daemon.json config file"
222
      (optional string)
270✔
223
  and itn_keys =
224
    if itn_features then
225
      flag "--itn-keys" ~aliases:[ "itn-keys" ] (optional string)
×
226
        ~doc:
227
          "PUBLICKEYS A comma-delimited list of Ed25519 public keys that are \
228
           permitted to send signed requests to the incentivized testnet \
229
           GraphQL server"
230
    else Command.Param.return None
270✔
231
  and itn_max_logs =
232
    if itn_features then
233
      flag "--itn-max-logs" ~aliases:[ "itn-max-logs" ] (optional int)
×
234
        ~doc:
235
          "NN Maximum number of logs to store to be made available via GraphQL \
236
           for incentivized testnet"
237
    else Command.Param.return None
270✔
238
  and demo_mode =
239
    flag "--demo-mode" ~aliases:[ "demo-mode" ] no_arg
270✔
240
      ~doc:
241
        "Run the daemon in demo-mode -- assume we're \"synced\" to the network \
242
         instantly"
243
  and coinbase_receiver_flag =
244
    flag "--coinbase-receiver" ~aliases:[ "coinbase-receiver" ]
270✔
245
      ~doc:
246
        (sprintf
270✔
247
           "PUBLICKEY Address to send coinbase rewards to (if this node is \
248
            producing blocks). If not provided, coinbase rewards will be sent \
249
            to the producer of a block. %s"
250
           receiver_key_warning )
251
      (optional public_key_compressed)
270✔
252
  and genesis_dir =
253
    flag "--genesis-ledger-dir" ~aliases:[ "genesis-ledger-dir" ]
270✔
254
      ~doc:
255
        "DIR Directory that contains the genesis ledger and the genesis \
256
         blockchain proof (default: <config-dir>)"
257
      (optional string)
270✔
258
  and run_snark_worker_flag =
259
    flag "--run-snark-worker" ~aliases:[ "run-snark-worker" ]
270✔
260
      ~doc:
261
        (sprintf "PUBLICKEY Run the SNARK worker with this public key. %s"
270✔
262
           receiver_key_warning )
263
      (optional public_key_compressed)
270✔
264
  and run_snark_coordinator_flag =
265
    flag "--run-snark-coordinator"
270✔
266
      ~aliases:[ "run-snark-coordinator" ]
267
      ~doc:
268
        (sprintf
270✔
269
           "PUBLICKEY Run a SNARK coordinator with this public key (ignored if \
270
            the run-snark-worker is set). %s"
271
           receiver_key_warning )
272
      (optional public_key_compressed)
270✔
273
  and snark_worker_parallelism_flag =
274
    flag "--snark-worker-parallelism"
270✔
275
      ~aliases:[ "snark-worker-parallelism" ]
276
      ~doc:
277
        "NUM Run the SNARK worker using this many threads. Equivalent to \
278
         setting OMP_NUM_THREADS, but doesn't affect block production."
279
      (optional int)
270✔
280
  and work_selection_method_flag =
281
    flag "--work-selection" ~aliases:[ "work-selection" ]
270✔
282
      ~doc:
283
        "seq|rand|roffset Choose work sequentially (seq), randomly (rand), or \
284
         sequentially with a random offset (roffset) (default: rand)"
285
      (optional work_selection_method)
270✔
286
  and libp2p_port = Flag.Port.Daemon.external_
287
  and client_port = Flag.Port.Daemon.client
288
  and rest_server_port = Flag.Port.Daemon.rest_server
289
  and limited_graphql_port = Flag.Port.Daemon.limited_graphql_server
290
  and itn_graphql_port =
291
    if itn_features then
292
      flag "--itn-graphql-port" ~aliases:[ "itn-graphql-port" ]
×
293
        ~doc:"PORT GraphQL-server for incentivized testnet interaction"
294
        (optional int)
×
295
    else Command.Param.return None
270✔
296
  and open_limited_graphql_port =
297
    flag "--open-limited-graphql-port"
270✔
298
      ~aliases:[ "open-limited-graphql-port" ]
299
      no_arg
300
      ~doc:
301
        "Have the limited GraphQL server listen on all addresses, not just \
302
         localhost (this is INSECURE, make sure your firewall is configured \
303
         correctly!)"
304
  and archive_process_location = Flag.Host_and_port.Daemon.archive
305
  and metrics_server_port =
306
    flag "--metrics-port" ~aliases:[ "metrics-port" ]
270✔
307
      ~doc:
308
        "PORT metrics server for scraping via Prometheus (default no \
309
         metrics-server)"
310
      (optional int16)
270✔
311
  and gc_stat_interval =
312
    flag "--gc-stat-interval" ~aliases:[ "gc-stat-interval" ] (optional float)
270✔
313
      ~doc:
314
        (sprintf
270✔
315
           "INTERVAL in mins for collecting GC stats for metrics (Default: %f)"
316
           !Mina_metrics.Runtime.gc_stat_interval_mins )
317
  and libp2p_metrics_port =
318
    flag "--libp2p-metrics-port" ~aliases:[ "libp2p-metrics-port" ]
270✔
319
      ~doc:
320
        "PORT libp2p metrics server for scraping via Prometheus (default no \
321
         libp2p-metrics-server)"
322
      (optional int16)
270✔
323
  and external_ip_opt =
324
    flag "--external-ip" ~aliases:[ "external-ip" ]
270✔
325
      ~doc:
326
        "IP External IP address for other nodes to connect to. You only need \
327
         to set this if auto-discovery fails for some reason."
328
      (optional string)
270✔
329
  and bind_ip_opt =
330
    flag "--bind-ip" ~aliases:[ "bind-ip" ]
270✔
331
      ~doc:"IP IP of network interface to use for peer connections"
332
      (optional string)
270✔
333
  and working_dir =
334
    flag "--working-dir" ~aliases:[ "working-dir" ]
270✔
335
      ~doc:
336
        "PATH path to chdir into before starting (useful for background mode, \
337
         defaults to cwd, or / if -background)"
338
      (optional string)
270✔
339
  and is_background =
340
    flag "--background" ~aliases:[ "background" ] no_arg
270✔
341
      ~doc:"Run process on the background"
342
  and is_archive_rocksdb =
343
    flag "--archive-rocksdb" ~aliases:[ "archive-rocksdb" ] no_arg
270✔
344
      ~doc:"Stores all the blocks heard in RocksDB"
345
  and log_json = Flag.Log.json
346
  and log_level = Flag.Log.level
347
  and file_log_level = Flag.Log.file_log_level
348
  and file_log_rotations = Flag.Log.file_log_rotations
349
  and snark_work_fee =
350
    flag "--snark-worker-fee" ~aliases:[ "snark-worker-fee" ]
270✔
351
      ~doc:
352
        (sprintf
270✔
353
           "FEE Amount a worker wants to get compensated for generating a \
354
            snark proof (default: %d)"
355
           (Currency.Fee.to_nanomina_int default_snark_worker_fee) )
270✔
356
      (optional txn_fee)
270✔
357
  and work_reassignment_wait =
358
    flag "--work-reassignment-wait"
270✔
359
      ~aliases:[ "work-reassignment-wait" ]
360
      (optional int)
270✔
361
      ~doc:
362
        (sprintf
270✔
363
           "WAIT-TIME in ms before a snark-work is reassigned (default: %dms)"
364
           Cli_lib.Default.work_reassignment_wait )
365
  and enable_tracing =
366
    flag "--tracing" ~aliases:[ "tracing" ] no_arg
270✔
367
      ~doc:"Trace into $config-directory/trace/$pid.trace"
368
  and enable_internal_tracing =
369
    flag "--internal-tracing" ~aliases:[ "internal-tracing" ] no_arg
270✔
370
      ~doc:
371
        "Enables internal tracing into \
372
         $config-directory/internal-tracing/internal-trace.jsonl"
373
  and insecure_rest_server =
374
    flag "--insecure-rest-server" ~aliases:[ "insecure-rest-server" ] no_arg
270✔
375
      ~doc:
376
        "Have REST server listen on all addresses, not just localhost (this is \
377
         INSECURE, make sure your firewall is configured correctly!)"
378
  (* FIXME #4095
379
     and limit_connections =
380
       flag "--limit-concurrent-connections"
381
         ~aliases:[ "limit-concurrent-connections"]
382
         ~doc:
383
           "true|false Limit the number of concurrent connections per IP \
384
            address (default: true)"
385
         (optional bool)*)
386
  (*TODO: This is being added to log all the snark works received for the
387
     beta-testnet challenge. We might want to remove this later?*)
388
  and log_received_snark_pool_diff =
389
    flag "--log-snark-work-gossip"
270✔
390
      ~aliases:[ "log-snark-work-gossip" ]
391
      ~doc:"true|false Log snark-pool diff received from peers (default: false)"
392
      (optional bool)
270✔
393
  and log_transaction_pool_diff =
394
    flag "--log-txn-pool-gossip" ~aliases:[ "log-txn-pool-gossip" ]
270✔
395
      ~doc:
396
        "true|false Log transaction-pool diff received from peers (default: \
397
         false)"
398
      (optional bool)
270✔
399
  and log_block_creation =
400
    flag "--log-block-creation" ~aliases:[ "log-block-creation" ]
270✔
401
      ~doc:
402
        "true|false Log the steps involved in including transactions and snark \
403
         work in a block (default: true)"
404
      (optional bool)
270✔
405
  and libp2p_keypair =
406
    flag "--libp2p-keypair" ~aliases:[ "libp2p-keypair" ] (optional string)
270✔
407
      ~doc:
408
        "KEYFILE Keypair (generated from `mina libp2p generate-keypair`) to \
409
         use with libp2p discovery"
410
  and is_seed =
411
    flag "--seed" ~aliases:[ "seed" ] ~doc:"Start the node as a seed node"
270✔
412
      no_arg
413
  and enable_flooding =
414
    flag "--enable-flooding" ~aliases:[ "enable-flooding" ]
270✔
415
      ~doc:
416
        "true|false Publish our own blocks/transactions to every peer we can \
417
         find (default: false)"
418
      (optional bool)
270✔
419
  and peer_exchange =
420
    flag "--enable-peer-exchange" ~aliases:[ "enable-peer-exchange" ]
270✔
421
      ~doc:
422
        "true|false Help keep the mesh connected when closing connections \
423
         (default: false)"
424
      (optional bool)
270✔
425
  and peer_protection_ratio =
426
    flag "--peer-protection-rate" ~aliases:[ "peer-protection-rate" ]
270✔
427
      ~doc:"float Proportion of peers to be marked as protected (default: 0.2)"
428
      (optional_with_default 0.2 float)
270✔
429
  and min_connections =
430
    flag "--min-connections" ~aliases:[ "min-connections" ]
270✔
431
      ~doc:
432
        (Printf.sprintf
270✔
433
           "NN min number of connections that this peer will have to neighbors \
434
            in the gossip network (default: %d)"
435
           Cli_lib.Default.min_connections )
436
      (optional int)
270✔
437
  and max_connections =
438
    flag "--max-connections" ~aliases:[ "max-connections" ]
270✔
439
      ~doc:
440
        (Printf.sprintf
270✔
441
           "NN max number of connections that this peer will have to neighbors \
442
            in the gossip network. Tuning this higher will strengthen your \
443
            connection to the network in exchange for using more RAM (default: \
444
            %d)"
445
           Cli_lib.Default.max_connections )
446
      (optional int)
270✔
447
  and validation_queue_size =
448
    flag "--validation-queue-size"
270✔
449
      ~aliases:[ "validation-queue-size" ]
450
      ~doc:
451
        (Printf.sprintf
270✔
452
           "NN size of the validation queue in the p2p network used to buffer \
453
            messages (like blocks and transactions received on the gossip \
454
            network) while validation is pending. If a transaction, for \
455
            example, is invalid, we don't forward the message on the gossip \
456
            net. If this queue is too small, we will drop messages without \
457
            validating them. If it is too large, we are susceptible to DoS \
458
            attacks on memory. (default: %d)"
459
           Cli_lib.Default.validation_queue_size )
460
      (optional int)
270✔
461
  and direct_peers_raw =
462
    flag "--direct-peer" ~aliases:[ "direct-peer" ]
270✔
463
      ~doc:
464
        "/ip4/IPADDR/tcp/PORT/p2p/PEERID Peers to always send new messages \
465
         to/from. These peers should also have you configured as a direct \
466
         peer, the relationship is intended to be symmetric"
467
      (listed string)
270✔
468
  and isolate =
469
    flag "--isolate-network" ~aliases:[ "isolate-network" ]
270✔
470
      ~doc:
471
        "true|false Only allow connections to the peers passed on the command \
472
         line or configured through GraphQL. (default: false)"
473
      (optional bool)
270✔
474
  and libp2p_peers_raw =
475
    flag "--peer" ~aliases:[ "peer" ]
270✔
476
      ~doc:
477
        "/ip4/IPADDR/tcp/PORT/p2p/PEERID initial \"bootstrap\" peers for \
478
         discovery"
479
      (listed string)
270✔
480
  and libp2p_peer_list_file =
481
    flag "--peer-list-file" ~aliases:[ "peer-list-file" ]
270✔
482
      ~doc:
483
        "PATH path to a file containing \"bootstrap\" peers for discovery, one \
484
         multiaddress per line"
485
      (optional string)
270✔
486
  and seed_peer_list_url =
487
    flag "--peer-list-url" ~aliases:[ "peer-list-url" ]
270✔
488
      ~doc:"URL URL of seed peer list file. Will be polled periodically."
489
      (optional string)
270✔
490
  and proposed_protocol_version =
491
    flag "--proposed-protocol-version"
270✔
492
      ~aliases:[ "proposed-protocol-version" ]
493
      (optional string)
270✔
494
      ~doc:"NN.NN.NN Proposed protocol version to signal other nodes"
495
  and config_files =
496
    flag "--config-file" ~aliases:[ "config-file" ]
270✔
497
      ~doc:
498
        "PATH path to a configuration file (overrides MINA_CONFIG_FILE, \
499
         default: <config_dir>/daemon.json). Pass multiple times to override \
500
         fields from earlier config files"
501
      (listed string)
270✔
502
  and _may_generate =
503
    flag "--generate-genesis-proof"
270✔
504
      ~aliases:[ "generate-genesis-proof" ]
505
      ~doc:"true|false Deprecated. Passing this flag has no effect"
506
      (optional bool)
270✔
507
  and disable_node_status =
508
    flag "--disable-node-status" ~aliases:[ "disable-node-status" ] no_arg
270✔
509
      ~doc:"Disable reporting node status to other nodes (default: enabled)"
510
  and cli_proof_level =
511
    flag "--proof-level" ~aliases:[ "proof-level" ]
270✔
512
      (optional (Arg_type.create Genesis_constants.Proof_level.of_string))
270✔
513
      ~doc:
514
        "full|check|none Internal, for testing. Start or connect to a network \
515
         with full proving (full), snark-testing with dummy proofs (check), or \
516
         dummy proofs (none)"
517
  and plugins = plugin_flag
518
  and precomputed_blocks_path =
519
    flag "--precomputed-blocks-file"
270✔
520
      ~aliases:[ "precomputed-blocks-file" ]
521
      (optional string)
270✔
522
      ~doc:"PATH Path to write precomputed blocks to, for replay or archiving"
523
  and log_precomputed_blocks =
524
    flag "--log-precomputed-blocks"
270✔
525
      ~aliases:[ "log-precomputed-blocks" ]
526
      (optional_with_default false bool)
270✔
527
      ~doc:"true|false Include precomputed blocks in the log (default: false)"
528
  and start_filtered_logs =
529
    flag "--start-filtered-logs" (listed string)
270✔
530
      ~doc:
531
        "LOG-FILTER Include filtered logs for the given filter. May be passed \
532
         multiple times"
533
  and block_reward_threshold =
534
    flag "--minimum-block-reward" ~aliases:[ "minimum-block-reward" ]
270✔
535
      ~doc:
536
        "AMOUNT Minimum reward a block produced by the node should have. Empty \
537
         blocks are created if the rewards are lower than the specified \
538
         threshold (default: No threshold, transactions and coinbase will be \
539
         included as long as the required snark work is available and can be \
540
         paid for)"
541
      (optional txn_amount)
270✔
542
  and stop_time =
543
    flag "--stop-time" ~aliases:[ "stop-time" ] (optional int)
270✔
544
      ~doc:
545
        (sprintf
270✔
546
           "UPTIME in hours after which the daemon stops itself (only if there \
547
            were no slots won within an hour after the stop time) (Default: \
548
            %d)"
549
           Cli_lib.Default.stop_time )
550
  and stop_time_interval =
551
    flag "--stop-time-interval" ~aliases:[ "stop-time-interval" ] (optional int)
270✔
552
      ~doc:
553
        (sprintf
270✔
554
           "UPTIME An upper bound (inclusive) on the random number of hours \
555
            added to the stop-time. Setting it to zero disables this \
556
            randomness. (Default: %d)"
557
           Cli_lib.Default.stop_time_interval )
558
  and upload_blocks_to_gcloud =
559
    flag "--upload-blocks-to-gcloud"
270✔
560
      ~aliases:[ "upload-blocks-to-gcloud" ]
561
      (optional_with_default false bool)
270✔
562
      ~doc:
563
        "true|false upload blocks to gcloud storage. Requires the environment \
564
         variables GCLOUD_KEYFILE, NETWORK_NAME, and \
565
         GCLOUD_BLOCK_UPLOAD_BUCKET"
566
  and all_peers_seen_metric =
567
    flag "--all-peers-seen-metric"
270✔
568
      ~aliases:[ "all-peers-seen-metric" ]
569
      (optional_with_default false bool)
270✔
570
      ~doc:
571
        "true|false whether to track the set of all peers ever seen for the \
572
         all_peers metric (default: false)"
573
  and node_status_url =
574
    flag "--node-status-url" ~aliases:[ "node-status-url" ] (optional string)
270✔
575
      ~doc:"URL of the node status collection service"
576
  and node_error_url =
577
    flag "--node-error-url" ~aliases:[ "node-error-url" ] (optional string)
270✔
578
      ~doc:"URL of the node error collection service"
579
  and simplified_node_stats =
580
    flag "--simplified-node-stats"
270✔
581
      ~aliases:[ "simplified-node-stats" ]
582
      (optional_with_default true bool)
270✔
583
      ~doc:"whether to report simplified node stats (default: true)"
584
  and contact_info =
585
    flag "--contact-info" ~aliases:[ "contact-info" ] (optional string)
270✔
586
      ~doc:
587
        "contact info used in node error report service (it could be either \
588
         email address or discord username), it should be less than 200 \
589
         characters"
590
    |> Command.Param.map ~f:(fun opt ->
270✔
591
           Option.value_map opt ~default:None ~f:(fun s ->
×
592
               if String.length s < 200 then Some s
×
593
               else
594
                 Mina_stdlib.Mina_user_error.raisef
×
595
                   "The length of contact info exceeds 200 characters:\n %s" s ) )
596
  and uptime_url_string =
597
    flag "--uptime-url" ~aliases:[ "uptime-url" ] (optional string)
270✔
598
      ~doc:"URL URL of the uptime service of the Mina delegation program"
599
  and uptime_submitter_key =
600
    flag "--uptime-submitter-key" ~aliases:[ "uptime-submitter-key" ]
270✔
601
      ~doc:
602
        "KEYFILE Private key file for the uptime submitter. You cannot provide \
603
         both `uptime-submitter-key` and `uptime-submitter-pubkey`."
604
      (optional string)
270✔
605
  and uptime_submitter_pubkey =
606
    flag "--uptime-submitter-pubkey"
270✔
607
      ~aliases:[ "uptime-submitter-pubkey" ]
608
      (optional string)
270✔
609
      ~doc:
610
        "PUBLICKEY Public key of the submitter to the Mina delegation program, \
611
         for the associated private key that is being tracked by this daemon. \
612
         You cannot provide both `uptime-submitter-key` and \
613
         `uptime-submitter-pubkey`."
614
  and uptime_send_node_commit =
615
    flag "--uptime-send-node-commit-sha"
270✔
616
      ~aliases:[ "uptime-send-node-commit-sha" ]
617
      ~doc:
618
        "true|false Whether to send the commit SHA used to build the node to \
619
         the uptime service. (default: false)"
620
      no_arg
621
  and hardfork_handling =
622
    (* The two hard fork modes are migrate-exit (the "auto" hard fork mode) and
623
       keep-running (the "legacy" hard fork mode). See
624
       https://github.com/MinaProtocol/MIPs/pull/32. This option currently only
625
       controls the ledger sync feature (keeping migrated versions of the root
626
       and epoch ledger databases alongside the stable ones). TODO: the code
627
       will eventually need to be updated so this option also causes the daemon
628
       to generate and save its own hard fork config at the [slot_chain_end] and
629
       then shut down. *)
630
    flag "--hardfork-handling" ~aliases:[ "hardfork-handling" ]
270✔
631
      ~doc:
632
        "keep-running|migrate-exit Internal flag, controlling how the daemon \
633
         handles an upcoming hard fork. Exposed for testing purposes. \
634
         Currently it only causes the daemon to maintain migrated versions of \
635
         the root and epoch ledger databases alongside the stable databases. \
636
         (default: keep-running). "
637
      (optional_with_default Hardfork_handling.Keep_running
270✔
638
         Hardfork_handling.arg )
639
  in
640
  let to_pubsub_topic_mode_option =
×
641
    let open Gossip_net.Libp2p in
642
    function
643
    | `String "ro" ->
×
644
        Some RO
645
    | `String "rw" ->
×
646
        Some RW
647
    | `String "none" ->
×
648
        Some N
649
    | `Null ->
×
650
        None
651
    | _ ->
×
652
        raise (Error.to_exn (Error.of_string "Invalid pubsub topic mode"))
×
653
  in
654
  fun () ->
655
    O1trace.thread "mina" (fun () ->
×
656
        let open Deferred.Let_syntax in
×
657
        let conf_dir = Mina_lib.Conf_dir.compute_conf_dir conf_dir in
658
        let%bind () = Mina_stdlib_unix.File_system.create_dir conf_dir in
×
659
        let () =
×
660
          if is_background then (
×
661
            Core.printf "Starting background mina daemon. (Log Dir: %s)\n%!"
662
              conf_dir ;
663
            Daemon.daemonize ~allow_threads_to_have_been_created:true
×
664
              ~redirect_stdout:`Dev_null ?cd:working_dir
665
              ~redirect_stderr:`Dev_null () )
666
          else Option.iter working_dir ~f:Caml.Sys.chdir
×
667
        in
668
        Stdout_log.setup log_json log_level ;
669
        (* 512MB logrotate max size = 1GB max filesystem usage *)
670
        let logrotate_max_size = 1024 * 1024 * 10 in
×
671
        Logger.Consumer_registry.register ~commit_id:Mina_version.commit_id
672
          ~id:Logger.Logger_id.mina
673
          ~processor:(Logger.Processor.raw ~log_level:file_log_level ())
×
674
          ~transport:
675
            (Logger_file_system.dumb_logrotate ~directory:conf_dir
676
               ~log_filename:"mina.log" ~max_size:logrotate_max_size
677
               ~num_rotate:file_log_rotations )
678
          () ;
679
        let best_tip_diff_log_size = 1024 * 1024 * 5 in
×
680
        Logger.Consumer_registry.register ~commit_id:Mina_version.commit_id
681
          ~id:Logger.Logger_id.best_tip_diff
682
          ~processor:(Logger.Processor.raw ())
×
683
          ~transport:
684
            (Logger_file_system.dumb_logrotate ~directory:conf_dir
685
               ~log_filename:"mina-best-tip.log"
686
               ~max_size:best_tip_diff_log_size ~num_rotate:1 )
687
          () ;
688
        let rejected_blocks_log_size = 1024 * 1024 * 5 in
×
689
        Logger.Consumer_registry.register ~commit_id:Mina_version.commit_id
690
          ~id:Logger.Logger_id.rejected_blocks
691
          ~processor:(Logger.Processor.raw ())
×
692
          ~transport:
693
            (Logger_file_system.dumb_logrotate ~directory:conf_dir
694
               ~log_filename:"mina-rejected-blocks.log"
695
               ~max_size:rejected_blocks_log_size ~num_rotate:50 )
696
          () ;
697
        Logger.Consumer_registry.register ~commit_id:Mina_version.commit_id
×
698
          ~id:Logger.Logger_id.oversized_logs
699
          ~processor:(Logger.Processor.raw ())
×
700
          ~transport:
701
            (Logger_file_system.dumb_logrotate ~directory:conf_dir
702
               ~log_filename:"mina-oversized-logs.log"
703
               ~max_size:logrotate_max_size ~num_rotate:20 )
704
          () ;
705
        (* Consumer for `[%log internal]` logging used for internal tracing *)
706
        Itn_logger.set_message_postprocessor
×
707
          Internal_tracing.For_itn_logger.post_process_message ;
708
        Logger.Consumer_registry.register ~commit_id:Mina_version.commit_id
×
709
          ~id:Logger.Logger_id.mina
710
          ~processor:Internal_tracing.For_logger.processor
711
          ~transport:
712
            (Internal_tracing.For_logger.json_lines_rotate_transport
×
713
               ~directory:(conf_dir ^ "/internal-tracing")
714
               () )
715
          () ;
716
        let version_metadata = [ ("commit", `String Mina_version.commit_id) ] in
×
717
        [%log info] "Mina daemon is booting up; built with commit $commit"
×
718
          ~metadata:version_metadata ;
719
        let%bind () =
720
          Mina_lib.Conf_dir.check_and_set_lockfile ~logger conf_dir
×
721
        in
722
        [%log info] "Booting may take several seconds, please wait" ;
×
723
        let wallets_disk_location = conf_dir ^/ "wallets" in
×
724
        let%bind wallets =
725
          (* Load wallets early, to give user errors before expensive
726
             initialization starts.
727
          *)
728
          Secrets.Wallets.load ~logger ~disk_location:wallets_disk_location
729
        in
730
        let%bind libp2p_keypair =
731
          let libp2p_keypair_old_format =
732
            Option.bind libp2p_keypair ~f:(fun libp2p_keypair ->
733
                match Mina_net2.Keypair.of_string libp2p_keypair with
×
734
                | Ok kp ->
×
735
                    Some kp
736
                | Error _ ->
×
737
                    if String.contains libp2p_keypair ',' then
738
                      [%log warn]
×
739
                        "I think -libp2p-keypair is in the old format, but I \
740
                         failed to parse it! Using it as a path..." ;
741
                    None )
×
742
          in
743
          match libp2p_keypair_old_format with
×
744
          | Some kp ->
×
745
              return (Some kp)
×
746
          | None -> (
×
747
              match libp2p_keypair with
748
              | None ->
×
749
                  return None
×
750
              | Some s ->
×
751
                  Secrets.Libp2p_keypair.Terminal_stdin.read_exn
752
                    ~should_prompt_user:false ~which:"libp2p keypair" s
753
                  |> Deferred.map ~f:Option.some )
×
754
        in
755
        let%bind () =
756
          let version_filename = conf_dir ^/ "mina.version" in
757
          let make_version () =
×
758
            let%map () =
759
              (*Delete any trace files if version changes. TODO: Implement rotate logic similar to log files*)
760
              Mina_stdlib_unix.File_system.remove_dir (conf_dir ^/ "trace")
×
761
            in
762
            Yojson.Safe.to_file version_filename (`Assoc version_metadata)
×
763
          in
764
          match
765
            Or_error.try_with_join (fun () ->
766
                match Yojson.Safe.from_file version_filename with
×
767
                | `Assoc list -> (
×
768
                    match String.Map.(find (of_alist_exn list) "commit") with
×
769
                    | Some (`String commit) ->
×
770
                        Ok commit
771
                    | _ ->
×
772
                        Or_error.errorf "commit not found in version file %s"
773
                          version_filename )
774
                | _ ->
×
775
                    Or_error.errorf "Unexpected value in %s" version_filename )
776
          with
777
          | Ok c ->
×
778
              if String.equal c Mina_version.commit_id then return ()
×
779
              else (
×
780
                [%log warn]
×
781
                  "Different version of Mina detected in config directory \
782
                   $config_directory, removing existing configuration"
783
                  ~metadata:[ ("config_directory", `String conf_dir) ] ;
784
                make_version () )
×
785
          | Error e ->
×
786
              [%log debug]
×
787
                "Error reading $file: $error. Cleaning up the config directory \
788
                 $config_directory"
789
                ~metadata:
790
                  [ ("error", `String (Error.to_string_mach e))
×
791
                  ; ("config_directory", `String conf_dir)
792
                  ; ("file", `String version_filename)
793
                  ] ;
794
              make_version ()
×
795
        in
796
        Parallel.init_master () ;
×
797
        let monitor = Async.Monitor.create ~name:"coda" () in
×
798
        let time_controller = Block_time.Controller.basic ~logger in
×
799
        let pids = Child_processes.Termination.create_pid_table () in
800
        let mina_initialization_deferred () =
×
801
          let config_file_installed =
×
802
            (* Search for config files installed as part of a deb/brew package.
803
               These files are commit-dependent, to ensure that we don't clobber
804
               configuration for dev builds or use incompatible configs.
805
            *)
806
            let config_file_installed =
807
              let json = "config_" ^ Mina_version.commit_id_short ^ ".json" in
808
              List.fold_until ~init:None
×
809
                (Cache_dir.possible_paths json)
×
810
                ~f:(fun _acc f ->
811
                  match Core.Sys.file_exists f with
×
812
                  | `Yes ->
×
813
                      Stop (Some f)
814
                  | _ ->
×
815
                      Continue None )
816
                ~finish:Fn.id
817
            in
818
            match config_file_installed with
819
            | Some config_file ->
×
820
                Some (config_file, `Must_exist)
821
            | None ->
×
822
                None
823
          in
824
          let config_file_configdir =
825
            (conf_dir ^/ "daemon.json", `May_be_missing)
×
826
          in
827
          let config_file_envvar =
828
            match Sys.getenv "MINA_CONFIG_FILE" with
829
            | Some config_file ->
×
830
                Some (config_file, `Must_exist)
831
            | None ->
×
832
                None
833
          in
834
          let config_files =
835
            Option.to_list config_file_installed
×
836
            @ (config_file_configdir :: Option.to_list config_file_envvar)
×
837
            @ List.map config_files ~f:(fun config_file ->
×
838
                  (config_file, `Must_exist) )
×
839
          in
840
          let genesis_constants =
841
            Genesis_constants.Compiled.genesis_constants
842
          in
843
          let constraint_constants =
844
            Genesis_constants.Compiled.constraint_constants
845
          in
846
          let compile_config = Mina_compile_config.Compiled.t in
847
          let ledger_backing_type =
848
            Mina_lib.Config.ledger_backing ~hardfork_handling
849
          in
850
          let%bind ( precomputed_values
851
                   , config_jsons
852
                   , config
853
                   , chain_state_locations ) =
854
            load_config_files ~logger ~conf_dir ~genesis_dir
×
855
              ~proof_level:Genesis_constants.Compiled.proof_level config_files
856
              ~genesis_constants ~constraint_constants ~cli_proof_level
857
              ~genesis_backing_type:ledger_backing_type
858
          in
859
          constraint_constants.block_window_duration_ms |> Float.of_int
×
860
          |> Time.Span.of_ms |> Mina_metrics.initialize_all ;
×
861

862
          let rev_daemon_configs =
×
863
            List.rev_filter_map config_jsons
864
              ~f:(fun (config_file, config_json) ->
865
                Option.map
×
866
                  YJ.Util.(
867
                    to_option Fn.id (YJ.Util.member "daemon" config_json))
×
868
                  ~f:(fun daemon_config -> (config_file, daemon_config)) )
×
869
          in
870
          let maybe_from_config (type a) (f : YJ.t -> a option)
×
871
              (keyname : string) (actual_value : a option) : a option =
872
            let open Option.Let_syntax in
×
873
            let open YJ.Util in
874
            match actual_value with
875
            | Some v ->
×
876
                Some v
877
            | None ->
×
878
                (* Load value from the latest config file that both
879
                   * has the key we are looking for, and
880
                   * has the key in a format that [f] can parse.
881
                *)
882
                let%map config_file, data =
883
                  List.find_map rev_daemon_configs
×
884
                    ~f:(fun (config_file, daemon_config) ->
885
                      let%bind json_val =
886
                        to_option Fn.id (member keyname daemon_config)
×
887
                      in
888
                      let%map data = f json_val in
×
889
                      (config_file, data) )
×
890
                in
891
                [%log debug] "Key $key being used from config file $config_file"
×
892
                  ~metadata:
893
                    [ ("key", `String keyname)
894
                    ; ("config_file", `String config_file)
895
                    ] ;
896
                data
×
897
          in
898
          let or_from_config map keyname actual_value ~default =
899
            match maybe_from_config map keyname actual_value with
×
900
            | Some x ->
×
901
                x
902
            | None ->
×
903
                [%log trace]
×
904
                  "Key '$key' not found in the config file, using default"
905
                  ~metadata:[ ("key", `String keyname) ] ;
906
                default
×
907
          in
908
          let get_port { Flag.Types.value; default; name } =
909
            or_from_config YJ.Util.to_int_option name ~default value
×
910
          in
911
          let libp2p_port = get_port libp2p_port in
912
          let rest_server_port = get_port rest_server_port in
×
913
          let limited_graphql_port =
×
914
            let ({ value; name } : int option Flag.Types.with_name) =
915
              limited_graphql_port
916
            in
917
            maybe_from_config YJ.Util.to_int_option name value
×
918
          in
919
          let client_port = get_port client_port in
920
          let snark_work_fee_flag =
×
921
            let json_to_currency_fee_option json =
922
              YJ.Util.to_int_option json
×
923
              |> Option.map ~f:Currency.Fee.of_nanomina_int_exn
×
924
            in
925
            or_from_config json_to_currency_fee_option "snark-worker-fee"
×
926
              ~default:compile_config.default_snark_worker_fee snark_work_fee
927
          in
928
          let node_status_url =
929
            maybe_from_config YJ.Util.to_string_option "node-status-url"
930
              node_status_url
931
          in
932
          (* FIXME #4095: pass this through to Gossip_net.Libp2p *)
933
          let _max_concurrent_connections =
×
934
            (*if
935
                 or_from_config YJ.Util.to_bool_option "max-concurrent-connections"
936
                   ~default:true limit_connections
937
               then Some 40
938
               else *)
939
            None
940
          in
941
          let work_selection_method =
942
            or_from_config
943
              (Fn.compose Option.return
×
944
                 (Fn.compose work_selection_method_val YJ.Util.to_string) )
×
945
              "work-selection"
946
              ~default:Cli_lib.Arg_type.Work_selection_method.Random
947
              work_selection_method_flag
948
          in
949
          let work_reassignment_wait =
×
950
            or_from_config YJ.Util.to_int_option "work-reassignment-wait"
951
              ~default:Cli_lib.Default.work_reassignment_wait
952
              work_reassignment_wait
953
          in
954
          let log_received_snark_pool_diff =
×
955
            or_from_config YJ.Util.to_bool_option "log-snark-work-gossip"
956
              ~default:false log_received_snark_pool_diff
957
          in
958
          let log_transaction_pool_diff =
×
959
            or_from_config YJ.Util.to_bool_option "log-txn-pool-gossip"
960
              ~default:false log_transaction_pool_diff
961
          in
962
          let log_block_creation =
×
963
            or_from_config YJ.Util.to_bool_option "log-block-creation"
964
              ~default:true log_block_creation
965
          in
966
          let log_gossip_heard =
×
967
            { Mina_networking.Config.snark_pool_diff =
968
                log_received_snark_pool_diff
969
            ; transaction_pool_diff = log_transaction_pool_diff
970
            ; new_state = true
971
            }
972
          in
973
          let json_to_publickey_compressed_option which json =
974
            YJ.Util.to_string_option json
×
975
            |> Option.bind ~f:(fun pk_str ->
×
976
                   match Public_key.Compressed.of_base58_check pk_str with
×
977
                   | Ok key -> (
×
978
                       match Public_key.decompress key with
979
                       | None ->
×
980
                           Mina_stdlib.Mina_user_error.raisef
981
                             ~where:"decompressing a public key"
982
                             "The %s public key %s could not be decompressed."
983
                             which pk_str
984
                       | Some _ ->
×
985
                           Some key )
986
                   | Error _e ->
×
987
                       Mina_stdlib.Mina_user_error.raisef
988
                         ~where:"decoding a public key"
989
                         "The %s public key %s could not be decoded." which
990
                         pk_str )
991
          in
992
          let run_snark_worker_flag =
993
            maybe_from_config
994
              (json_to_publickey_compressed_option "snark worker")
×
995
              "run-snark-worker" run_snark_worker_flag
996
          in
997
          let run_snark_coordinator_flag =
×
998
            maybe_from_config
999
              (json_to_publickey_compressed_option "snark coordinator")
×
1000
              "run-snark-coordinator" run_snark_coordinator_flag
1001
          in
1002
          let snark_worker_parallelism_flag =
×
1003
            maybe_from_config YJ.Util.to_int_option "snark-worker-parallelism"
1004
              snark_worker_parallelism_flag
1005
          in
1006
          let coinbase_receiver_flag =
×
1007
            maybe_from_config
1008
              (json_to_publickey_compressed_option "coinbase receiver")
×
1009
              "coinbase-receiver" coinbase_receiver_flag
1010
          in
1011
          let%bind external_ip =
1012
            match external_ip_opt with
1013
            | None ->
×
1014
                Find_ip.find ~logger
1015
            | Some ip ->
×
1016
                return @@ Unix.Inet_addr.of_string ip
×
1017
          in
1018
          let bind_ip =
×
1019
            Option.value bind_ip_opt ~default:"0.0.0.0"
1020
            |> Unix.Inet_addr.of_string
×
1021
          in
1022
          let addrs_and_ports : Node_addrs_and_ports.t =
×
1023
            { external_ip; bind_ip; peer = None; client_port; libp2p_port }
1024
          in
1025
          let block_production_key =
1026
            maybe_from_config YJ.Util.to_string_option "block-producer-key"
1027
              block_production_key
1028
          in
1029
          let block_production_pubkey =
×
1030
            maybe_from_config
1031
              (json_to_publickey_compressed_option "block producer")
×
1032
              "block-producer-pubkey" block_production_pubkey
1033
          in
1034
          let block_production_password =
×
1035
            maybe_from_config YJ.Util.to_string_option "block-producer-password"
1036
              block_production_password
1037
          in
1038
          Option.iter
×
1039
            ~f:(fun password ->
1040
              match Sys.getenv Secrets.Keypair.env with
×
1041
              | Some env_pass when not (String.equal env_pass password) ->
×
1042
                  [%log warn]
×
1043
                    "$envkey environment variable doesn't match value provided \
1044
                     on command-line or daemon.json. Using value from $envkey"
1045
                    ~metadata:[ ("envkey", `String Secrets.Keypair.env) ]
1046
              | _ ->
×
1047
                  Unix.putenv ~key:Secrets.Keypair.env ~data:password )
1048
            block_production_password ;
1049
          let%bind block_production_keypair =
1050
            match
1051
              ( block_production_key
1052
              , block_production_pubkey
1053
              , Sys.getenv "MINA_BP_PRIVKEY" )
×
1054
            with
1055
            | Some _, Some _, _ ->
×
1056
                Mina_stdlib.Mina_user_error.raise
×
1057
                  "You cannot provide both `block-producer-key` and \
1058
                   `block_production_pubkey`"
1059
            | None, Some _, Some _ ->
×
1060
                Mina_stdlib.Mina_user_error.raise
×
1061
                  "You cannot provide both `MINA_BP_PRIVKEY` and \
1062
                   `block_production_pubkey`"
1063
            | None, None, None ->
×
1064
                Deferred.return None
×
1065
            | None, None, Some base58_privkey ->
×
1066
                let kp =
1067
                  Private_key.of_base58_check_exn base58_privkey
1068
                  |> Keypair.of_private_key_exn
×
1069
                in
1070
                Deferred.return (Some kp)
×
1071
            (* CLI argument takes precedence over env variable *)
1072
            | Some sk_file, None, (Some _ | None) ->
×
1073
                [%log warn]
×
1074
                  "`block-producer-key` is deprecated. Please set \
1075
                   `MINA_BP_PRIVKEY` environment variable instead." ;
1076
                let%map kp =
1077
                  Secrets.Keypair.Terminal_stdin.read_exn
×
1078
                    ~should_prompt_user:false ~which:"block producer keypair"
1079
                    sk_file
1080
                in
1081
                Some kp
×
1082
            | None, Some tracked_pubkey, None ->
×
1083
                let%map kp =
1084
                  Secrets.Wallets.get_tracked_keypair ~logger
×
1085
                    ~which:"block producer keypair"
1086
                    ~read_from_env_exn:
1087
                      (Secrets.Keypair.Terminal_stdin.read_exn
1088
                         ~should_prompt_user:false ~should_reask:false )
1089
                    ~conf_dir tracked_pubkey
1090
                in
1091
                Some kp
×
1092
          in
1093
          let%bind client_trustlist =
1094
            Reader.load_sexp
×
1095
              (conf_dir ^/ "client_trustlist")
×
1096
              [%of_sexp: Unix.Cidr.t list]
1097
            >>| Or_error.ok
×
1098
          in
1099
          let client_trustlist =
×
1100
            let mina_client_trustlist = "MINA_CLIENT_TRUSTLIST" in
1101
            let cidrs_of_env_str env_str env_var =
1102
              let cidrs =
×
1103
                String.split ~on:',' env_str
1104
                |> List.filter_map ~f:(fun str ->
×
1105
                       try Some (Unix.Cidr.of_string str)
×
1106
                       with _ ->
×
1107
                         [%log warn] "Could not parse address $address in %s"
×
1108
                           env_var
1109
                           ~metadata:[ ("address", `String str) ] ;
1110
                         None )
×
1111
              in
1112
              Some
×
1113
                (List.append cidrs (Option.value ~default:[] client_trustlist))
×
1114
            in
1115
            match Unix.getenv mina_client_trustlist with
1116
            | Some env_str ->
×
1117
                cidrs_of_env_str env_str mina_client_trustlist
×
1118
            | None ->
×
1119
                client_trustlist
1120
          in
1121
          let get_monitor_infos monitor =
1122
            let rec get_monitors accum monitor =
×
1123
              match Async_kernel.Monitor.parent monitor with
×
1124
              | None ->
×
1125
                  List.rev accum
1126
              | Some parent ->
×
1127
                  get_monitors (parent :: accum) parent
1128
            in
1129
            let monitors = get_monitors [ monitor ] monitor in
1130
            List.map monitors ~f:(fun monitor ->
×
1131
                match Async_kernel.Monitor.sexp_of_t monitor with
×
1132
                | Sexp.List sexps ->
×
1133
                    `List (List.map ~f:Error_json.sexp_record_to_yojson sexps)
×
1134
                | Sexp.Atom _ ->
×
1135
                    failwith "Expected a sexp list" )
1136
          in
1137
          let o1trace context =
1138
            Execution_context.find_local context O1trace.local_storage_id
×
1139
            |> Option.value ~default:[]
×
1140
            |> List.map ~f:(fun x -> `String x)
×
1141
          in
1142
          Stream.iter
1143
            (Async_kernel.Async_kernel_scheduler.long_cycles_with_context
1144
               ~at_least:(sec 0.5 |> Time_ns.Span.of_span_float_round_nearest) )
×
1145
            ~f:(fun (span, context) ->
1146
              let secs = Time_ns.Span.to_sec span in
×
1147
              let monitor_infos = get_monitor_infos context.monitor in
×
1148
              let o1trace = o1trace context in
×
1149
              [%log internal] "Long_async_cycle"
×
1150
                ~metadata:
1151
                  [ ("duration", `Float secs); ("trace", `List o1trace) ] ;
1152
              [%log debug]
×
1153
                ~metadata:
1154
                  [ ("long_async_cycle", `Float secs)
1155
                  ; ("monitors", `List monitor_infos)
1156
                  ; ("o1trace", `List o1trace)
1157
                  ]
1158
                "Long async cycle, $long_async_cycle seconds, $monitors, \
1159
                 $o1trace" ;
1160
              Mina_metrics.(
×
1161
                Runtime.Long_async_histogram.observe Runtime.long_async_cycle
1162
                  secs) ) ;
1163
          Stream.iter Async_kernel.Async_kernel_scheduler.long_jobs_with_context
×
1164
            ~f:(fun (context, span) ->
1165
              let secs = Time_ns.Span.to_sec span in
×
1166
              let monitor_infos = get_monitor_infos context.monitor in
×
1167
              let o1trace = o1trace context in
×
1168
              [%log internal] "Long_async_job"
×
1169
                ~metadata:
1170
                  [ ("duration", `Float secs); ("trace", `List o1trace) ] ;
1171
              [%log debug]
×
1172
                ~metadata:
1173
                  [ ("long_async_job", `Float secs)
1174
                  ; ("monitors", `List monitor_infos)
1175
                  ; ("o1trace", `List o1trace)
1176
                  ; ( "most_recent_2_backtrace"
1177
                    , `String
1178
                        (String.concat ~sep:"␤"
×
1179
                           (List.map ~f:Backtrace.to_string
×
1180
                              (List.take
×
1181
                                 (Execution_context.backtrace_history context)
×
1182
                                 2 ) ) ) )
1183
                  ]
1184
                "Long async job, $long_async_job seconds, $monitors, $o1trace" ;
1185
              Mina_metrics.(
×
1186
                Runtime.Long_job_histogram.observe Runtime.long_async_job secs) ) ;
1187
          let trace_database_initialization typ location =
×
1188
            (* can't use %log ppx here, because we're using the passed-in location *)
1189
            Logger.trace logger ~module_:__MODULE__ "Creating %s at %s"
×
1190
              ~location typ
1191
          in
1192
          let trust_dir = chain_state_locations.trust in
1193
          let%bind () = Async.Unix.mkdir ~p:() trust_dir in
×
1194
          let%bind trust_system = Trust_system.create trust_dir in
×
1195
          trace_database_initialization "trust_system" __LOC__ trust_dir ;
×
1196
          let genesis_state_hash =
×
1197
            (Precomputed_values.genesis_state_hashes precomputed_values)
×
1198
              .state_hash
1199
          in
1200
          let genesis_ledger_hash =
1201
            Precomputed_values.genesis_ledger precomputed_values
1202
            |> Lazy.force |> Mina_ledger.Ledger.merkle_root
×
1203
          in
1204
          let block_production_keypairs =
×
1205
            block_production_keypair
1206
            |> Option.map ~f:(fun kp ->
1207
                   (kp, Public_key.compress kp.Keypair.public_key) )
×
1208
            |> Option.to_list |> Keypair.And_compressed_pk.Set.of_list
×
1209
          in
1210
          let epoch_ledger_location =
×
1211
            chain_state_locations.epoch_ledger ^/ "epoch_ledger"
1212
          in
1213
          let module Context = struct
×
1214
            let logger = logger
1215

1216
            let constraint_constants = precomputed_values.constraint_constants
1217

1218
            let consensus_constants = precomputed_values.consensus_constants
1219
          end in
1220
          let consensus_local_state =
1221
            Consensus.Data.Local_state.create
1222
              ~context:(module Context)
1223
              ~genesis_ledger:precomputed_values.genesis_ledger
1224
              ~genesis_epoch_data:precomputed_values.genesis_epoch_data
1225
              ~epoch_ledger_location
1226
              ( Option.map block_production_keypair ~f:(fun keypair ->
1227
                    let open Keypair in
×
1228
                    Public_key.compress keypair.public_key )
1229
              |> Option.to_list |> Public_key.Compressed.Set.of_list )
×
1230
              ~genesis_state_hash:
1231
                precomputed_values.protocol_state_with_hashes.hash.state_hash
1232
              ~epoch_ledger_backing_type:ledger_backing_type
1233
          in
1234
          trace_database_initialization "epoch ledger" __LOC__
×
1235
            epoch_ledger_location ;
1236
          let%bind peer_list_file_contents_or_empty =
1237
            match libp2p_peer_list_file with
1238
            | None ->
×
1239
                return []
×
1240
            | Some file -> (
×
1241
                match%bind
1242
                  Monitor.try_with_or_error ~here:[%here] (fun () ->
×
1243
                      Reader.file_contents file )
×
1244
                with
1245
                | Ok contents ->
×
1246
                    return (Mina_net2.Multiaddr.of_file_contents contents)
×
1247
                | Error _ ->
×
1248
                    Mina_stdlib.Mina_user_error.raisef
1249
                      ~where:"reading libp2p peer address file"
1250
                      "The file %s could not be read.\n\n\
1251
                       It must be a newline-separated list of libp2p \
1252
                       multiaddrs (ex: /ip4/IPADDR/tcp/PORT/p2p/PEERID)"
1253
                      file )
1254
          in
1255
          List.iter libp2p_peers_raw ~f:(fun raw_peer ->
×
1256
              if not Mina_net2.Multiaddr.(valid_as_peer @@ of_string raw_peer)
×
1257
              then
1258
                Mina_stdlib.Mina_user_error.raisef
×
1259
                  ~where:"decoding peer as a multiaddress"
1260
                  "The given peer \"%s\" is not a valid multiaddress (ex: \
1261
                   /ip4/IPADDR/tcp/PORT/p2p/PEERID)"
1262
                  raw_peer ) ;
1263
          let initial_peers =
×
1264
            List.concat
1265
              [ List.map ~f:Mina_net2.Multiaddr.of_string libp2p_peers_raw
×
1266
              ; peer_list_file_contents_or_empty
1267
              ; List.map ~f:Mina_net2.Multiaddr.of_string
×
1268
                @@ or_from_config
×
1269
                     (Fn.compose Option.some
×
1270
                        (YJ.Util.convert_each YJ.Util.to_string) )
×
1271
                     "peers" None ~default:[]
1272
              ]
1273
          in
1274
          let direct_peers =
×
1275
            List.map ~f:Mina_net2.Multiaddr.of_string direct_peers_raw
1276
          in
1277
          let min_connections =
×
1278
            or_from_config YJ.Util.to_int_option "min-connections"
1279
              ~default:Cli_lib.Default.min_connections min_connections
1280
          in
1281
          let max_connections =
×
1282
            or_from_config YJ.Util.to_int_option "max-connections"
1283
              ~default:Cli_lib.Default.max_connections max_connections
1284
          in
1285
          let pubsub_v1 = Gossip_net.Libp2p.N in
×
1286
          (* TODO uncomment after introducing Bitswap-based block retrieval *)
1287
          (* let pubsub_v1 =
1288
               or_from_config to_pubsub_topic_mode_option "pubsub-v1"
1289
                 ~default:Cli_lib.Default.pubsub_v1 pubsub_v1
1290
             in *)
1291
          let pubsub_v0 =
1292
            or_from_config to_pubsub_topic_mode_option "pubsub-v0"
1293
              ~default:Cli_lib.Default.pubsub_v0 None
1294
          in
1295
          let validation_queue_size =
×
1296
            or_from_config YJ.Util.to_int_option "validation-queue-size"
1297
              ~default:Cli_lib.Default.validation_queue_size
1298
              validation_queue_size
1299
          in
1300
          let stop_time =
×
1301
            or_from_config YJ.Util.to_int_option "stop-time"
1302
              ~default:Cli_lib.Default.stop_time stop_time
1303
          in
1304
          let stop_time_interval =
×
1305
            or_from_config YJ.Util.to_int_option "stop-time-interval"
1306
              ~default:Cli_lib.Default.stop_time_interval stop_time_interval
1307
          in
1308
          if enable_tracing then Mina_tracing.start conf_dir |> don't_wait_for ;
×
1309
          let%bind () =
1310
            if enable_internal_tracing then
1311
              Internal_tracing.toggle ~commit_id:Mina_version.commit_id ~logger
×
1312
                `Enabled
1313
            else Deferred.unit
×
1314
          in
1315
          let seed_peer_list_url =
×
1316
            Option.value_map seed_peer_list_url ~f:Option.some
1317
              ~default:
1318
                (Option.bind config.daemon
×
1319
                   ~f:(fun { Runtime_config.Daemon.peer_list_url; _ } ->
1320
                     peer_list_url ) )
×
1321
          in
1322
          if is_seed then [%log info] "Starting node as a seed node"
×
1323
          else if demo_mode then [%log info] "Starting node in demo mode"
×
1324
          else if
×
1325
            List.is_empty initial_peers && Option.is_none seed_peer_list_url
×
1326
          then
1327
            Mina_stdlib.Mina_user_error.raise
×
1328
              {|No peers were given.
1329

1330
Pass one of -peer, -peer-list-file, -seed, -peer-list-url.|} ;
1331
          let chain_id =
1332
            let protocol_transaction_version =
1333
              Protocol_version.(transaction current)
×
1334
            in
1335
            let protocol_network_version =
1336
              Protocol_version.(transaction current)
×
1337
            in
1338
            chain_id ~genesis_state_hash
1339
              ~genesis_constants:precomputed_values.genesis_constants
1340
              ~constraint_system_digests:
1341
                (Lazy.force precomputed_values.constraint_system_digests)
×
1342
              ~protocol_transaction_version ~protocol_network_version
1343
          in
1344
          [%log info] "Daemon will use chain id %s" chain_id ;
×
1345
          [%log info] "Daemon running protocol version %s"
×
1346
            Protocol_version.(to_string current) ;
×
1347
          let gossip_net_params =
×
1348
            Gossip_net.Libp2p.Config.
1349
              { timeout = Time.Span.of_sec 3.
×
1350
              ; logger
1351
              ; mina_net_location = chain_state_locations.mina_net
1352
              ; chain_id
1353
              ; unsafe_no_trust_ip = false
1354
              ; seed_peer_list_url =
1355
                  Option.map seed_peer_list_url ~f:Uri.of_string
×
1356
              ; initial_peers
1357
              ; addrs_and_ports
1358
              ; metrics_port = libp2p_metrics_port
1359
              ; trust_system
1360
              ; flooding = Option.value ~default:false enable_flooding
×
1361
              ; direct_peers
1362
              ; peer_protection_ratio
1363
              ; peer_exchange = Option.value ~default:false peer_exchange
×
1364
              ; min_connections
1365
              ; max_connections
1366
              ; validation_queue_size
1367
              ; isolate = Option.value ~default:false isolate
×
1368
              ; keypair = libp2p_keypair
1369
              ; all_peers_seen_metric
1370
              ; known_private_ip_nets =
1371
                  Option.value ~default:[] client_trustlist
×
1372
              ; time_controller
1373
              ; pubsub_v1
1374
              ; pubsub_v0
1375
              }
1376
          in
1377
          let net_config =
1378
            { Mina_networking.Config.genesis_ledger_hash
1379
            ; log_gossip_heard
1380
            ; is_seed
1381
            ; creatable_gossip_net =
1382
                Mina_networking.Gossip_net.(
1383
                  Any.Creatable
1384
                    ((module Libp2p), Libp2p.create ~pids gossip_net_params))
×
1385
            }
1386
          in
1387
          let coinbase_receiver : Consensus.Coinbase_receiver.t =
1388
            Option.value_map coinbase_receiver_flag ~default:`Producer
×
1389
              ~f:(fun pk -> `Other pk)
×
1390
          in
1391
          let proposed_protocol_version_opt =
1392
            Mina_run.get_proposed_protocol_version_opt ~conf_dir ~logger
1393
              proposed_protocol_version
1394
          in
1395
          ( match
×
1396
              (uptime_url_string, uptime_submitter_key, uptime_submitter_pubkey)
1397
            with
1398
          | Some _, Some _, None | Some _, None, Some _ | None, None, None ->
×
1399
              ()
1400
          | _ ->
×
1401
              Mina_stdlib.Mina_user_error.raise
×
1402
                "Must provide both --uptime-url and exactly one of \
1403
                 --uptime-submitter-key or --uptime-submitter-pubkey" ) ;
1404
          let uptime_url =
1405
            Option.map uptime_url_string ~f:(fun s -> Uri.of_string s)
×
1406
          in
1407
          let uptime_submitter_opt =
×
1408
            Option.map uptime_submitter_pubkey ~f:(fun s ->
1409
                match Public_key.Compressed.of_base58_check s with
×
1410
                | Ok pk -> (
×
1411
                    match Public_key.decompress pk with
1412
                    | Some _ ->
×
1413
                        pk
1414
                    | None ->
×
1415
                        failwithf
1416
                          "Invalid public key %s for uptime submitter (could \
1417
                           not decompress)"
1418
                          s () )
1419
                | Error err ->
×
1420
                    Mina_stdlib.Mina_user_error.raisef
1421
                      "Invalid public key %s for uptime submitter, %s" s
1422
                      (Error.to_string_hum err) () )
×
1423
          in
1424
          let%bind uptime_submitter_keypair =
1425
            match (uptime_submitter_key, uptime_submitter_opt) with
1426
            | None, None ->
×
1427
                return None
×
1428
            | None, Some pk ->
×
1429
                let%map kp =
1430
                  Secrets.Wallets.get_tracked_keypair ~logger
×
1431
                    ~which:"uptime submitter keypair"
1432
                    ~read_from_env_exn:
1433
                      (Secrets.Uptime_keypair.Terminal_stdin.read_exn
1434
                         ~should_prompt_user:false ~should_reask:false )
1435
                    ~conf_dir pk
1436
                in
1437
                Some kp
×
1438
            | Some sk_file, None ->
×
1439
                let%map kp =
1440
                  Secrets.Uptime_keypair.Terminal_stdin.read_exn
×
1441
                    ~should_prompt_user:false ~should_reask:false
1442
                    ~which:"uptime submitter keypair" sk_file
1443
                in
1444
                Some kp
×
1445
            | _ ->
×
1446
                (* unreachable, because of earlier check *)
1447
                failwith
1448
                  "Cannot provide both uptime submitter public key and uptime \
1449
                   submitter keyfile"
1450
          in
1451
          if itn_features then
×
1452
            (* set queue bound directly in Itn_logger
1453
               adding bound to Mina_lib config introduces cycle
1454
            *)
1455
            Option.iter itn_max_logs ~f:Itn_logger.set_queue_bound ;
×
1456
          let start_time = Time.now () in
×
1457
          let%map mina =
1458
            Mina_lib.create ~commit_id:Mina_version.commit_id ~wallets
×
1459
              (Mina_lib.Config.make ~logger ~pids ~trust_system ~conf_dir
×
1460
                 ~file_log_level ~log_level ~log_json ~chain_id ~is_seed
1461
                 ~disable_node_status ~demo_mode ~coinbase_receiver ~net_config
1462
                 ~gossip_net_params ~proposed_protocol_version_opt
1463
                 ~work_selection_method:
1464
                   (Cli_lib.Arg_type.work_selection_method_to_module
×
1465
                      work_selection_method )
1466
                 ~snark_worker_config:
1467
                   { Mina_lib.Config.Snark_worker_config
1468
                     .initial_snark_worker_key = run_snark_worker_flag
1469
                   ; shutdown_on_disconnect = true
1470
                   ; num_threads = snark_worker_parallelism_flag
1471
                   }
1472
                 ~snark_coordinator_key:run_snark_coordinator_flag
1473
                 ~snark_pool_disk_location:chain_state_locations.snark_pool
1474
                 ~wallets_disk_location:(conf_dir ^/ "wallets")
×
1475
                 ~persistent_root_location:chain_state_locations.root
1476
                 ~persistent_frontier_location:chain_state_locations.frontier
1477
                 ~epoch_ledger_location
1478
                 ~proof_cache_location:chain_state_locations.proof_cache
1479
                 ~zkapp_vk_cache_location:chain_state_locations.zkapp_vk_cache
1480
                 ~snark_work_fee:snark_work_fee_flag ~time_controller
1481
                 ~block_production_keypairs ~monitor ~consensus_local_state
1482
                 ~is_archive_rocksdb ~work_reassignment_wait
1483
                 ~archive_process_location ~log_block_creation
1484
                 ~precomputed_values ~start_time ?precomputed_blocks_path
1485
                 ~log_precomputed_blocks ~start_filtered_logs
1486
                 ~upload_blocks_to_gcloud ~block_reward_threshold ~uptime_url
1487
                 ~uptime_submitter_keypair ~uptime_send_node_commit ~stop_time
1488
                 ~stop_time_interval ~node_status_url
1489
                 ~graphql_control_port:itn_graphql_port ~simplified_node_stats
1490
                 ~zkapp_cmd_limit:(ref compile_config.zkapp_cmd_limit)
1491
                 ~itn_features ~compile_config ~hardfork_handling () )
1492
          in
1493
          { mina
×
1494
          ; client_trustlist
1495
          ; rest_server_port
1496
          ; limited_graphql_port
1497
          ; itn_graphql_port
1498
          }
1499
        in
1500
        (* Breaks a dependency cycle with monitor initilization and coda *)
1501
        let mina_ref : Mina_lib.t option ref = ref None in
1502
        Option.iter node_error_url ~f:(fun url ->
1503
            let get_node_state () =
×
1504
              match !mina_ref with
×
1505
              | None ->
×
1506
                  Deferred.return None
1507
              | Some mina ->
×
1508
                  let%map node_state = Mina_lib.get_node_state mina in
×
1509
                  Some node_state
×
1510
            in
1511
            Node_error_service.set_config ~get_node_state
1512
              ~node_error_url:(Uri.of_string url) ~contact_info ) ;
×
1513
        Mina_run.handle_shutdown ~monitor ~time_controller ~conf_dir
×
1514
          ~child_pids:pids ~top_logger:logger mina_ref ;
1515
        Async.Scheduler.within' ~monitor
×
1516
        @@ fun () ->
1517
        let%bind { mina
1518
                 ; client_trustlist
1519
                 ; rest_server_port
1520
                 ; limited_graphql_port
1521
                 ; itn_graphql_port
1522
                 } =
1523
          mina_initialization_deferred ()
×
1524
        in
1525
        mina_ref := Some mina ;
×
1526
        (*This pipe is consumed only by integration tests*)
1527
        don't_wait_for
1528
          (Pipe_lib.Strict_pipe.Reader.iter_without_pushback
×
1529
             (Mina_lib.validated_transitions mina)
×
1530
             ~f:ignore ) ;
1531
        Mina_run.setup_local_server ?client_trustlist ~rest_server_port
×
1532
          ~insecure_rest_server ~open_limited_graphql_port ?limited_graphql_port
1533
          ?itn_graphql_port ?auth_keys:itn_keys mina ;
1534
        let%bind () =
1535
          Option.map metrics_server_port ~f:(fun port ->
1536
              let forward_uri =
×
1537
                Option.map libp2p_metrics_port ~f:(fun port ->
1538
                    Uri.with_uri ~scheme:(Some "http") ~host:(Some "127.0.0.1")
×
1539
                      ~port:(Some port) ~path:(Some "/metrics") Uri.empty )
1540
              in
1541
              Mina_metrics.Runtime.(
×
1542
                gc_stat_interval_mins :=
1543
                  Option.value ~default:!gc_stat_interval_mins gc_stat_interval) ;
×
1544
              Mina_metrics.server ?forward_uri ~port ~logger () >>| ignore )
×
1545
          |> Option.value ~default:Deferred.unit
×
1546
        in
1547
        let () = Mina_plugins.init_plugins ~logger mina plugins in
×
1548
        return mina )
×
1549

1550
let daemon logger ~itn_features =
1551
  let compile_config = Mina_compile_config.Compiled.t in
135✔
1552
  Command.async ~summary:"Mina daemon"
1553
    (Command.Param.map
135✔
1554
       (setup_daemon logger ~itn_features
135✔
1555
          ~default_snark_worker_fee:compile_config.default_snark_worker_fee )
1556
       ~f:(fun setup_daemon () ->
1557
         (* Immediately disable updating the time offset. *)
1558
         Block_time.Controller.disable_setting_offset () ;
×
1559
         let%bind mina = setup_daemon () in
×
1560
         let%bind () = Mina_lib.start mina in
×
1561
         [%log info] "Daemon ready. Clients can now connect" ;
×
1562
         Async.never () ) )
×
1563

1564
let replay_blocks logger ~itn_features =
1565
  let replay_flag =
135✔
1566
    let open Command.Param in
1567
    flag "--blocks-filename" ~aliases:[ "-blocks-filename" ] (required string)
135✔
1568
      ~doc:"PATH The file to read the precomputed blocks from"
1569
  in
1570
  let read_kind =
1571
    let open Command.Param in
1572
    flag "--format" ~aliases:[ "-format" ] (optional string)
135✔
1573
      ~doc:"json|sexp The format to read lines of the file in (default: json)"
1574
  in
1575
  let compile_config = Mina_compile_config.Compiled.t in
1576
  Command.async ~summary:"Start mina daemon with blocks replayed from a file"
1577
    (Command.Param.map3 replay_flag read_kind
135✔
1578
       (setup_daemon logger ~itn_features
135✔
1579
          ~default_snark_worker_fee:compile_config.default_snark_worker_fee )
1580
       ~f:(fun blocks_filename read_kind setup_daemon () ->
1581
         (* Enable updating the time offset. *)
1582
         Block_time.Controller.enable_setting_offset () ;
×
1583
         let read_block_line =
×
1584
           match Option.map ~f:String.lowercase read_kind with
1585
           | Some "json" | None -> (
×
1586
               fun line ->
1587
                 match
×
1588
                   Yojson.Safe.from_string line
1589
                   |> Mina_block.Precomputed.of_yojson
×
1590
                 with
1591
                 | Ok block ->
×
1592
                     block
1593
                 | Error err ->
×
1594
                     failwithf "Could not read block: %s" err () )
1595
           | Some "sexp" ->
×
1596
               fun line ->
1597
                 Sexp.of_string_conv_exn line Mina_block.Precomputed.t_of_sexp
×
1598
           | _ ->
×
1599
               failwith "Expected one of 'json', 'sexp' for -format flag"
1600
         in
1601
         let blocks =
1602
           Sequence.unfold ~init:(In_channel.create blocks_filename)
×
1603
             ~f:(fun blocks_file ->
1604
               match In_channel.input_line blocks_file with
×
1605
               | Some line ->
×
1606
                   Some (read_block_line line, blocks_file)
×
1607
               | None ->
×
1608
                   In_channel.close blocks_file ;
1609
                   None )
×
1610
         in
1611
         let%bind mina = setup_daemon () in
×
1612
         let%bind () = Mina_lib.start_with_precomputed_blocks mina blocks in
×
1613
         [%log info]
×
1614
           "Daemon is ready, replayed precomputed blocks. Clients can now \
1615
            connect" ;
1616
         Async.never () ) )
×
1617

1618
let dump_type_shapes =
1619
  let max_depth_flag =
1620
    let open Command.Param in
1621
    flag "--max-depth" ~aliases:[ "-max-depth" ] (optional int)
135✔
1622
      ~doc:"NN Maximum depth of shape S-expressions"
1623
  in
1624
  Command.basic ~summary:"Print serialization shapes of versioned types"
135✔
1625
    (Command.Param.map max_depth_flag ~f:(fun max_depth () ->
135✔
1626
         Ppx_version_runtime.Shapes.iteri
×
1627
           ~f:(fun ~key:path ~data:(shape, ty_decl) ->
1628
             let open Bin_prot.Shape in
×
1629
             let canonical = eval shape in
1630
             let digest = Canonical.to_digest canonical |> Digest.to_hex in
×
1631
             let shape_summary =
×
1632
               let shape_sexp =
1633
                 Canonical.to_string_hum canonical |> Sexp.of_string
×
1634
               in
1635
               (* elide the shape below specified depth, so that changes to
1636
                  contained types aren't considered a change to the containing
1637
                  type, even though the shape digests differ
1638
               *)
1639
               let summary_sexp =
×
1640
                 match max_depth with
1641
                 | None ->
×
1642
                     shape_sexp
1643
                 | Some n ->
×
1644
                     let rec go sexp depth =
1645
                       if depth > n then Sexp.Atom "."
×
1646
                       else
1647
                         match sexp with
×
1648
                         | Sexp.Atom _ ->
×
1649
                             sexp
1650
                         | Sexp.List items ->
×
1651
                             Sexp.List
1652
                               (List.map items ~f:(fun item ->
×
1653
                                    go item (depth + 1) ) )
×
1654
                     in
1655
                     go shape_sexp 0
×
1656
               in
1657
               Sexp.to_string summary_sexp
×
1658
             in
1659
             Core_kernel.printf "%s, %s, %s, %s\n" path digest shape_summary
1660
               ty_decl ) ) )
1661

1662
let primitive_ok = function
1663
  | "array" | "bytes" | "string" | "bigstring" ->
×
1664
      false
1665
  | "int" | "int32" | "int64" | "nativeint" | "char" | "bool" | "float" ->
×
1666
      true
1667
  | "unit" | "option" | "list" ->
×
1668
      true
1669
  | "kimchi_backend_bigint_32_V1" ->
×
1670
      true
1671
  | "Mina_stdlib.Bounded_types.String.t"
×
1672
  | "Mina_stdlib.Bounded_types.String.Tagged.t"
×
1673
  | "Mina_stdlib.Bounded_types.Array.t" ->
×
1674
      true
1675
  | "8fabab0a-4992-11e6-8cca-9ba2c4686d9e" ->
×
1676
      true (* hashtbl *)
1677
  | "ac8a9ff4-4994-11e6-9a1b-9fb4e933bd9d" ->
×
1678
      true (* Make_iterable_binable *)
1679
  | s ->
×
1680
      failwithf "unknown primitive %s" s ()
1681

1682
let audit_type_shapes : Command.t =
1683
  let rec shape_ok (shape : Sexp.t) : bool =
1684
    match shape with
×
1685
    | List [ Atom "Exp"; exp ] ->
×
1686
        exp_ok exp
1687
    | List [] ->
×
1688
        true
1689
    | _ ->
×
1690
        failwithf "bad shape: %s" (Sexp.to_string shape) ()
×
1691
  and exp_ok (exp : Sexp.t) : bool =
1692
    match exp with
×
1693
    | List [ Atom "Base"; Atom tyname; List exps ] ->
×
1694
        primitive_ok tyname && List.for_all exps ~f:shape_ok
×
1695
    | List [ Atom "Record"; List fields ] ->
×
1696
        List.for_all fields ~f:(fun field ->
1697
            match field with
×
1698
            | List [ Atom _; sh ] ->
×
1699
                shape_ok sh
1700
            | _ ->
×
1701
                failwithf "unhandled rec field: %s" (Sexp.to_string_hum field)
×
1702
                  () )
1703
    | List [ Atom "Tuple"; List exps ] ->
×
1704
        List.for_all exps ~f:shape_ok
1705
    | List [ Atom "Variant"; List ctors ] ->
×
1706
        List.for_all ctors ~f:(fun ctor ->
1707
            match ctor with
×
1708
            | List [ Atom _ctr; List exps ] ->
×
1709
                List.for_all exps ~f:shape_ok
1710
            | _ ->
×
1711
                failwithf "unhandled variant: %s" (Sexp.to_string_hum ctor) () )
×
1712
    | List [ Atom "Poly_variant"; List [ List [ Atom "sorted"; List ctors ] ] ]
×
1713
      ->
1714
        List.for_all ctors ~f:(fun ctor ->
1715
            match ctor with
×
1716
            | List [ Atom _ctr ] ->
×
1717
                true
1718
            | List [ Atom _ctr; List fields ] ->
×
1719
                List.for_all fields ~f:shape_ok
1720
            | _ ->
×
1721
                failwithf "unhandled poly variant: %s" (Sexp.to_string_hum ctor)
×
1722
                  () )
1723
    | List [ Atom "Application"; sh; List args ] ->
×
1724
        shape_ok sh && List.for_all args ~f:shape_ok
×
1725
    | List [ Atom "Rec_app"; Atom _; List args ] ->
×
1726
        List.for_all args ~f:shape_ok
1727
    | List [ Atom "Var"; Atom _ ] ->
×
1728
        true
1729
    | List (Atom ctr :: _) ->
×
1730
        failwithf "unhandled ctor (%s) in exp_ok: %s" ctr
1731
          (Sexp.to_string_hum exp) ()
×
1732
    | List [] | List _ | Atom _ ->
×
1733
        failwithf "bad format: %s" (Sexp.to_string_hum exp) ()
×
1734
  in
1735
  let handle_shape (path : string) (shape : Bin_prot.Shape.t) (ty_decl : string)
1736
      (good : int ref) (bad : int ref) =
1737
    let open Bin_prot.Shape in
×
1738
    let path, file = String.lsplit2_exn ~on:':' path in
1739
    let canonical = eval shape in
×
1740
    let shape_sexp = Canonical.to_string_hum canonical |> Sexp.of_string in
×
1741
    if not @@ shape_ok shape_sexp then (
×
1742
      incr bad ;
1743
      Core.eprintf "%s has a bad shape in %s (%s):\n%s\n" path file ty_decl
×
1744
        (Canonical.to_string_hum canonical) )
×
1745
    else incr good
×
1746
  in
1747
  Command.basic ~summary:"Audit shapes of versioned types"
135✔
1748
    (Command.Param.return (fun () ->
135✔
1749
         let bad, good = (ref 0, ref 0) in
×
1750
         Ppx_version_runtime.Shapes.iteri
1751
           ~f:(fun ~key:path ~data:(shape, ty_decl) ->
1752
             handle_shape path shape ty_decl good bad ) ;
×
1753
         Core.printf "good shapes:\n\t%d\nbad shapes:\n\t%d\n%!" !good !bad ;
1754
         if !bad > 0 then Core.exit 1 ) )
×
1755

1756
(*NOTE A previous version of this function included compile time ppx that didn't compile, and was never
1757
  evaluated under any build profile
1758
*)
1759
let ensure_testnet_id_still_good _ = Deferred.unit
135✔
1760

1761
let snark_hashes =
1762
  let module Hashes = struct
1763
    type t = string list [@@deriving to_yojson]
×
1764
  end in
1765
  let open Command.Let_syntax in
1766
  Command.basic ~summary:"List hashes of proving and verification keys"
135✔
1767
    [%map_open
1768
      let json = Cli_lib.Flag.json in
1769
      fun () -> if json then Core.printf "[]\n%!"]
×
1770

1771
let internal_commands logger ~itn_features =
1772
  [ ( Snark_worker.Intf.command_name
135✔
1773
    , Snark_worker.command ~proof_level:Genesis_constants.Compiled.proof_level
1774
        ~constraint_constants:Genesis_constants.Compiled.constraint_constants
1775
        ~commit_id:Mina_version.commit_id )
1776
  ; ("snark-hashes", snark_hashes)
1777
  ; ( "run-prover"
1778
    , Command.async
135✔
1779
        ~summary:"Run prover on a sexp provided on a single line of stdin"
1780
        (let%map_open.Command signature_kind = Cli_lib.Flag.signature_kind in
1781
         fun () ->
1782
           let logger = Logger.create () in
×
1783
           let constraint_constants =
×
1784
             Genesis_constants.Compiled.constraint_constants
1785
           in
1786
           let proof_level = Genesis_constants.Compiled.proof_level in
1787
           Parallel.init_master () ;
1788
           match%bind Reader.read_sexp (Lazy.force Reader.stdin) with
×
1789
           | `Ok sexp ->
×
1790
               let%bind conf_dir = Unix.mkdtemp "/tmp/mina-prover" in
×
1791
               [%log info] "Prover state being logged to %s" conf_dir ;
×
1792
               let%bind prover =
1793
                 Prover.create ~commit_id:Mina_version.commit_id ~logger
×
1794
                   ~proof_level ~constraint_constants
1795
                   ~pids:(Pid.Table.create ()) ~conf_dir ~signature_kind ()
×
1796
               in
1797
               Prover.prove_from_input_sexp prover sexp >>| ignore
×
1798
           | `Eof ->
×
1799
               failwith "early EOF while reading sexp" ) )
1800
  ; ( "run-snark-worker-single"
1801
    , Command.async
135✔
1802
        ~summary:"Run snark-worker on a sexp provided on a single line of stdin"
1803
        (let open Command.Let_syntax in
1804
        let%map_open filename =
1805
          flag "--file" (required string)
135✔
1806
            ~doc:"File containing the s-expression of the snark work to execute"
1807
        and signature_kind = Cli_lib.Flag.signature_kind in
1808
        fun () ->
1809
          let open Deferred.Let_syntax in
×
1810
          let logger = Logger.create () in
1811
          let constraint_constants =
×
1812
            Genesis_constants.Compiled.constraint_constants
1813
          in
1814
          let proof_level = Genesis_constants.Compiled.proof_level in
1815
          Parallel.init_master () ;
1816
          match%bind
1817
            Reader.with_file filename ~f:(fun reader ->
×
1818
                [%log info] "Created reader for %s" filename ;
×
1819
                Reader.read_sexp reader )
×
1820
          with
1821
          | `Ok sexp -> (
×
1822
              let%bind worker_state =
1823
                Snark_worker.Inputs.Worker_state.create ~proof_level
×
1824
                  ~constraint_constants ~signature_kind ()
1825
              in
1826
              let sok_message =
×
1827
                { Mina_base.Sok_message.fee = Currency.Fee.of_mina_int_exn 0
×
1828
                ; prover = Quickcheck.random_value Public_key.Compressed.gen
×
1829
                }
1830
              in
1831
              let spec =
1832
                [%of_sexp:
1833
                  ( Transaction_witness.Stable.Latest.t
1834
                  , Ledger_proof.t )
1835
                  Snark_work_lib.Work.Single.Spec.t] sexp
1836
              in
1837
              match%map
1838
                Snark_worker.Inputs.perform_single worker_state
×
1839
                  ~message:sok_message spec
1840
              with
1841
              | Ok _ ->
×
1842
                  [%log info] "Successfully worked"
×
1843
              | Error err ->
×
1844
                  [%log error] "Work didn't work: $err"
×
1845
                    ~metadata:[ ("err", Error_json.error_to_yojson err) ] )
×
1846
          | `Eof ->
×
1847
              failwith "early EOF while reading sexp") )
1848
  ; ( "run-verifier"
1849
    , Command.async
135✔
1850
        ~summary:"Run verifier on a proof provided on a single line of stdin"
1851
        (let open Command.Let_syntax in
1852
        let%map_open mode =
1853
          flag "--mode" ~aliases:[ "-mode" ] (required string)
135✔
1854
            ~doc:"transaction/blockchain the snark to verify. Defaults to json"
1855
        and format =
1856
          flag "--format" ~aliases:[ "-format" ] (optional string)
135✔
1857
            ~doc:"sexp/json the format to parse input in"
1858
        and limit =
1859
          flag "--limit" ~aliases:[ "-limit" ] (optional int)
135✔
1860
            ~doc:"limit the number of proofs taken from the file"
1861
        in
1862
        fun () ->
1863
          let open Async in
×
1864
          let logger = Logger.create () in
1865
          let constraint_constants =
×
1866
            Genesis_constants.Compiled.constraint_constants
1867
          in
1868
          let proof_level = Genesis_constants.Compiled.proof_level in
1869
          Parallel.init_master () ;
1870
          let%bind conf_dir = Unix.mkdtemp "/tmp/mina-verifier" in
×
1871
          let mode =
×
1872
            match mode with
1873
            | "transaction" ->
×
1874
                `Transaction
1875
            | "blockchain" ->
×
1876
                `Blockchain
1877
            | mode ->
×
1878
                failwithf
×
1879
                  "Expected mode flag to be one of transaction, blockchain, \
1880
                   got '%s'"
1881
                  mode ()
1882
          in
1883
          let format =
1884
            match format with
1885
            | Some "sexp" ->
×
1886
                `Sexp
1887
            | Some "json" | None ->
×
1888
                `Json
1889
            | Some format ->
×
1890
                failwithf
×
1891
                  "Expected format flag to be one of sexp, json, got '%s'"
1892
                  format ()
1893
          in
1894
          let%bind input =
1895
            match format with
1896
            | `Sexp -> (
×
1897
                let%map input_sexp =
1898
                  match%map Reader.read_sexp (Lazy.force Reader.stdin) with
×
1899
                  | `Ok input_sexp ->
×
1900
                      input_sexp
1901
                  | `Eof ->
×
1902
                      failwith "early EOF while reading sexp"
1903
                in
1904
                match mode with
×
1905
                | `Transaction ->
×
1906
                    `Transaction
1907
                      (List.t_of_sexp
×
1908
                         (Tuple2.t_of_sexp Ledger_proof.t_of_sexp
×
1909
                            Sok_message.t_of_sexp )
1910
                         input_sexp )
1911
                | `Blockchain ->
×
1912
                    `Blockchain
1913
                      (List.t_of_sexp Blockchain_snark.Blockchain.t_of_sexp
×
1914
                         input_sexp ) )
1915
            | `Json -> (
×
1916
                let%map input_line =
1917
                  match%map Reader.read_line (Lazy.force Reader.stdin) with
×
1918
                  | `Ok input_line ->
×
1919
                      input_line
1920
                  | `Eof ->
×
1921
                      failwith "early EOF while reading json"
1922
                in
1923
                match mode with
×
1924
                | `Transaction -> (
×
1925
                    match
1926
                      [%derive.of_yojson: (Ledger_proof.t * Sok_message.t) list]
×
1927
                        (Yojson.Safe.from_string input_line)
×
1928
                    with
1929
                    | Ok input ->
×
1930
                        `Transaction input
1931
                    | Error err ->
×
1932
                        failwithf "Could not parse JSON: %s" err () )
1933
                | `Blockchain -> (
×
1934
                    match
1935
                      [%derive.of_yojson: Blockchain_snark.Blockchain.t list]
×
1936
                        (Yojson.Safe.from_string input_line)
×
1937
                    with
1938
                    | Ok input ->
×
1939
                        `Blockchain input
1940
                    | Error err ->
×
1941
                        failwithf "Could not parse JSON: %s" err () ) )
1942
          in
1943

1944
          let%bind verifier =
1945
            Verifier.For_tests.default ~constraint_constants ~proof_level
×
1946
              ~commit_id:Mina_version.commit_id ~logger
1947
              ~pids:(Pid.Table.create ()) ~conf_dir:(Some conf_dir) ()
×
1948
          in
1949
          let%bind result =
1950
            let cap lst =
1951
              Option.value_map ~default:Fn.id ~f:(Fn.flip List.take) limit lst
×
1952
            in
1953
            match input with
1954
            | `Transaction input ->
×
1955
                input |> cap |> Verifier.verify_transaction_snarks verifier
×
1956
            | `Blockchain input ->
×
1957
                input |> cap |> Verifier.verify_blockchain_snarks verifier
×
1958
          in
1959
          match result with
×
1960
          | Ok (Ok ()) ->
×
1961
              printf "Proofs verified successfully" ;
1962
              exit 0
×
1963
          | Ok (Error err) ->
×
1964
              printf "Proofs failed to verify:\n%s\n"
1965
                (Yojson.Safe.pretty_to_string (Error_json.error_to_yojson err)) ;
×
1966
              exit 1
×
1967
          | Error err ->
×
1968
              printf "Failed while verifying proofs:\n%s"
1969
                (Error.to_string_hum err) ;
×
1970
              exit 2) )
×
1971
  ; ( "dump-structured-events"
1972
    , Command.async ~summary:"Dump the registered structured events"
135✔
1973
        (let open Command.Let_syntax in
1974
        let%map outfile =
1975
          Core_kernel.Command.Param.flag "--out-file" ~aliases:[ "-out-file" ]
135✔
1976
            (Core_kernel.Command.Flag.optional Core_kernel.Command.Param.string)
135✔
1977
            ~doc:"FILENAME File to output to. Defaults to stdout"
1978
        and pretty =
1979
          Core_kernel.Command.Param.flag "--pretty" ~aliases:[ "-pretty" ]
135✔
1980
            Core_kernel.Command.Param.no_arg
1981
            ~doc:"  Set to output 'pretty' JSON"
1982
        in
1983
        fun () ->
1984
          let out_channel =
×
1985
            match outfile with
1986
            | Some outfile ->
×
1987
                Core_kernel.Out_channel.create outfile
×
1988
            | None ->
×
1989
                Core_kernel.Out_channel.stdout
1990
          in
1991
          let json =
1992
            Structured_log_events.dump_registered_events ()
1993
            |> [%derive.to_yojson:
1994
                 (string * Structured_log_events.id * string list) list]
×
1995
          in
1996
          if pretty then Yojson.Safe.pretty_to_channel out_channel json
×
1997
          else Yojson.Safe.to_channel out_channel json ;
×
1998
          ( match outfile with
1999
          | Some _ ->
×
2000
              Core_kernel.Out_channel.close out_channel
×
2001
          | None ->
×
2002
              () ) ;
2003
          Deferred.return ()) )
2004
  ; ("dump-type-shapes", dump_type_shapes)
2005
  ; ("replay-blocks", replay_blocks logger ~itn_features)
135✔
2006
  ; ("audit-type-shapes", audit_type_shapes)
2007
  ; ( "test-genesis-block-generation"
2008
    , Command.async ~summary:"Generate a genesis proof"
135✔
2009
        (let open Command.Let_syntax in
2010
        let%map_open config_files =
2011
          flag "--config-file" ~aliases:[ "config-file" ]
135✔
2012
            ~doc:
2013
              "PATH path to a configuration file (overrides MINA_CONFIG_FILE, \
2014
               default: <config_dir>/daemon.json). Pass multiple times to \
2015
               override fields from earlier config files"
2016
            (listed string)
135✔
2017
        and conf_dir = Cli_lib.Flag.conf_dir
2018
        and genesis_dir =
2019
          flag "--genesis-ledger-dir" ~aliases:[ "genesis-ledger-dir" ]
135✔
2020
            ~doc:
2021
              "DIR Directory that contains the genesis ledger and the genesis \
2022
               blockchain proof (default: <config-dir>)"
2023
            (optional string)
135✔
2024
        and signature_kind = Cli_lib.Flag.signature_kind in
2025
        fun () ->
2026
          let open Deferred.Let_syntax in
×
2027
          Parallel.init_master () ;
2028
          let logger = Logger.create () in
×
2029
          let conf_dir = Mina_lib.Conf_dir.compute_conf_dir conf_dir in
×
2030
          let genesis_constants =
×
2031
            Genesis_constants.Compiled.genesis_constants
2032
          in
2033
          let constraint_constants =
2034
            Genesis_constants.Compiled.constraint_constants
2035
          in
2036
          let proof_level = Genesis_constants.Proof_level.Full in
2037
          let config_files =
2038
            List.map config_files ~f:(fun config_file ->
2039
                (config_file, `Must_exist) )
×
2040
          in
2041
          let%bind ( precomputed_values
2042
                   , _config_jsons
2043
                   , _config
2044
                   , _chain_state_locations ) =
2045
            load_config_files ~logger ~conf_dir ~genesis_dir ~genesis_constants
×
2046
              ~constraint_constants ~proof_level ~cli_proof_level:None
2047
              ~genesis_backing_type:Stable_db config_files
2048
          in
2049
          let pids = Child_processes.Termination.create_pid_table () in
×
2050
          let%bind prover =
2051
            (* We create a prover process (unnecessarily) here, to have a more
2052
               realistic test.
2053
            *)
2054
            Prover.create ~commit_id:Mina_version.commit_id ~logger ~pids
×
2055
              ~conf_dir ~proof_level
2056
              ~constraint_constants:precomputed_values.constraint_constants
2057
              ~signature_kind ()
2058
          in
2059
          match%bind
2060
            Prover.create_genesis_block prover
×
2061
              (Genesis_proof.to_inputs precomputed_values)
×
2062
          with
2063
          | Ok block ->
×
2064
              Format.eprintf "Generated block@.%s@."
2065
                ( Yojson.Safe.to_string
×
2066
                @@ Blockchain_snark.Blockchain.to_yojson block ) ;
×
2067
              exit 0
×
2068
          | Error err ->
×
2069
              Format.eprintf "Failed to generate block@.%s@."
2070
                (Yojson.Safe.to_string @@ Error_json.error_to_yojson err) ;
×
2071
              exit 1) )
×
2072
  ]
2073

2074
let mina_commands logger ~itn_features =
2075
  [ ("accounts", Client.accounts)
135✔
2076
  ; ("daemon", daemon logger ~itn_features)
135✔
2077
  ; ("client", Client.client)
2078
  ; ("advanced", Client.advanced ~itn_features)
2079
  ; ("ledger", Client.ledger)
2080
  ; ("libp2p", Client.libp2p)
2081
  ; ( "internal"
2082
    , Command.group ~summary:"Internal commands"
135✔
2083
        (internal_commands logger ~itn_features) )
135✔
2084
  ; (Parallel.worker_command_name, Parallel.worker_command)
2085
  ; ("transaction-snark-profiler", Transaction_snark_profiler.command)
2086
  ]
2087

2088
let print_version_help coda_exe version =
2089
  (* mimic Jane Street command help *)
2090
  let lines =
×
2091
    [ "print version information"
2092
    ; ""
2093
    ; sprintf "  %s %s" (Filename.basename coda_exe) version
×
2094
    ; ""
2095
    ; "=== flags ==="
2096
    ; ""
2097
    ; "  [-help]  print this help text and exit"
2098
    ; "           (alias: -?)"
2099
    ]
2100
  in
2101
  List.iter lines ~f:(Core.printf "%s\n%!")
×
2102

2103
let print_version_info () = Core.printf "Commit %s\n" Mina_version.commit_id
×
2104

2105
let () =
2106
  Random.self_init () ;
2107
  let itn_features = Sys.getenv "ITN_FEATURES" |> Option.is_some in
135✔
2108
  let logger = Logger.create ~itn_features () in
135✔
2109
  don't_wait_for (ensure_testnet_id_still_good logger) ;
135✔
2110
  (* Turn on snark debugging in prod for now *)
2111
  Snarky_backendless.Snark.set_eval_constraints true ;
135✔
2112
  (* intercept command-line processing for "version", because we don't
2113
     use the Jane Street scripts that generate their version information
2114
  *)
2115
  (let is_version_cmd s =
135✔
2116
     List.mem [ "version"; "-version"; "--version" ] s ~equal:String.equal
×
2117
   in
2118
   match Sys.get_argv () with
2119
   | [| _mina_exe; version |] when is_version_cmd version ->
×
2120
       Mina_version.print_version ()
×
2121
   | _ ->
135✔
2122
       Command.run
×
2123
         (Command.group ~summary:"Mina" ~preserve_subcommand_order:()
135✔
2124
            (mina_commands logger ~itn_features) ) ) ;
135✔
2125
  Core.exit 0
×
2126

2127
let linkme = ()
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc