lib.rs 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188
  1. use crate::config::{
  2. AnchorPackage, Config, ConfigOverride, Manifest, ProgramDeployment, ProgramWorkspace, WithPath,
  3. };
  4. use anchor_client::Cluster;
  5. use anchor_lang::idl::{IdlAccount, IdlInstruction};
  6. use anchor_lang::{AccountDeserialize, AnchorDeserialize, AnchorSerialize};
  7. use anchor_syn::idl::Idl;
  8. use anyhow::{anyhow, Context, Result};
  9. use clap::Clap;
  10. use flate2::read::ZlibDecoder;
  11. use flate2::write::{GzEncoder, ZlibEncoder};
  12. use flate2::Compression;
  13. use heck::SnakeCase;
  14. use rand::rngs::OsRng;
  15. use reqwest::blocking::multipart::{Form, Part};
  16. use reqwest::blocking::Client;
  17. use serde::{Deserialize, Serialize};
  18. use solana_client::rpc_client::RpcClient;
  19. use solana_client::rpc_config::RpcSendTransactionConfig;
  20. use solana_program::instruction::{AccountMeta, Instruction};
  21. use solana_sdk::account_utils::StateMut;
  22. use solana_sdk::bpf_loader_upgradeable::UpgradeableLoaderState;
  23. use solana_sdk::commitment_config::CommitmentConfig;
  24. use solana_sdk::pubkey::Pubkey;
  25. use solana_sdk::signature::Keypair;
  26. use solana_sdk::signature::Signer;
  27. use solana_sdk::sysvar;
  28. use solana_sdk::transaction::Transaction;
  29. use std::collections::BTreeMap;
  30. use std::collections::HashMap;
  31. use std::fs::{self, File};
  32. use std::io::prelude::*;
  33. use std::path::{Path, PathBuf};
  34. use std::process::{Child, Stdio};
  35. use std::string::ToString;
  36. pub mod config;
  37. pub mod template;
  38. // Version of the docker image.
  39. pub const VERSION: &str = env!("CARGO_PKG_VERSION");
  40. pub const DOCKER_BUILDER_VERSION: &str = VERSION;
  41. #[derive(Debug, Clap)]
  42. #[clap(version = VERSION)]
  43. pub struct Opts {
  44. #[clap(flatten)]
  45. pub cfg_override: ConfigOverride,
  46. #[clap(subcommand)]
  47. pub command: Command,
  48. }
  49. #[derive(Debug, Clap)]
  50. pub enum Command {
  51. /// Initializes a workspace.
  52. Init {
  53. name: String,
  54. #[clap(short, long)]
  55. typescript: bool,
  56. },
  57. /// Builds the workspace.
  58. Build {
  59. /// Output directory for the IDL.
  60. #[clap(short, long)]
  61. idl: Option<String>,
  62. /// True if the build artifact needs to be deterministic and verifiable.
  63. #[clap(short, long)]
  64. verifiable: bool,
  65. #[clap(short, long)]
  66. program_name: Option<String>,
  67. /// Version of the Solana toolchain to use. For --verifiable builds
  68. /// only.
  69. #[clap(short, long)]
  70. solana_version: Option<String>,
  71. },
  72. /// Verifies the on-chain bytecode matches the locally compiled artifact.
  73. /// Run this command inside a program subdirectory, i.e., in the dir
  74. /// containing the program's Cargo.toml.
  75. Verify {
  76. /// The deployed program to compare against.
  77. program_id: Pubkey,
  78. #[clap(short, long)]
  79. program_name: Option<String>,
  80. /// Version of the Solana toolchain to use. For --verifiable builds
  81. /// only.
  82. #[clap(short, long)]
  83. solana_version: Option<String>,
  84. },
  85. /// Runs integration tests against a localnetwork.
  86. Test {
  87. /// Use this flag if you want to run tests against previously deployed
  88. /// programs.
  89. #[clap(long)]
  90. skip_deploy: bool,
  91. /// Flag to skip starting a local validator, if the configured cluster
  92. /// url is a localnet.
  93. #[clap(long)]
  94. skip_local_validator: bool,
  95. /// Flag to skip building the program in the workspace,
  96. /// use this to save time when running test and the program code is not altered.
  97. #[clap(long)]
  98. skip_build: bool,
  99. /// Flag to keep the local validator running after tests
  100. /// to be able to check the transactions.
  101. #[clap(long)]
  102. detach: bool,
  103. #[clap(multiple_values = true)]
  104. args: Vec<String>,
  105. },
  106. /// Creates a new program.
  107. New { name: String },
  108. /// Commands for interacting with interface definitions.
  109. Idl {
  110. #[clap(subcommand)]
  111. subcmd: IdlCommand,
  112. },
  113. /// Deploys each program in the workspace.
  114. Deploy {
  115. #[clap(short, long)]
  116. program_name: Option<String>,
  117. },
  118. /// Runs the deploy migration script.
  119. Migrate,
  120. /// Deploys, initializes an IDL, and migrates all in one command.
  121. /// Upgrades a single program. The configured wallet must be the upgrade
  122. /// authority.
  123. Upgrade {
  124. /// The program to upgrade.
  125. #[clap(short, long)]
  126. program_id: Pubkey,
  127. /// Filepath to the new program binary.
  128. program_filepath: String,
  129. },
  130. #[cfg(feature = "dev")]
  131. /// Runs an airdrop loop, continuously funding the configured wallet.
  132. Airdrop {
  133. #[clap(short, long)]
  134. url: Option<String>,
  135. },
  136. /// Cluster commands.
  137. Cluster {
  138. #[clap(subcommand)]
  139. subcmd: ClusterCommand,
  140. },
  141. /// Starts a node shell with an Anchor client setup according to the local
  142. /// config.
  143. Shell,
  144. /// Runs the script defined by the current workspace's Anchor.toml.
  145. Run {
  146. /// The name of the script to run.
  147. script: String,
  148. },
  149. /// Saves an api token from the registry locally.
  150. Login {
  151. /// API access token.
  152. token: String,
  153. },
  154. /// Publishes a verified build to the Anchor registry.
  155. Publish {
  156. /// The name of the program to publish.
  157. program: String,
  158. },
  159. /// Keypair commands.
  160. Keys {
  161. #[clap(subcommand)]
  162. subcmd: KeysCommand,
  163. },
  164. }
  165. #[derive(Debug, Clap)]
  166. pub enum KeysCommand {
  167. List,
  168. }
  169. #[derive(Debug, Clap)]
  170. pub enum IdlCommand {
  171. /// Initializes a program's IDL account. Can only be run once.
  172. Init {
  173. program_id: Pubkey,
  174. #[clap(short, long)]
  175. filepath: String,
  176. },
  177. /// Writes an IDL into a buffer account. This can be used with SetBuffer
  178. /// to perform an upgrade.
  179. WriteBuffer {
  180. program_id: Pubkey,
  181. #[clap(short, long)]
  182. filepath: String,
  183. },
  184. /// Sets a new IDL buffer for the program.
  185. SetBuffer {
  186. program_id: Pubkey,
  187. /// Address of the buffer account to set as the idl on the program.
  188. #[clap(short, long)]
  189. buffer: Pubkey,
  190. },
  191. /// Upgrades the IDL to the new file. An alias for first writing and then
  192. /// then setting the idl buffer account.
  193. Upgrade {
  194. program_id: Pubkey,
  195. #[clap(short, long)]
  196. filepath: String,
  197. },
  198. /// Sets a new authority on the IDL account.
  199. SetAuthority {
  200. /// The IDL account buffer to set the authority of. If none is given,
  201. /// then the canonical IDL account is used.
  202. address: Option<Pubkey>,
  203. /// Program to change the IDL authority.
  204. #[clap(short, long)]
  205. program_id: Pubkey,
  206. /// New authority of the IDL account.
  207. #[clap(short, long)]
  208. new_authority: Pubkey,
  209. },
  210. /// Command to remove the ability to modify the IDL account. This should
  211. /// likely be used in conjection with eliminating an "upgrade authority" on
  212. /// the program.
  213. EraseAuthority {
  214. #[clap(short, long)]
  215. program_id: Pubkey,
  216. },
  217. /// Outputs the authority for the IDL account.
  218. Authority {
  219. /// The program to view.
  220. program_id: Pubkey,
  221. },
  222. /// Parses an IDL from source.
  223. Parse {
  224. /// Path to the program's interface definition.
  225. #[clap(short, long)]
  226. file: String,
  227. /// Output file for the idl (stdout if not specified).
  228. #[clap(short, long)]
  229. out: Option<String>,
  230. },
  231. /// Fetches an IDL for the given address from a cluster.
  232. /// The address can be a program, IDL account, or IDL buffer.
  233. Fetch {
  234. address: Pubkey,
  235. /// Output file for the idl (stdout if not specified).
  236. #[clap(short, long)]
  237. out: Option<String>,
  238. },
  239. }
  240. #[derive(Debug, Clap)]
  241. pub enum ClusterCommand {
  242. /// Prints common cluster urls.
  243. List,
  244. }
  245. pub fn entry(opts: Opts) -> Result<()> {
  246. match opts.command {
  247. Command::Init { name, typescript } => init(&opts.cfg_override, name, typescript),
  248. Command::New { name } => new(&opts.cfg_override, name),
  249. Command::Build {
  250. idl,
  251. verifiable,
  252. program_name,
  253. solana_version,
  254. } => build(
  255. &opts.cfg_override,
  256. idl,
  257. verifiable,
  258. program_name,
  259. solana_version,
  260. None,
  261. None,
  262. ),
  263. Command::Verify {
  264. program_id,
  265. program_name,
  266. solana_version,
  267. } => verify(&opts.cfg_override, program_id, program_name, solana_version),
  268. Command::Deploy { program_name } => deploy(&opts.cfg_override, program_name),
  269. Command::Upgrade {
  270. program_id,
  271. program_filepath,
  272. } => upgrade(&opts.cfg_override, program_id, program_filepath),
  273. Command::Idl { subcmd } => idl(&opts.cfg_override, subcmd),
  274. Command::Migrate => migrate(&opts.cfg_override),
  275. Command::Test {
  276. skip_deploy,
  277. skip_local_validator,
  278. skip_build,
  279. detach,
  280. args,
  281. } => test(
  282. &opts.cfg_override,
  283. skip_deploy,
  284. skip_local_validator,
  285. skip_build,
  286. detach,
  287. args,
  288. ),
  289. #[cfg(feature = "dev")]
  290. Command::Airdrop => airdrop(cfg_override),
  291. Command::Cluster { subcmd } => cluster(subcmd),
  292. Command::Shell => shell(&opts.cfg_override),
  293. Command::Run { script } => run(&opts.cfg_override, script),
  294. Command::Login { token } => login(&opts.cfg_override, token),
  295. Command::Publish { program } => publish(&opts.cfg_override, program),
  296. Command::Keys { subcmd } => keys(&opts.cfg_override, subcmd),
  297. }
  298. }
  299. fn init(cfg_override: &ConfigOverride, name: String, typescript: bool) -> Result<()> {
  300. if Config::discover(cfg_override)?.is_some() {
  301. return Err(anyhow!("Workspace already initialized"));
  302. }
  303. fs::create_dir(name.clone())?;
  304. std::env::set_current_dir(&name)?;
  305. fs::create_dir("app")?;
  306. let mut cfg = Config::default();
  307. cfg.scripts.insert(
  308. "test".to_owned(),
  309. if typescript {
  310. "ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
  311. } else {
  312. "mocha -t 1000000 tests/"
  313. }
  314. .to_owned(),
  315. );
  316. let mut localnet = BTreeMap::new();
  317. localnet.insert(
  318. name.to_snake_case(),
  319. ProgramDeployment {
  320. address: template::default_program_id(),
  321. path: None,
  322. idl: None,
  323. },
  324. );
  325. cfg.programs.insert(Cluster::Localnet, localnet);
  326. let toml = cfg.to_string();
  327. let mut file = File::create("Anchor.toml")?;
  328. file.write_all(toml.as_bytes())?;
  329. // Build virtual manifest.
  330. let mut virt_manifest = File::create("Cargo.toml")?;
  331. virt_manifest.write_all(template::virtual_manifest().as_bytes())?;
  332. // Initialize .gitignore file
  333. let mut virt_manifest = File::create(".gitignore")?;
  334. virt_manifest.write_all(template::git_ignore().as_bytes())?;
  335. // Build the program.
  336. fs::create_dir("programs")?;
  337. new_program(&name)?;
  338. // Build the test suite.
  339. fs::create_dir("tests")?;
  340. // Build the migrations directory.
  341. fs::create_dir("migrations")?;
  342. if typescript {
  343. // Build typescript config
  344. let mut ts_config = File::create("tsconfig.json")?;
  345. ts_config.write_all(template::ts_config().as_bytes())?;
  346. let mut ts_package_json = File::create("package.json")?;
  347. ts_package_json.write_all(template::ts_package_json().as_bytes())?;
  348. let mut deploy = File::create("migrations/deploy.ts")?;
  349. deploy.write_all(template::ts_deploy_script().as_bytes())?;
  350. let mut mocha = File::create(&format!("tests/{}.ts", name))?;
  351. mocha.write_all(template::ts_mocha(&name).as_bytes())?;
  352. } else {
  353. let mut package_json = File::create("package.json")?;
  354. package_json.write_all(template::package_json().as_bytes())?;
  355. let mut mocha = File::create(&format!("tests/{}.js", name))?;
  356. mocha.write_all(template::mocha(&name).as_bytes())?;
  357. let mut deploy = File::create("migrations/deploy.js")?;
  358. deploy.write_all(template::deploy_script().as_bytes())?;
  359. }
  360. // Install node modules.
  361. let yarn_result = std::process::Command::new("yarn")
  362. .stdout(Stdio::inherit())
  363. .stderr(Stdio::inherit())
  364. .output()
  365. .map_err(|e| anyhow::format_err!("yarn install failed: {}", e.to_string()))?;
  366. if !yarn_result.status.success() {
  367. println!("Failed yarn install will attempt to npm install");
  368. std::process::Command::new("npm")
  369. .stdout(Stdio::inherit())
  370. .stderr(Stdio::inherit())
  371. .output()
  372. .map_err(|e| anyhow::format_err!("npm install failed: {}", e.to_string()))?;
  373. println!("Failed to install node dependencies")
  374. }
  375. println!("{} initialized", name);
  376. Ok(())
  377. }
  378. // Creates a new program crate in the `programs/<name>` directory.
  379. fn new(cfg_override: &ConfigOverride, name: String) -> Result<()> {
  380. with_workspace(cfg_override, |cfg| {
  381. match cfg.path().parent() {
  382. None => {
  383. println!("Unable to make new program");
  384. }
  385. Some(parent) => {
  386. std::env::set_current_dir(&parent)?;
  387. new_program(&name)?;
  388. println!("Created new program.");
  389. }
  390. };
  391. Ok(())
  392. })
  393. }
  394. // Creates a new program crate in the current directory with `name`.
  395. fn new_program(name: &str) -> Result<()> {
  396. fs::create_dir(&format!("programs/{}", name))?;
  397. fs::create_dir(&format!("programs/{}/src/", name))?;
  398. let mut cargo_toml = File::create(&format!("programs/{}/Cargo.toml", name))?;
  399. cargo_toml.write_all(template::cargo_toml(name).as_bytes())?;
  400. let mut xargo_toml = File::create(&format!("programs/{}/Xargo.toml", name))?;
  401. xargo_toml.write_all(template::xargo_toml().as_bytes())?;
  402. let mut lib_rs = File::create(&format!("programs/{}/src/lib.rs", name))?;
  403. lib_rs.write_all(template::lib_rs(name).as_bytes())?;
  404. Ok(())
  405. }
  406. pub fn build(
  407. cfg_override: &ConfigOverride,
  408. idl: Option<String>,
  409. verifiable: bool,
  410. program_name: Option<String>,
  411. solana_version: Option<String>,
  412. stdout: Option<File>, // Used for the package registry server.
  413. stderr: Option<File>, // Used for the package registry server.
  414. ) -> Result<()> {
  415. // Change to the workspace member directory, if needed.
  416. if let Some(program_name) = program_name.as_ref() {
  417. cd_member(cfg_override, program_name)?;
  418. }
  419. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  420. let cargo = Manifest::discover()?;
  421. let idl_out = match idl {
  422. Some(idl) => Some(PathBuf::from(idl)),
  423. None => {
  424. let cfg_parent = match cfg.path().parent() {
  425. None => return Err(anyhow!("Invalid Anchor.toml")),
  426. Some(parent) => parent,
  427. };
  428. fs::create_dir_all(cfg_parent.join("target/idl"))?;
  429. Some(cfg_parent.join("target/idl"))
  430. }
  431. };
  432. let solana_version = match solana_version.is_some() {
  433. true => solana_version,
  434. false => cfg.solana_version.clone(),
  435. };
  436. match cargo {
  437. // No Cargo.toml so build the entire workspace.
  438. None => build_all(
  439. &cfg,
  440. cfg.path(),
  441. idl_out,
  442. verifiable,
  443. solana_version,
  444. stdout,
  445. stderr,
  446. )?,
  447. // If the Cargo.toml is at the root, build the entire workspace.
  448. Some(cargo) if cargo.path().parent() == cfg.path().parent() => build_all(
  449. &cfg,
  450. cfg.path(),
  451. idl_out,
  452. verifiable,
  453. solana_version,
  454. stdout,
  455. stderr,
  456. )?,
  457. // Cargo.toml represents a single package. Build it.
  458. Some(cargo) => build_cwd(
  459. &cfg,
  460. cargo.path().to_path_buf(),
  461. idl_out,
  462. verifiable,
  463. solana_version,
  464. stdout,
  465. stderr,
  466. )?,
  467. }
  468. set_workspace_dir_or_exit();
  469. Ok(())
  470. }
  471. fn build_all(
  472. cfg: &WithPath<Config>,
  473. cfg_path: &Path,
  474. idl_out: Option<PathBuf>,
  475. verifiable: bool,
  476. solana_version: Option<String>,
  477. stdout: Option<File>, // Used for the package registry server.
  478. stderr: Option<File>, // Used for the package registry server.
  479. ) -> Result<()> {
  480. let cur_dir = std::env::current_dir()?;
  481. let r = match cfg_path.parent() {
  482. None => Err(anyhow!("Invalid Anchor.toml at {}", cfg_path.display())),
  483. Some(_parent) => {
  484. for p in cfg.get_program_list()? {
  485. build_cwd(
  486. cfg,
  487. p.join("Cargo.toml"),
  488. idl_out.clone(),
  489. verifiable,
  490. solana_version.clone(),
  491. stdout.as_ref().map(|f| f.try_clone()).transpose()?,
  492. stderr.as_ref().map(|f| f.try_clone()).transpose()?,
  493. )?;
  494. }
  495. Ok(())
  496. }
  497. };
  498. std::env::set_current_dir(cur_dir)?;
  499. r
  500. }
  501. // Runs the build command outside of a workspace.
  502. fn build_cwd(
  503. cfg: &WithPath<Config>,
  504. cargo_toml: PathBuf,
  505. idl_out: Option<PathBuf>,
  506. verifiable: bool,
  507. solana_version: Option<String>,
  508. stdout: Option<File>,
  509. stderr: Option<File>,
  510. ) -> Result<()> {
  511. match cargo_toml.parent() {
  512. None => return Err(anyhow!("Unable to find parent")),
  513. Some(p) => std::env::set_current_dir(&p)?,
  514. };
  515. match verifiable {
  516. false => _build_cwd(idl_out),
  517. true => build_cwd_verifiable(cfg, cargo_toml, solana_version, stdout, stderr),
  518. }
  519. }
  520. // Builds an anchor program in a docker image and copies the build artifacts
  521. // into the `target/` directory.
  522. fn build_cwd_verifiable(
  523. cfg: &WithPath<Config>,
  524. cargo_toml: PathBuf,
  525. solana_version: Option<String>,
  526. stdout: Option<File>,
  527. stderr: Option<File>,
  528. ) -> Result<()> {
  529. // Create output dirs.
  530. let workspace_dir = cfg.path().parent().unwrap().canonicalize()?;
  531. fs::create_dir_all(workspace_dir.join("target/verifiable"))?;
  532. fs::create_dir_all(workspace_dir.join("target/idl"))?;
  533. let container_name = "anchor-program";
  534. // Build the binary in docker.
  535. let result = docker_build(
  536. cfg,
  537. container_name,
  538. cargo_toml,
  539. solana_version,
  540. stdout,
  541. stderr,
  542. );
  543. // Wipe the generated docker-target dir.
  544. println!("Cleaning up the docker target directory");
  545. let exit = std::process::Command::new("docker")
  546. .args(&[
  547. "exec",
  548. container_name,
  549. "rm",
  550. "-rf",
  551. "/workdir/docker-target",
  552. ])
  553. .stdout(Stdio::inherit())
  554. .stderr(Stdio::inherit())
  555. .output()
  556. .map_err(|e| anyhow::format_err!("Docker rm docker-target failed: {}", e.to_string()))?;
  557. if !exit.status.success() {
  558. return Err(anyhow!("Failed to build program"));
  559. }
  560. // Remove the docker image.
  561. println!("Removing the docker image");
  562. let exit = std::process::Command::new("docker")
  563. .args(&["rm", "-f", container_name])
  564. .stdout(Stdio::inherit())
  565. .stderr(Stdio::inherit())
  566. .output()
  567. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  568. if !exit.status.success() {
  569. println!("Unable to remove docker container");
  570. std::process::exit(exit.status.code().unwrap_or(1));
  571. }
  572. // Build the idl.
  573. if let Ok(Some(idl)) = extract_idl("src/lib.rs") {
  574. println!("Extracting the IDL");
  575. let out_file = workspace_dir.join(format!("target/idl/{}.json", idl.name));
  576. write_idl(&idl, OutFile::File(out_file))?;
  577. }
  578. result
  579. }
  580. fn docker_build(
  581. cfg: &WithPath<Config>,
  582. container_name: &str,
  583. cargo_toml: PathBuf,
  584. solana_version: Option<String>,
  585. stdout: Option<File>,
  586. stderr: Option<File>,
  587. ) -> Result<()> {
  588. let binary_name = Manifest::from_path(&cargo_toml)?.lib_name()?;
  589. // Docker vars.
  590. let image_name = cfg.docker();
  591. let volume_mount = format!(
  592. "{}:/workdir",
  593. cfg.path().parent().unwrap().canonicalize()?.display()
  594. );
  595. println!("Using image {:?}", image_name);
  596. // Start the docker image running detached in the background.
  597. println!("Run docker image");
  598. let exit = std::process::Command::new("docker")
  599. .args(&[
  600. "run",
  601. "-it",
  602. "-d",
  603. "--name",
  604. container_name,
  605. "--env",
  606. "CARGO_TARGET_DIR=/workdir/docker-target",
  607. "-v",
  608. &volume_mount,
  609. &image_name,
  610. "bash",
  611. ])
  612. .stdout(Stdio::inherit())
  613. .stderr(Stdio::inherit())
  614. .output()
  615. .map_err(|e| anyhow::format_err!("Docker build failed: {}", e.to_string()))?;
  616. if !exit.status.success() {
  617. return Err(anyhow!("Failed to build program"));
  618. }
  619. // Set the solana version in the container, if given. Otherwise use the
  620. // default.
  621. if let Some(solana_version) = solana_version {
  622. println!("Using solana version: {}", solana_version);
  623. // Fetch the installer.
  624. let exit = std::process::Command::new("docker")
  625. .args(&[
  626. "exec",
  627. container_name,
  628. "curl",
  629. "-sSfL",
  630. &format!("https://release.solana.com/v{0}/install", solana_version,),
  631. "-o",
  632. "solana_installer.sh",
  633. ])
  634. .stdout(Stdio::inherit())
  635. .stderr(Stdio::inherit())
  636. .output()
  637. .map_err(|e| anyhow!("Failed to set solana version: {:?}", e))?;
  638. if !exit.status.success() {
  639. return Err(anyhow!("Failed to set solana version"));
  640. }
  641. // Run the installer.
  642. let exit = std::process::Command::new("docker")
  643. .args(&["exec", container_name, "sh", "solana_installer.sh"])
  644. .stdout(Stdio::inherit())
  645. .stderr(Stdio::inherit())
  646. .output()
  647. .map_err(|e| anyhow!("Failed to set solana version: {:?}", e))?;
  648. if !exit.status.success() {
  649. return Err(anyhow!("Failed to set solana version"));
  650. }
  651. // Remove the installer.
  652. let exit = std::process::Command::new("docker")
  653. .args(&["exec", container_name, "rm", "-f", "solana_installer.sh"])
  654. .stdout(Stdio::inherit())
  655. .stderr(Stdio::inherit())
  656. .output()
  657. .map_err(|e| anyhow!("Failed to remove installer: {:?}", e))?;
  658. if !exit.status.success() {
  659. return Err(anyhow!("Failed to remove installer"));
  660. }
  661. }
  662. let manifest_path = pathdiff::diff_paths(
  663. cargo_toml.canonicalize()?,
  664. cfg.path().parent().unwrap().canonicalize()?,
  665. )
  666. .ok_or_else(|| anyhow!("Unable to diff paths"))?;
  667. println!(
  668. "Building {} manifest: {:?}",
  669. binary_name,
  670. manifest_path.display().to_string()
  671. );
  672. // Execute the build.
  673. let exit = std::process::Command::new("docker")
  674. .args(&[
  675. "exec",
  676. container_name,
  677. "cargo",
  678. "build-bpf",
  679. "--manifest-path",
  680. &manifest_path.display().to_string(),
  681. ])
  682. .stdout(match stdout {
  683. None => Stdio::inherit(),
  684. Some(f) => f.into(),
  685. })
  686. .stderr(match stderr {
  687. None => Stdio::inherit(),
  688. Some(f) => f.into(),
  689. })
  690. .output()
  691. .map_err(|e| anyhow::format_err!("Docker build failed: {}", e.to_string()))?;
  692. if !exit.status.success() {
  693. return Err(anyhow!("Failed to build program"));
  694. }
  695. // Copy the binary out of the docker image.
  696. println!("Copying out the build artifacts");
  697. let out_file = cfg
  698. .path()
  699. .parent()
  700. .unwrap()
  701. .canonicalize()?
  702. .join(format!("target/verifiable/{}.so", binary_name))
  703. .display()
  704. .to_string();
  705. // This requires the target directory of any built program to be located at
  706. // the root of the workspace.
  707. let bin_artifact = format!(
  708. "{}:/workdir/docker-target/deploy/{}.so",
  709. container_name, binary_name
  710. );
  711. let exit = std::process::Command::new("docker")
  712. .args(&["cp", &bin_artifact, &out_file])
  713. .stdout(Stdio::inherit())
  714. .stderr(Stdio::inherit())
  715. .output()
  716. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  717. if !exit.status.success() {
  718. return Err(anyhow!(
  719. "Failed to copy binary out of docker. Is the target directory set correctly?"
  720. ));
  721. }
  722. // Done.
  723. Ok(())
  724. }
  725. fn _build_cwd(idl_out: Option<PathBuf>) -> Result<()> {
  726. let exit = std::process::Command::new("cargo")
  727. .arg("build-bpf")
  728. .stdout(Stdio::inherit())
  729. .stderr(Stdio::inherit())
  730. .output()
  731. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  732. if !exit.status.success() {
  733. std::process::exit(exit.status.code().unwrap_or(1));
  734. }
  735. // Always assume idl is located ar src/lib.rs.
  736. if let Some(idl) = extract_idl("src/lib.rs")? {
  737. let out = match idl_out {
  738. None => PathBuf::from(".").join(&idl.name).with_extension("json"),
  739. Some(o) => PathBuf::from(&o.join(&idl.name).with_extension("json")),
  740. };
  741. write_idl(&idl, OutFile::File(out))?;
  742. }
  743. Ok(())
  744. }
  745. fn verify(
  746. cfg_override: &ConfigOverride,
  747. program_id: Pubkey,
  748. program_name: Option<String>,
  749. solana_version: Option<String>,
  750. ) -> Result<()> {
  751. // Change to the workspace member directory, if needed.
  752. if let Some(program_name) = program_name.as_ref() {
  753. cd_member(cfg_override, program_name)?;
  754. }
  755. // Proceed with the command.
  756. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  757. let cargo = Manifest::discover()?.ok_or_else(|| anyhow!("Cargo.toml not found"))?;
  758. // Build the program we want to verify.
  759. let cur_dir = std::env::current_dir()?;
  760. build(
  761. cfg_override,
  762. None,
  763. true,
  764. None,
  765. match solana_version.is_some() {
  766. true => solana_version,
  767. false => cfg.solana_version.clone(),
  768. },
  769. None,
  770. None,
  771. )?;
  772. std::env::set_current_dir(&cur_dir)?;
  773. // Verify binary.
  774. let binary_name = cargo.lib_name()?;
  775. let bin_path = cfg
  776. .path()
  777. .parent()
  778. .ok_or_else(|| anyhow!("Unable to find workspace root"))?
  779. .join("target/verifiable/")
  780. .join(format!("{}.so", binary_name));
  781. let bin_ver = verify_bin(program_id, &bin_path, cfg.provider.cluster.url())?;
  782. if !bin_ver.is_verified {
  783. println!("Error: Binaries don't match");
  784. std::process::exit(1);
  785. }
  786. // Verify IDL (only if it's not a buffer account).
  787. if let Some(local_idl) = extract_idl("src/lib.rs")? {
  788. if bin_ver.state != BinVerificationState::Buffer {
  789. let deployed_idl = fetch_idl(cfg_override, program_id)?;
  790. if local_idl != deployed_idl {
  791. println!("Error: IDLs don't match");
  792. std::process::exit(1);
  793. }
  794. }
  795. }
  796. println!("{} is verified.", program_id);
  797. Ok(())
  798. }
  799. fn cd_member(cfg_override: &ConfigOverride, program_name: &str) -> Result<()> {
  800. // Change directories to the given `program_name`, if given.
  801. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  802. for program in cfg.read_all_programs()? {
  803. let cargo_toml = program.path.join("Cargo.toml");
  804. if !cargo_toml.exists() {
  805. return Err(anyhow!(
  806. "Did not find Cargo.toml at the path: {}",
  807. program.path.display()
  808. ));
  809. }
  810. let p_lib_name = Manifest::from_path(&cargo_toml)?.lib_name()?;
  811. if program_name == p_lib_name {
  812. std::env::set_current_dir(&program.path)?;
  813. return Ok(());
  814. }
  815. }
  816. return Err(anyhow!("{} is not part of the workspace", program_name,));
  817. }
  818. pub fn verify_bin(program_id: Pubkey, bin_path: &Path, cluster: &str) -> Result<BinVerification> {
  819. let client = RpcClient::new(cluster.to_string());
  820. // Get the deployed build artifacts.
  821. let (deployed_bin, state) = {
  822. let account = client
  823. .get_account_with_commitment(&program_id, CommitmentConfig::default())?
  824. .value
  825. .map_or(Err(anyhow!("Account not found")), Ok)?;
  826. match account.state()? {
  827. UpgradeableLoaderState::Program {
  828. programdata_address,
  829. } => {
  830. let account = client
  831. .get_account_with_commitment(&programdata_address, CommitmentConfig::default())?
  832. .value
  833. .map_or(Err(anyhow!("Account not found")), Ok)?;
  834. let bin = account.data
  835. [UpgradeableLoaderState::programdata_data_offset().unwrap_or(0)..]
  836. .to_vec();
  837. if let UpgradeableLoaderState::ProgramData {
  838. slot,
  839. upgrade_authority_address,
  840. } = account.state()?
  841. {
  842. let state = BinVerificationState::ProgramData {
  843. slot,
  844. upgrade_authority_address,
  845. };
  846. (bin, state)
  847. } else {
  848. return Err(anyhow!("Expected program data"));
  849. }
  850. }
  851. UpgradeableLoaderState::Buffer { .. } => {
  852. let offset = UpgradeableLoaderState::buffer_data_offset().unwrap_or(0);
  853. (
  854. account.data[offset..].to_vec(),
  855. BinVerificationState::Buffer,
  856. )
  857. }
  858. _ => return Err(anyhow!("Invalid program id")),
  859. }
  860. };
  861. let mut local_bin = {
  862. let mut f = File::open(bin_path)?;
  863. let mut contents = vec![];
  864. f.read_to_end(&mut contents)?;
  865. contents
  866. };
  867. // The deployed program probably has zero bytes appended. The default is
  868. // 2x the binary size in case of an upgrade.
  869. if local_bin.len() < deployed_bin.len() {
  870. local_bin.append(&mut vec![0; deployed_bin.len() - local_bin.len()]);
  871. }
  872. // Finally, check the bytes.
  873. let is_verified = local_bin == deployed_bin;
  874. Ok(BinVerification { state, is_verified })
  875. }
  876. #[derive(PartialEq)]
  877. pub struct BinVerification {
  878. pub state: BinVerificationState,
  879. pub is_verified: bool,
  880. }
  881. #[derive(PartialEq)]
  882. pub enum BinVerificationState {
  883. Buffer,
  884. ProgramData {
  885. slot: u64,
  886. upgrade_authority_address: Option<Pubkey>,
  887. },
  888. }
  889. // Fetches an IDL for the given program_id.
  890. fn fetch_idl(cfg_override: &ConfigOverride, idl_addr: Pubkey) -> Result<Idl> {
  891. let cfg = Config::discover(cfg_override)?.expect("Inside a workspace");
  892. let client = RpcClient::new(cfg.provider.cluster.url().to_string());
  893. let mut account = client
  894. .get_account_with_commitment(&idl_addr, CommitmentConfig::processed())?
  895. .value
  896. .map_or(Err(anyhow!("Account not found")), Ok)?;
  897. if account.executable {
  898. let idl_addr = IdlAccount::address(&idl_addr);
  899. account = client
  900. .get_account_with_commitment(&idl_addr, CommitmentConfig::processed())?
  901. .value
  902. .map_or(Err(anyhow!("Account not found")), Ok)?;
  903. }
  904. // Cut off account discriminator.
  905. let mut d: &[u8] = &account.data[8..];
  906. let idl_account: IdlAccount = AnchorDeserialize::deserialize(&mut d)?;
  907. let mut z = ZlibDecoder::new(&idl_account.data[..]);
  908. let mut s = Vec::new();
  909. z.read_to_end(&mut s)?;
  910. serde_json::from_slice(&s[..]).map_err(Into::into)
  911. }
  912. fn extract_idl(file: &str) -> Result<Option<Idl>> {
  913. let file = shellexpand::tilde(file);
  914. anchor_syn::idl::file::parse(&*file)
  915. }
  916. fn idl(cfg_override: &ConfigOverride, subcmd: IdlCommand) -> Result<()> {
  917. match subcmd {
  918. IdlCommand::Init {
  919. program_id,
  920. filepath,
  921. } => idl_init(cfg_override, program_id, filepath),
  922. IdlCommand::WriteBuffer {
  923. program_id,
  924. filepath,
  925. } => idl_write_buffer(cfg_override, program_id, filepath).map(|_| ()),
  926. IdlCommand::SetBuffer { program_id, buffer } => {
  927. idl_set_buffer(cfg_override, program_id, buffer)
  928. }
  929. IdlCommand::Upgrade {
  930. program_id,
  931. filepath,
  932. } => idl_upgrade(cfg_override, program_id, filepath),
  933. IdlCommand::SetAuthority {
  934. program_id,
  935. address,
  936. new_authority,
  937. } => idl_set_authority(cfg_override, program_id, address, new_authority),
  938. IdlCommand::EraseAuthority { program_id } => idl_erase_authority(cfg_override, program_id),
  939. IdlCommand::Authority { program_id } => idl_authority(cfg_override, program_id),
  940. IdlCommand::Parse { file, out } => idl_parse(file, out),
  941. IdlCommand::Fetch { address, out } => idl_fetch(cfg_override, address, out),
  942. }
  943. }
  944. fn idl_init(cfg_override: &ConfigOverride, program_id: Pubkey, idl_filepath: String) -> Result<()> {
  945. with_workspace(cfg_override, |cfg| {
  946. let keypair = cfg.provider.wallet.to_string();
  947. let bytes = std::fs::read(idl_filepath)?;
  948. let idl: Idl = serde_json::from_reader(&*bytes)?;
  949. let idl_address = create_idl_account(cfg, &keypair, &program_id, &idl)?;
  950. println!("Idl account created: {:?}", idl_address);
  951. Ok(())
  952. })
  953. }
  954. fn idl_write_buffer(
  955. cfg_override: &ConfigOverride,
  956. program_id: Pubkey,
  957. idl_filepath: String,
  958. ) -> Result<Pubkey> {
  959. with_workspace(cfg_override, |cfg| {
  960. let keypair = cfg.provider.wallet.to_string();
  961. let bytes = std::fs::read(idl_filepath)?;
  962. let idl: Idl = serde_json::from_reader(&*bytes)?;
  963. let idl_buffer = create_idl_buffer(cfg, &keypair, &program_id, &idl)?;
  964. idl_write(cfg, &program_id, &idl, idl_buffer)?;
  965. println!("Idl buffer created: {:?}", idl_buffer);
  966. Ok(idl_buffer)
  967. })
  968. }
  969. fn idl_set_buffer(cfg_override: &ConfigOverride, program_id: Pubkey, buffer: Pubkey) -> Result<()> {
  970. with_workspace(cfg_override, |cfg| {
  971. let keypair = solana_sdk::signature::read_keypair_file(&cfg.provider.wallet.to_string())
  972. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  973. let client = RpcClient::new(cfg.provider.cluster.url().to_string());
  974. // Instruction to set the buffer onto the IdlAccount.
  975. let set_buffer_ix = {
  976. let accounts = vec![
  977. AccountMeta::new(buffer, false),
  978. AccountMeta::new(IdlAccount::address(&program_id), false),
  979. AccountMeta::new(keypair.pubkey(), true),
  980. ];
  981. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  982. data.append(&mut IdlInstruction::SetBuffer.try_to_vec()?);
  983. Instruction {
  984. program_id,
  985. accounts,
  986. data,
  987. }
  988. };
  989. // Build the transaction.
  990. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  991. let tx = Transaction::new_signed_with_payer(
  992. &[set_buffer_ix],
  993. Some(&keypair.pubkey()),
  994. &[&keypair],
  995. recent_hash,
  996. );
  997. // Send the transaction.
  998. client.send_and_confirm_transaction_with_spinner_and_config(
  999. &tx,
  1000. CommitmentConfig::confirmed(),
  1001. RpcSendTransactionConfig {
  1002. skip_preflight: true,
  1003. ..RpcSendTransactionConfig::default()
  1004. },
  1005. )?;
  1006. Ok(())
  1007. })
  1008. }
  1009. fn idl_upgrade(
  1010. cfg_override: &ConfigOverride,
  1011. program_id: Pubkey,
  1012. idl_filepath: String,
  1013. ) -> Result<()> {
  1014. let buffer = idl_write_buffer(cfg_override, program_id, idl_filepath)?;
  1015. idl_set_buffer(cfg_override, program_id, buffer)
  1016. }
  1017. fn idl_authority(cfg_override: &ConfigOverride, program_id: Pubkey) -> Result<()> {
  1018. with_workspace(cfg_override, |cfg| {
  1019. let client = RpcClient::new(cfg.provider.cluster.url().to_string());
  1020. let idl_address = {
  1021. let account = client
  1022. .get_account_with_commitment(&program_id, CommitmentConfig::processed())?
  1023. .value
  1024. .map_or(Err(anyhow!("Account not found")), Ok)?;
  1025. if account.executable {
  1026. IdlAccount::address(&program_id)
  1027. } else {
  1028. program_id
  1029. }
  1030. };
  1031. let account = client.get_account(&idl_address)?;
  1032. let mut data: &[u8] = &account.data;
  1033. let idl_account: IdlAccount = AccountDeserialize::try_deserialize(&mut data)?;
  1034. println!("{:?}", idl_account.authority);
  1035. Ok(())
  1036. })
  1037. }
  1038. fn idl_set_authority(
  1039. cfg_override: &ConfigOverride,
  1040. program_id: Pubkey,
  1041. address: Option<Pubkey>,
  1042. new_authority: Pubkey,
  1043. ) -> Result<()> {
  1044. with_workspace(cfg_override, |cfg| {
  1045. // Misc.
  1046. let idl_address = match address {
  1047. None => IdlAccount::address(&program_id),
  1048. Some(addr) => addr,
  1049. };
  1050. let keypair = solana_sdk::signature::read_keypair_file(&cfg.provider.wallet.to_string())
  1051. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1052. let client = RpcClient::new(cfg.provider.cluster.url().to_string());
  1053. // Instruction data.
  1054. let data =
  1055. serialize_idl_ix(anchor_lang::idl::IdlInstruction::SetAuthority { new_authority })?;
  1056. // Instruction accounts.
  1057. let accounts = vec![
  1058. AccountMeta::new(idl_address, false),
  1059. AccountMeta::new_readonly(keypair.pubkey(), true),
  1060. ];
  1061. // Instruction.
  1062. let ix = Instruction {
  1063. program_id,
  1064. accounts,
  1065. data,
  1066. };
  1067. // Send transaction.
  1068. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  1069. let tx = Transaction::new_signed_with_payer(
  1070. &[ix],
  1071. Some(&keypair.pubkey()),
  1072. &[&keypair],
  1073. recent_hash,
  1074. );
  1075. client.send_and_confirm_transaction_with_spinner_and_config(
  1076. &tx,
  1077. CommitmentConfig::confirmed(),
  1078. RpcSendTransactionConfig {
  1079. skip_preflight: true,
  1080. ..RpcSendTransactionConfig::default()
  1081. },
  1082. )?;
  1083. println!("Authority update complete.");
  1084. Ok(())
  1085. })
  1086. }
  1087. fn idl_erase_authority(cfg_override: &ConfigOverride, program_id: Pubkey) -> Result<()> {
  1088. println!("Are you sure you want to erase the IDL authority: [y/n]");
  1089. let stdin = std::io::stdin();
  1090. let mut stdin_lines = stdin.lock().lines();
  1091. let input = stdin_lines.next().unwrap().unwrap();
  1092. if input != "y" {
  1093. println!("Not erasing.");
  1094. return Ok(());
  1095. }
  1096. // Program will treat the zero authority as erased.
  1097. let new_authority = Pubkey::new_from_array([0u8; 32]);
  1098. idl_set_authority(cfg_override, program_id, None, new_authority)?;
  1099. Ok(())
  1100. }
  1101. // Write the idl to the account buffer, chopping up the IDL into pieces
  1102. // and sending multiple transactions in the event the IDL doesn't fit into
  1103. // a single transaction.
  1104. fn idl_write(cfg: &Config, program_id: &Pubkey, idl: &Idl, idl_address: Pubkey) -> Result<()> {
  1105. // Remove the metadata before deploy.
  1106. let mut idl = idl.clone();
  1107. idl.metadata = None;
  1108. // Misc.
  1109. let keypair = solana_sdk::signature::read_keypair_file(&cfg.provider.wallet.to_string())
  1110. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1111. let client = RpcClient::new(cfg.provider.cluster.url().to_string());
  1112. // Serialize and compress the idl.
  1113. let idl_data = {
  1114. let json_bytes = serde_json::to_vec(&idl)?;
  1115. let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
  1116. e.write_all(&json_bytes)?;
  1117. e.finish()?
  1118. };
  1119. const MAX_WRITE_SIZE: usize = 1000;
  1120. let mut offset = 0;
  1121. while offset < idl_data.len() {
  1122. // Instruction data.
  1123. let data = {
  1124. let start = offset;
  1125. let end = std::cmp::min(offset + MAX_WRITE_SIZE, idl_data.len());
  1126. serialize_idl_ix(anchor_lang::idl::IdlInstruction::Write {
  1127. data: idl_data[start..end].to_vec(),
  1128. })?
  1129. };
  1130. // Instruction accounts.
  1131. let accounts = vec![
  1132. AccountMeta::new(idl_address, false),
  1133. AccountMeta::new_readonly(keypair.pubkey(), true),
  1134. ];
  1135. // Instruction.
  1136. let ix = Instruction {
  1137. program_id: *program_id,
  1138. accounts,
  1139. data,
  1140. };
  1141. // Send transaction.
  1142. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  1143. let tx = Transaction::new_signed_with_payer(
  1144. &[ix],
  1145. Some(&keypair.pubkey()),
  1146. &[&keypair],
  1147. recent_hash,
  1148. );
  1149. client.send_and_confirm_transaction_with_spinner_and_config(
  1150. &tx,
  1151. CommitmentConfig::confirmed(),
  1152. RpcSendTransactionConfig {
  1153. skip_preflight: true,
  1154. ..RpcSendTransactionConfig::default()
  1155. },
  1156. )?;
  1157. offset += MAX_WRITE_SIZE;
  1158. }
  1159. Ok(())
  1160. }
  1161. fn idl_parse(file: String, out: Option<String>) -> Result<()> {
  1162. let idl = extract_idl(&file)?.ok_or_else(|| anyhow!("IDL not parsed"))?;
  1163. let out = match out {
  1164. None => OutFile::Stdout,
  1165. Some(out) => OutFile::File(PathBuf::from(out)),
  1166. };
  1167. write_idl(&idl, out)
  1168. }
  1169. fn idl_fetch(cfg_override: &ConfigOverride, address: Pubkey, out: Option<String>) -> Result<()> {
  1170. let idl = fetch_idl(cfg_override, address)?;
  1171. let out = match out {
  1172. None => OutFile::Stdout,
  1173. Some(out) => OutFile::File(PathBuf::from(out)),
  1174. };
  1175. write_idl(&idl, out)
  1176. }
  1177. fn write_idl(idl: &Idl, out: OutFile) -> Result<()> {
  1178. let idl_json = serde_json::to_string_pretty(idl)?;
  1179. match out {
  1180. OutFile::Stdout => println!("{}", idl_json),
  1181. OutFile::File(out) => std::fs::write(out, idl_json)?,
  1182. };
  1183. Ok(())
  1184. }
  1185. enum OutFile {
  1186. Stdout,
  1187. File(PathBuf),
  1188. }
  1189. // Builds, deploys, and tests all workspace programs in a single command.
  1190. fn test(
  1191. cfg_override: &ConfigOverride,
  1192. skip_deploy: bool,
  1193. skip_local_validator: bool,
  1194. skip_build: bool,
  1195. detach: bool,
  1196. extra_args: Vec<String>,
  1197. ) -> Result<()> {
  1198. with_workspace(cfg_override, |cfg| {
  1199. // Build if needed.
  1200. if !skip_build {
  1201. build(cfg_override, None, false, None, None, None, None)?;
  1202. }
  1203. // Run the deploy against the cluster in two cases:
  1204. //
  1205. // 1. The cluster is not localnet.
  1206. // 2. The cluster is localnet, but we're not booting a local validator.
  1207. //
  1208. // In either case, skip the deploy if the user specifies.
  1209. let is_localnet = cfg.provider.cluster == Cluster::Localnet;
  1210. if (!is_localnet || skip_local_validator) && !skip_deploy {
  1211. deploy(cfg_override, None)?;
  1212. }
  1213. // Start local test validator, if needed.
  1214. let mut validator_handle = None;
  1215. if is_localnet && (!skip_local_validator) {
  1216. let flags = match skip_deploy {
  1217. true => None,
  1218. false => Some(genesis_flags(cfg)?),
  1219. };
  1220. validator_handle = Some(start_test_validator(cfg, flags)?);
  1221. }
  1222. // Setup log reader.
  1223. let log_streams = stream_logs(cfg);
  1224. // Run the tests.
  1225. let test_result: Result<_> = {
  1226. let cmd = cfg
  1227. .scripts
  1228. .get("test")
  1229. .expect("Not able to find command for `test`")
  1230. .clone();
  1231. let mut args: Vec<&str> = cmd
  1232. .split(' ')
  1233. .chain(extra_args.iter().map(|arg| arg.as_str()))
  1234. .collect();
  1235. let program = args.remove(0);
  1236. std::process::Command::new(program)
  1237. .args(args)
  1238. .env("ANCHOR_PROVIDER_URL", cfg.provider.cluster.url())
  1239. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  1240. .stdout(Stdio::inherit())
  1241. .stderr(Stdio::inherit())
  1242. .output()
  1243. .map_err(anyhow::Error::from)
  1244. .context(cmd)
  1245. };
  1246. // Keep validator running if needed.
  1247. if test_result.is_ok() && detach {
  1248. println!("Local validator still running. Press Ctrl + C quit.");
  1249. std::io::stdin().lock().lines().next().unwrap().unwrap();
  1250. }
  1251. // Check all errors and shut down.
  1252. if let Some(mut child) = validator_handle {
  1253. if let Err(err) = child.kill() {
  1254. println!("Failed to kill subprocess {}: {}", child.id(), err);
  1255. }
  1256. }
  1257. for mut child in log_streams? {
  1258. if let Err(err) = child.kill() {
  1259. println!("Failed to kill subprocess {}: {}", child.id(), err);
  1260. }
  1261. }
  1262. // Must exist *after* shutting down the validator and log streams.
  1263. match test_result {
  1264. Ok(exit) => {
  1265. if !exit.status.success() {
  1266. std::process::exit(exit.status.code().unwrap());
  1267. }
  1268. }
  1269. Err(err) => {
  1270. println!("Failed to run test: {:#}", err)
  1271. }
  1272. }
  1273. Ok(())
  1274. })
  1275. }
  1276. // Returns the solana-test-validator flags to embed the workspace programs
  1277. // in the genesis block. This allows us to run tests without every deploying.
  1278. fn genesis_flags(cfg: &WithPath<Config>) -> Result<Vec<String>> {
  1279. let programs = cfg.programs.get(&Cluster::Localnet);
  1280. let mut flags = Vec::new();
  1281. for mut program in cfg.read_all_programs()? {
  1282. let binary_path = program.binary_path().display().to_string();
  1283. // Use the [programs.cluster] override and fallback to the keypair
  1284. // files if no override is given.
  1285. let address = programs
  1286. .and_then(|m| m.get(&program.lib_name))
  1287. .map(|deployment| Ok(deployment.address.to_string()))
  1288. .unwrap_or_else(|| program.pubkey().map(|p| p.to_string()))?;
  1289. flags.push("--bpf-program".to_string());
  1290. flags.push(address.clone());
  1291. flags.push(binary_path);
  1292. if let Some(mut idl) = program.idl.as_mut() {
  1293. // Add program address to the IDL.
  1294. idl.metadata = Some(serde_json::to_value(IdlTestMetadata { address })?);
  1295. // Persist it.
  1296. let idl_out = PathBuf::from("target/idl")
  1297. .join(&idl.name)
  1298. .with_extension("json");
  1299. write_idl(idl, OutFile::File(idl_out))?;
  1300. }
  1301. }
  1302. if let Some(test) = cfg.test.as_ref() {
  1303. for entry in &test.genesis {
  1304. flags.push("--bpf-program".to_string());
  1305. flags.push(entry.address.clone());
  1306. flags.push(entry.program.clone());
  1307. }
  1308. }
  1309. Ok(flags)
  1310. }
  1311. fn stream_logs(config: &WithPath<Config>) -> Result<Vec<std::process::Child>> {
  1312. let program_logs_dir = ".anchor/program-logs";
  1313. if Path::new(program_logs_dir).exists() {
  1314. std::fs::remove_dir_all(program_logs_dir)?;
  1315. }
  1316. fs::create_dir_all(program_logs_dir)?;
  1317. let mut handles = vec![];
  1318. for program in config.read_all_programs()? {
  1319. let mut file = File::open(&format!("target/idl/{}.json", program.lib_name))?;
  1320. let mut contents = vec![];
  1321. file.read_to_end(&mut contents)?;
  1322. let idl: Idl = serde_json::from_slice(&contents)?;
  1323. let metadata = idl
  1324. .metadata
  1325. .ok_or_else(|| anyhow!("Program address not found."))?;
  1326. let metadata: IdlTestMetadata = serde_json::from_value(metadata)?;
  1327. let log_file = File::create(format!(
  1328. "{}/{}.{}.log",
  1329. program_logs_dir, metadata.address, program.lib_name,
  1330. ))?;
  1331. let stdio = std::process::Stdio::from(log_file);
  1332. let child = std::process::Command::new("solana")
  1333. .arg("logs")
  1334. .arg(metadata.address)
  1335. .arg("--url")
  1336. .arg(config.provider.cluster.url())
  1337. .stdout(stdio)
  1338. .spawn()?;
  1339. handles.push(child);
  1340. }
  1341. if let Some(test) = config.test.as_ref() {
  1342. for entry in &test.genesis {
  1343. let log_file = File::create(format!("{}/{}.log", program_logs_dir, entry.address))?;
  1344. let stdio = std::process::Stdio::from(log_file);
  1345. let child = std::process::Command::new("solana")
  1346. .arg("logs")
  1347. .arg(entry.address.clone())
  1348. .arg("--url")
  1349. .arg(config.provider.cluster.url())
  1350. .stdout(stdio)
  1351. .spawn()?;
  1352. handles.push(child);
  1353. }
  1354. }
  1355. Ok(handles)
  1356. }
  1357. #[derive(Debug, Serialize, Deserialize)]
  1358. pub struct IdlTestMetadata {
  1359. address: String,
  1360. }
  1361. fn start_test_validator(cfg: &Config, flags: Option<Vec<String>>) -> Result<Child> {
  1362. fs::create_dir_all(".anchor")?;
  1363. let test_ledger_filename = ".anchor/test-ledger";
  1364. let test_ledger_log_filename = ".anchor/test-ledger-log.txt";
  1365. if Path::new(test_ledger_filename).exists() {
  1366. std::fs::remove_dir_all(test_ledger_filename)?;
  1367. }
  1368. if Path::new(test_ledger_log_filename).exists() {
  1369. std::fs::remove_file(test_ledger_log_filename)?;
  1370. }
  1371. // Start a validator for testing.
  1372. let test_validator_stdout = File::create(test_ledger_log_filename)?;
  1373. let test_validator_stderr = test_validator_stdout.try_clone()?;
  1374. let validator_handle = std::process::Command::new("solana-test-validator")
  1375. .arg("--ledger")
  1376. .arg(test_ledger_filename)
  1377. .arg("--mint")
  1378. .arg(cfg.wallet_kp()?.pubkey().to_string())
  1379. .args(flags.unwrap_or_default())
  1380. .stdout(Stdio::from(test_validator_stdout))
  1381. .stderr(Stdio::from(test_validator_stderr))
  1382. .spawn()
  1383. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1384. // Wait for the validator to be ready.
  1385. let client = RpcClient::new("http://localhost:8899".to_string());
  1386. let mut count = 0;
  1387. let ms_wait = 5000;
  1388. while count < ms_wait {
  1389. let r = client.get_recent_blockhash();
  1390. if r.is_ok() {
  1391. break;
  1392. }
  1393. std::thread::sleep(std::time::Duration::from_millis(1));
  1394. count += 1;
  1395. }
  1396. if count == 5000 {
  1397. println!("Unable to start test validator.");
  1398. std::process::exit(1);
  1399. }
  1400. Ok(validator_handle)
  1401. }
  1402. fn deploy(cfg_override: &ConfigOverride, program_str: Option<String>) -> Result<()> {
  1403. with_workspace(cfg_override, |cfg| {
  1404. let url = cfg.provider.cluster.url().to_string();
  1405. let keypair = cfg.provider.wallet.to_string();
  1406. // Deploy the programs.
  1407. println!("Deploying workspace: {}", url);
  1408. println!("Upgrade authority: {}", keypair);
  1409. for mut program in cfg.read_all_programs()? {
  1410. if let Some(single_prog_str) = &program_str {
  1411. let program_name = program.path.file_name().unwrap().to_str().unwrap();
  1412. if single_prog_str.as_str() != program_name {
  1413. continue;
  1414. }
  1415. }
  1416. let binary_path = program.binary_path().display().to_string();
  1417. println!(
  1418. "Deploying program {:?}...",
  1419. program.path.file_name().unwrap().to_str().unwrap()
  1420. );
  1421. println!("Program path: {}...", binary_path);
  1422. let file = program.keypair_file()?;
  1423. // Send deploy transactions.
  1424. let exit = std::process::Command::new("solana")
  1425. .arg("program")
  1426. .arg("deploy")
  1427. .arg("--url")
  1428. .arg(&url)
  1429. .arg("--keypair")
  1430. .arg(&keypair)
  1431. .arg("--program-id")
  1432. .arg(file.path().display().to_string())
  1433. .arg(&binary_path)
  1434. .stdout(Stdio::inherit())
  1435. .stderr(Stdio::inherit())
  1436. .output()
  1437. .expect("Must deploy");
  1438. if !exit.status.success() {
  1439. println!("There was a problem deploying: {:?}.", exit);
  1440. std::process::exit(exit.status.code().unwrap_or(1));
  1441. }
  1442. let program_pubkey = program.pubkey()?;
  1443. if let Some(mut idl) = program.idl.as_mut() {
  1444. // Add program address to the IDL.
  1445. idl.metadata = Some(serde_json::to_value(IdlTestMetadata {
  1446. address: program_pubkey.to_string(),
  1447. })?);
  1448. // Persist it.
  1449. let idl_out = PathBuf::from("target/idl")
  1450. .join(&idl.name)
  1451. .with_extension("json");
  1452. write_idl(idl, OutFile::File(idl_out))?;
  1453. }
  1454. }
  1455. println!("Deploy success");
  1456. Ok(())
  1457. })
  1458. }
  1459. fn upgrade(
  1460. cfg_override: &ConfigOverride,
  1461. program_id: Pubkey,
  1462. program_filepath: String,
  1463. ) -> Result<()> {
  1464. let path: PathBuf = program_filepath.parse().unwrap();
  1465. let program_filepath = path.canonicalize()?.display().to_string();
  1466. with_workspace(cfg_override, |cfg| {
  1467. let exit = std::process::Command::new("solana")
  1468. .arg("program")
  1469. .arg("deploy")
  1470. .arg("--url")
  1471. .arg(cfg.provider.cluster.url())
  1472. .arg("--keypair")
  1473. .arg(&cfg.provider.wallet.to_string())
  1474. .arg("--program-id")
  1475. .arg(program_id.to_string())
  1476. .arg(&program_filepath)
  1477. .stdout(Stdio::inherit())
  1478. .stderr(Stdio::inherit())
  1479. .output()
  1480. .expect("Must deploy");
  1481. if !exit.status.success() {
  1482. println!("There was a problem deploying: {:?}.", exit);
  1483. std::process::exit(exit.status.code().unwrap_or(1));
  1484. }
  1485. Ok(())
  1486. })
  1487. }
  1488. fn create_idl_account(
  1489. cfg: &Config,
  1490. keypair_path: &str,
  1491. program_id: &Pubkey,
  1492. idl: &Idl,
  1493. ) -> Result<Pubkey> {
  1494. // Misc.
  1495. let idl_address = IdlAccount::address(program_id);
  1496. let keypair = solana_sdk::signature::read_keypair_file(keypair_path)
  1497. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1498. let client = RpcClient::new(cfg.provider.cluster.url().to_string());
  1499. let idl_data = serialize_idl(idl)?;
  1500. // Run `Create instruction.
  1501. {
  1502. let data = serialize_idl_ix(anchor_lang::idl::IdlInstruction::Create {
  1503. data_len: (idl_data.len() as u64) * 2, // Double for future growth.
  1504. })?;
  1505. let program_signer = Pubkey::find_program_address(&[], program_id).0;
  1506. let accounts = vec![
  1507. AccountMeta::new_readonly(keypair.pubkey(), true),
  1508. AccountMeta::new(idl_address, false),
  1509. AccountMeta::new_readonly(program_signer, false),
  1510. AccountMeta::new_readonly(solana_program::system_program::ID, false),
  1511. AccountMeta::new_readonly(*program_id, false),
  1512. AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
  1513. ];
  1514. let ix = Instruction {
  1515. program_id: *program_id,
  1516. accounts,
  1517. data,
  1518. };
  1519. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  1520. let tx = Transaction::new_signed_with_payer(
  1521. &[ix],
  1522. Some(&keypair.pubkey()),
  1523. &[&keypair],
  1524. recent_hash,
  1525. );
  1526. client.send_and_confirm_transaction_with_spinner_and_config(
  1527. &tx,
  1528. CommitmentConfig::confirmed(),
  1529. RpcSendTransactionConfig {
  1530. skip_preflight: true,
  1531. ..RpcSendTransactionConfig::default()
  1532. },
  1533. )?;
  1534. }
  1535. // Write directly to the IDL account buffer.
  1536. idl_write(cfg, program_id, idl, IdlAccount::address(program_id))?;
  1537. Ok(idl_address)
  1538. }
  1539. fn create_idl_buffer(
  1540. cfg: &Config,
  1541. keypair_path: &str,
  1542. program_id: &Pubkey,
  1543. idl: &Idl,
  1544. ) -> Result<Pubkey> {
  1545. let keypair = solana_sdk::signature::read_keypair_file(keypair_path)
  1546. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1547. let client = RpcClient::new(cfg.provider.cluster.url().to_string());
  1548. let buffer = Keypair::generate(&mut OsRng);
  1549. // Creates the new buffer account with the system program.
  1550. let create_account_ix = {
  1551. let space = 8 + 32 + 4 + serialize_idl(idl)?.len() as usize;
  1552. let lamports = client.get_minimum_balance_for_rent_exemption(space)?;
  1553. solana_sdk::system_instruction::create_account(
  1554. &keypair.pubkey(),
  1555. &buffer.pubkey(),
  1556. lamports,
  1557. space as u64,
  1558. program_id,
  1559. )
  1560. };
  1561. // Program instruction to create the buffer.
  1562. let create_buffer_ix = {
  1563. let accounts = vec![
  1564. AccountMeta::new(buffer.pubkey(), false),
  1565. AccountMeta::new_readonly(keypair.pubkey(), true),
  1566. AccountMeta::new_readonly(sysvar::rent::ID, false),
  1567. ];
  1568. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  1569. data.append(&mut IdlInstruction::CreateBuffer.try_to_vec()?);
  1570. Instruction {
  1571. program_id: *program_id,
  1572. accounts,
  1573. data,
  1574. }
  1575. };
  1576. // Build the transaction.
  1577. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  1578. let tx = Transaction::new_signed_with_payer(
  1579. &[create_account_ix, create_buffer_ix],
  1580. Some(&keypair.pubkey()),
  1581. &[&keypair, &buffer],
  1582. recent_hash,
  1583. );
  1584. // Send the transaction.
  1585. client.send_and_confirm_transaction_with_spinner_and_config(
  1586. &tx,
  1587. CommitmentConfig::confirmed(),
  1588. RpcSendTransactionConfig {
  1589. skip_preflight: true,
  1590. ..RpcSendTransactionConfig::default()
  1591. },
  1592. )?;
  1593. Ok(buffer.pubkey())
  1594. }
  1595. // Serialize and compress the idl.
  1596. fn serialize_idl(idl: &Idl) -> Result<Vec<u8>> {
  1597. let json_bytes = serde_json::to_vec(idl)?;
  1598. let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
  1599. e.write_all(&json_bytes)?;
  1600. e.finish().map_err(Into::into)
  1601. }
  1602. fn serialize_idl_ix(ix_inner: anchor_lang::idl::IdlInstruction) -> Result<Vec<u8>> {
  1603. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  1604. data.append(&mut ix_inner.try_to_vec()?);
  1605. Ok(data)
  1606. }
  1607. fn migrate(cfg_override: &ConfigOverride) -> Result<()> {
  1608. with_workspace(cfg_override, |cfg| {
  1609. println!("Running migration deploy script");
  1610. let url = cfg.provider.cluster.url().to_string();
  1611. let cur_dir = std::env::current_dir()?;
  1612. let use_ts =
  1613. Path::new("tsconfig.json").exists() && Path::new("migrations/deploy.ts").exists();
  1614. if !Path::new(".anchor").exists() {
  1615. fs::create_dir(".anchor")?;
  1616. }
  1617. std::env::set_current_dir(".anchor")?;
  1618. let exit = if use_ts {
  1619. let module_path = cur_dir.join("migrations/deploy.ts");
  1620. let deploy_script_host_str =
  1621. template::deploy_ts_script_host(&url, &module_path.display().to_string());
  1622. std::fs::write("deploy.ts", deploy_script_host_str)?;
  1623. std::process::Command::new("ts-node")
  1624. .arg("deploy.ts")
  1625. .stdout(Stdio::inherit())
  1626. .stderr(Stdio::inherit())
  1627. .output()?
  1628. } else {
  1629. let module_path = cur_dir.join("migrations/deploy.js");
  1630. let deploy_script_host_str =
  1631. template::deploy_js_script_host(&url, &module_path.display().to_string());
  1632. std::fs::write("deploy.js", deploy_script_host_str)?;
  1633. std::process::Command::new("node")
  1634. .arg("deploy.js")
  1635. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  1636. .stdout(Stdio::inherit())
  1637. .stderr(Stdio::inherit())
  1638. .output()?
  1639. };
  1640. if !exit.status.success() {
  1641. println!("Deploy failed.");
  1642. std::process::exit(exit.status.code().unwrap());
  1643. }
  1644. println!("Deploy complete.");
  1645. Ok(())
  1646. })
  1647. }
  1648. fn set_workspace_dir_or_exit() {
  1649. let d = match Config::discover(&ConfigOverride::default()) {
  1650. Err(_) => {
  1651. println!("Not in anchor workspace.");
  1652. std::process::exit(1);
  1653. }
  1654. Ok(d) => d,
  1655. };
  1656. match d {
  1657. None => {
  1658. println!("Not in anchor workspace.");
  1659. std::process::exit(1);
  1660. }
  1661. Some(cfg) => {
  1662. match cfg.path().parent() {
  1663. None => {
  1664. println!("Unable to make new program");
  1665. }
  1666. Some(parent) => {
  1667. if std::env::set_current_dir(&parent).is_err() {
  1668. println!("Not in anchor workspace.");
  1669. std::process::exit(1);
  1670. }
  1671. }
  1672. };
  1673. }
  1674. }
  1675. }
  1676. #[cfg(feature = "dev")]
  1677. fn airdrop(cfg_override: &ConfigOverride) -> Result<()> {
  1678. let url = cfg_override
  1679. .cluster
  1680. .unwrap_or_else(|| "https://api.devnet.solana.com".to_string());
  1681. loop {
  1682. let exit = std::process::Command::new("solana")
  1683. .arg("airdrop")
  1684. .arg("10")
  1685. .arg("--url")
  1686. .arg(&url)
  1687. .stdout(Stdio::inherit())
  1688. .stderr(Stdio::inherit())
  1689. .output()
  1690. .expect("Must airdrop");
  1691. if !exit.status.success() {
  1692. println!("There was a problem airdropping: {:?}.", exit);
  1693. std::process::exit(exit.status.code().unwrap_or(1));
  1694. }
  1695. std::thread::sleep(std::time::Duration::from_millis(10000));
  1696. }
  1697. }
  1698. fn cluster(_cmd: ClusterCommand) -> Result<()> {
  1699. println!("Cluster Endpoints:\n");
  1700. println!("* Mainnet - https://solana-api.projectserum.com");
  1701. println!("* Mainnet - https://api.mainnet-beta.solana.com");
  1702. println!("* Devnet - https://api.devnet.solana.com");
  1703. println!("* Testnet - https://api.testnet.solana.com");
  1704. Ok(())
  1705. }
  1706. fn shell(cfg_override: &ConfigOverride) -> Result<()> {
  1707. with_workspace(cfg_override, |cfg| {
  1708. let programs = {
  1709. // Create idl map from all workspace programs.
  1710. let mut idls: HashMap<String, Idl> = cfg
  1711. .read_all_programs()?
  1712. .iter()
  1713. .filter(|program| program.idl.is_some())
  1714. .map(|program| {
  1715. (
  1716. program.idl.as_ref().unwrap().name.clone(),
  1717. program.idl.clone().unwrap(),
  1718. )
  1719. })
  1720. .collect();
  1721. // Insert all manually specified idls into the idl map.
  1722. if let Some(programs) = cfg.programs.get(&cfg.provider.cluster) {
  1723. let _ = programs
  1724. .iter()
  1725. .map(|(name, pd)| {
  1726. if let Some(idl_fp) = &pd.idl {
  1727. let file_str =
  1728. std::fs::read_to_string(idl_fp).expect("Unable to read IDL file");
  1729. let idl = serde_json::from_str(&file_str).expect("Idl not readable");
  1730. idls.insert(name.clone(), idl);
  1731. }
  1732. })
  1733. .collect::<Vec<_>>();
  1734. }
  1735. // Finalize program list with all programs with IDLs.
  1736. match cfg.programs.get(&cfg.provider.cluster) {
  1737. None => Vec::new(),
  1738. Some(programs) => programs
  1739. .iter()
  1740. .filter_map(|(name, program_deployment)| {
  1741. Some(ProgramWorkspace {
  1742. name: name.to_string(),
  1743. program_id: program_deployment.address,
  1744. idl: match idls.get(name) {
  1745. None => return None,
  1746. Some(idl) => idl.clone(),
  1747. },
  1748. })
  1749. })
  1750. .collect::<Vec<ProgramWorkspace>>(),
  1751. }
  1752. };
  1753. let js_code = template::node_shell(
  1754. cfg.provider.cluster.url(),
  1755. &cfg.provider.wallet.to_string(),
  1756. programs,
  1757. )?;
  1758. let mut child = std::process::Command::new("node")
  1759. .args(&["-e", &js_code, "-i", "--experimental-repl-await"])
  1760. .stdout(Stdio::inherit())
  1761. .stderr(Stdio::inherit())
  1762. .spawn()
  1763. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1764. if !child.wait()?.success() {
  1765. println!("Error running node shell");
  1766. return Ok(());
  1767. }
  1768. Ok(())
  1769. })
  1770. }
  1771. fn run(cfg_override: &ConfigOverride, script: String) -> Result<()> {
  1772. with_workspace(cfg_override, |cfg| {
  1773. let script = cfg
  1774. .scripts
  1775. .get(&script)
  1776. .ok_or_else(|| anyhow!("Unable to find script"))?;
  1777. let exit = std::process::Command::new("bash")
  1778. .arg("-c")
  1779. .arg(&script)
  1780. .env("ANCHOR_PROVIDER_URL", cfg.provider.cluster.url())
  1781. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  1782. .stdout(Stdio::inherit())
  1783. .stderr(Stdio::inherit())
  1784. .output()
  1785. .unwrap();
  1786. if !exit.status.success() {
  1787. std::process::exit(exit.status.code().unwrap_or(1));
  1788. }
  1789. Ok(())
  1790. })
  1791. }
  1792. fn login(_cfg_override: &ConfigOverride, token: String) -> Result<()> {
  1793. let dir = shellexpand::tilde("~/.config/anchor");
  1794. if !Path::new(&dir.to_string()).exists() {
  1795. fs::create_dir(dir.to_string())?;
  1796. }
  1797. std::env::set_current_dir(dir.to_string())?;
  1798. // Freely overwrite the entire file since it's not used for anything else.
  1799. let mut file = File::create("credentials")?;
  1800. file.write_all(template::credentials(&token).as_bytes())?;
  1801. Ok(())
  1802. }
  1803. fn publish(cfg_override: &ConfigOverride, program_name: String) -> Result<()> {
  1804. // Discover the various workspace configs.
  1805. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1806. let program = cfg
  1807. .get_program(&program_name)?
  1808. .ok_or_else(|| anyhow!("Workspace member not found"))?;
  1809. let program_cargo_lock = pathdiff::diff_paths(
  1810. program.path().join("Cargo.lock"),
  1811. cfg.path().parent().unwrap(),
  1812. )
  1813. .ok_or_else(|| anyhow!("Unable to diff Cargo.lock path"))?;
  1814. let cargo_lock = Path::new("Cargo.lock");
  1815. // There must be a Cargo.lock
  1816. if !program_cargo_lock.exists() && !cargo_lock.exists() {
  1817. return Err(anyhow!("Cargo.lock must exist for a verifiable build"));
  1818. }
  1819. println!("Publishing will make your code public. Are you sure? Enter (yes)/no:");
  1820. let answer = std::io::stdin().lock().lines().next().unwrap().unwrap();
  1821. if answer != "yes" {
  1822. println!("Aborting");
  1823. return Ok(());
  1824. }
  1825. let anchor_package = AnchorPackage::from(program_name.clone(), &cfg)?;
  1826. let anchor_package_bytes = serde_json::to_vec(&anchor_package)?;
  1827. // Build the program before sending it to the server.
  1828. build(
  1829. cfg_override,
  1830. None,
  1831. true,
  1832. Some(program_name.clone()),
  1833. cfg.solana_version.clone(),
  1834. None,
  1835. None,
  1836. )?;
  1837. // Set directory to top of the workspace.
  1838. let workspace_dir = cfg.path().parent().unwrap();
  1839. std::env::set_current_dir(workspace_dir)?;
  1840. // Create the workspace tarball.
  1841. let dot_anchor = workspace_dir.join(".anchor");
  1842. fs::create_dir_all(&dot_anchor)?;
  1843. let tarball_filename = dot_anchor.join(format!("{}.tar.gz", program_name));
  1844. let tar_gz = File::create(&tarball_filename)?;
  1845. let enc = GzEncoder::new(tar_gz, Compression::default());
  1846. let mut tar = tar::Builder::new(enc);
  1847. // Files that will always be included if they exist.
  1848. println!("PACKING: Anchor.toml");
  1849. tar.append_path("Anchor.toml")?;
  1850. if cargo_lock.exists() {
  1851. println!("PACKING: Cargo.lock");
  1852. tar.append_path(cargo_lock)?;
  1853. }
  1854. if Path::new("Cargo.toml").exists() {
  1855. println!("PACKING: Cargo.toml");
  1856. tar.append_path("Cargo.toml")?;
  1857. }
  1858. if Path::new("LICENSE").exists() {
  1859. println!("PACKING: LICENSE");
  1860. tar.append_path("LICENSE")?;
  1861. }
  1862. if Path::new("README.md").exists() {
  1863. println!("PACKING: README.md");
  1864. tar.append_path("README.md")?;
  1865. }
  1866. // All workspace programs.
  1867. for path in cfg.get_program_list()? {
  1868. let mut dirs = walkdir::WalkDir::new(&path)
  1869. .into_iter()
  1870. .filter_entry(|e| !is_hidden(e));
  1871. // Skip the parent dir.
  1872. let _ = dirs.next().unwrap()?;
  1873. for entry in dirs {
  1874. let e = entry.map_err(|e| anyhow!("{:?}", e))?;
  1875. let e = pathdiff::diff_paths(e.path(), cfg.path().parent().unwrap())
  1876. .ok_or_else(|| anyhow!("Unable to diff paths"))?;
  1877. let path_str = e.display().to_string();
  1878. // Skip target dir.
  1879. if !path_str.contains("target/") && !path_str.contains("/target") {
  1880. // Only add the file if it's not empty.
  1881. let metadata = std::fs::File::open(&e)?.metadata()?;
  1882. if metadata.len() > 0 {
  1883. println!("PACKING: {}", e.display().to_string());
  1884. if e.is_dir() {
  1885. tar.append_dir_all(&e, &e)?;
  1886. } else {
  1887. tar.append_path(&e)?;
  1888. }
  1889. }
  1890. }
  1891. }
  1892. }
  1893. // Tar pack complete.
  1894. tar.into_inner()?;
  1895. // Upload the tarball to the server.
  1896. let token = registry_api_token(cfg_override)?;
  1897. let form = Form::new()
  1898. .part("manifest", Part::bytes(anchor_package_bytes))
  1899. .part("workspace", {
  1900. let file = File::open(&tarball_filename)?;
  1901. Part::reader(file)
  1902. });
  1903. let client = Client::new();
  1904. let resp = client
  1905. .post(&format!("{}/api/v0/build", cfg.registry.url))
  1906. .bearer_auth(token)
  1907. .multipart(form)
  1908. .send()?;
  1909. if resp.status() == 200 {
  1910. println!("Build triggered");
  1911. } else {
  1912. println!(
  1913. "{:?}",
  1914. resp.text().unwrap_or_else(|_| "Server error".to_string())
  1915. );
  1916. }
  1917. Ok(())
  1918. }
  1919. fn registry_api_token(_cfg_override: &ConfigOverride) -> Result<String> {
  1920. #[derive(Debug, Deserialize)]
  1921. struct Registry {
  1922. token: String,
  1923. }
  1924. #[derive(Debug, Deserialize)]
  1925. struct Credentials {
  1926. registry: Registry,
  1927. }
  1928. let filename = shellexpand::tilde("~/.config/anchor/credentials");
  1929. let mut file = File::open(filename.to_string())?;
  1930. let mut contents = String::new();
  1931. file.read_to_string(&mut contents)?;
  1932. let credentials_toml: Credentials = toml::from_str(&contents)?;
  1933. Ok(credentials_toml.registry.token)
  1934. }
  1935. fn keys(cfg_override: &ConfigOverride, cmd: KeysCommand) -> Result<()> {
  1936. match cmd {
  1937. KeysCommand::List => keys_list(cfg_override),
  1938. }
  1939. }
  1940. fn keys_list(cfg_override: &ConfigOverride) -> Result<()> {
  1941. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1942. for program in cfg.read_all_programs()? {
  1943. let pubkey = program.pubkey()?;
  1944. println!("{}: {}", program.lib_name, pubkey.to_string());
  1945. }
  1946. Ok(())
  1947. }
  1948. // with_workspace ensures the current working directory is always the top level
  1949. // workspace directory, i.e., where the `Anchor.toml` file is located, before
  1950. // and after the closure invocation.
  1951. //
  1952. // The closure passed into this function must never change the working directory
  1953. // to be outside the workspace. Doing so will have undefined behavior.
  1954. fn with_workspace<R>(cfg_override: &ConfigOverride, f: impl FnOnce(&WithPath<Config>) -> R) -> R {
  1955. set_workspace_dir_or_exit();
  1956. let cfg = Config::discover(cfg_override)
  1957. .expect("Previously set the workspace dir")
  1958. .expect("Anchor.toml must always exist");
  1959. let r = f(&cfg);
  1960. set_workspace_dir_or_exit();
  1961. r
  1962. }
  1963. fn is_hidden(entry: &walkdir::DirEntry) -> bool {
  1964. entry
  1965. .file_name()
  1966. .to_str()
  1967. .map(|s| s == "." || s.starts_with('.') || s == "target")
  1968. .unwrap_or(false)
  1969. }