forked from mimblewimble/grin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnrd_validation_rules.rs
More file actions
400 lines (332 loc) · 13 KB
/
Copy pathnrd_validation_rules.rs
File metadata and controls
400 lines (332 loc) · 13 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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod chain_test_helper;
use grin_chain as chain;
use grin_core as core;
use grin_keychain as keychain;
use grin_util as util;
use self::chain_test_helper::{clean_output_dir, genesis_block, init_chain};
use crate::chain::{Chain, Error, Options};
use crate::core::core::{
Block, BlockHeader, KernelFeatures, NRDRelativeHeight, Transaction, TxKernel,
};
use crate::core::libtx::{aggsig, build, reward, ProofBuilder};
use crate::core::{consensus, global, pow};
use crate::keychain::{BlindingFactor, ExtKeychain, ExtKeychainPath, Identifier, Keychain};
use chrono::Duration;
fn build_block<K>(
chain: &Chain,
keychain: &K,
key_id: &Identifier,
txs: Vec<Transaction>,
) -> Result<Block, Error>
where
K: Keychain,
{
let prev = chain.head_header()?;
build_block_from_prev(&prev, chain, keychain, key_id, txs)
}
fn build_block_from_prev<K>(
prev: &BlockHeader,
chain: &Chain,
keychain: &K,
key_id: &Identifier,
txs: Vec<Transaction>,
) -> Result<Block, Error>
where
K: Keychain,
{
let next_header_info =
consensus::next_difficulty(prev.height, chain.difficulty_iter().unwrap());
let fee = txs.iter().map(|x| x.fee(prev.height + 1)).sum();
let reward =
reward::output(keychain, &ProofBuilder::new(keychain), key_id, fee, false).unwrap();
let mut block = Block::new(prev, &txs, next_header_info.clone().difficulty, reward)?;
block.header.timestamp = prev.timestamp + Duration::seconds(60);
block.header.pow.secondary_scaling = next_header_info.secondary_scaling;
chain.set_txhashset_roots(&mut block)?;
block.header.pow.proof.edge_bits = global::min_edge_bits();
pow::pow_size(
&mut block.header,
next_header_info.difficulty,
global::proofsize(),
global::min_edge_bits(),
)
.unwrap();
Ok(block)
}
#[test]
fn process_block_nrd_validation() -> Result<(), Error> {
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
global::set_local_nrd_enabled(true);
util::init_test_logger();
let chain_dir = ".grin.nrd_kernel";
clean_output_dir(chain_dir);
let keychain = ExtKeychain::from_random_seed(false).unwrap();
let builder = ProofBuilder::new(&keychain);
let genesis = genesis_block(&keychain);
let chain = init_chain(chain_dir, genesis.clone());
for n in 1..9 {
let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier();
let block = build_block(&chain, &keychain, &key_id, vec![])?;
chain.process_block(block, Options::NONE)?;
}
assert_eq!(chain.head()?.height, 8);
let mut kernel = TxKernel::with_features(KernelFeatures::NoRecentDuplicate {
fee: 20000.into(),
relative_height: NRDRelativeHeight::new(2)?,
});
// // Construct the message to be signed.
let msg = kernel.msg_to_sign().unwrap();
// // Generate a kernel with public excess and associated signature.
let excess = BlindingFactor::rand(&keychain.secp());
let skey = excess.secret_key(&keychain.secp()).unwrap();
kernel.excess = keychain.secp().commit(0, skey).unwrap();
let pubkey = &kernel.excess.to_pubkey(&keychain.secp()).unwrap();
kernel.excess_sig =
aggsig::sign_with_blinding(&keychain.secp(), &msg, &excess, Some(&pubkey)).unwrap();
kernel.verify().unwrap();
let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier();
let key_id3 = ExtKeychainPath::new(1, 3, 0, 0, 0).to_identifier();
let tx1 = build::transaction_with_kernel(
&[
build::coinbase_input(consensus::REWARD, key_id1.clone()),
build::output(consensus::REWARD - 20000, key_id2.clone()),
],
kernel.clone(),
excess.clone(),
&keychain,
&builder,
)
.unwrap();
let tx2 = build::transaction_with_kernel(
&[
build::input(consensus::REWARD - 20000, key_id2.clone()),
build::output(consensus::REWARD - 40000, key_id3.clone()),
],
kernel.clone(),
excess.clone(),
&keychain,
&builder,
)
.unwrap();
let key_id9 = ExtKeychainPath::new(1, 9, 0, 0, 0).to_identifier();
let key_id10 = ExtKeychainPath::new(1, 10, 0, 0, 0).to_identifier();
let key_id11 = ExtKeychainPath::new(1, 11, 0, 0, 0).to_identifier();
// Block containing both tx1 and tx2 is invalid.
// Not valid for two duplicate NRD kernels to co-exist in same block.
// Jump through some hoops to build an invalid block by disabling the feature flag.
// TODO - We need a good way of building invalid stuff in tests.
let block_invalid_9 = {
global::set_local_nrd_enabled(false);
let block = build_block(&chain, &keychain, &key_id9, vec![tx1.clone(), tx2.clone()])?;
global::set_local_nrd_enabled(true);
block
};
assert!(chain.process_block(block_invalid_9, Options::NONE).is_err());
assert_eq!(chain.head()?.height, 8);
// Block containing tx1 is valid.
let block_valid_9 = build_block(&chain, &keychain, &key_id9, vec![tx1.clone()])?;
chain.process_block(block_valid_9, Options::NONE)?;
// Block at height 10 is invalid if it contains tx2 due to NRD rule (relative_height=2).
// Jump through some hoops to build an invalid block by disabling the feature flag.
// TODO - We need a good way of building invalid stuff in tests.
let block_invalid_10 = {
global::set_local_nrd_enabled(false);
let block = build_block(&chain, &keychain, &key_id10, vec![tx2.clone()])?;
global::set_local_nrd_enabled(true);
block
};
assert!(chain
.process_block(block_invalid_10, Options::NONE)
.is_err());
// Block at height 10 is valid if we do not include tx2.
let block_valid_10 = build_block(&chain, &keychain, &key_id10, vec![])?;
chain.process_block(block_valid_10, Options::NONE)?;
// Block at height 11 is valid with tx2 as NRD rule is met (relative_height=2).
let block_valid_11 = build_block(&chain, &keychain, &key_id11, vec![tx2.clone()])?;
chain.process_block(block_valid_11, Options::NONE)?;
clean_output_dir(chain_dir);
Ok(())
}
#[test]
fn process_block_nrd_validation_relative_height_1() -> Result<(), Error> {
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
global::set_local_nrd_enabled(true);
util::init_test_logger();
let chain_dir = ".grin.nrd_kernel_relative_height_1";
clean_output_dir(chain_dir);
let keychain = ExtKeychain::from_random_seed(false).unwrap();
let builder = ProofBuilder::new(&keychain);
let genesis = genesis_block(&keychain);
let chain = init_chain(chain_dir, genesis.clone());
for n in 1..9 {
let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier();
let block = build_block(&chain, &keychain, &key_id, vec![])?;
chain.process_block(block, Options::NONE)?;
}
assert_eq!(chain.head()?.height, 8);
let mut kernel = TxKernel::with_features(KernelFeatures::NoRecentDuplicate {
fee: 20000.into(),
relative_height: NRDRelativeHeight::new(1)?,
});
// // Construct the message to be signed.
let msg = kernel.msg_to_sign().unwrap();
// // Generate a kernel with public excess and associated signature.
let excess = BlindingFactor::rand(&keychain.secp());
let skey = excess.secret_key(&keychain.secp()).unwrap();
kernel.excess = keychain.secp().commit(0, skey).unwrap();
let pubkey = &kernel.excess.to_pubkey(&keychain.secp()).unwrap();
kernel.excess_sig =
aggsig::sign_with_blinding(&keychain.secp(), &msg, &excess, Some(&pubkey)).unwrap();
kernel.verify().unwrap();
let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier();
let key_id3 = ExtKeychainPath::new(1, 3, 0, 0, 0).to_identifier();
let tx1 = build::transaction_with_kernel(
&[
build::coinbase_input(consensus::REWARD, key_id1.clone()),
build::output(consensus::REWARD - 20000, key_id2.clone()),
],
kernel.clone(),
excess.clone(),
&keychain,
&builder,
)
.unwrap();
let tx2 = build::transaction_with_kernel(
&[
build::input(consensus::REWARD - 20000, key_id2.clone()),
build::output(consensus::REWARD - 40000, key_id3.clone()),
],
kernel.clone(),
excess.clone(),
&keychain,
&builder,
)
.unwrap();
let key_id9 = ExtKeychainPath::new(1, 9, 0, 0, 0).to_identifier();
let key_id10 = ExtKeychainPath::new(1, 10, 0, 0, 0).to_identifier();
// Block containing both tx1 and tx2 is invalid.
// Not valid for two duplicate NRD kernels to co-exist in same block.
// Jump through some hoops here to build an "invalid" block.
// TODO - We need a good way of building invalid stuff for tests.
let block_invalid_9 = {
global::set_local_nrd_enabled(false);
let block = build_block(&chain, &keychain, &key_id9, vec![tx1.clone(), tx2.clone()])?;
global::set_local_nrd_enabled(true);
block
};
assert!(chain.process_block(block_invalid_9, Options::NONE).is_err());
assert_eq!(chain.head()?.height, 8);
// Block containing tx1 is valid.
let block_valid_9 = build_block(&chain, &keychain, &key_id9, vec![tx1.clone()])?;
chain.process_block(block_valid_9, Options::NONE)?;
// Block at height 10 is valid with tx2 as NRD rule is met (relative_height=1).
let block_valid_10 = build_block(&chain, &keychain, &key_id10, vec![tx2.clone()])?;
chain.process_block(block_valid_10, Options::NONE)?;
clean_output_dir(chain_dir);
Ok(())
}
#[test]
fn process_block_nrd_validation_fork() -> Result<(), Error> {
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
global::set_local_nrd_enabled(true);
util::init_test_logger();
let chain_dir = ".grin.nrd_kernel_fork";
clean_output_dir(chain_dir);
let keychain = ExtKeychain::from_random_seed(false).unwrap();
let builder = ProofBuilder::new(&keychain);
let genesis = genesis_block(&keychain);
let chain = init_chain(chain_dir, genesis.clone());
for n in 1..9 {
let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier();
let block = build_block(&chain, &keychain, &key_id, vec![])?;
chain.process_block(block, Options::NONE)?;
}
let header_8 = chain.head_header()?;
assert_eq!(header_8.height, 8);
let mut kernel = TxKernel::with_features(KernelFeatures::NoRecentDuplicate {
fee: 20000.into(),
relative_height: NRDRelativeHeight::new(2)?,
});
// // Construct the message to be signed.
let msg = kernel.msg_to_sign().unwrap();
// // Generate a kernel with public excess and associated signature.
let excess = BlindingFactor::rand(&keychain.secp());
let skey = excess.secret_key(&keychain.secp()).unwrap();
kernel.excess = keychain.secp().commit(0, skey).unwrap();
let pubkey = &kernel.excess.to_pubkey(&keychain.secp()).unwrap();
kernel.excess_sig =
aggsig::sign_with_blinding(&keychain.secp(), &msg, &excess, Some(&pubkey)).unwrap();
kernel.verify().unwrap();
let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier();
let key_id3 = ExtKeychainPath::new(1, 3, 0, 0, 0).to_identifier();
let tx1 = build::transaction_with_kernel(
&[
build::coinbase_input(consensus::REWARD, key_id1.clone()),
build::output(consensus::REWARD - 20000, key_id2.clone()),
],
kernel.clone(),
excess.clone(),
&keychain,
&builder,
)
.unwrap();
let tx2 = build::transaction_with_kernel(
&[
build::input(consensus::REWARD - 20000, key_id2.clone()),
build::output(consensus::REWARD - 40000, key_id3.clone()),
],
kernel.clone(),
excess.clone(),
&keychain,
&builder,
)
.unwrap();
let key_id9 = ExtKeychainPath::new(1, 9, 0, 0, 0).to_identifier();
let key_id10 = ExtKeychainPath::new(1, 10, 0, 0, 0).to_identifier();
let key_id11 = ExtKeychainPath::new(1, 11, 0, 0, 0).to_identifier();
// Block containing tx1 is valid.
let block_valid_9 =
build_block_from_prev(&header_8, &chain, &keychain, &key_id9, vec![tx1.clone()])?;
chain.process_block(block_valid_9.clone(), Options::NONE)?;
// Block at height 10 is valid if we do not include tx2.
let block_valid_10 =
build_block_from_prev(&block_valid_9.header, &chain, &keychain, &key_id10, vec![])?;
chain.process_block(block_valid_10, Options::NONE)?;
// Process an alternative "fork" block also at height 9.
// The "other" block at height 9 should not affect this one in terms of NRD kernels
// as the recent kernel index should be rewound.
let block_valid_9b =
build_block_from_prev(&header_8, &chain, &keychain, &key_id9, vec![tx1.clone()])?;
chain.process_block(block_valid_9b.clone(), Options::NONE)?;
// Process an alternative block at height 10 on this same fork.
let block_valid_10b =
build_block_from_prev(&block_valid_9b.header, &chain, &keychain, &key_id10, vec![])?;
chain.process_block(block_valid_10b.clone(), Options::NONE)?;
// Block at height 11 is valid with tx2 as NRD rule is met (relative_height=2).
let block_valid_11b = build_block_from_prev(
&block_valid_10b.header,
&chain,
&keychain,
&key_id11,
vec![tx2.clone()],
)?;
chain.process_block(block_valid_11b, Options::NONE)?;
clean_output_dir(chain_dir);
Ok(())
}