lib.rs 87 KB

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