dfx_core/config/model/
dfinity.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
#![allow(dead_code)]
#![allow(clippy::should_implement_trait)] // for from_str.  why now?
use crate::config::directories::get_user_dfx_config_dir;
use crate::config::model::bitcoin_adapter::BitcoinAdapterLogLevel;
use crate::config::model::canister_http_adapter::HttpAdapterLogLevel;
use crate::config::model::extension_canister_type::apply_extension_canister_types;
use crate::error::config::{GetOutputEnvFileError, GetTempPathError};
use crate::error::dfx_config::AddDependenciesError::CanisterCircularDependency;
use crate::error::dfx_config::GetCanisterNamesWithDependenciesError::AddDependenciesFailed;
use crate::error::dfx_config::GetComputeAllocationError::GetComputeAllocationFailed;
use crate::error::dfx_config::GetFreezingThresholdError::GetFreezingThresholdFailed;
use crate::error::dfx_config::GetLogVisibilityError::GetLogVisibilityFailed;
use crate::error::dfx_config::GetMemoryAllocationError::GetMemoryAllocationFailed;
use crate::error::dfx_config::GetPullCanistersError::PullCanistersSameId;
use crate::error::dfx_config::GetRemoteCanisterIdError::GetRemoteCanisterIdFailed;
use crate::error::dfx_config::GetReservedCyclesLimitError::GetReservedCyclesLimitFailed;
use crate::error::dfx_config::GetSpecifiedIdError::GetSpecifiedIdFailed;
use crate::error::dfx_config::GetWasmMemoryLimitError::GetWasmMemoryLimitFailed;
use crate::error::dfx_config::{
    AddDependenciesError, GetCanisterConfigError, GetCanisterNamesWithDependenciesError,
    GetComputeAllocationError, GetFreezingThresholdError, GetLogVisibilityError,
    GetMemoryAllocationError, GetPullCanistersError, GetRemoteCanisterIdError,
    GetReservedCyclesLimitError, GetSpecifiedIdError, GetWasmMemoryLimitError,
};
use crate::error::fs::CanonicalizePathError;
use crate::error::load_dfx_config::LoadDfxConfigError;
use crate::error::load_dfx_config::LoadDfxConfigError::{
    DetermineCurrentWorkingDirFailed, ResolveConfigPath,
};
use crate::error::load_networks_config::LoadNetworksConfigError;
use crate::error::load_networks_config::LoadNetworksConfigError::{
    GetConfigPathFailed, LoadConfigFromFileFailed,
};
use crate::error::socket_addr_conversion::SocketAddrConversionError;
use crate::error::socket_addr_conversion::SocketAddrConversionError::{
    EmptyIterator, ParseSocketAddrFailed,
};
use crate::error::structured_file::StructuredFileError;
use crate::error::structured_file::StructuredFileError::DeserializeJsonFileFailed;
use crate::extension::manager::ExtensionManager;
use crate::fs::create_dir_all;
use crate::json::save_json_file;
use crate::json::structure::{PossiblyStr, SerdeVec};
use crate::util::ByteSchema;
use byte_unit::Byte;
use candid::Principal;
use ic_utils::interfaces::management_canister::LogVisibility;
use schemars::JsonSchema;
use serde::de::{Error as _, MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::default::Default;
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::time::Duration;

use super::network_descriptor::MOTOKO_PLAYGROUND_CANISTER_TIMEOUT_SECONDS;

pub const CONFIG_FILE_NAME: &str = "dfx.json";

pub const BUILTIN_CANISTER_TYPES: [&str; 5] = ["rust", "motoko", "assets", "custom", "pull"];

const EMPTY_CONFIG_DEFAULTS: ConfigDefaults = ConfigDefaults {
    bitcoin: None,
    bootstrap: None,
    build: None,
    canister_http: None,
    proxy: None,
    replica: None,
};

const EMPTY_CONFIG_DEFAULTS_BUILD: ConfigDefaultsBuild = ConfigDefaultsBuild {
    packtool: None,
    args: None,
};

/// # Remote Canister Configuration
/// This field allows canisters to be marked 'remote' for certain networks.
/// On networks where this canister contains a remote ID, the canister is not deployed.
/// Instead it is assumed to exist already under control of a different project.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct ConfigCanistersCanisterRemote {
    /// # Remote Candid File
    /// On networks where this canister is marked 'remote', this candid file is used instead of the one declared in the canister settings.
    pub candid: Option<PathBuf>,

    /// # Network to Remote ID Mapping
    /// This field contains mappings from network names to remote canister IDs (Principals).
    /// For all networks listed here, this canister is considered 'remote'.
    #[schemars(with = "BTreeMap<String, String>")]
    pub id: BTreeMap<String, Principal>,
}

/// # Wasm Optimization Levels
/// Wasm optimization levels that are passed to `wasm-opt`. "cycles" defaults to O3, "size" defaults to Oz.
/// O4 through O0 focus on performance (with O0 performing no optimizations), and Oz and Os focus on reducing binary size, where Oz is more aggressive than Os.
/// O3 and Oz empirically give best cycle savings and code size savings respectively.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum WasmOptLevel {
    #[serde(rename = "cycles")]
    Cycles,
    #[serde(rename = "size")]
    Size,
    O4,
    O3,
    O2,
    O1,
    O0,
    Oz,
    Os,
}
impl std::fmt::Display for WasmOptLevel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        std::fmt::Debug::fmt(self, f)
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "lowercase")]
pub enum MetadataVisibility {
    /// Anyone can query the metadata
    #[default]
    Public,

    /// Only the controllers of the canister can query the metadata.
    Private,
}

/// # Canister Metadata Configuration
/// Configures a custom metadata section for the canister wasm.
/// dfx uses the first definition of a given name matching the current network, ignoring any of the same name that follow.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct CanisterMetadataSection {
    /// # Name
    /// The name of the wasm section
    pub name: String,

    /// # Visibility
    #[serde(default)]
    pub visibility: MetadataVisibility,

    /// # Networks
    /// Networks this section applies to.
    /// If this field is absent, then it applies to all networks.
    /// An empty array means this element will not apply to any network.
    pub networks: Option<BTreeSet<String>>,

    /// # Path
    /// Path to file containing section contents.
    /// Conflicts with `content`.
    /// For sections with name=`candid:service`, this field is optional, and if not specified, dfx will use
    /// the canister's candid definition.
    /// If specified for a Motoko canister, the service defined in the specified path must be a valid subtype of the canister's
    /// actual candid service definition.
    pub path: Option<PathBuf>,

    /// # Content
    /// Content of this metadata section.
    /// Conflicts with `path`.
    pub content: Option<String>,
}

impl CanisterMetadataSection {
    pub fn applies_to_network(&self, network: &str) -> bool {
        self.networks
            .as_ref()
            .map(|networks| networks.contains(network))
            .unwrap_or(true)
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct Pullable {
    /// # wasm_url
    /// The Url to download canister wasm.
    pub wasm_url: String,
    /// # wasm_hash
    /// SHA256 hash of the wasm module located at wasm_url.
    /// Only define this if the on-chain canister wasm is expected not to match the wasm at wasm_url.
    /// The hash can also be specified via a URL using the `wasm_hash_url` field.
    /// If both are defined, the `wasm_hash_url` field will be ignored.
    pub wasm_hash: Option<String>,
    /// # wasm_hash_url
    /// Specify the SHA256 hash of the wasm module via this URL.
    /// Only define this if the on-chain canister wasm is expected not to match the wasm at wasm_url.
    /// The hash can also be specified directly using the `wasm_hash` field.
    /// If both are defined, the `wasm_hash_url` field will be ignored.
    pub wasm_hash_url: Option<String>,
    /// # dependencies
    /// Canister IDs (Principal) of direct dependencies.
    #[schemars(with = "Vec::<String>")]
    pub dependencies: Vec<Principal>,
    /// # init_guide
    /// A message to guide consumers how to initialize the canister.
    pub init_guide: String,
    /// # init_arg
    /// A default initialization argument for the canister that consumers can use.
    pub init_arg: Option<String>,
}

pub type TechStackCategoryMap = HashMap<String, HashMap<String, String>>;

/// # Tech Stack
/// The tech stack used to build a canister.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct TechStack {
    /// # cdk
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cdk: Option<TechStackCategoryMap>,
    /// # language
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<TechStackCategoryMap>,
    /// # lib
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lib: Option<TechStackCategoryMap>,
    /// # tool
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool: Option<TechStackCategoryMap>,
    /// # other
    #[serde(skip_serializing_if = "Option::is_none")]
    pub other: Option<TechStackCategoryMap>,
}

pub const DEFAULT_SHARED_LOCAL_BIND: &str = "127.0.0.1:4943"; // hex for "IC"
pub const DEFAULT_PROJECT_LOCAL_BIND: &str = "127.0.0.1:8000";
pub const DEFAULT_IC_GATEWAY: &str = "https://icp0.io";
pub const DEFAULT_IC_GATEWAY_TRAILING_SLASH: &str = "https://icp0.io/";
pub const DEFAULT_REPLICA_PORT: u16 = 8080;

/// # Canister Configuration
/// Configurations for a single canister.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct ConfigCanistersCanister {
    /// # Declarations Configuration
    /// Defines which canister interface declarations to generate,
    /// and where to generate them.
    #[serde(default)]
    pub declarations: CanisterDeclarationsConfig,

    /// # Remote Configuration
    /// Used to mark the canister as 'remote' on certain networks.
    #[serde(default)]
    pub remote: Option<ConfigCanistersCanisterRemote>,

    /// # Canister-Specific Build Argument
    /// This field defines an additional argument to pass to the Motoko compiler when building the canister.
    pub args: Option<String>,

    /// # Resource Allocation Settings
    /// Defines initial values for resource allocation settings.
    #[serde(default)]
    pub initialization_values: InitializationValues,

    /// # Dependencies
    /// Defines on which canisters this canister depends on.
    #[serde(default)]
    pub dependencies: Vec<String>,

    /// # Force Frontend URL
    /// Mostly unused.
    /// If this value is not null, a frontend URL is displayed after deployment even if the canister type is not 'asset'.
    pub frontend: Option<BTreeMap<String, String>>,

    /// # Type-Specific Canister Properties
    /// Depending on the canister type, different fields are required.
    /// These are defined in this object.
    #[serde(flatten)]
    pub type_specific: CanisterTypeProperties,

    /// # Post-Install Commands
    /// One or more commands to run post canister installation.
    /// These commands are executed in the root of the project.
    #[serde(default)]
    pub post_install: SerdeVec<String>,

    /// # Path to Canister Entry Point
    /// Entry point for e.g. Motoko Compiler.
    pub main: Option<PathBuf>,

    /// # Shrink Canister Wasm
    /// Whether run `ic-wasm shrink` after building the Canister.
    /// Enabled by default for Rust/Motoko canisters.
    /// Disabled by default for custom canisters.
    pub shrink: Option<bool>,

    /// # Optimize Canister Wasm
    /// Invoke wasm level optimizations after building the canister. Optimization level can be set to "cycles" to optimize for cycle usage, "size" to optimize for binary size, or any of "O4, O3, O2, O1, O0, Oz, Os".
    /// Disabled by default.
    /// If this option is specified, the `shrink` option will be ignored.
    #[serde(default)]
    pub optimize: Option<WasmOptLevel>,

    /// # Metadata
    /// Defines metadata sections to set in the canister .wasm
    #[serde(default)]
    pub metadata: Vec<CanisterMetadataSection>,

    /// # Pullable
    /// Defines required properties so that this canister is ready for `dfx deps pull` by other projects.
    #[serde(default)]
    pub pullable: Option<Pullable>,

    /// # Tech Stack
    /// Defines the tech stack used to build this canister.
    #[serde(default)]
    pub tech_stack: Option<TechStack>,

    /// # Gzip Canister Wasm
    /// Disabled by default.
    pub gzip: Option<bool>,

    /// # Specified Canister ID
    /// Attempts to create the canister with this Canister ID.
    /// This option only works with non-mainnet replica.
    /// If the `--specified-id` argument is also provided, this `specified_id` field will be ignored.
    #[schemars(with = "Option<String>")]
    pub specified_id: Option<Principal>,

    /// # Init Arg
    /// The Candid initialization argument for installing the canister.
    /// If the `--argument` or `--argument-file` argument is also provided, this `init_arg` field will be ignored.
    pub init_arg: Option<String>,

    /// # Init Arg File
    /// The Candid initialization argument file for installing the canister.
    /// If the `--argument` or `--argument-file` argument is also provided, this `init_arg_file` field will be ignored.
    pub init_arg_file: Option<String>,
}

#[derive(Clone, Debug, Serialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CanisterTypeProperties {
    /// # Rust-Specific Properties
    Rust {
        /// # Package Name
        /// Name of the Rust package that compiles this canister's Wasm.
        package: String,

        /// # Crate name
        /// Name of the Rust crate that compiles to this canister's Wasm.
        /// If left unspecified, defaults to the crate with the same name as the package.
        #[serde(rename = "crate")]
        crate_name: Option<String>,

        /// # Candid File
        /// Path of this canister's candid interface declaration.
        candid: PathBuf,
    },
    /// # Asset-Specific Properties
    Assets {
        /// # Asset Source Folder
        /// Folders from which assets are uploaded.
        source: Vec<PathBuf>,

        /// # Build Commands
        /// Commands that are executed in order to produce this canister's assets.
        /// Expected to produce assets in one of the paths specified by the 'source' field.
        /// Optional if there is no build necessary or the assets can be built using the default `npm run build` command.
        #[schemars(default)]
        build: SerdeVec<String>,

        /// # NPM workspace
        /// The workspace in package.json that this canister is in, if it is not in the root workspace.
        workspace: Option<String>,
    },
    /// # Custom-Specific Properties
    Custom {
        /// # Wasm Path
        /// Path to Wasm to be installed. URLs to a Wasm module are also acceptable.
        /// A canister that has a URL to a Wasm module can not also have `build` steps.
        wasm: String,

        /// # Candid File
        /// Path to this canister's candid interface declaration.  A URL to a candid file is also acceptable.
        candid: String,

        /// # Build Commands
        /// Commands that are executed in order to produce this canister's Wasm module.
        /// Expected to produce the Wasm in the path specified by the 'wasm' field.
        /// No build commands are allowed if the `wasm` field is a URL.
        /// These commands are executed in the root of the project.
        #[schemars(default)]
        build: SerdeVec<String>,
    },
    /// # Motoko-Specific Properties
    Motoko,
    /// # Pull-Specific Properties
    Pull {
        /// # Canister ID
        /// Principal of the canister on the ic network.
        #[schemars(with = "String")]
        id: Principal,
    },
}

impl CanisterTypeProperties {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Rust { .. } => "rust",
            Self::Motoko { .. } => "motoko",
            Self::Assets { .. } => "assets",
            Self::Custom { .. } => "custom",
            Self::Pull { .. } => "pull",
        }
    }
}

#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CanisterLogVisibility {
    #[default]
    Controllers,
    Public,
    #[schemars(with = "Vec::<String>")]
    AllowedViewers(Vec<Principal>),
}

impl From<CanisterLogVisibility> for LogVisibility {
    fn from(value: CanisterLogVisibility) -> Self {
        match value {
            CanisterLogVisibility::Controllers => LogVisibility::Controllers,
            CanisterLogVisibility::Public => LogVisibility::Public,
            CanisterLogVisibility::AllowedViewers(viewers) => {
                LogVisibility::AllowedViewers(viewers)
            }
        }
    }
}

/// # Initial Resource Allocations
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct InitializationValues {
    /// # Compute Allocation
    /// Must be a number between 0 and 100, inclusively.
    /// It indicates how much compute power should be guaranteed to this canister, expressed as a percentage of the maximum compute power that a single canister can allocate.
    pub compute_allocation: Option<PossiblyStr<u64>>,

    /// # Memory Allocation
    /// Maximum memory (in bytes) this canister is allowed to occupy.
    /// Can be specified as an integer, or as an SI unit string (e.g. "4KB", "2 MiB")
    #[schemars(with = "Option<ByteSchema>")]
    pub memory_allocation: Option<Byte>,

    /// # Freezing Threshold
    /// Freezing threshould of the canister, measured in seconds.
    /// Valid inputs are numbers (seconds) or strings parsable by humantime (e.g. "15days 2min 2s").
    #[serde(with = "humantime_serde")]
    #[schemars(with = "Option<String>")]
    pub freezing_threshold: Option<Duration>,

    /// # Reserved Cycles Limit
    /// Specifies the upper limit of the canister's reserved cycles balance.
    ///
    /// Reserved cycles are cycles that the system sets aside for future use by the canister.
    /// If a subnet's storage exceeds 450 GiB, then every time a canister allocates new storage bytes,
    /// the system sets aside some amount of cycles from the main balance of the canister.
    /// These reserved cycles will be used to cover future payments for the newly allocated bytes.
    /// The reserved cycles are not transferable and the amount of reserved cycles depends on how full the subnet is.
    ///
    /// A setting of 0 means that the canister will trap if it tries to allocate new storage while the subnet's memory usage exceeds 450 GiB.
    #[schemars(with = "Option<u128>")]
    pub reserved_cycles_limit: Option<u128>,

    /// # Wasm Memory Limit
    /// Specifies a soft limit (in bytes) on the Wasm memory usage of the canister.
    ///
    /// Update calls, timers, heartbeats, installs, and post-upgrades fail if the
    /// Wasm memory usage exceeds this limit. The main purpose of this setting is
    /// to protect against the case when the canister reaches the hard 4GiB
    /// limit.
    ///
    /// Must be a number of bytes between 0 and 2^48 (i.e. 256 TiB), inclusive.
    /// Can be specified as an integer, or as an SI unit string (e.g. "4KB", "2 MiB")
    #[schemars(with = "Option<ByteSchema>")]
    pub wasm_memory_limit: Option<Byte>,

    /// # Log Visibility
    /// Specifies who is allowed to read the canister's logs.
    ///
    /// Can be "public", "controllers" or "allowed_viewers" with a list of principals.
    #[schemars(with = "Option<CanisterLogVisibility>")]
    pub log_visibility: Option<CanisterLogVisibility>,
}

/// # Declarations Configuration
/// Configurations about which canister interface declarations to generate,
/// and where to generate them.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct CanisterDeclarationsConfig {
    /// # Declaration Output Directory
    /// Directory to place declarations for that canister.
    /// Default is 'src/declarations/<canister_name>'.
    pub output: Option<PathBuf>,

    /// # Languages to generate
    /// A list of languages to generate type declarations.
    /// Supported options are 'js', 'ts', 'did', 'mo'.
    /// Default is ['js', 'ts', 'did'].
    pub bindings: Option<Vec<String>>,

    /// # Canister ID ENV Override
    /// A string that will replace process.env.CANISTER_ID_{canister_name_uppercase}
    /// in the 'src/dfx/assets/language_bindings/canister.js' template.
    pub env_override: Option<String>,

    /// # Node compatibility flag
    /// Flag to pre-populate generated declarations with better defaults for various types of projects
    /// Default is false
    #[serde(default)]
    pub node_compatibility: bool,
}

/// # Bitcoin Adapter Configuration
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ConfigDefaultsBitcoin {
    /// # Enable Bitcoin Adapter
    #[serde(default)]
    pub enabled: bool,

    /// # Available Nodes
    /// Addresses of nodes to connect to (in case discovery from seeds is not possible/sufficient).
    #[serde(default)]
    pub nodes: Option<Vec<SocketAddr>>,

    /// # Logging Level
    /// The logging level of the adapter.
    #[serde(default = "default_bitcoin_log_level")]
    pub log_level: BitcoinAdapterLogLevel,

    /// # Initialization Argument
    /// The initialization argument for the bitcoin canister.
    #[serde(default = "default_bitcoin_canister_init_arg")]
    pub canister_init_arg: String,
}

pub fn default_bitcoin_log_level() -> BitcoinAdapterLogLevel {
    BitcoinAdapterLogLevel::Info
}

pub fn default_bitcoin_canister_init_arg() -> String {
    "(record { stability_threshold = 0 : nat; network = variant { regtest }; blocks_source = principal \"aaaaa-aa\"; fees = record { get_utxos_base = 0 : nat; get_utxos_cycles_per_ten_instructions = 0 : nat; get_utxos_maximum = 0 : nat; get_balance = 0 : nat; get_balance_maximum = 0 : nat; get_current_fee_percentiles = 0 : nat; get_current_fee_percentiles_maximum = 0 : nat;  send_transaction_base = 0 : nat; send_transaction_per_byte = 0 : nat; }; syncing = variant { enabled }; api_access = variant { enabled }; disable_api_if_not_fully_synced = variant { enabled }})".to_string()
}

impl Default for ConfigDefaultsBitcoin {
    fn default() -> Self {
        ConfigDefaultsBitcoin {
            enabled: false,
            nodes: None,
            log_level: default_bitcoin_log_level(),
            canister_init_arg: default_bitcoin_canister_init_arg(),
        }
    }
}

/// # HTTP Adapter Configuration
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ConfigDefaultsCanisterHttp {
    /// # Enable HTTP Adapter
    #[serde(default = "default_as_true")]
    pub enabled: bool,

    /// # Logging Level
    /// The logging level of the adapter.
    #[serde(default)]
    pub log_level: HttpAdapterLogLevel,
}

impl Default for ConfigDefaultsCanisterHttp {
    fn default() -> Self {
        ConfigDefaultsCanisterHttp {
            enabled: true,
            log_level: HttpAdapterLogLevel::default(),
        }
    }
}

fn default_as_true() -> bool {
    // sigh https://github.com/serde-rs/serde/issues/368
    true
}

/// # Bootstrap Server Configuration
/// The bootstrap command has been removed.  All of these fields are ignored.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ConfigDefaultsBootstrap {
    /// Specifies the IP address that the bootstrap server listens on. Defaults to 127.0.0.1.
    #[serde(default = "default_bootstrap_ip")]
    pub ip: IpAddr,

    /// Specifies the port number that the bootstrap server listens on. Defaults to 8081.
    #[serde(default = "default_bootstrap_port")]
    pub port: u16,

    /// Specifies the maximum number of seconds that the bootstrap server
    /// will wait for upstream requests to complete. Defaults to 30.
    #[serde(default = "default_bootstrap_timeout")]
    pub timeout: u64,
}

pub fn default_bootstrap_ip() -> IpAddr {
    IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))
}
pub fn default_bootstrap_port() -> u16 {
    8081
}
pub fn default_bootstrap_timeout() -> u64 {
    30
}

impl Default for ConfigDefaultsBootstrap {
    fn default() -> Self {
        ConfigDefaultsBootstrap {
            ip: default_bootstrap_ip(),
            port: default_bootstrap_port(),
            timeout: default_bootstrap_timeout(),
        }
    }
}

/// # Build Process Configuration
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct ConfigDefaultsBuild {
    /// Main command to run the packtool.
    /// This command is executed in the root of the project.
    pub packtool: Option<String>,

    /// Arguments for packtool.
    pub args: Option<String>,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ReplicaLogLevel {
    Critical,
    Error,
    Warning,
    Info,
    Debug,
    Trace,
}

impl Default for ReplicaLogLevel {
    fn default() -> Self {
        Self::Error
    }
}

impl ReplicaLogLevel {
    pub fn to_ic_starter_string(&self) -> String {
        match self {
            Self::Critical => "critical".to_string(),
            Self::Error => "error".to_string(),
            Self::Warning => "warning".to_string(),
            Self::Info => "info".to_string(),
            Self::Debug => "debug".to_string(),
            Self::Trace => "trace".to_string(),
        }
    }
}

/// # Local Replica Configuration
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ConfigDefaultsReplica {
    /// Port the replica listens on.
    pub port: Option<u16>,

    /// # Subnet Type
    /// Determines the subnet type the replica will run as.
    /// Affects things like cycles accounting, message size limits, cycle limits.
    /// Defaults to 'application'.
    pub subnet_type: Option<ReplicaSubnetType>,

    /// Run replica with the provided log level. Default is 'error'. Debug prints still get displayed
    pub log_level: Option<ReplicaLogLevel>,
}

/// Configuration for the HTTP gateway.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ConfigDefaultsProxy {
    /// A list of domains that can be served. These are used for canister resolution [default: localhost]
    pub domain: Option<SerdeVec<String>>,
}

// Schemars doesn't add the enum value's docstrings. Therefore the explanations have to be up here.
/// # Network Type
/// Type 'ephemeral' is used for networks that are regularly reset.
/// Type 'persistent' is used for networks that last for a long time and where it is preferred that canister IDs get stored in source control.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "lowercase")]
pub enum NetworkType {
    // We store ephemeral canister ids in .dfx/{network}/canister_ids.json
    #[default]
    Ephemeral,

    // We store persistent canister ids in canister_ids.json (adjacent to dfx.json)
    Persistent,
}

impl NetworkType {
    fn ephemeral() -> Self {
        NetworkType::Ephemeral
    }
    fn persistent() -> Self {
        NetworkType::Persistent
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "lowercase")]
pub enum ReplicaSubnetType {
    System,
    #[default]
    Application,
    VerifiedApplication,
}

impl ReplicaSubnetType {
    /// Converts the value to the string expected by ic-starter for its --subnet-type argument
    pub fn as_ic_starter_string(&self) -> String {
        match self {
            ReplicaSubnetType::System => "system".to_string(),
            ReplicaSubnetType::Application => "application".to_string(),
            ReplicaSubnetType::VerifiedApplication => "verified_application".to_string(),
        }
    }
}

fn default_playground_timeout_seconds() -> u64 {
    MOTOKO_PLAYGROUND_CANISTER_TIMEOUT_SECONDS
}

/// Playground config to borrow canister from instead of creating new canisters.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct PlaygroundConfig {
    /// Canister ID of the playground canister
    pub playground_canister: String,

    /// How many seconds a canister can be borrowed for
    #[serde(default = "default_playground_timeout_seconds")]
    pub timeout_seconds: u64,
}

/// # Custom Network Configuration
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ConfigNetworkProvider {
    /// The URL(s) this network can be reached at.
    pub providers: Vec<String>,

    /// Persistence type of this network.
    #[serde(default = "NetworkType::persistent")]
    pub r#type: NetworkType,
    pub playground: Option<PlaygroundConfig>,
}

/// # Local Replica Configuration
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ConfigLocalProvider {
    /// Bind address for the webserver.
    /// For the shared local network, the default is 127.0.0.1:4943.
    /// For project-specific local networks, the default is 127.0.0.1:8000.
    pub bind: Option<String>,

    /// Persistence type of this network.
    #[serde(default = "NetworkType::ephemeral")]
    pub r#type: NetworkType,

    pub bitcoin: Option<ConfigDefaultsBitcoin>,
    pub bootstrap: Option<ConfigDefaultsBootstrap>,
    pub canister_http: Option<ConfigDefaultsCanisterHttp>,
    pub replica: Option<ConfigDefaultsReplica>,
    pub playground: Option<PlaygroundConfig>,
    pub proxy: Option<ConfigDefaultsProxy>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum ConfigNetwork {
    ConfigNetworkProvider(ConfigNetworkProvider),
    ConfigLocalProvider(ConfigLocalProvider),
}

#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub enum Profile {
    // debug is for development only
    Debug,
    // release is for production
    Release,
}

/// Defaults to use on dfx start.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct ConfigDefaults {
    pub bitcoin: Option<ConfigDefaultsBitcoin>,
    pub bootstrap: Option<ConfigDefaultsBootstrap>,
    pub build: Option<ConfigDefaultsBuild>,
    pub canister_http: Option<ConfigDefaultsCanisterHttp>,
    pub proxy: Option<ConfigDefaultsProxy>,
    pub replica: Option<ConfigDefaultsReplica>,
}

/// # dfx.json
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct ConfigInterface {
    pub profile: Option<Profile>,

    /// Used to keep track of dfx.json versions.
    pub version: Option<u32>,

    /// # dfx version
    /// Pins the dfx version for this project.
    pub dfx: Option<String>,

    /// Mapping between canisters and their settings.
    pub canisters: Option<BTreeMap<String, ConfigCanistersCanister>>,

    /// Defaults for dfx start.
    pub defaults: Option<ConfigDefaults>,

    /// Mapping between network names and their configurations.
    /// Networks 'ic' and 'local' are implicitly defined.
    pub networks: Option<BTreeMap<String, ConfigNetwork>>,

    /// If set, environment variables will be output to this file (without overwriting any user-defined variables, if the file already exists).
    pub output_env_file: Option<PathBuf>,
}

pub type TopLevelConfigNetworks = BTreeMap<String, ConfigNetwork>;

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct NetworksConfigInterface {
    pub networks: TopLevelConfigNetworks,
}

impl ConfigCanistersCanister {}

pub fn to_socket_addr(s: &str) -> Result<SocketAddr, SocketAddrConversionError> {
    match s.to_socket_addrs() {
        Ok(mut a) => match a.next() {
            Some(res) => Ok(res),
            None => Err(EmptyIterator(s.to_string())),
        },
        Err(err) => Err(ParseSocketAddrFailed(s.to_string(), err)),
    }
}

impl ConfigDefaultsBuild {
    pub fn get_packtool(&self) -> Option<String> {
        match &self.packtool {
            Some(v) if !v.is_empty() => self.packtool.to_owned(),
            _ => None,
        }
    }
    pub fn get_args(&self) -> Option<String> {
        match &self.args {
            Some(v) if !v.is_empty() => self.args.to_owned(),
            _ => None,
        }
    }
}

impl ConfigDefaults {
    pub fn get_build(&self) -> &ConfigDefaultsBuild {
        match &self.build {
            Some(x) => x,
            None => &EMPTY_CONFIG_DEFAULTS_BUILD,
        }
    }
}

impl NetworksConfigInterface {
    pub fn get_network(&self, name: &str) -> Option<&ConfigNetwork> {
        self.networks.get(name)
    }
}

impl ConfigInterface {
    pub fn get_defaults(&self) -> &ConfigDefaults {
        match &self.defaults {
            Some(v) => v,
            _ => &EMPTY_CONFIG_DEFAULTS,
        }
    }

    pub fn get_network(&self, name: &str) -> Option<&ConfigNetwork> {
        self.networks
            .as_ref()
            .and_then(|networks| networks.get(name))
    }

    pub fn get_version(&self) -> u32 {
        self.version.unwrap_or(1)
    }
    pub fn get_dfx(&self) -> Option<String> {
        self.dfx.to_owned()
    }

    /// Return the names of the specified canister and all of its dependencies.
    /// If none specified, return the names of all canisters.
    pub fn get_canister_names_with_dependencies(
        &self,
        some_canister: Option<&str>,
    ) -> Result<Vec<String>, GetCanisterNamesWithDependenciesError> {
        self.canisters
            .as_ref()
            .ok_or(GetCanisterNamesWithDependenciesError::CanistersFieldDoesNotExist())
            .and_then(|canister_map| match some_canister {
                Some(specific_canister) => {
                    let mut names = HashSet::new();
                    let mut path = vec![];
                    add_dependencies(canister_map, &mut names, &mut path, specific_canister)
                        .map(|_| names.into_iter().collect())
                        .map_err(|err| AddDependenciesFailed(specific_canister.to_string(), err))
                }
                None => Ok(canister_map.keys().cloned().collect()),
            })
    }

    pub fn get_remote_canister_id(
        &self,
        canister: &str,
        network: &str,
    ) -> Result<Option<Principal>, GetRemoteCanisterIdError> {
        let maybe_principal = self
            .get_canister_config(canister)
            .map_err(|e| {
                GetRemoteCanisterIdFailed(
                    Box::new(canister.to_string()),
                    Box::new(network.to_string()),
                    e,
                )
            })?
            .remote
            .as_ref()
            .and_then(|r| r.id.get(network))
            .copied();

        Ok(maybe_principal)
    }

    pub fn is_remote_canister(
        &self,
        canister: &str,
        network: &str,
    ) -> Result<bool, GetRemoteCanisterIdError> {
        Ok(self.get_remote_canister_id(canister, network)?.is_some())
    }

    pub fn get_compute_allocation(
        &self,
        canister_name: &str,
    ) -> Result<Option<u64>, GetComputeAllocationError> {
        Ok(self
            .get_canister_config(canister_name)
            .map_err(|e| GetComputeAllocationFailed(canister_name.to_string(), e))?
            .initialization_values
            .compute_allocation
            .map(|x| x.0))
    }

    pub fn get_memory_allocation(
        &self,
        canister_name: &str,
    ) -> Result<Option<Byte>, GetMemoryAllocationError> {
        Ok(self
            .get_canister_config(canister_name)
            .map_err(|e| GetMemoryAllocationFailed(canister_name.to_string(), e))?
            .initialization_values
            .memory_allocation)
    }

    pub fn get_freezing_threshold(
        &self,
        canister_name: &str,
    ) -> Result<Option<Duration>, GetFreezingThresholdError> {
        Ok(self
            .get_canister_config(canister_name)
            .map_err(|e| GetFreezingThresholdFailed(canister_name.to_string(), e))?
            .initialization_values
            .freezing_threshold)
    }

    pub fn get_reserved_cycles_limit(
        &self,
        canister_name: &str,
    ) -> Result<Option<u128>, GetReservedCyclesLimitError> {
        Ok(self
            .get_canister_config(canister_name)
            .map_err(|e| GetReservedCyclesLimitFailed(canister_name.to_string(), e))?
            .initialization_values
            .reserved_cycles_limit)
    }

    pub fn get_wasm_memory_limit(
        &self,
        canister_name: &str,
    ) -> Result<Option<Byte>, GetWasmMemoryLimitError> {
        Ok(self
            .get_canister_config(canister_name)
            .map_err(|e| GetWasmMemoryLimitFailed(canister_name.to_string(), e))?
            .initialization_values
            .wasm_memory_limit)
    }

    pub fn get_log_visibility(
        &self,
        canister_name: &str,
    ) -> Result<Option<LogVisibility>, GetLogVisibilityError> {
        Ok(self
            .get_canister_config(canister_name)
            .map_err(|e| GetLogVisibilityFailed(canister_name.to_string(), e))?
            .initialization_values
            .log_visibility
            .clone()
            .map(|visibility| visibility.into()))
    }

    fn get_canister_config(
        &self,
        canister_name: &str,
    ) -> Result<&ConfigCanistersCanister, GetCanisterConfigError> {
        self.canisters
            .as_ref()
            .ok_or(GetCanisterConfigError::CanistersFieldDoesNotExist())?
            .get(canister_name)
            .ok_or_else(|| GetCanisterConfigError::CanisterNotFound(canister_name.to_string()))
    }

    pub fn get_pull_canisters(&self) -> Result<BTreeMap<String, Principal>, GetPullCanistersError> {
        let mut res = BTreeMap::new();
        let mut id_to_name: BTreeMap<Principal, &String> = BTreeMap::new();
        if let Some(map) = &self.canisters {
            for (k, v) in map {
                if let CanisterTypeProperties::Pull { id } = v.type_specific {
                    if let Some(other_name) = id_to_name.get(&id) {
                        return Err(PullCanistersSameId(other_name.to_string(), k.clone(), id));
                    }
                    res.insert(k.clone(), id);
                    id_to_name.insert(id, k);
                }
            }
        };
        Ok(res)
    }

    pub fn get_specified_id(
        &self,
        canister_name: &str,
    ) -> Result<Option<Principal>, GetSpecifiedIdError> {
        Ok(self
            .get_canister_config(canister_name)
            .map_err(|e| GetSpecifiedIdFailed(canister_name.to_string(), e))?
            .specified_id)
    }
}

fn add_dependencies(
    all_canisters: &BTreeMap<String, ConfigCanistersCanister>,
    names: &mut HashSet<String>,
    path: &mut Vec<String>,
    canister_name: &str,
) -> Result<(), AddDependenciesError> {
    let inserted = names.insert(String::from(canister_name));

    if !inserted {
        return if path.contains(&String::from(canister_name)) {
            path.push(String::from(canister_name));
            Err(CanisterCircularDependency(path.clone()))
        } else {
            Ok(())
        };
    }

    let canister_config = all_canisters
        .get(canister_name)
        .ok_or_else(|| AddDependenciesError::CanisterNotFound(canister_name.to_string()))?;

    path.push(String::from(canister_name));

    for canister in &canister_config.dependencies {
        add_dependencies(all_canisters, names, path, canister)?;
    }

    path.pop();

    Ok(())
}

#[derive(Clone, Debug)]
pub struct Config {
    path: PathBuf,
    json: Value,
    // public interface to the config:
    pub config: ConfigInterface,
}

#[allow(dead_code)]
impl Config {
    fn resolve_config_path(working_dir: &Path) -> Result<Option<PathBuf>, CanonicalizePathError> {
        let mut curr = crate::fs::canonicalize(working_dir)?;
        while curr.parent().is_some() {
            if curr.join(CONFIG_FILE_NAME).is_file() {
                return Ok(Some(curr.join(CONFIG_FILE_NAME)));
            } else {
                curr.pop();
            }
        }

        // Have to check if the config could be in the root (e.g. on VMs / CI).
        if curr.join(CONFIG_FILE_NAME).is_file() {
            return Ok(Some(curr.join(CONFIG_FILE_NAME)));
        }

        Ok(None)
    }

    fn from_file(
        path: &Path,
        extension_manager: Option<&ExtensionManager>,
    ) -> Result<Config, LoadDfxConfigError> {
        let content = crate::fs::read(path)?;
        Config::from_slice(path.to_path_buf(), &content, extension_manager)
    }

    pub fn from_dir(
        working_dir: &Path,
        extension_manager: Option<&ExtensionManager>,
    ) -> Result<Option<Config>, LoadDfxConfigError> {
        let path = Config::resolve_config_path(working_dir).map_err(ResolveConfigPath)?;
        path.map(|path| Config::from_file(&path, extension_manager))
            .transpose()
    }

    pub fn from_current_dir(
        extension_manager: Option<&ExtensionManager>,
    ) -> Result<Option<Config>, LoadDfxConfigError> {
        let working_dir = std::env::current_dir().map_err(DetermineCurrentWorkingDirFailed)?;
        Config::from_dir(&working_dir, extension_manager)
    }

    fn from_slice(
        path: PathBuf,
        content: &[u8],
        extension_manager: Option<&ExtensionManager>,
    ) -> Result<Config, LoadDfxConfigError> {
        let json: Value = serde_json::from_slice(content)
            .map_err(|e| LoadDfxConfigError::DeserializeValueFailed(Box::new(path.clone()), e))?;
        let effective_json = apply_extension_canister_types(json.clone(), extension_manager)?;

        let config = serde_json::from_value(effective_json)
            .map_err(|e| LoadDfxConfigError::DeserializeValueFailed(Box::new(path.clone()), e))?;
        Ok(Config { path, json, config })
    }

    /// Create a configuration from a string.
    #[cfg(test)]
    pub(crate) fn from_str(content: &str) -> Result<Config, StructuredFileError> {
        Ok(Config::from_slice(PathBuf::from("-"), content.as_bytes(), None).unwrap())
    }

    #[cfg(test)]
    pub(crate) fn from_str_and_path(
        path: PathBuf,
        content: &str,
    ) -> Result<Config, StructuredFileError> {
        Ok(Config::from_slice(path, content.as_bytes(), None).unwrap())
    }

    pub fn get_path(&self) -> &PathBuf {
        &self.path
    }
    pub fn get_temp_path(&self) -> Result<PathBuf, GetTempPathError> {
        let path = self.get_path().parent().unwrap().join(".dfx");
        create_dir_all(&path)?;
        Ok(path)
    }
    pub fn get_json(&self) -> &Value {
        &self.json
    }
    pub fn get_mut_json(&mut self) -> &mut Value {
        &mut self.json
    }
    pub fn get_config(&self) -> &ConfigInterface {
        &self.config
    }

    pub fn get_project_root(&self) -> &Path {
        // a configuration path contains a file name specifically. As
        // such we should be returning at least root as parent. If
        // this is invariance is broken, we must fail.
        self.path.parent().expect(
            "An incorrect configuration path was set with no parent, i.e. did not include root",
        )
    }

    // returns the path to the output env file if any, guaranteed to be
    // a child relative to the project root
    pub fn get_output_env_file(
        &self,
        from_cmdline: Option<PathBuf>,
    ) -> Result<Option<PathBuf>, GetOutputEnvFileError> {
        from_cmdline
            .or(self.config.output_env_file.clone())
            .map(|p| {
                if p.is_relative() {
                    let p = self.get_project_root().join(p);

                    // cannot canonicalize a path that doesn't exist, but the parent should exist
                    let env_parent = crate::fs::parent(&p)?;
                    let env_parent = crate::fs::canonicalize(&env_parent)?;
                    if !env_parent.starts_with(self.get_project_root()) {
                        Err(GetOutputEnvFileError::OutputEnvFileMustBeInProjectRoot(p))
                    } else {
                        Ok(self.get_project_root().join(p))
                    }
                } else {
                    Err(GetOutputEnvFileError::OutputEnvFileMustBeRelative(p))
                }
            })
            .transpose()
    }

    pub fn save(&self) -> Result<(), StructuredFileError> {
        save_json_file(&self.path, &self.json)
    }
}

// grumble grumble https://github.com/serde-rs/serde/issues/2231
impl<'de> Deserialize<'de> for CanisterTypeProperties {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(PropertiesVisitor)
    }
}

struct PropertiesVisitor;

impl<'de> Visitor<'de> for PropertiesVisitor {
    type Value = CanisterTypeProperties;
    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("canister type metadata")
    }
    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let missing_field = A::Error::missing_field;
        let mut wasm = None;
        let mut candid = None;
        let mut package = None;
        let mut crate_name = None;
        let mut source = None;
        let mut build = None;
        let mut r#type = None;
        let mut id = None;
        let mut workspace = None;
        while let Some(key) = map.next_key::<String>()? {
            match &*key {
                "package" => package = Some(map.next_value()?),
                "crate" => crate_name = Some(map.next_value()?),
                "source" => source = Some(map.next_value()?),
                "candid" => candid = Some(map.next_value()?),
                "build" => build = Some(map.next_value()?),
                "wasm" => wasm = Some(map.next_value()?),
                "type" => r#type = Some(map.next_value::<String>()?),
                "id" => id = Some(map.next_value()?),
                "workspace" => workspace = Some(map.next_value()?),
                _ => continue,
            }
        }
        let props = match r#type.as_deref() {
            Some("motoko") | None => CanisterTypeProperties::Motoko,
            Some("rust") => CanisterTypeProperties::Rust {
                candid: PathBuf::from(candid.ok_or_else(|| missing_field("candid"))?),
                package: package.ok_or_else(|| missing_field("package"))?,
                crate_name,
            },
            Some("assets") => CanisterTypeProperties::Assets {
                source: source.ok_or_else(|| missing_field("source"))?,
                build: build.unwrap_or_default(),
                workspace,
            },
            Some("custom") => CanisterTypeProperties::Custom {
                build: build.unwrap_or_default(),
                candid: candid.ok_or_else(|| missing_field("candid"))?,
                wasm: wasm.ok_or_else(|| missing_field("wasm"))?,
            },
            Some("pull") => CanisterTypeProperties::Pull {
                id: id.ok_or_else(|| missing_field("id"))?,
            },
            Some(x) => return Err(A::Error::unknown_variant(x, &BUILTIN_CANISTER_TYPES)),
        };
        Ok(props)
    }
}

#[derive(Clone)]
pub struct NetworksConfig {
    path: PathBuf,
    json: Value,
    // public interface to the networsk config:
    networks_config: NetworksConfigInterface,
}

impl NetworksConfig {
    pub fn get_path(&self) -> &PathBuf {
        &self.path
    }
    pub fn get_interface(&self) -> &NetworksConfigInterface {
        &self.networks_config
    }

    pub fn new() -> Result<NetworksConfig, LoadNetworksConfigError> {
        let dir = get_user_dfx_config_dir().map_err(GetConfigPathFailed)?;

        let path = dir.join("networks.json");
        if path.exists() {
            NetworksConfig::from_file(&path).map_err(LoadConfigFromFileFailed)
        } else {
            Ok(NetworksConfig {
                path,
                json: Default::default(),
                networks_config: NetworksConfigInterface {
                    networks: BTreeMap::new(),
                },
            })
        }
    }

    fn from_file(path: &Path) -> Result<NetworksConfig, StructuredFileError> {
        let content = crate::fs::read(path)?;

        let networks: BTreeMap<String, ConfigNetwork> = serde_json::from_slice(&content)
            .map_err(|e| DeserializeJsonFileFailed(Box::new(path.to_path_buf()), e))?;
        let networks_config = NetworksConfigInterface { networks };
        let json = serde_json::from_slice(&content)
            .map_err(|e| DeserializeJsonFileFailed(Box::new(path.to_path_buf()), e))?;
        let path = PathBuf::from(path);
        Ok(NetworksConfig {
            path,
            json,
            networks_config,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn find_dfinity_config_current_path() {
        let root_dir = tempfile::tempdir().unwrap();
        let root_path = root_dir.into_path().canonicalize().unwrap();
        let config_path = root_path.join("foo/fah/bar").join(CONFIG_FILE_NAME);

        std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
        std::fs::write(&config_path, "{}").unwrap();

        assert_eq!(
            config_path,
            Config::resolve_config_path(config_path.parent().unwrap())
                .unwrap()
                .unwrap(),
        );
    }

    #[test]
    fn find_dfinity_config_parent() {
        let root_dir = tempfile::tempdir().unwrap();
        let root_path = root_dir.into_path().canonicalize().unwrap();
        let config_path = root_path.join("foo/fah/bar").join(CONFIG_FILE_NAME);

        std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
        std::fs::write(&config_path, "{}").unwrap();

        assert!(
            Config::resolve_config_path(config_path.parent().unwrap().parent().unwrap())
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn find_dfinity_config_subdir() {
        let root_dir = tempfile::tempdir().unwrap();
        let root_path = root_dir.into_path().canonicalize().unwrap();
        let config_path = root_path.join("foo/fah/bar").join(CONFIG_FILE_NAME);
        let subdir_path = config_path.parent().unwrap().join("baz/blue");

        std::fs::create_dir_all(&subdir_path).unwrap();
        std::fs::write(&config_path, "{}").unwrap();

        assert_eq!(
            config_path,
            Config::resolve_config_path(subdir_path.as_path())
                .unwrap()
                .unwrap(),
        );
    }

    #[test]
    fn local_defaults_to_ephemeral() {
        let config = Config::from_str(
            r#"{
            "networks": {
                "local": {
                    "bind": "localhost:8000"
                }
            }
        }"#,
        )
        .unwrap();

        let network = config.get_config().get_network("local").unwrap();
        if let ConfigNetwork::ConfigLocalProvider(local_network) = network {
            assert_eq!(local_network.r#type, NetworkType::Ephemeral);
        } else {
            panic!("not a local provider");
        }
    }

    #[test]
    fn local_can_override_to_persistent() {
        let config = Config::from_str(
            r#"{
            "networks": {
                "local": {
                    "bind": "localhost:8000",
                    "type": "persistent"
                }
            }
        }"#,
        )
        .unwrap();

        let network = config.get_config().get_network("local").unwrap();
        if let ConfigNetwork::ConfigLocalProvider(local_network) = network {
            assert_eq!(local_network.r#type, NetworkType::Persistent);
        } else {
            panic!("not a local provider");
        }
    }

    #[test]
    fn network_defaults_to_persistent() {
        let config = Config::from_str(
            r#"{
            "networks": {
                "somewhere": {
                    "providers": [ "https://1.2.3.4:5000" ]
                }
            }
        }"#,
        )
        .unwrap();

        let network = config.get_config().get_network("somewhere").unwrap();
        if let ConfigNetwork::ConfigNetworkProvider(network_provider) = network {
            assert_eq!(network_provider.r#type, NetworkType::Persistent);
        } else {
            panic!("not a network provider");
        }
    }

    #[test]
    fn network_can_override_to_ephemeral() {
        let config = Config::from_str(
            r#"{
            "networks": {
                "staging": {
                    "providers": [ "https://1.2.3.4:5000" ],
                    "type": "ephemeral"
                }
            }
        }"#,
        )
        .unwrap();

        let network = config.get_config().get_network("staging").unwrap();
        if let ConfigNetwork::ConfigNetworkProvider(network_provider) = network {
            assert_eq!(network_provider.r#type, NetworkType::Ephemeral);
        } else {
            panic!("not a network provider");
        }

        assert_eq!(
            config.get_config().get_network("staging").unwrap(),
            &ConfigNetwork::ConfigNetworkProvider(ConfigNetworkProvider {
                providers: vec![String::from("https://1.2.3.4:5000")],
                r#type: NetworkType::Ephemeral,
                playground: None,
            })
        );
    }

    #[test]
    fn get_correct_initialization_values() {
        let config = Config::from_str(
            r#"{
              "canisters": {
                "test_project": {
                  "initialization_values": {
                    "compute_allocation" : "100",
                    "memory_allocation": "8GB"
                  }
                }
              }
        }"#,
        )
        .unwrap();

        let config_interface = config.get_config();
        let compute_allocation = config_interface
            .get_compute_allocation("test_project")
            .unwrap()
            .unwrap();
        assert_eq!(100, compute_allocation);

        let memory_allocation = config_interface
            .get_memory_allocation("test_project")
            .unwrap()
            .unwrap();
        assert_eq!("8GB".parse::<Byte>().unwrap(), memory_allocation);

        let config_no_values = Config::from_str(
            r#"{
              "canisters": {
                "test_project_two": {
                }
              }
        }"#,
        )
        .unwrap();
        let config_interface = config_no_values.get_config();
        let compute_allocation = config_interface
            .get_compute_allocation("test_project_two")
            .unwrap();
        let memory_allocation = config_interface
            .get_memory_allocation("test_project_two")
            .unwrap();
        assert_eq!(None, compute_allocation);
        assert_eq!(None, memory_allocation);
    }
}