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

MinaProtocol / mina / 499

20 Aug 2025 06:34PM UTC coverage: 33.256% (+0.01%) from 33.242%
499

push

buildkite

web-flow
Merge pull request #17641 from MinaProtocol/lyh/improve-genesis-ledger-creation

Improve Genesis Ledger Creation

10 of 30 new or added lines in 9 files covered. (33.33%)

1219 existing lines in 13 files now uncovered.

24095 of 72454 relevant lines covered (33.26%)

24752.12 hits per line

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

22.0
/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 []
49✔
51

52
let load_config_files ~logger ~genesis_constants ~constraint_constants ~conf_dir
53
    ~genesis_dir ~cli_proof_level ~proof_level config_files =
54
  let%bind config_jsons =
55
    let config_files_paths =
56
      List.map config_files ~f:(fun (config_file, _) -> `String config_file)
×
57
    in
58
    [%log info] "Reading configuration files $config_files"
×
59
      ~metadata:[ ("config_files", `List config_files_paths) ] ;
60
    Deferred.List.filter_map config_files
×
61
      ~f:(fun (config_file, handle_missing) ->
62
        match%bind Genesis_ledger_helper.load_config_json config_file with
×
63
        | Ok config_json ->
×
64
            let%map config_json =
65
              Genesis_ledger_helper.upgrade_old_config ~logger config_file
×
66
                config_json
67
            in
68
            Some (config_file, config_json)
×
69
        | Error err -> (
×
70
            match handle_missing with
71
            | `Must_exist ->
×
72
                Mina_stdlib.Mina_user_error.raisef
73
                  ~where:"reading configuration file"
74
                  "The configuration file %s could not be read:\n%s" config_file
75
                  (Error.to_string_hum err)
×
76
            | `May_be_missing ->
×
77
                [%log warn] "Could not read configuration from $config_file"
×
78
                  ~metadata:
79
                    [ ("config_file", `String config_file)
80
                    ; ("error", Error_json.error_to_yojson err)
×
81
                    ] ;
82
                return None ) )
×
83
  in
84
  let config =
×
85
    List.fold ~init:Runtime_config.default config_jsons
86
      ~f:(fun config (config_file, config_json) ->
87
        match Runtime_config.of_yojson config_json with
×
88
        | Ok loaded_config ->
×
89
            Runtime_config.combine config loaded_config
90
        | Error err ->
×
91
            [%log fatal]
×
92
              "Could not parse configuration from $config_file: $error"
93
              ~metadata:
94
                [ ("config_file", `String config_file)
95
                ; ("config_json", config_json)
96
                ; ("error", `String err)
97
                ] ;
98
            failwithf "Could not parse configuration file: %s" err () )
×
99
  in
100
  let genesis_dir = Option.value ~default:(conf_dir ^/ "genesis") genesis_dir in
×
101
  let%bind precomputed_values =
102
    match%map
103
      Genesis_ledger_helper.init_from_config_file ~cli_proof_level ~genesis_dir
×
104
        ~logger ~genesis_constants ~constraint_constants ~proof_level config
105
    with
106
    | Ok (precomputed_values, _) ->
×
107
        precomputed_values
108
    | Error err ->
×
109
        let ( json_config
110
            , `Accounts_omitted
111
                ( `Genesis genesis_accounts_omitted
112
                , `Staking staking_accounts_omitted
113
                , `Next next_accounts_omitted ) ) =
114
          Runtime_config.to_yojson_without_accounts config
115
        in
116
        let append_accounts_omitted s =
×
117
          Option.value_map
×
118
            ~f:(fun i -> List.cons (s ^ "_accounts_omitted", `Int i))
×
119
            ~default:Fn.id
120
        in
121
        let metadata =
122
          append_accounts_omitted "genesis" genesis_accounts_omitted
123
          @@ append_accounts_omitted "staking" staking_accounts_omitted
×
124
          @@ append_accounts_omitted "next" next_accounts_omitted []
×
125
          @ [ ("config", json_config)
126
            ; ( "name"
127
              , `String
128
                  (Option.value ~default:"not provided"
×
129
                     (let%bind.Option ledger = config.ledger in
130
                      Option.first_some ledger.name ledger.hash ) ) )
×
131
            ; ("error", Error_json.error_to_yojson err)
×
132
            ]
133
        in
134
        [%log info]
×
135
          "Initializing with runtime configuration. Ledger source: $name"
136
          ~metadata ;
137
        Error.raise err
×
138
  in
139
  return (precomputed_values, config_jsons, config)
×
140

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

UNCOV
783
          constraint_constants.block_window_duration_ms |> Float.of_int
×
UNCOV
784
          |> Time.Span.of_ms |> Mina_metrics.initialize_all ;
×
785

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

1138
            let constraint_constants = precomputed_values.constraint_constants
1139

1140
            let consensus_constants = precomputed_values.consensus_constants
1141
          end in
1142
          let consensus_local_state =
1143
            Consensus.Data.Local_state.create
1144
              ~context:(module Context)
1145
              ~genesis_ledger:precomputed_values.genesis_ledger
1146
              ~genesis_epoch_data:precomputed_values.genesis_epoch_data
1147
              ~epoch_ledger_location
1148
              ( Option.map block_production_keypair ~f:(fun keypair ->
UNCOV
1149
                    let open Keypair in
×
1150
                    Public_key.compress keypair.public_key )
1151
              |> Option.to_list |> Public_key.Compressed.Set.of_list )
×
1152
              ~genesis_state_hash:
1153
                precomputed_values.protocol_state_with_hashes.hash.state_hash
1154
          in
UNCOV
1155
          trace_database_initialization "epoch ledger" __LOC__
×
1156
            epoch_ledger_location ;
1157
          let%bind peer_list_file_contents_or_empty =
1158
            match libp2p_peer_list_file with
UNCOV
1159
            | None ->
×
UNCOV
1160
                return []
×
1161
            | Some file -> (
×
1162
                match%bind
1163
                  Monitor.try_with_or_error ~here:[%here] (fun () ->
×
UNCOV
1164
                      Reader.file_contents file )
×
1165
                with
1166
                | Ok contents ->
×
UNCOV
1167
                    return (Mina_net2.Multiaddr.of_file_contents contents)
×
1168
                | Error _ ->
×
1169
                    Mina_stdlib.Mina_user_error.raisef
1170
                      ~where:"reading libp2p peer address file"
1171
                      "The file %s could not be read.\n\n\
1172
                       It must be a newline-separated list of libp2p \
1173
                       multiaddrs (ex: /ip4/IPADDR/tcp/PORT/p2p/PEERID)"
1174
                      file )
1175
          in
UNCOV
1176
          List.iter libp2p_peers_raw ~f:(fun raw_peer ->
×
UNCOV
1177
              if not Mina_net2.Multiaddr.(valid_as_peer @@ of_string raw_peer)
×
1178
              then
1179
                Mina_stdlib.Mina_user_error.raisef
×
1180
                  ~where:"decoding peer as a multiaddress"
1181
                  "The given peer \"%s\" is not a valid multiaddress (ex: \
1182
                   /ip4/IPADDR/tcp/PORT/p2p/PEERID)"
1183
                  raw_peer ) ;
UNCOV
1184
          let initial_peers =
×
1185
            List.concat
1186
              [ List.map ~f:Mina_net2.Multiaddr.of_string libp2p_peers_raw
×
1187
              ; peer_list_file_contents_or_empty
1188
              ; List.map ~f:Mina_net2.Multiaddr.of_string
×
UNCOV
1189
                @@ or_from_config
×
1190
                     (Fn.compose Option.some
×
1191
                        (YJ.Util.convert_each YJ.Util.to_string) )
×
1192
                     "peers" None ~default:[]
1193
              ]
1194
          in
UNCOV
1195
          let direct_peers =
×
1196
            List.map ~f:Mina_net2.Multiaddr.of_string direct_peers_raw
1197
          in
UNCOV
1198
          let min_connections =
×
1199
            or_from_config YJ.Util.to_int_option "min-connections"
1200
              ~default:Cli_lib.Default.min_connections min_connections
1201
          in
UNCOV
1202
          let max_connections =
×
1203
            or_from_config YJ.Util.to_int_option "max-connections"
1204
              ~default:Cli_lib.Default.max_connections max_connections
1205
          in
UNCOV
1206
          let pubsub_v1 = Gossip_net.Libp2p.N in
×
1207
          (* TODO uncomment after introducing Bitswap-based block retrieval *)
1208
          (* let pubsub_v1 =
1209
               or_from_config to_pubsub_topic_mode_option "pubsub-v1"
1210
                 ~default:Cli_lib.Default.pubsub_v1 pubsub_v1
1211
             in *)
1212
          let pubsub_v0 =
1213
            or_from_config to_pubsub_topic_mode_option "pubsub-v0"
1214
              ~default:Cli_lib.Default.pubsub_v0 None
1215
          in
UNCOV
1216
          let validation_queue_size =
×
1217
            or_from_config YJ.Util.to_int_option "validation-queue-size"
1218
              ~default:Cli_lib.Default.validation_queue_size
1219
              validation_queue_size
1220
          in
UNCOV
1221
          let stop_time =
×
1222
            or_from_config YJ.Util.to_int_option "stop-time"
1223
              ~default:Cli_lib.Default.stop_time stop_time
1224
          in
UNCOV
1225
          if enable_tracing then Mina_tracing.start conf_dir |> don't_wait_for ;
×
1226
          let%bind () =
1227
            if enable_internal_tracing then
UNCOV
1228
              Internal_tracing.toggle ~commit_id:Mina_version.commit_id ~logger
×
1229
                `Enabled
1230
            else Deferred.unit
×
1231
          in
1232
          let seed_peer_list_url =
×
1233
            Option.value_map seed_peer_list_url ~f:Option.some
1234
              ~default:
UNCOV
1235
                (Option.bind config.daemon
×
1236
                   ~f:(fun { Runtime_config.Daemon.peer_list_url; _ } ->
1237
                     peer_list_url ) )
×
1238
          in
1239
          if is_seed then [%log info] "Starting node as a seed node"
×
UNCOV
1240
          else if demo_mode then [%log info] "Starting node in demo mode"
×
1241
          else if
×
1242
            List.is_empty initial_peers && Option.is_none seed_peer_list_url
×
1243
          then
1244
            Mina_stdlib.Mina_user_error.raise
×
1245
              {|No peers were given.
1246

1247
Pass one of -peer, -peer-list-file, -seed, -peer-list-url.|} ;
1248
          let chain_id =
1249
            let protocol_transaction_version =
UNCOV
1250
              Protocol_version.(transaction current)
×
1251
            in
1252
            let protocol_network_version =
UNCOV
1253
              Protocol_version.(transaction current)
×
1254
            in
1255
            chain_id ~genesis_state_hash
1256
              ~genesis_constants:precomputed_values.genesis_constants
1257
              ~constraint_system_digests:
UNCOV
1258
                (Lazy.force precomputed_values.constraint_system_digests)
×
1259
              ~protocol_transaction_version ~protocol_network_version
1260
          in
UNCOV
1261
          [%log info] "Daemon will use chain id %s" chain_id ;
×
UNCOV
1262
          [%log info] "Daemon running protocol version %s"
×
1263
            Protocol_version.(to_string current) ;
×
1264
          let gossip_net_params =
×
1265
            Gossip_net.Libp2p.Config.
1266
              { timeout = Time.Span.of_sec 3.
×
1267
              ; logger
1268
              ; conf_dir
1269
              ; chain_id
1270
              ; unsafe_no_trust_ip = false
1271
              ; seed_peer_list_url =
UNCOV
1272
                  Option.map seed_peer_list_url ~f:Uri.of_string
×
1273
              ; initial_peers
1274
              ; addrs_and_ports
1275
              ; metrics_port = libp2p_metrics_port
1276
              ; trust_system
UNCOV
1277
              ; flooding = Option.value ~default:false enable_flooding
×
1278
              ; direct_peers
1279
              ; peer_protection_ratio
UNCOV
1280
              ; peer_exchange = Option.value ~default:false peer_exchange
×
1281
              ; min_connections
1282
              ; max_connections
1283
              ; validation_queue_size
UNCOV
1284
              ; isolate = Option.value ~default:false isolate
×
1285
              ; keypair = libp2p_keypair
1286
              ; all_peers_seen_metric
1287
              ; known_private_ip_nets =
UNCOV
1288
                  Option.value ~default:[] client_trustlist
×
1289
              ; time_controller
1290
              ; pubsub_v1
1291
              ; pubsub_v0
1292
              }
1293
          in
1294
          let net_config =
1295
            { Mina_networking.Config.genesis_ledger_hash
1296
            ; log_gossip_heard
1297
            ; is_seed
1298
            ; creatable_gossip_net =
1299
                Mina_networking.Gossip_net.(
1300
                  Any.Creatable
UNCOV
1301
                    ((module Libp2p), Libp2p.create ~pids gossip_net_params))
×
1302
            }
1303
          in
1304
          let coinbase_receiver : Consensus.Coinbase_receiver.t =
UNCOV
1305
            Option.value_map coinbase_receiver_flag ~default:`Producer
×
UNCOV
1306
              ~f:(fun pk -> `Other pk)
×
1307
          in
1308
          let proposed_protocol_version_opt =
1309
            Mina_run.get_proposed_protocol_version_opt ~conf_dir ~logger
1310
              proposed_protocol_version
1311
          in
UNCOV
1312
          ( match
×
1313
              (uptime_url_string, uptime_submitter_key, uptime_submitter_pubkey)
1314
            with
UNCOV
1315
          | Some _, Some _, None | Some _, None, Some _ | None, None, None ->
×
1316
              ()
1317
          | _ ->
×
UNCOV
1318
              Mina_stdlib.Mina_user_error.raise
×
1319
                "Must provide both --uptime-url and exactly one of \
1320
                 --uptime-submitter-key or --uptime-submitter-pubkey" ) ;
1321
          let uptime_url =
UNCOV
1322
            Option.map uptime_url_string ~f:(fun s -> Uri.of_string s)
×
1323
          in
1324
          let uptime_submitter_opt =
×
1325
            Option.map uptime_submitter_pubkey ~f:(fun s ->
1326
                match Public_key.Compressed.of_base58_check s with
×
UNCOV
1327
                | Ok pk -> (
×
1328
                    match Public_key.decompress pk with
1329
                    | Some _ ->
×
1330
                        pk
1331
                    | None ->
×
1332
                        failwithf
1333
                          "Invalid public key %s for uptime submitter (could \
1334
                           not decompress)"
1335
                          s () )
UNCOV
1336
                | Error err ->
×
1337
                    Mina_stdlib.Mina_user_error.raisef
1338
                      "Invalid public key %s for uptime submitter, %s" s
UNCOV
1339
                      (Error.to_string_hum err) () )
×
1340
          in
1341
          let%bind uptime_submitter_keypair =
1342
            match (uptime_submitter_key, uptime_submitter_opt) with
UNCOV
1343
            | None, None ->
×
UNCOV
1344
                return None
×
1345
            | None, Some pk ->
×
1346
                let%map kp =
1347
                  Secrets.Wallets.get_tracked_keypair ~logger
×
1348
                    ~which:"uptime submitter keypair"
1349
                    ~read_from_env_exn:
1350
                      (Secrets.Uptime_keypair.Terminal_stdin.read_exn
1351
                         ~should_prompt_user:false ~should_reask:false )
1352
                    ~conf_dir pk
1353
                in
UNCOV
1354
                Some kp
×
UNCOV
1355
            | Some sk_file, None ->
×
1356
                let%map kp =
1357
                  Secrets.Uptime_keypair.Terminal_stdin.read_exn
×
1358
                    ~should_prompt_user:false ~should_reask:false
1359
                    ~which:"uptime submitter keypair" sk_file
1360
                in
UNCOV
1361
                Some kp
×
UNCOV
1362
            | _ ->
×
1363
                (* unreachable, because of earlier check *)
1364
                failwith
1365
                  "Cannot provide both uptime submitter public key and uptime \
1366
                   submitter keyfile"
1367
          in
UNCOV
1368
          if itn_features then
×
1369
            (* set queue bound directly in Itn_logger
1370
               adding bound to Mina_lib config introduces cycle
1371
            *)
UNCOV
1372
            Option.iter itn_max_logs ~f:Itn_logger.set_queue_bound ;
×
UNCOV
1373
          let start_time = Time.now () in
×
1374
          let%map mina =
1375
            Mina_lib.create ~commit_id:Mina_version.commit_id ~wallets
×
UNCOV
1376
              (Mina_lib.Config.make ~logger ~pids ~trust_system ~conf_dir
×
1377
                 ~file_log_level ~log_level ~log_json ~chain_id ~is_seed
1378
                 ~disable_node_status ~demo_mode ~coinbase_receiver ~net_config
1379
                 ~gossip_net_params ~proposed_protocol_version_opt
1380
                 ~work_selection_method:
UNCOV
1381
                   (Cli_lib.Arg_type.work_selection_method_to_module
×
1382
                      work_selection_method )
1383
                 ~snark_worker_config:
1384
                   { Mina_lib.Config.Snark_worker_config
1385
                     .initial_snark_worker_key = run_snark_worker_flag
1386
                   ; shutdown_on_disconnect = true
1387
                   ; num_threads = snark_worker_parallelism_flag
1388
                   }
1389
                 ~snark_coordinator_key:run_snark_coordinator_flag
UNCOV
1390
                 ~snark_pool_disk_location:(conf_dir ^/ "snark_pool")
×
UNCOV
1391
                 ~wallets_disk_location:(conf_dir ^/ "wallets")
×
1392
                 ~persistent_root_location:(conf_dir ^/ "root")
×
1393
                 ~persistent_frontier_location:(conf_dir ^/ "frontier")
×
1394
                 ~epoch_ledger_location ~snark_work_fee:snark_work_fee_flag
1395
                 ~time_controller ~block_production_keypairs ~monitor
1396
                 ~consensus_local_state ~is_archive_rocksdb
1397
                 ~work_reassignment_wait ~archive_process_location
1398
                 ~log_block_creation ~precomputed_values ~start_time
1399
                 ?precomputed_blocks_path ~log_precomputed_blocks
1400
                 ~start_filtered_logs ~upload_blocks_to_gcloud
1401
                 ~block_reward_threshold ~uptime_url ~uptime_submitter_keypair
1402
                 ~uptime_send_node_commit ~stop_time ~node_status_url
1403
                 ~graphql_control_port:itn_graphql_port ~simplified_node_stats
1404
                 ~zkapp_cmd_limit:(ref compile_config.zkapp_cmd_limit)
1405
                 ~itn_features ~compile_config () )
1406
          in
UNCOV
1407
          { mina
×
1408
          ; client_trustlist
1409
          ; rest_server_port
1410
          ; limited_graphql_port
1411
          ; itn_graphql_port
1412
          }
1413
        in
1414
        (* Breaks a dependency cycle with monitor initilization and coda *)
1415
        let mina_ref : Mina_lib.t option ref = ref None in
1416
        Option.iter node_error_url ~f:(fun url ->
UNCOV
1417
            let get_node_state () =
×
UNCOV
1418
              match !mina_ref with
×
1419
              | None ->
×
1420
                  Deferred.return None
1421
              | Some mina ->
×
UNCOV
1422
                  let%map node_state = Mina_lib.get_node_state mina in
×
1423
                  Some node_state
×
1424
            in
1425
            Node_error_service.set_config ~get_node_state
UNCOV
1426
              ~node_error_url:(Uri.of_string url) ~contact_info ) ;
×
UNCOV
1427
        Mina_run.handle_shutdown ~monitor ~time_controller ~conf_dir
×
1428
          ~child_pids:pids ~top_logger:logger mina_ref ;
1429
        Async.Scheduler.within' ~monitor
×
1430
        @@ fun () ->
1431
        let%bind { mina
1432
                 ; client_trustlist
1433
                 ; rest_server_port
1434
                 ; limited_graphql_port
1435
                 ; itn_graphql_port
1436
                 } =
UNCOV
1437
          mina_initialization_deferred ()
×
1438
        in
1439
        mina_ref := Some mina ;
×
1440
        (*This pipe is consumed only by integration tests*)
1441
        don't_wait_for
UNCOV
1442
          (Pipe_lib.Strict_pipe.Reader.iter_without_pushback
×
UNCOV
1443
             (Mina_lib.validated_transitions mina)
×
1444
             ~f:ignore ) ;
1445
        Mina_run.setup_local_server ?client_trustlist ~rest_server_port
×
1446
          ~insecure_rest_server ~open_limited_graphql_port ?limited_graphql_port
1447
          ?itn_graphql_port ?auth_keys:itn_keys mina ;
1448
        let%bind () =
1449
          Option.map metrics_server_port ~f:(fun port ->
UNCOV
1450
              let forward_uri =
×
1451
                Option.map libp2p_metrics_port ~f:(fun port ->
1452
                    Uri.with_uri ~scheme:(Some "http") ~host:(Some "127.0.0.1")
×
1453
                      ~port:(Some port) ~path:(Some "/metrics") Uri.empty )
1454
              in
UNCOV
1455
              Mina_metrics.Runtime.(
×
1456
                gc_stat_interval_mins :=
1457
                  Option.value ~default:!gc_stat_interval_mins gc_stat_interval) ;
×
UNCOV
1458
              Mina_metrics.server ?forward_uri ~port ~logger () >>| ignore )
×
1459
          |> Option.value ~default:Deferred.unit
×
1460
        in
1461
        let () = Mina_plugins.init_plugins ~logger mina plugins in
×
UNCOV
1462
        return mina )
×
1463

1464
let daemon logger ~itn_features =
1465
  let compile_config = Mina_compile_config.Compiled.t in
49✔
1466
  Command.async ~summary:"Mina daemon"
1467
    (Command.Param.map
49✔
1468
       (setup_daemon logger ~itn_features
49✔
1469
          ~default_snark_worker_fee:compile_config.default_snark_worker_fee )
1470
       ~f:(fun setup_daemon () ->
1471
         (* Immediately disable updating the time offset. *)
UNCOV
1472
         Block_time.Controller.disable_setting_offset () ;
×
UNCOV
1473
         let%bind mina = setup_daemon () in
×
1474
         let%bind () = Mina_lib.start mina in
×
1475
         [%log info] "Daemon ready. Clients can now connect" ;
×
1476
         Async.never () ) )
×
1477

1478
let replay_blocks logger ~itn_features =
1479
  let replay_flag =
49✔
1480
    let open Command.Param in
1481
    flag "--blocks-filename" ~aliases:[ "-blocks-filename" ] (required string)
49✔
1482
      ~doc:"PATH The file to read the precomputed blocks from"
1483
  in
1484
  let read_kind =
1485
    let open Command.Param in
1486
    flag "--format" ~aliases:[ "-format" ] (optional string)
49✔
1487
      ~doc:"json|sexp The format to read lines of the file in (default: json)"
1488
  in
1489
  let compile_config = Mina_compile_config.Compiled.t in
1490
  Command.async ~summary:"Start mina daemon with blocks replayed from a file"
1491
    (Command.Param.map3 replay_flag read_kind
49✔
1492
       (setup_daemon logger ~itn_features
49✔
1493
          ~default_snark_worker_fee:compile_config.default_snark_worker_fee )
1494
       ~f:(fun blocks_filename read_kind setup_daemon () ->
1495
         (* Enable updating the time offset. *)
UNCOV
1496
         Block_time.Controller.enable_setting_offset () ;
×
UNCOV
1497
         let read_block_line =
×
1498
           match Option.map ~f:String.lowercase read_kind with
1499
           | Some "json" | None -> (
×
1500
               fun line ->
1501
                 match
×
1502
                   Yojson.Safe.from_string line
1503
                   |> Mina_block.Precomputed.of_yojson
×
1504
                 with
1505
                 | Ok block ->
×
1506
                     block
1507
                 | Error err ->
×
1508
                     failwithf "Could not read block: %s" err () )
1509
           | Some "sexp" ->
×
1510
               fun line ->
1511
                 Sexp.of_string_conv_exn line Mina_block.Precomputed.t_of_sexp
×
UNCOV
1512
           | _ ->
×
1513
               failwith "Expected one of 'json', 'sexp' for -format flag"
1514
         in
1515
         let blocks =
UNCOV
1516
           Sequence.unfold ~init:(In_channel.create blocks_filename)
×
1517
             ~f:(fun blocks_file ->
1518
               match In_channel.input_line blocks_file with
×
UNCOV
1519
               | Some line ->
×
1520
                   Some (read_block_line line, blocks_file)
×
1521
               | None ->
×
1522
                   In_channel.close blocks_file ;
1523
                   None )
×
1524
         in
1525
         let%bind mina = setup_daemon () in
×
UNCOV
1526
         let%bind () = Mina_lib.start_with_precomputed_blocks mina blocks in
×
1527
         [%log info]
×
1528
           "Daemon is ready, replayed precomputed blocks. Clients can now \
1529
            connect" ;
UNCOV
1530
         Async.never () ) )
×
1531

1532
let dump_type_shapes =
1533
  let max_depth_flag =
1534
    let open Command.Param in
1535
    flag "--max-depth" ~aliases:[ "-max-depth" ] (optional int)
49✔
1536
      ~doc:"NN Maximum depth of shape S-expressions"
1537
  in
1538
  Command.basic ~summary:"Print serialization shapes of versioned types"
49✔
1539
    (Command.Param.map max_depth_flag ~f:(fun max_depth () ->
49✔
UNCOV
1540
         Ppx_version_runtime.Shapes.iteri
×
1541
           ~f:(fun ~key:path ~data:(shape, ty_decl) ->
1542
             let open Bin_prot.Shape in
×
1543
             let canonical = eval shape in
1544
             let digest = Canonical.to_digest canonical |> Digest.to_hex in
×
UNCOV
1545
             let shape_summary =
×
1546
               let shape_sexp =
1547
                 Canonical.to_string_hum canonical |> Sexp.of_string
×
1548
               in
1549
               (* elide the shape below specified depth, so that changes to
1550
                  contained types aren't considered a change to the containing
1551
                  type, even though the shape digests differ
1552
               *)
UNCOV
1553
               let summary_sexp =
×
1554
                 match max_depth with
1555
                 | None ->
×
1556
                     shape_sexp
1557
                 | Some n ->
×
1558
                     let rec go sexp depth =
1559
                       if depth > n then Sexp.Atom "."
×
1560
                       else
1561
                         match sexp with
×
UNCOV
1562
                         | Sexp.Atom _ ->
×
1563
                             sexp
1564
                         | Sexp.List items ->
×
1565
                             Sexp.List
1566
                               (List.map items ~f:(fun item ->
×
UNCOV
1567
                                    go item (depth + 1) ) )
×
1568
                     in
1569
                     go shape_sexp 0
×
1570
               in
1571
               Sexp.to_string summary_sexp
×
1572
             in
1573
             Core_kernel.printf "%s, %s, %s, %s\n" path digest shape_summary
1574
               ty_decl ) ) )
1575

1576
let primitive_ok = function
UNCOV
1577
  | "array" | "bytes" | "string" | "bigstring" ->
×
1578
      false
1579
  | "int" | "int32" | "int64" | "nativeint" | "char" | "bool" | "float" ->
×
1580
      true
1581
  | "unit" | "option" | "list" ->
×
1582
      true
1583
  | "kimchi_backend_bigint_32_V1" ->
×
1584
      true
1585
  | "Mina_stdlib.Bounded_types.String.t"
×
UNCOV
1586
  | "Mina_stdlib.Bounded_types.String.Tagged.t"
×
1587
  | "Mina_stdlib.Bounded_types.Array.t" ->
×
1588
      true
1589
  | "8fabab0a-4992-11e6-8cca-9ba2c4686d9e" ->
×
1590
      true (* hashtbl *)
1591
  | "ac8a9ff4-4994-11e6-9a1b-9fb4e933bd9d" ->
×
1592
      true (* Make_iterable_binable *)
1593
  | s ->
×
1594
      failwithf "unknown primitive %s" s ()
1595

1596
let audit_type_shapes : Command.t =
1597
  let rec shape_ok (shape : Sexp.t) : bool =
UNCOV
1598
    match shape with
×
UNCOV
1599
    | List [ Atom "Exp"; exp ] ->
×
1600
        exp_ok exp
1601
    | List [] ->
×
1602
        true
1603
    | _ ->
×
UNCOV
1604
        failwithf "bad shape: %s" (Sexp.to_string shape) ()
×
1605
  and exp_ok (exp : Sexp.t) : bool =
1606
    match exp with
×
UNCOV
1607
    | List [ Atom "Base"; Atom tyname; List exps ] ->
×
1608
        primitive_ok tyname && List.for_all exps ~f:shape_ok
×
1609
    | List [ Atom "Record"; List fields ] ->
×
1610
        List.for_all fields ~f:(fun field ->
1611
            match field with
×
UNCOV
1612
            | List [ Atom _; sh ] ->
×
1613
                shape_ok sh
1614
            | _ ->
×
UNCOV
1615
                failwithf "unhandled rec field: %s" (Sexp.to_string_hum field)
×
1616
                  () )
1617
    | List [ Atom "Tuple"; List exps ] ->
×
1618
        List.for_all exps ~f:shape_ok
1619
    | List [ Atom "Variant"; List ctors ] ->
×
1620
        List.for_all ctors ~f:(fun ctor ->
1621
            match ctor with
×
UNCOV
1622
            | List [ Atom _ctr; List exps ] ->
×
1623
                List.for_all exps ~f:shape_ok
1624
            | _ ->
×
UNCOV
1625
                failwithf "unhandled variant: %s" (Sexp.to_string_hum ctor) () )
×
1626
    | List [ Atom "Poly_variant"; List [ List [ Atom "sorted"; List ctors ] ] ]
×
1627
      ->
1628
        List.for_all ctors ~f:(fun ctor ->
UNCOV
1629
            match ctor with
×
UNCOV
1630
            | List [ Atom _ctr ] ->
×
1631
                true
1632
            | List [ Atom _ctr; List fields ] ->
×
1633
                List.for_all fields ~f:shape_ok
1634
            | _ ->
×
UNCOV
1635
                failwithf "unhandled poly variant: %s" (Sexp.to_string_hum ctor)
×
1636
                  () )
1637
    | List [ Atom "Application"; sh; List args ] ->
×
UNCOV
1638
        shape_ok sh && List.for_all args ~f:shape_ok
×
1639
    | List [ Atom "Rec_app"; Atom _; List args ] ->
×
1640
        List.for_all args ~f:shape_ok
1641
    | List [ Atom "Var"; Atom _ ] ->
×
1642
        true
1643
    | List (Atom ctr :: _) ->
×
1644
        failwithf "unhandled ctor (%s) in exp_ok: %s" ctr
1645
          (Sexp.to_string_hum exp) ()
×
UNCOV
1646
    | List [] | List _ | Atom _ ->
×
1647
        failwithf "bad format: %s" (Sexp.to_string_hum exp) ()
×
1648
  in
1649
  let handle_shape (path : string) (shape : Bin_prot.Shape.t) (ty_decl : string)
1650
      (good : int ref) (bad : int ref) =
UNCOV
1651
    let open Bin_prot.Shape in
×
1652
    let path, file = String.lsplit2_exn ~on:':' path in
1653
    let canonical = eval shape in
×
UNCOV
1654
    let shape_sexp = Canonical.to_string_hum canonical |> Sexp.of_string in
×
1655
    if not @@ shape_ok shape_sexp then (
×
1656
      incr bad ;
1657
      Core.eprintf "%s has a bad shape in %s (%s):\n%s\n" path file ty_decl
×
UNCOV
1658
        (Canonical.to_string_hum canonical) )
×
1659
    else incr good
×
1660
  in
1661
  Command.basic ~summary:"Audit shapes of versioned types"
49✔
1662
    (Command.Param.return (fun () ->
49✔
UNCOV
1663
         let bad, good = (ref 0, ref 0) in
×
1664
         Ppx_version_runtime.Shapes.iteri
1665
           ~f:(fun ~key:path ~data:(shape, ty_decl) ->
UNCOV
1666
             handle_shape path shape ty_decl good bad ) ;
×
1667
         Core.printf "good shapes:\n\t%d\nbad shapes:\n\t%d\n%!" !good !bad ;
1668
         if !bad > 0 then Core.exit 1 ) )
×
1669

1670
(*NOTE A previous version of this function included compile time ppx that didn't compile, and was never
1671
  evaluated under any build profile
1672
*)
1673
let ensure_testnet_id_still_good _ = Deferred.unit
49✔
1674

1675
let snark_hashes =
1676
  let module Hashes = struct
UNCOV
1677
    type t = string list [@@deriving to_yojson]
×
1678
  end in
1679
  let open Command.Let_syntax in
1680
  Command.basic ~summary:"List hashes of proving and verification keys"
49✔
1681
    [%map_open
1682
      let json = Cli_lib.Flag.json in
UNCOV
1683
      fun () -> if json then Core.printf "[]\n%!"]
×
1684

1685
let internal_commands logger ~itn_features =
1686
  [ ( Snark_worker.Intf.command_name
49✔
1687
    , Snark_worker.command ~proof_level:Genesis_constants.Compiled.proof_level
1688
        ~constraint_constants:Genesis_constants.Compiled.constraint_constants
1689
        ~commit_id:Mina_version.commit_id )
1690
  ; ("snark-hashes", snark_hashes)
1691
  ; ( "run-prover"
1692
    , Command.async
49✔
1693
        ~summary:"Run prover on a sexp provided on a single line of stdin"
1694
        (Command.Param.return (fun () ->
49✔
UNCOV
1695
             let logger = Logger.create () in
×
UNCOV
1696
             let constraint_constants =
×
1697
               Genesis_constants.Compiled.constraint_constants
1698
             in
1699
             let proof_level = Genesis_constants.Compiled.proof_level in
1700
             Parallel.init_master () ;
UNCOV
1701
             match%bind Reader.read_sexp (Lazy.force Reader.stdin) with
×
UNCOV
1702
             | `Ok sexp ->
×
1703
                 let%bind conf_dir = Unix.mkdtemp "/tmp/mina-prover" in
×
1704
                 [%log info] "Prover state being logged to %s" conf_dir ;
×
1705
                 let%bind prover =
1706
                   Prover.create ~commit_id:Mina_version.commit_id ~logger
×
1707
                     ~proof_level ~constraint_constants
1708
                     ~pids:(Pid.Table.create ()) ~conf_dir
×
1709
                     ~signature_kind:Mina_signature_kind.t_DEPRECATED ()
1710
                 in
UNCOV
1711
                 Prover.prove_from_input_sexp prover sexp >>| ignore
×
UNCOV
1712
             | `Eof ->
×
1713
                 failwith "early EOF while reading sexp" ) ) )
1714
  ; ( "run-snark-worker-single"
1715
    , Command.async
49✔
1716
        ~summary:"Run snark-worker on a sexp provided on a single line of stdin"
1717
        (let open Command.Let_syntax in
1718
        let%map_open filename =
1719
          flag "--file" (required string)
49✔
1720
            ~doc:"File containing the s-expression of the snark work to execute"
1721
        in
1722
        fun () ->
UNCOV
1723
          let open Deferred.Let_syntax in
×
1724
          let logger = Logger.create () in
1725
          let constraint_constants =
×
1726
            Genesis_constants.Compiled.constraint_constants
1727
          in
1728
          let proof_level = Genesis_constants.Compiled.proof_level in
1729
          Parallel.init_master () ;
1730
          match%bind
UNCOV
1731
            Reader.with_file filename ~f:(fun reader ->
×
UNCOV
1732
                [%log info] "Created reader for %s" filename ;
×
1733
                Reader.read_sexp reader )
×
1734
          with
1735
          | `Ok sexp -> (
×
1736
              let signature_kind = Mina_signature_kind.t_DEPRECATED in
1737
              let%bind worker_state =
UNCOV
1738
                Snark_worker.Inputs.Worker_state.create ~proof_level
×
1739
                  ~constraint_constants ~signature_kind ()
1740
              in
UNCOV
1741
              let sok_message =
×
UNCOV
1742
                { Mina_base.Sok_message.fee = Currency.Fee.of_mina_int_exn 0
×
1743
                ; prover = Quickcheck.random_value Public_key.Compressed.gen
×
1744
                }
1745
              in
1746
              let spec =
1747
                [%of_sexp:
1748
                  ( Transaction_witness.Stable.Latest.t
1749
                  , Ledger_proof.t )
1750
                  Snark_work_lib.Work.Single.Spec.t] sexp
1751
              in
1752
              match%map
UNCOV
1753
                Snark_worker.Inputs.perform_single worker_state
×
1754
                  ~message:sok_message spec
1755
              with
UNCOV
1756
              | Ok _ ->
×
UNCOV
1757
                  [%log info] "Successfully worked"
×
1758
              | Error err ->
×
1759
                  [%log error] "Work didn't work: $err"
×
1760
                    ~metadata:[ ("err", Error_json.error_to_yojson err) ] )
×
1761
          | `Eof ->
×
1762
              failwith "early EOF while reading sexp") )
1763
  ; ( "run-verifier"
1764
    , Command.async
49✔
1765
        ~summary:"Run verifier on a proof provided on a single line of stdin"
1766
        (let open Command.Let_syntax in
1767
        let%map_open mode =
1768
          flag "--mode" ~aliases:[ "-mode" ] (required string)
49✔
1769
            ~doc:"transaction/blockchain the snark to verify. Defaults to json"
1770
        and format =
1771
          flag "--format" ~aliases:[ "-format" ] (optional string)
49✔
1772
            ~doc:"sexp/json the format to parse input in"
1773
        and limit =
1774
          flag "--limit" ~aliases:[ "-limit" ] (optional int)
49✔
1775
            ~doc:"limit the number of proofs taken from the file"
1776
        in
1777
        fun () ->
UNCOV
1778
          let open Async in
×
1779
          let logger = Logger.create () in
1780
          let constraint_constants =
×
1781
            Genesis_constants.Compiled.constraint_constants
1782
          in
1783
          let proof_level = Genesis_constants.Compiled.proof_level in
1784
          Parallel.init_master () ;
UNCOV
1785
          let%bind conf_dir = Unix.mkdtemp "/tmp/mina-verifier" in
×
UNCOV
1786
          let mode =
×
1787
            match mode with
1788
            | "transaction" ->
×
1789
                `Transaction
1790
            | "blockchain" ->
×
1791
                `Blockchain
1792
            | mode ->
×
UNCOV
1793
                failwithf
×
1794
                  "Expected mode flag to be one of transaction, blockchain, \
1795
                   got '%s'"
1796
                  mode ()
1797
          in
1798
          let format =
1799
            match format with
UNCOV
1800
            | Some "sexp" ->
×
1801
                `Sexp
1802
            | Some "json" | None ->
×
1803
                `Json
1804
            | Some format ->
×
UNCOV
1805
                failwithf
×
1806
                  "Expected format flag to be one of sexp, json, got '%s'"
1807
                  format ()
1808
          in
1809
          let%bind input =
1810
            match format with
UNCOV
1811
            | `Sexp -> (
×
1812
                let%map input_sexp =
1813
                  match%map Reader.read_sexp (Lazy.force Reader.stdin) with
×
UNCOV
1814
                  | `Ok input_sexp ->
×
1815
                      input_sexp
1816
                  | `Eof ->
×
1817
                      failwith "early EOF while reading sexp"
1818
                in
UNCOV
1819
                match mode with
×
UNCOV
1820
                | `Transaction ->
×
1821
                    `Transaction
1822
                      (List.t_of_sexp
×
UNCOV
1823
                         (Tuple2.t_of_sexp Ledger_proof.t_of_sexp
×
1824
                            Sok_message.t_of_sexp )
1825
                         input_sexp )
UNCOV
1826
                | `Blockchain ->
×
1827
                    `Blockchain
1828
                      (List.t_of_sexp Blockchain_snark.Blockchain.t_of_sexp
×
1829
                         input_sexp ) )
1830
            | `Json -> (
×
1831
                let%map input_line =
1832
                  match%map Reader.read_line (Lazy.force Reader.stdin) with
×
UNCOV
1833
                  | `Ok input_line ->
×
1834
                      input_line
1835
                  | `Eof ->
×
1836
                      failwith "early EOF while reading json"
1837
                in
UNCOV
1838
                match mode with
×
UNCOV
1839
                | `Transaction -> (
×
1840
                    match
1841
                      [%derive.of_yojson: (Ledger_proof.t * Sok_message.t) list]
×
UNCOV
1842
                        (Yojson.Safe.from_string input_line)
×
1843
                    with
1844
                    | Ok input ->
×
1845
                        `Transaction input
1846
                    | Error err ->
×
1847
                        failwithf "Could not parse JSON: %s" err () )
1848
                | `Blockchain -> (
×
1849
                    match
1850
                      [%derive.of_yojson: Blockchain_snark.Blockchain.t list]
×
UNCOV
1851
                        (Yojson.Safe.from_string input_line)
×
1852
                    with
1853
                    | Ok input ->
×
1854
                        `Blockchain input
1855
                    | Error err ->
×
1856
                        failwithf "Could not parse JSON: %s" err () ) )
1857
          in
1858

1859
          let%bind verifier =
UNCOV
1860
            Verifier.For_tests.default ~constraint_constants ~proof_level
×
1861
              ~commit_id:Mina_version.commit_id ~logger
1862
              ~pids:(Pid.Table.create ()) ~conf_dir:(Some conf_dir) ()
×
1863
          in
1864
          let%bind result =
1865
            let cap lst =
UNCOV
1866
              Option.value_map ~default:Fn.id ~f:(Fn.flip List.take) limit lst
×
1867
            in
1868
            match input with
UNCOV
1869
            | `Transaction input ->
×
UNCOV
1870
                input |> cap |> Verifier.verify_transaction_snarks verifier
×
1871
            | `Blockchain input ->
×
1872
                input |> cap |> Verifier.verify_blockchain_snarks verifier
×
1873
          in
1874
          match result with
×
UNCOV
1875
          | Ok (Ok ()) ->
×
1876
              printf "Proofs verified successfully" ;
1877
              exit 0
×
UNCOV
1878
          | Ok (Error err) ->
×
1879
              printf "Proofs failed to verify:\n%s\n"
1880
                (Yojson.Safe.pretty_to_string (Error_json.error_to_yojson err)) ;
×
UNCOV
1881
              exit 1
×
1882
          | Error err ->
×
1883
              printf "Failed while verifying proofs:\n%s"
1884
                (Error.to_string_hum err) ;
×
UNCOV
1885
              exit 2) )
×
1886
  ; ( "dump-structured-events"
1887
    , Command.async ~summary:"Dump the registered structured events"
49✔
1888
        (let open Command.Let_syntax in
1889
        let%map outfile =
1890
          Core_kernel.Command.Param.flag "--out-file" ~aliases:[ "-out-file" ]
49✔
1891
            (Core_kernel.Command.Flag.optional Core_kernel.Command.Param.string)
49✔
1892
            ~doc:"FILENAME File to output to. Defaults to stdout"
1893
        and pretty =
1894
          Core_kernel.Command.Param.flag "--pretty" ~aliases:[ "-pretty" ]
49✔
1895
            Core_kernel.Command.Param.no_arg
1896
            ~doc:"  Set to output 'pretty' JSON"
1897
        in
1898
        fun () ->
UNCOV
1899
          let out_channel =
×
1900
            match outfile with
1901
            | Some outfile ->
×
UNCOV
1902
                Core_kernel.Out_channel.create outfile
×
1903
            | None ->
×
1904
                Core_kernel.Out_channel.stdout
1905
          in
1906
          let json =
1907
            Structured_log_events.dump_registered_events ()
1908
            |> [%derive.to_yojson:
UNCOV
1909
                 (string * Structured_log_events.id * string list) list]
×
1910
          in
1911
          if pretty then Yojson.Safe.pretty_to_channel out_channel json
×
UNCOV
1912
          else Yojson.Safe.to_channel out_channel json ;
×
1913
          ( match outfile with
1914
          | Some _ ->
×
UNCOV
1915
              Core_kernel.Out_channel.close out_channel
×
1916
          | None ->
×
1917
              () ) ;
1918
          Deferred.return ()) )
1919
  ; ("dump-type-shapes", dump_type_shapes)
1920
  ; ("replay-blocks", replay_blocks logger ~itn_features)
49✔
1921
  ; ("audit-type-shapes", audit_type_shapes)
1922
  ; ( "test-genesis-block-generation"
1923
    , Command.async ~summary:"Generate a genesis proof"
49✔
1924
        (let open Command.Let_syntax in
1925
        let%map_open config_files =
1926
          flag "--config-file" ~aliases:[ "config-file" ]
49✔
1927
            ~doc:
1928
              "PATH path to a configuration file (overrides MINA_CONFIG_FILE, \
1929
               default: <config_dir>/daemon.json). Pass multiple times to \
1930
               override fields from earlier config files"
1931
            (listed string)
49✔
1932
        and conf_dir = Cli_lib.Flag.conf_dir
1933
        and genesis_dir =
1934
          flag "--genesis-ledger-dir" ~aliases:[ "genesis-ledger-dir" ]
49✔
1935
            ~doc:
1936
              "DIR Directory that contains the genesis ledger and the genesis \
1937
               blockchain proof (default: <config-dir>)"
1938
            (optional string)
49✔
1939
        in
1940
        fun () ->
UNCOV
1941
          let open Deferred.Let_syntax in
×
1942
          Parallel.init_master () ;
1943
          let logger = Logger.create () in
×
UNCOV
1944
          let conf_dir = Mina_lib.Conf_dir.compute_conf_dir conf_dir in
×
1945
          let genesis_constants =
×
1946
            Genesis_constants.Compiled.genesis_constants
1947
          in
1948
          let constraint_constants =
1949
            Genesis_constants.Compiled.constraint_constants
1950
          in
1951
          let proof_level = Genesis_constants.Proof_level.Full in
1952
          let config_files =
1953
            List.map config_files ~f:(fun config_file ->
UNCOV
1954
                (config_file, `Must_exist) )
×
1955
          in
1956
          let%bind precomputed_values, _config_jsons, _config =
UNCOV
1957
            load_config_files ~logger ~conf_dir ~genesis_dir ~genesis_constants
×
1958
              ~constraint_constants ~proof_level config_files
1959
              ~cli_proof_level:None
1960
          in
UNCOV
1961
          let pids = Child_processes.Termination.create_pid_table () in
×
1962
          let%bind prover =
1963
            (* We create a prover process (unnecessarily) here, to have a more
1964
               realistic test.
1965
            *)
UNCOV
1966
            Prover.create ~commit_id:Mina_version.commit_id ~logger ~pids
×
1967
              ~conf_dir ~proof_level
1968
              ~constraint_constants:precomputed_values.constraint_constants
1969
              ~signature_kind:Mina_signature_kind.t_DEPRECATED ()
1970
          in
1971
          match%bind
UNCOV
1972
            Prover.create_genesis_block prover
×
UNCOV
1973
              (Genesis_proof.to_inputs precomputed_values)
×
1974
          with
1975
          | Ok block ->
×
1976
              Format.eprintf "Generated block@.%s@."
1977
                ( Yojson.Safe.to_string
×
UNCOV
1978
                @@ Blockchain_snark.Blockchain.to_yojson block ) ;
×
1979
              exit 0
×
1980
          | Error err ->
×
1981
              Format.eprintf "Failed to generate block@.%s@."
1982
                (Yojson.Safe.to_string @@ Error_json.error_to_yojson err) ;
×
UNCOV
1983
              exit 1) )
×
1984
  ]
1985

1986
let mina_commands logger ~itn_features =
1987
  [ ("accounts", Client.accounts)
49✔
1988
  ; ("daemon", daemon logger ~itn_features)
49✔
1989
  ; ("client", Client.client)
1990
  ; ("advanced", Client.advanced ~itn_features)
1991
  ; ("ledger", Client.ledger)
1992
  ; ("libp2p", Client.libp2p)
1993
  ; ( "internal"
1994
    , Command.group ~summary:"Internal commands"
49✔
1995
        (internal_commands logger ~itn_features) )
49✔
1996
  ; (Parallel.worker_command_name, Parallel.worker_command)
1997
  ; ("transaction-snark-profiler", Transaction_snark_profiler.command)
1998
  ]
1999

2000
let print_version_help coda_exe version =
2001
  (* mimic Jane Street command help *)
UNCOV
2002
  let lines =
×
2003
    [ "print version information"
2004
    ; ""
UNCOV
2005
    ; sprintf "  %s %s" (Filename.basename coda_exe) version
×
2006
    ; ""
2007
    ; "=== flags ==="
2008
    ; ""
2009
    ; "  [-help]  print this help text and exit"
2010
    ; "           (alias: -?)"
2011
    ]
2012
  in
UNCOV
2013
  List.iter lines ~f:(Core.printf "%s\n%!")
×
2014

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

2017
let () =
2018
  Random.self_init () ;
2019
  let itn_features = Sys.getenv "ITN_FEATURES" |> Option.is_some in
49✔
2020
  let logger = Logger.create ~itn_features () in
49✔
2021
  don't_wait_for (ensure_testnet_id_still_good logger) ;
49✔
2022
  (* Turn on snark debugging in prod for now *)
2023
  Snarky_backendless.Snark.set_eval_constraints true ;
49✔
2024
  (* intercept command-line processing for "version", because we don't
2025
     use the Jane Street scripts that generate their version information
2026
  *)
2027
  (let is_version_cmd s =
49✔
UNCOV
2028
     List.mem [ "version"; "-version"; "--version" ] s ~equal:String.equal
×
2029
   in
2030
   match Sys.get_argv () with
UNCOV
2031
   | [| _mina_exe; version |] when is_version_cmd version ->
×
UNCOV
2032
       Mina_version.print_version ()
×
2033
   | _ ->
49✔
2034
       Command.run
×
2035
         (Command.group ~summary:"Mina" ~preserve_subcommand_order:()
49✔
2036
            (mina_commands logger ~itn_features) ) ) ;
49✔
UNCOV
2037
  Core.exit 0
×
2038

2039
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