lib.rs 102 KB

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