config.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. use anchor_client::Cluster;
  2. use anchor_syn::idl::Idl;
  3. use anyhow::{anyhow, Error, Result};
  4. use clap::Clap;
  5. use serde::{Deserialize, Serialize};
  6. use solana_sdk::pubkey::Pubkey;
  7. use solana_sdk::signature::{Keypair, Signer};
  8. use std::collections::BTreeMap;
  9. use std::convert::TryFrom;
  10. use std::fs::{self, File};
  11. use std::io::prelude::*;
  12. use std::ops::Deref;
  13. use std::path::Path;
  14. use std::path::PathBuf;
  15. use std::str::FromStr;
  16. #[derive(Default, Debug, Clap)]
  17. pub struct ConfigOverride {
  18. /// Cluster override.
  19. #[clap(global = true, long = "provider.cluster")]
  20. pub cluster: Option<Cluster>,
  21. /// Wallet override.
  22. #[clap(global = true, long = "provider.wallet")]
  23. pub wallet: Option<WalletPath>,
  24. }
  25. pub struct WithPath<T> {
  26. inner: T,
  27. path: PathBuf,
  28. }
  29. impl<T> WithPath<T> {
  30. pub fn new(inner: T, path: PathBuf) -> Self {
  31. Self { inner, path }
  32. }
  33. pub fn path(&self) -> &PathBuf {
  34. &self.path
  35. }
  36. pub fn into_inner(self) -> T {
  37. self.inner
  38. }
  39. }
  40. impl<T> std::convert::AsRef<T> for WithPath<T> {
  41. fn as_ref(&self) -> &T {
  42. &self.inner
  43. }
  44. }
  45. #[derive(Debug, Clone, PartialEq)]
  46. pub struct Manifest(cargo_toml::Manifest);
  47. impl Manifest {
  48. pub fn from_path(p: impl AsRef<Path>) -> Result<Self> {
  49. cargo_toml::Manifest::from_path(p)
  50. .map(Manifest)
  51. .map_err(Into::into)
  52. }
  53. pub fn lib_name(&self) -> Result<String> {
  54. if self.lib.is_some() && self.lib.as_ref().unwrap().name.is_some() {
  55. Ok(self
  56. .lib
  57. .as_ref()
  58. .unwrap()
  59. .name
  60. .as_ref()
  61. .unwrap()
  62. .to_string())
  63. } else {
  64. Ok(self
  65. .package
  66. .as_ref()
  67. .ok_or_else(|| anyhow!("package section not provided"))?
  68. .name
  69. .to_string())
  70. }
  71. }
  72. // Climbs each parent directory until we find a Cargo.toml.
  73. pub fn discover() -> Result<Option<WithPath<Manifest>>> {
  74. let _cwd = std::env::current_dir()?;
  75. let mut cwd_opt = Some(_cwd.as_path());
  76. while let Some(cwd) = cwd_opt {
  77. for f in fs::read_dir(cwd)? {
  78. let p = f?.path();
  79. if let Some(filename) = p.file_name() {
  80. if filename.to_str() == Some("Cargo.toml") {
  81. let m = WithPath::new(Manifest::from_path(&p)?, p);
  82. return Ok(Some(m));
  83. }
  84. }
  85. }
  86. // Not found. Go up a directory level.
  87. cwd_opt = cwd.parent();
  88. }
  89. Ok(None)
  90. }
  91. }
  92. impl Deref for Manifest {
  93. type Target = cargo_toml::Manifest;
  94. fn deref(&self) -> &Self::Target {
  95. &self.0
  96. }
  97. }
  98. impl WithPath<Config> {
  99. pub fn get_program_list(&self) -> Result<Vec<PathBuf>> {
  100. // Canonicalize the workspace filepaths to compare with relative paths.
  101. let (members, exclude) = self.canonicalize_workspace()?;
  102. // Get all candidate programs.
  103. //
  104. // If [workspace.members] exists, then use that.
  105. // Otherwise, default to `programs/*`.
  106. let program_paths: Vec<PathBuf> = {
  107. if members.is_empty() {
  108. let path = self.path().parent().unwrap().join("programs");
  109. fs::read_dir(path)?
  110. .filter(|entry| entry.as_ref().map(|e| e.path().is_dir()).unwrap_or(false))
  111. .map(|dir| dir.map(|d| d.path().canonicalize().unwrap()))
  112. .collect::<Vec<Result<PathBuf, std::io::Error>>>()
  113. .into_iter()
  114. .collect::<Result<Vec<PathBuf>, std::io::Error>>()?
  115. } else {
  116. members
  117. }
  118. };
  119. // Filter out everything part of the exclude array.
  120. Ok(program_paths
  121. .into_iter()
  122. .filter(|m| !exclude.contains(m))
  123. .collect())
  124. }
  125. // TODO: this should read idl dir instead of parsing source.
  126. pub fn read_all_programs(&self) -> Result<Vec<Program>> {
  127. let mut r = vec![];
  128. for path in self.get_program_list()? {
  129. let idl = anchor_syn::idl::file::parse(path.join("src/lib.rs"))?;
  130. let lib_name = Manifest::from_path(&path.join("Cargo.toml"))?.lib_name()?;
  131. r.push(Program {
  132. lib_name,
  133. path,
  134. idl,
  135. });
  136. }
  137. Ok(r)
  138. }
  139. pub fn canonicalize_workspace(&self) -> Result<(Vec<PathBuf>, Vec<PathBuf>)> {
  140. let members = self
  141. .workspace
  142. .members
  143. .iter()
  144. .map(|m| {
  145. self.path()
  146. .parent()
  147. .unwrap()
  148. .join(m)
  149. .canonicalize()
  150. .unwrap()
  151. })
  152. .collect();
  153. let exclude = self
  154. .workspace
  155. .exclude
  156. .iter()
  157. .map(|m| {
  158. self.path()
  159. .parent()
  160. .unwrap()
  161. .join(m)
  162. .canonicalize()
  163. .unwrap()
  164. })
  165. .collect();
  166. Ok((members, exclude))
  167. }
  168. pub fn get_program(&self, name: &str) -> Result<Option<WithPath<Program>>> {
  169. for program in self.read_all_programs()? {
  170. let cargo_toml = program.path.join("Cargo.toml");
  171. if !cargo_toml.exists() {
  172. return Err(anyhow!(
  173. "Did not find Cargo.toml at the path: {}",
  174. program.path.display()
  175. ));
  176. }
  177. let p_lib_name = Manifest::from_path(&cargo_toml)?.lib_name()?;
  178. if name == p_lib_name {
  179. let path = self
  180. .path()
  181. .parent()
  182. .unwrap()
  183. .canonicalize()?
  184. .join(&program.path);
  185. return Ok(Some(WithPath::new(program, path)));
  186. }
  187. }
  188. Ok(None)
  189. }
  190. }
  191. impl<T> std::ops::Deref for WithPath<T> {
  192. type Target = T;
  193. fn deref(&self) -> &Self::Target {
  194. &self.inner
  195. }
  196. }
  197. impl<T> std::ops::DerefMut for WithPath<T> {
  198. fn deref_mut(&mut self) -> &mut Self::Target {
  199. &mut self.inner
  200. }
  201. }
  202. #[derive(Debug, Default)]
  203. pub struct Config {
  204. pub anchor_version: Option<String>,
  205. pub solana_version: Option<String>,
  206. pub registry: RegistryConfig,
  207. pub provider: ProviderConfig,
  208. pub programs: ProgramsConfig,
  209. pub scripts: ScriptsConfig,
  210. pub workspace: WorkspaceConfig,
  211. pub test: Option<Test>,
  212. }
  213. #[derive(Clone, Debug, Serialize, Deserialize)]
  214. pub struct RegistryConfig {
  215. pub url: String,
  216. }
  217. impl Default for RegistryConfig {
  218. fn default() -> Self {
  219. Self {
  220. url: "https://anchor.projectserum.com".to_string(),
  221. }
  222. }
  223. }
  224. #[derive(Debug, Default)]
  225. pub struct ProviderConfig {
  226. pub cluster: Cluster,
  227. pub wallet: WalletPath,
  228. }
  229. pub type ScriptsConfig = BTreeMap<String, String>;
  230. pub type ProgramsConfig = BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>;
  231. #[derive(Debug, Default, Clone, Serialize, Deserialize)]
  232. pub struct WorkspaceConfig {
  233. #[serde(default, skip_serializing_if = "Vec::is_empty")]
  234. pub members: Vec<String>,
  235. #[serde(default, skip_serializing_if = "Vec::is_empty")]
  236. pub exclude: Vec<String>,
  237. }
  238. impl Config {
  239. pub fn docker(&self) -> String {
  240. let ver = self
  241. .anchor_version
  242. .clone()
  243. .unwrap_or_else(|| crate::DOCKER_BUILDER_VERSION.to_string());
  244. format!("projectserum/build:v{}", ver)
  245. }
  246. pub fn discover(cfg_override: &ConfigOverride) -> Result<Option<WithPath<Config>>> {
  247. Config::_discover().map(|opt| {
  248. opt.map(|mut cfg| {
  249. if let Some(cluster) = cfg_override.cluster.clone() {
  250. cfg.provider.cluster = cluster;
  251. }
  252. if let Some(wallet) = cfg_override.wallet.clone() {
  253. cfg.provider.wallet = wallet;
  254. }
  255. cfg
  256. })
  257. })
  258. }
  259. // Climbs each parent directory until we find an Anchor.toml.
  260. fn _discover() -> Result<Option<WithPath<Config>>> {
  261. let _cwd = std::env::current_dir()?;
  262. let mut cwd_opt = Some(_cwd.as_path());
  263. while let Some(cwd) = cwd_opt {
  264. for f in fs::read_dir(cwd)? {
  265. let p = f?.path();
  266. if let Some(filename) = p.file_name() {
  267. if filename.to_str() == Some("Anchor.toml") {
  268. let cfg = Config::from_path(&p)?;
  269. return Ok(Some(WithPath::new(cfg, p)));
  270. }
  271. }
  272. }
  273. cwd_opt = cwd.parent();
  274. }
  275. Ok(None)
  276. }
  277. fn from_path(p: impl AsRef<Path>) -> Result<Self> {
  278. let mut cfg_file = File::open(&p)?;
  279. let mut cfg_contents = String::new();
  280. cfg_file.read_to_string(&mut cfg_contents)?;
  281. let cfg = cfg_contents.parse()?;
  282. Ok(cfg)
  283. }
  284. pub fn wallet_kp(&self) -> Result<Keypair> {
  285. solana_sdk::signature::read_keypair_file(&self.provider.wallet.to_string())
  286. .map_err(|_| anyhow!("Unable to read keypair file"))
  287. }
  288. }
  289. #[derive(Debug, Serialize, Deserialize)]
  290. struct _Config {
  291. anchor_version: Option<String>,
  292. solana_version: Option<String>,
  293. programs: Option<BTreeMap<String, BTreeMap<String, serde_json::Value>>>,
  294. registry: Option<RegistryConfig>,
  295. provider: Provider,
  296. workspace: Option<WorkspaceConfig>,
  297. scripts: Option<ScriptsConfig>,
  298. test: Option<Test>,
  299. }
  300. #[derive(Debug, Serialize, Deserialize)]
  301. struct Provider {
  302. cluster: String,
  303. wallet: String,
  304. }
  305. impl ToString for Config {
  306. fn to_string(&self) -> String {
  307. let programs = {
  308. let c = ser_programs(&self.programs);
  309. if c.is_empty() {
  310. None
  311. } else {
  312. Some(c)
  313. }
  314. };
  315. let cfg = _Config {
  316. anchor_version: self.anchor_version.clone(),
  317. solana_version: self.solana_version.clone(),
  318. registry: Some(self.registry.clone()),
  319. provider: Provider {
  320. cluster: format!("{}", self.provider.cluster),
  321. wallet: self.provider.wallet.to_string(),
  322. },
  323. test: self.test.clone(),
  324. scripts: match self.scripts.is_empty() {
  325. true => None,
  326. false => Some(self.scripts.clone()),
  327. },
  328. programs,
  329. workspace: (!self.workspace.members.is_empty() || !self.workspace.exclude.is_empty())
  330. .then(|| self.workspace.clone()),
  331. };
  332. toml::to_string(&cfg).expect("Must be well formed")
  333. }
  334. }
  335. impl FromStr for Config {
  336. type Err = Error;
  337. fn from_str(s: &str) -> Result<Self, Self::Err> {
  338. let cfg: _Config = toml::from_str(s)
  339. .map_err(|e| anyhow::format_err!("Unable to deserialize config: {}", e.to_string()))?;
  340. Ok(Config {
  341. anchor_version: cfg.anchor_version,
  342. solana_version: cfg.solana_version,
  343. registry: cfg.registry.unwrap_or_default(),
  344. provider: ProviderConfig {
  345. cluster: cfg.provider.cluster.parse()?,
  346. wallet: shellexpand::tilde(&cfg.provider.wallet).parse()?,
  347. },
  348. scripts: cfg.scripts.unwrap_or_else(BTreeMap::new),
  349. test: cfg.test,
  350. programs: cfg.programs.map_or(Ok(BTreeMap::new()), deser_programs)?,
  351. workspace: cfg.workspace.unwrap_or_default(),
  352. })
  353. }
  354. }
  355. fn ser_programs(
  356. programs: &BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>,
  357. ) -> BTreeMap<String, BTreeMap<String, serde_json::Value>> {
  358. programs
  359. .iter()
  360. .map(|(cluster, programs)| {
  361. let cluster = cluster.to_string();
  362. let programs = programs
  363. .iter()
  364. .map(|(name, deployment)| {
  365. (
  366. name.clone(),
  367. to_value(&_ProgramDeployment::from(deployment)),
  368. )
  369. })
  370. .collect::<BTreeMap<String, serde_json::Value>>();
  371. (cluster, programs)
  372. })
  373. .collect::<BTreeMap<String, BTreeMap<String, serde_json::Value>>>()
  374. }
  375. fn to_value(dep: &_ProgramDeployment) -> serde_json::Value {
  376. if dep.path.is_none() && dep.idl.is_none() {
  377. return serde_json::Value::String(dep.address.to_string());
  378. }
  379. serde_json::to_value(dep).unwrap()
  380. }
  381. fn deser_programs(
  382. programs: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
  383. ) -> Result<BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>> {
  384. programs
  385. .iter()
  386. .map(|(cluster, programs)| {
  387. let cluster: Cluster = cluster.parse()?;
  388. let programs = programs
  389. .iter()
  390. .map(|(name, program_id)| {
  391. Ok((
  392. name.clone(),
  393. ProgramDeployment::try_from(match &program_id {
  394. serde_json::Value::String(address) => _ProgramDeployment {
  395. address: address.parse()?,
  396. path: None,
  397. idl: None,
  398. },
  399. serde_json::Value::Object(_) => {
  400. serde_json::from_value(program_id.clone())
  401. .map_err(|_| anyhow!("Unable to read toml"))?
  402. }
  403. _ => return Err(anyhow!("Invalid toml type")),
  404. })?,
  405. ))
  406. })
  407. .collect::<Result<BTreeMap<String, ProgramDeployment>>>()?;
  408. Ok((cluster, programs))
  409. })
  410. .collect::<Result<BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>>>()
  411. }
  412. #[derive(Debug, Clone, Serialize, Deserialize)]
  413. pub struct Test {
  414. pub genesis: Option<Vec<GenesisEntry>>,
  415. pub clone: Option<Vec<CloneEntry>>,
  416. pub validator: Option<Validator>,
  417. pub startup_wait: Option<i32>,
  418. }
  419. #[derive(Debug, Clone, Serialize, Deserialize)]
  420. pub struct GenesisEntry {
  421. // Base58 pubkey string.
  422. pub address: String,
  423. // Filepath to the compiled program to embed into the genesis.
  424. pub program: String,
  425. }
  426. #[derive(Debug, Clone, Serialize, Deserialize)]
  427. pub struct CloneEntry {
  428. // Base58 pubkey string.
  429. pub address: String,
  430. }
  431. #[derive(Debug, Default, Clone, Serialize, Deserialize)]
  432. pub struct Validator {
  433. // IP address to bind the validator ports. [default: 0.0.0.0]
  434. #[serde(default = "default_bind_address")]
  435. pub bind_address: String,
  436. // Range to use for dynamically assigned ports. [default: 1024-65535]
  437. #[serde(skip_serializing_if = "Option::is_none")]
  438. pub dynamic_port_range: Option<String>,
  439. // Enable the faucet on this port [deafult: 9900].
  440. #[serde(skip_serializing_if = "Option::is_none")]
  441. pub faucet_port: Option<u16>,
  442. // Give the faucet address this much SOL in genesis. [default: 1000000]
  443. #[serde(skip_serializing_if = "Option::is_none")]
  444. pub faucet_sol: Option<String>,
  445. // Gossip DNS name or IP address for the validator to advertise in gossip. [default: 127.0.0.1]
  446. #[serde(skip_serializing_if = "Option::is_none")]
  447. pub gossip_host: Option<String>,
  448. // Gossip port number for the validator
  449. #[serde(skip_serializing_if = "Option::is_none")]
  450. pub gossip_port: Option<u16>,
  451. // URL for Solana's JSON RPC or moniker.
  452. #[serde(skip_serializing_if = "Option::is_none")]
  453. pub url: Option<String>,
  454. // Use DIR as ledger location
  455. #[serde(default = "default_ledger_path")]
  456. pub ledger: String,
  457. // Keep this amount of shreds in root slots. [default: 10000]
  458. #[serde(skip_serializing_if = "Option::is_none")]
  459. pub limit_ledger_size: Option<String>,
  460. // Enable JSON RPC on this port, and the next port for the RPC websocket. [default: 8899]
  461. #[serde(default = "default_rpc_port")]
  462. pub rpc_port: u16,
  463. // Override the number of slots in an epoch.
  464. #[serde(skip_serializing_if = "Option::is_none")]
  465. pub slots_per_epoch: Option<String>,
  466. // Warp the ledger to WARP_SLOT after starting the validator.
  467. #[serde(skip_serializing_if = "Option::is_none")]
  468. pub warp_slot: Option<String>,
  469. }
  470. fn default_ledger_path() -> String {
  471. ".anchor/test-ledger".to_string()
  472. }
  473. fn default_bind_address() -> String {
  474. "0.0.0.0".to_string()
  475. }
  476. fn default_rpc_port() -> u16 {
  477. 8899
  478. }
  479. #[derive(Debug, Clone)]
  480. pub struct Program {
  481. pub lib_name: String,
  482. // Canonicalized path to the program directory.
  483. pub path: PathBuf,
  484. pub idl: Option<Idl>,
  485. }
  486. impl Program {
  487. pub fn pubkey(&self) -> Result<Pubkey> {
  488. self.keypair().map(|kp| kp.pubkey())
  489. }
  490. pub fn keypair(&self) -> Result<Keypair> {
  491. let file = self.keypair_file()?;
  492. solana_sdk::signature::read_keypair_file(file.path())
  493. .map_err(|_| anyhow!("failed to read keypair for program: {}", self.lib_name))
  494. }
  495. // Lazily initializes the keypair file with a new key if it doesn't exist.
  496. pub fn keypair_file(&self) -> Result<WithPath<File>> {
  497. fs::create_dir_all("target/deploy/")?;
  498. let path = std::env::current_dir()
  499. .expect("Must have current dir")
  500. .join(format!("target/deploy/{}-keypair.json", self.lib_name));
  501. if path.exists() {
  502. return Ok(WithPath::new(File::open(&path)?, path));
  503. }
  504. let program_kp = Keypair::generate(&mut rand::rngs::OsRng);
  505. let mut file = File::create(&path)?;
  506. file.write_all(format!("{:?}", &program_kp.to_bytes()).as_bytes())?;
  507. Ok(WithPath::new(file, path))
  508. }
  509. pub fn binary_path(&self) -> PathBuf {
  510. std::env::current_dir()
  511. .expect("Must have current dir")
  512. .join(format!("target/deploy/{}.so", self.lib_name))
  513. }
  514. }
  515. #[derive(Debug, Default)]
  516. pub struct ProgramDeployment {
  517. pub address: Pubkey,
  518. pub path: Option<String>,
  519. pub idl: Option<String>,
  520. }
  521. impl TryFrom<_ProgramDeployment> for ProgramDeployment {
  522. type Error = anyhow::Error;
  523. fn try_from(pd: _ProgramDeployment) -> Result<Self, Self::Error> {
  524. Ok(ProgramDeployment {
  525. address: pd.address.parse()?,
  526. path: pd.path,
  527. idl: pd.idl,
  528. })
  529. }
  530. }
  531. #[derive(Debug, Default, Serialize, Deserialize)]
  532. pub struct _ProgramDeployment {
  533. pub address: String,
  534. pub path: Option<String>,
  535. pub idl: Option<String>,
  536. }
  537. impl From<&ProgramDeployment> for _ProgramDeployment {
  538. fn from(pd: &ProgramDeployment) -> Self {
  539. Self {
  540. address: pd.address.to_string(),
  541. path: pd.path.clone(),
  542. idl: pd.idl.clone(),
  543. }
  544. }
  545. }
  546. pub struct ProgramWorkspace {
  547. pub name: String,
  548. pub program_id: Pubkey,
  549. pub idl: Idl,
  550. }
  551. #[derive(Debug, Serialize, Deserialize)]
  552. pub struct AnchorPackage {
  553. pub name: String,
  554. pub address: String,
  555. pub idl: Option<String>,
  556. }
  557. impl AnchorPackage {
  558. pub fn from(name: String, cfg: &WithPath<Config>) -> Result<Self> {
  559. let cluster = &cfg.provider.cluster;
  560. if cluster != &Cluster::Mainnet {
  561. return Err(anyhow!("Publishing requires the mainnet cluster"));
  562. }
  563. let program_details = cfg
  564. .programs
  565. .get(cluster)
  566. .ok_or_else(|| anyhow!("Program not provided in Anchor.toml"))?
  567. .get(&name)
  568. .ok_or_else(|| anyhow!("Program not provided in Anchor.toml"))?;
  569. let idl = program_details.idl.clone();
  570. let address = program_details.address.to_string();
  571. Ok(Self { name, address, idl })
  572. }
  573. }
  574. serum_common::home_path!(WalletPath, ".config/solana/id.json");