-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathmod.rs
More file actions
200 lines (179 loc) · 6.36 KB
/
mod.rs
File metadata and controls
200 lines (179 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use crate::poke::load_session;
use crate::utils::mnemonic;
use crate::utils::stacks::StacksRpc;
use clarity_repl::clarity::codec::transaction::{
StacksTransaction, StacksTransactionSigner, TransactionAnchorMode, TransactionAuth,
TransactionPayload, TransactionPostConditionMode, TransactionPublicKeyEncoding,
TransactionSmartContract, TransactionSpendingCondition,
};
use clarity_repl::clarity::codec::StacksMessageCodec;
use clarity_repl::clarity::{
codec::{
transaction::{
RecoverableSignature, SinglesigHashMode, SinglesigSpendingCondition, TransactionVersion,
},
StacksString,
},
util::{
address::AddressHashMode,
secp256k1::{Secp256k1PrivateKey, Secp256k1PublicKey},
StacksAddress,
},
};
use clarity_repl::repl::settings::{Account, InitialContract};
use libsecp256k1::{PublicKey, SecretKey};
use std::collections::BTreeMap;
use std::path::PathBuf;
use tiny_hderive::bip32::ExtendedPrivKey;
#[derive(Deserialize, Debug)]
struct Balance {
balance: String,
nonce: u64,
balance_proof: String,
nonce_proof: String,
}
#[allow(dead_code)]
pub enum Network {
Devnet,
Testnet,
Mainnet,
}
pub fn publish_contract(
contract: &InitialContract,
deployers_lookup: &BTreeMap<String, Account>,
deployers_nonces: &mut BTreeMap<String, u64>,
node_url: &str,
deployment_fee_rate: u64,
network: &Network,
) -> Result<(String, u64), String> {
let contract_name = contract.name.clone().unwrap();
let payload = TransactionSmartContract {
name: contract_name.as_str().into(),
code_body: StacksString::from_string(&contract.code).unwrap(),
};
let deployer = match deployers_lookup.get(&contract_name) {
Some(deployer) => deployer,
None => deployers_lookup.get("*").unwrap(),
};
let bip39_seed = match mnemonic::get_bip39_seed_from_mnemonic(&deployer.mnemonic, "") {
Ok(bip39_seed) => bip39_seed,
Err(_) => panic!(),
};
let ext = ExtendedPrivKey::derive(&bip39_seed[..], deployer.derivation.as_str()).unwrap();
let secret_key = SecretKey::parse_slice(&ext.secret()).unwrap();
let public_key = PublicKey::from_secret_key(&secret_key);
let wrapped_public_key =
Secp256k1PublicKey::from_slice(&public_key.serialize_compressed()).unwrap();
let wrapped_secret_key = Secp256k1PrivateKey::from_slice(&ext.secret()).unwrap();
let anchor_mode = TransactionAnchorMode::Any;
let tx_fee = deployment_fee_rate * contract.code.len() as u64;
let stacks_rpc = StacksRpc::new(&node_url);
let nonce = match deployers_nonces.get(&deployer.name) {
Some(nonce) => *nonce,
None => {
let nonce = stacks_rpc
.get_nonce(&deployer.address)
.expect("Unable to retrieve account");
deployers_nonces.insert(deployer.name.clone(), nonce);
nonce
}
};
let signer_addr = StacksAddress::from_public_keys(
0,
&AddressHashMode::SerializeP2PKH,
1,
&vec![wrapped_public_key],
)
.unwrap();
let spending_condition = TransactionSpendingCondition::Singlesig(SinglesigSpendingCondition {
signer: signer_addr.bytes.clone(),
nonce: nonce,
tx_fee: tx_fee,
hash_mode: SinglesigHashMode::P2PKH,
key_encoding: TransactionPublicKeyEncoding::Compressed,
signature: RecoverableSignature::empty(),
});
let auth = TransactionAuth::Standard(spending_condition);
let unsigned_tx = StacksTransaction {
version: match network {
Network::Mainnet => TransactionVersion::Mainnet,
_ => TransactionVersion::Testnet,
},
chain_id: match network {
Network::Mainnet => 0x00000001,
_ => 0x80000000,
},
auth: auth,
anchor_mode: anchor_mode,
post_condition_mode: TransactionPostConditionMode::Deny,
post_conditions: vec![],
payload: TransactionPayload::SmartContract(payload),
};
let mut unsigned_tx_bytes = vec![];
unsigned_tx
.consensus_serialize(&mut unsigned_tx_bytes)
.expect("FATAL: invalid transaction");
let mut tx_signer = StacksTransactionSigner::new(&unsigned_tx);
tx_signer.sign_origin(&wrapped_secret_key).unwrap();
let signed_tx = tx_signer.get_tx().unwrap();
let txid = match stacks_rpc.post_transaction(signed_tx) {
Ok(res) => res.txid,
Err(e) => return Err(format!("{:?}", e)),
};
deployers_nonces.insert(deployer.name.clone(), nonce + 1);
Ok((txid, nonce))
}
pub fn publish_all_contracts(
manifest_path: PathBuf,
network: Network,
) -> Result<Vec<String>, Vec<String>> {
let start_repl = false;
let (session, chain, output) = match load_session(manifest_path, start_repl, &network) {
Ok((session, chain, output)) => (session, chain, output),
Err(e) => return Err(vec![e]),
};
if let Some(message) = output {
println!("{}", message);
println!("{}", yellow!("Would you like to continue [Y/n]:"));
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).unwrap();
if buffer == "n\n" {
println!("{}", red!("Contracts deployment aborted"));
std::process::exit(1);
}
}
let mut results = vec![];
let mut deployers_nonces = BTreeMap::new();
let mut deployers_lookup = BTreeMap::new();
let settings = session.settings;
for account in settings.initial_accounts.iter() {
if account.name == "deployer" {
deployers_lookup.insert("*".into(), account.clone());
}
}
for contract in settings.initial_contracts.iter() {
match publish_contract(
contract,
&deployers_lookup,
&mut deployers_nonces,
&settings.node,
chain.network.deployment_fee_rate,
&network,
) {
Ok((txid, nonce)) => {
results.push(format!(
"Contract {} broadcasted in mempool (txid: {}, nonce: {})",
contract.name.as_ref().unwrap(),
txid,
nonce
));
}
Err(err) => {
results.push(err.to_string());
break;
}
}
}
// If devnet, we should be pulling all the links.
Ok(results)
}