lib.rs 88 KB

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