-
Notifications
You must be signed in to change notification settings - Fork 6
/
lib.rs
executable file
·285 lines (247 loc) · 9.26 KB
/
lib.rs
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#![cfg_attr(not(feature = "std"), no_std)]
#![feature(min_specialization)]
pub mod merkle_tree;
use ink_lang as ink;
#[ink::contract]
pub mod mixer {
use super::*;
use ink_prelude::vec::Vec;
use ink_storage::{traits::SpreadAllocate, Mapping};
use poseidon::poseidon::PoseidonRef;
use protocol_ink_lib::keccak::Keccak256;
use protocol_ink_lib::utils::truncate_and_pad;
use protocol_ink_lib::zeroes::zeroes;
use scale::Encode;
use verifier::MixerVerifierRef;
pub const ROOT_HISTORY_SIZE: u32 = 100;
pub const ERROR_MSG: &'static str =
"requested transfer failed. this can be the case if the contract does not\
have sufficient free funds or if the transfer would have brought the\
contract's balance below minimum balance.";
#[ink(storage)]
#[derive(SpreadAllocate)]
pub struct Mixer {
deposit_size: Balance,
merkle_tree: merkle_tree::MerkleTree,
used_nullifiers: Mapping<[u8; 32], bool>,
poseidon: PoseidonRef,
verifier: MixerVerifierRef,
}
#[ink(event)]
pub struct Deposit {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
commitment: [u8; 32],
value: Balance,
}
#[ink(event)]
pub struct Withdraw {
#[ink(topic)]
recipient: AccountId,
#[ink(topic)]
relayer: AccountId,
fee: Balance,
refund: Balance,
}
/// The mixer error types.
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Error {
/// Returned if a mapping item is not found
ItemNotFound,
/// Returned if the merkle tree is full.
MerkleTreeIsFull,
/// Hash error
HashError,
/// Verify error
VerifyError,
/// Nullifier is known
NullifierKnown,
/// Invalid Withdraw Proof
InvalidWithdrawProof,
}
/// The mixer result type.
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct WithdrawParams {
proof_bytes: Vec<u8>,
root: [u8; 32],
nullifier_hash: [u8; 32],
recipient: AccountId,
relayer: AccountId,
fee: Balance,
refund: Balance,
}
impl Mixer {
#[ink(constructor)]
pub fn new(
levels: u32,
deposit_size: Balance,
version: u32,
poseidon_contract_hash: Hash,
verifier_contract_hash: Hash,
) -> Self {
let salt = version.to_le_bytes();
let poseidon = PoseidonRef::new()
.endowment(0)
.code_hash(poseidon_contract_hash)
.salt_bytes(salt)
.instantiate()
.unwrap_or_else(|error| {
ink_env::debug_print!("contract error in poseidon init {:?}", error);
panic!("failed at instantiating the Poseidon contract: {:?}", error)
});
let verifier = MixerVerifierRef::new()
.endowment(0)
.code_hash(verifier_contract_hash)
.salt_bytes(salt)
.instantiate()
.unwrap_or_else(|error| {
panic!(
"failed at instantiating the MixerVerifier contract: {:?}",
error
)
});
ink_lang::utils::initialize_contract(|contract: &mut Mixer| {
contract.deposit_size = deposit_size;
contract.poseidon = poseidon;
contract.verifier = verifier;
contract.merkle_tree.levels = levels;
contract.merkle_tree.current_root_index = 0;
contract.merkle_tree.next_index = 0;
for i in 0..levels {
contract.merkle_tree.filled_subtrees.insert(i, &zeroes(i));
}
contract.merkle_tree.roots.insert(0, &zeroes(levels));
})
}
/// Returns the `levels` value.
#[ink(message)]
pub fn levels(&self) -> u32 {
self.merkle_tree.levels
}
/// Returns the `deposit_size` value.
#[ink(message)]
pub fn deposit_size(&self) -> Balance {
self.deposit_size
}
#[ink(message, payable)]
pub fn deposit(&mut self, commitment: [u8; 32]) -> Result<u32> {
assert!(
self.env().transferred_value() == self.deposit_size,
"Deposit size is not correct"
);
let index = self.merkle_tree.insert(self.poseidon.clone(), commitment);
self.env().emit_event(Deposit {
from: self.env().caller(),
commitment,
value: self.env().transferred_value(),
});
index
}
#[ink(message, payable)]
pub fn send_fund_to_contract(&self) {
ink_env::debug_println!("funds sent");
}
#[ink(message)]
pub fn withdraw(&mut self, withdraw_params: WithdrawParams) -> Result<()> {
assert!(
self.merkle_tree.is_known_root(withdraw_params.root),
"Root is not known"
);
if self.is_known_nullifier(withdraw_params.nullifier_hash) {
return Err(Error::NullifierKnown);
}
let element_encoder = |v: &[u8]| {
let mut output = [0u8; 32];
output.iter_mut().zip(v).for_each(|(b1, b2)| *b1 = *b2);
output
};
// Format the public input bytes
let recipient_bytes = truncate_and_pad(withdraw_params.recipient.as_ref());
let relayer_bytes = truncate_and_pad(withdraw_params.relayer.as_ref());
let fee_bytes = &withdraw_params.fee.encode();
let refund_bytes = &withdraw_params.refund.encode();
let mut arbitrary_data_bytes = Vec::new();
arbitrary_data_bytes.extend_from_slice(&recipient_bytes);
arbitrary_data_bytes.extend_from_slice(&relayer_bytes);
arbitrary_data_bytes.extend_from_slice(&fee_bytes);
arbitrary_data_bytes.extend_from_slice(&refund_bytes);
let arbitrary_input =
Keccak256::hash(&arbitrary_data_bytes).map_err(|_| Error::HashError)?;
// Join the public input bytes
let mut bytes = Vec::new();
bytes.extend_from_slice(&withdraw_params.nullifier_hash);
bytes.extend_from_slice(&withdraw_params.root);
bytes.extend_from_slice(&arbitrary_input);
// Verify the proof
let result = self.verify(bytes, withdraw_params.proof_bytes)?;
if !result {
return Err(Error::InvalidWithdrawProof);
}
// Set used nullifier to true after successfuly verification
self.used_nullifiers
.insert(withdraw_params.nullifier_hash, &true);
let actual_amount = self.deposit_size - withdraw_params.fee;
// Send the funds
// TODO: Support "PSP22"-like tokens and Native token
// TODO: SPEC this more with Drew and create task/issue
if self
.env()
.transfer(withdraw_params.recipient, actual_amount)
.is_err()
{
panic!("{}", ERROR_MSG);
}
if self
.env()
.transfer(withdraw_params.relayer, withdraw_params.fee)
.is_err()
{
panic!("{}", ERROR_MSG);
}
if withdraw_params.refund > 0 {
if self
.env()
.transfer(withdraw_params.recipient, withdraw_params.refund)
.is_err()
{
ink_env::debug_println!("refund processing failed");
panic!("{}", ERROR_MSG);
}
}
self.env().emit_event(Withdraw {
recipient: withdraw_params.recipient,
relayer: withdraw_params.relayer,
fee: withdraw_params.fee,
refund: withdraw_params.refund,
});
Ok(())
}
#[ink(message)]
pub fn insert_nullifier(&mut self, nullifier: [u8; 32]) {
self.used_nullifiers.insert(&nullifier, &true);
}
/// Returns native contract address
#[ink(message)]
pub fn native_contract_account_id(&self) -> Option<AccountId> {
Some(self.env().account_id())
}
fn verify(&self, public_input: Vec<u8>, proof_bytes: Vec<u8>) -> Result<bool> {
self.verifier
.verify(public_input, proof_bytes)
.map_err(|_| Error::VerifyError)
}
#[ink(message)]
pub fn is_known_nullifier(&self, nullifier: [u8; 32]) -> bool {
self.used_nullifiers.get(&nullifier).unwrap_or(false)
}
/// Returns native contract balance
#[ink(message)]
pub fn native_contract_balance(&self) -> Balance {
self.env().balance()
}
}
}