deploy_contract.rs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. use std::{
  2. env::set_current_dir,
  3. fs::{read, read_dir, read_to_string, File},
  4. io::{ErrorKind, Write},
  5. path::{Path, PathBuf},
  6. str::FromStr,
  7. };
  8. use rand::{rngs::OsRng, RngCore};
  9. use darkfi::{
  10. crypto::keypair::SecretKey,
  11. node::{MemoryState, State},
  12. runtime::vm_runtime::{Runtime, ENTRYPOINT},
  13. util::cli::{fg_green, fg_red},
  14. zkas::ZkBinary,
  15. Error, Result,
  16. };
  17. const CIRCUIT_DIR_NAME: &str = "proof";
  18. const CONTRACT_FILE_NAME: &str = "contract.wasm";
  19. const DEPLOY_KEY_NAME: &str = "deploy.key";
  20. /// Creates a new deploy key used for deploying private smart contracts.
  21. /// This key allows to update the wasm code and the zk circuits on chain
  22. /// by creating a signature. When deployed, the contract can be accessed
  23. /// by requesting the public counterpart of this secret key.
  24. pub fn create_deploy_key(mut rng: impl RngCore, path: &Path) -> Result<SecretKey> {
  25. let secret = SecretKey::random(&mut rng);
  26. let mut file = File::create(path)?;
  27. file.write_all(bs58::encode(&secret.to_bytes()).into_string().as_bytes())?;
  28. Ok(secret)
  29. }
  30. /// Reads a deploy key from a file on the filesystem and returns it.
  31. fn read_deploy_key(s: &Path) -> core::result::Result<SecretKey, std::io::Error> {
  32. eprintln!("Trying to read deploy key from file: {:?}", s);
  33. let contents = read_to_string(s)?;
  34. let secret = SecretKey::from_str(&contents).unwrap();
  35. Ok(secret)
  36. }
  37. /// Creates necessary data to deploy a given smart contract on the network.
  38. /// For consistency, we point this function to a directory where our smart
  39. /// contract and the compiled circuits are contained. This is going to give
  40. /// us a uniform approach to scm and gives a generic layout of the source:
  41. /// ```text
  42. /// smart-contract
  43. /// ├── Cargo.toml
  44. /// ├── deploy.key
  45. /// ├── Makefile
  46. /// ├── proof
  47. /// │   ├── circuit0.zk
  48. /// │   ├── circuit0.zk.bin
  49. /// │   ├── circuit1.zk
  50. /// │   └── circuit1.zk.bin
  51. /// ├── contract.wasm
  52. /// ├── src
  53. /// │   └── lib.rs
  54. /// └── tests
  55. /// ```
  56. //pub fn create_deploy_data(path: &Path) -> Result<ContractDeploy> {
  57. pub fn create_deploy_data(path: &Path) -> Result<()> {
  58. // Try to chdir into the contract directory
  59. if let Err(e) = set_current_dir(path) {
  60. eprintln!("Failed to chdir into {:?}", path);
  61. return Err(e.into())
  62. }
  63. let deploy_key: SecretKey;
  64. let deploy_key = match read_deploy_key(&PathBuf::from(DEPLOY_KEY_NAME)) {
  65. Ok(v) => deploy_key = v,
  66. Err(e) => {
  67. if e.kind() == ErrorKind::NotFound {
  68. // We didn't find a deploy key, generate a new one.
  69. eprintln!("Did not find an existing key, creating a new one.");
  70. match create_deploy_key(&mut OsRng, &PathBuf::from(DEPLOY_KEY_NAME)) {
  71. Ok(v) => {
  72. eprintln!("Created new deploy key in \"{}\".", DEPLOY_KEY_NAME);
  73. deploy_key = v;
  74. }
  75. Err(e) => {
  76. eprintln!("Failed to create new deploy key");
  77. return Err(e)
  78. }
  79. }
  80. }
  81. eprintln!("Failed to read deploy key");
  82. return Err(e.into())
  83. }
  84. };
  85. // Search for ZK circuits in the directory. If none are found, we'll bail.
  86. // The logic searches for `.zk.bin` files created by zkas.
  87. eprintln!("Searching for compiled ZK circuits in \"{}\" ...", CIRCUIT_DIR_NAME);
  88. let mut circuits = vec![];
  89. for i in read_dir(CIRCUIT_DIR_NAME)? {
  90. if let Err(e) = i {
  91. eprintln!("Error iterating over \"{}\" directory", CIRCUIT_DIR_NAME);
  92. return Err(e.into())
  93. }
  94. let f = i.unwrap();
  95. let fname = f.file_name();
  96. let fname = fname.to_str().unwrap();
  97. if fname.ends_with(".zk.bin") {
  98. // Validate that the files can be properly decoded
  99. eprintln!("{} {}", fg_green("Found:"), f.path().display());
  100. let buf = read(f.path())?;
  101. if let Err(e) = ZkBinary::decode(&buf) {
  102. eprintln!("{} Failed to decode zkas bincode in {:?}", fg_red("Error:"), f.path());
  103. return Err(e)
  104. }
  105. circuits.push(buf.clone());
  106. }
  107. }
  108. if circuits.is_empty() {
  109. return Err(Error::Custom("Found no valid ZK circuits".to_string()))
  110. }
  111. // Validate wasm binary. We inspect the bincode and try to load it into
  112. // the wasm runtime. If loaded, we then look for the `ENTRYPOINT` function
  113. // which we hardcode into our sdk and runtime and is the canonical way to
  114. // run wasm binaries on chain.
  115. eprintln!("Inspecting wasm binary in \"{}\"", CONTRACT_FILE_NAME);
  116. let wasm_bytes = read(CONTRACT_FILE_NAME)?;
  117. eprintln!("Initializing moch wasm runtime to check validity");
  118. let runtime = match Runtime::new(&wasm_bytes, MemoryState::new(State::dummy()?)) {
  119. Ok(v) => {
  120. eprintln!("Found {} wasm binary", fg_green("valid"));
  121. v
  122. }
  123. Err(e) => {
  124. eprintln!("Failed to initialize wasm runtime");
  125. return Err(e)
  126. }
  127. };
  128. eprintln!("Looking for entrypoint function inside the wasm");
  129. if let Err(e) = runtime.instance.exports.get_function(ENTRYPOINT) {
  130. eprintln!("{} Could not find entrypoint function", fg_red("Error:"));
  131. return Err(e.into())
  132. }
  133. // TODO: Create a ZK proof enforcing the deploy key relations with their public
  134. // counterparts (public key and contract address)
  135. let mut total_bytes = 0;
  136. total_bytes += wasm_bytes.len();
  137. for circuit in circuits {
  138. total_bytes += circuit.len();
  139. }
  140. // TODO: Return the data back to the main function, and work further in creating
  141. // a transaction and broadcasting it.
  142. Ok(())
  143. }