chik-consensus 0.27.0

Utility functions and types used by the Chik blockchain full node
Documentation
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
401
402
403
404
405
406
407
408
409
410
411
use super::conditions::{NewCoin, SpendBundleConditions, SpendConditions};
use super::run_block_generator::{
    get_coinspends_for_trusted_block, get_coinspends_with_conditions_for_trusted_block,
    run_block_generator, run_block_generator2,
};
use crate::allocator::make_allocator;
use crate::consensus_constants::TEST_CONSTANTS;
use crate::flags::{COST_CONDITIONS, DONT_VALIDATE_SIGNATURE, MEMPOOL_MODE};
use chik_bls::Signature;
use chik_protocol::Program;
use chik_protocol::{Bytes, Bytes48};
use klvmr::allocator::NodePtr;
use klvmr::Allocator;
use std::iter::zip;
use text_diff::diff;
use text_diff::Difference;

use rstest::rstest;

pub(crate) fn print_conditions(a: &Allocator, c: &SpendBundleConditions) -> String {
    let mut ret = String::new();
    if c.reserve_fee > 0 {
        ret += &format!("RESERVE_FEE: {}\n", c.reserve_fee);
    }

    if c.height_absolute > 0 {
        ret += &format!("ASSERT_HEIGHT_ABSOLUTE {}\n", c.height_absolute);
    }
    if c.seconds_absolute > 0 {
        ret += &format!("ASSERT_SECONDS_ABSOLUTE {}\n", c.seconds_absolute);
    }
    if let Some(val) = c.before_seconds_absolute {
        ret += &format!("ASSERT_BEFORE_SECONDS_ABSOLUTE {val}\n");
    }
    if let Some(val) = c.before_height_absolute {
        ret += &format!("ASSERT_BEFORE_HEIGHT_ABSOLUTE {val}\n");
    }
    let mut agg_sigs = Vec::<(Bytes48, Bytes)>::new();
    for (pk, msg) in &c.agg_sig_unsafe {
        agg_sigs.push((pk.to_bytes().into(), a.atom(*msg).as_ref().into()));
    }
    agg_sigs.sort();
    for (pk, msg) in agg_sigs {
        ret += &format!(
            "AGG_SIG_UNSAFE pk: {} msg: {}\n",
            hex::encode(pk),
            hex::encode(msg)
        );
    }
    ret += "SPENDS:\n";

    let mut spends: Vec<SpendConditions> = c.spends.clone();
    spends.sort_by_key(|s| *s.coin_id);
    for s in spends {
        ret += &format!(
            "- coin id: {} ph: {} exe-cost: {} cond-cost: {}\n",
            hex::encode(*s.coin_id),
            hex::encode(a.atom(s.puzzle_hash)),
            s.execution_cost,
            s.condition_cost,
        );

        if let Some(val) = s.height_relative {
            ret += &format!("  ASSERT_HEIGHT_RELATIVE {val}\n");
        }
        if let Some(val) = s.seconds_relative {
            ret += &format!("  ASSERT_SECONDS_RELATIVE {val}\n");
        }
        if let Some(val) = s.before_height_relative {
            ret += &format!("  ASSERT_BEFORE_HEIGHT_RELATIVE {val}\n");
        }
        if let Some(val) = s.before_seconds_relative {
            ret += &format!("  ASSERT_BEFORE_SECONDS_RELATIVE {val}\n");
        }
        let mut create_coin: Vec<&NewCoin> = s.create_coin.iter().collect();
        create_coin.sort_by_key(|cc| (cc.puzzle_hash, cc.amount));
        for cc in create_coin {
            if cc.hint == NodePtr::NIL {
                ret += &format!(
                    "  CREATE_COIN: ph: {} amount: {}\n",
                    hex::encode(cc.puzzle_hash),
                    cc.amount
                );
            } else {
                ret += &format!(
                    "  CREATE_COIN: ph: {} amount: {} hint: {}\n",
                    hex::encode(cc.puzzle_hash),
                    cc.amount,
                    hex::encode(a.atom(cc.hint))
                );
            }
        }

        for sig_conds in [
            (&s.agg_sig_me, "AGG_SIG_ME"),
            (&s.agg_sig_parent, "AGG_SIG_PARENT"),
            (&s.agg_sig_puzzle, "AGG_SIG_PUZZLE"),
            (&s.agg_sig_amount, "AGG_SIG_AMOUNT"),
            (&s.agg_sig_puzzle_amount, "AGG_SIG_PUZZLE_AMOUNT"),
            (&s.agg_sig_parent_amount, "AGG_SIG_PARENT_AMOUNT"),
            (&s.agg_sig_parent_puzzle, "AGG_SIG_PARENT_PUZZLE"),
        ] {
            let mut agg_sigs = Vec::<(Bytes48, Bytes)>::new();
            for (pk, msg) in sig_conds.0 {
                agg_sigs.push((pk.to_bytes().into(), a.atom(*msg).as_ref().into()));
            }
            agg_sigs.sort();
            for (pk, msg) in &agg_sigs {
                ret += &format!(
                    "  {} pk: {} msg: {}\n",
                    sig_conds.1,
                    hex::encode(pk),
                    hex::encode(msg)
                );
            }
        }
    }

    ret += &format!("cost: {}\n", c.cost);
    ret += &format!("execution-cost: {}\n", c.execution_cost);
    ret += &format!("condition-cost: {}\n", c.condition_cost);
    ret += &format!("removal_amount: {}\n", c.removal_amount);
    ret += &format!("addition_amount: {}\n", c.addition_amount);
    ret
}

pub(crate) fn print_diff(output: &str, expected: &str) {
    println!("\x1b[102m \x1b[0m - output from test");
    println!("\x1b[101m \x1b[0m - expected output");
    for diff in diff(expected, output, "\n").1 {
        match diff {
            Difference::Same(s) => {
                let lines: Vec<&str> = s.split('\n').collect();
                if lines.len() <= 6 {
                    for l in &lines {
                        println!(" {l}");
                    }
                } else {
                    for l in &lines[0..3] {
                        println!(" {l}");
                    }
                    println!(" ...");
                    for l in &lines[lines.len() - 3..] {
                        println!(" {l}");
                    }
                }
            }
            Difference::Rem(s) => {
                println!("\x1b[91m");
                for l in s.split('\n') {
                    println!("-{l}");
                }
                println!("\x1b[0m");
            }
            Difference::Add(s) => {
                println!("\x1b[92m");
                for l in s.split('\n') {
                    println!("+{l}");
                }
                println!("\x1b[0m");
            }
        }
    }
}

#[rstest]
#[case("aa-million-messages")]
#[case("new-agg-sigs")]
#[case("infinity-g1")]
#[case("block-1ee588dc")]
#[case("block-6fe59b24")]
#[case("block-b45268ac")]
#[case("block-c2a8df0d")]
#[case("block-e5002df2")]
#[case("block-4671894")]
#[case("block-225758")]
#[case("assert-puzzle-announce-fail")]
#[case("block-834752")]
#[case("block-834752-compressed")]
#[case("block-834760")]
#[case("block-834761")]
#[case("block-834765")]
#[case("block-834766")]
#[case("block-834768")]
#[case("create-coin-different-amounts")]
#[case("create-coin-hint-duplicate-outputs")]
#[case("create-coin-hint")]
#[case("create-coin-hint2")]
#[case("deep-recursion-plus")]
#[case("double-spend")]
#[case("duplicate-coin-announce")]
#[case("duplicate-create-coin")]
#[case("duplicate-height-absolute-div")]
#[case("duplicate-height-absolute-substr-tail")]
#[case("duplicate-height-absolute-substr")]
#[case("duplicate-height-absolute")]
#[case("duplicate-height-relative")]
#[case("duplicate-outputs")]
#[case("duplicate-reserve-fee")]
#[case("duplicate-seconds-absolute")]
#[case("duplicate-seconds-relative")]
#[case("height-absolute-ladder")]
#[case("infinite-recursion1")]
#[case("infinite-recursion2")]
#[case("infinite-recursion3")]
#[case("infinite-recursion4")]
#[case("invalid-conditions")]
#[case("just-puzzle-announce")]
#[case("many-create-coin")]
#[case("many-large-ints-negative")]
#[case("many-large-ints")]
#[case("max-height")]
#[case("multiple-reserve-fee")]
#[case("negative-reserve-fee")]
#[case("recursion-pairs")]
#[case("unknown-condition")]
#[case("duplicate-messages")]
fn run_generator(#[case] name: &str) {
    use std::fs::{read_to_string, write};

    // When making changes to print_conditions() enabling this will update the
    // test cases to match. Make sure to carefully review the diff before
    // landing an automatic update of the test case.
    const UPDATE_TESTS: bool = false;

    let filename = format!("../../generator-tests/{name}.txt");
    println!("file: {filename}");
    let test_file = read_to_string(&filename).expect("test file not found");
    let (generator, expected) = test_file.split_once('\n').expect("invalid test file");
    let generator = hex::decode(generator).expect("invalid hex encoded generator");

    let expected = match expected.split_once("STRICT:\n") {
        Some((c, m)) => [c, m],
        None => [expected, expected],
    };

    let mut block_refs = Vec::<Vec<u8>>::new();

    let filename2 = format!("../../generator-tests/{name}.env");
    if let Ok(env_hex) = read_to_string(&filename2) {
        println!("block-ref file: {filename2}");
        block_refs.push(hex::decode(env_hex).expect("hex decode env-file"));
    }

    let mut write_back = format!("{}\n", hex::encode(&generator));
    let mut last_output = String::new();

    for (flags, expected) in zip(&[0, MEMPOOL_MODE], expected) {
        let mut flags = *flags;
        if name == "aa-million-messages" {
            // this test requires running after hard fork 2, where the COST_CONDITIONS
            // flag is set
            flags |= COST_CONDITIONS;
        }

        println!("flags: {flags:x}");
        let mut a2 = make_allocator(flags);
        let conds2 = run_block_generator2(
            &mut a2,
            &generator,
            &block_refs,
            11_000_000_000,
            flags | DONT_VALIDATE_SIGNATURE,
            &Signature::default(),
            None,
            &TEST_CONSTANTS,
        );

        let (expected_cost, output) = match conds2 {
            Ok(ref conditions) => {
                let cond_cost: u64 = conditions.spends.iter().map(|v| v.condition_cost).sum();
                assert_eq!(cond_cost, conditions.condition_cost);
                let exe_cost: u64 = conditions.spends.iter().map(|v| v.execution_cost).sum();
                // the generator itself has execution cost. At least the cost of
                // a quote
                assert!(exe_cost <= conditions.execution_cost);
                (conditions.cost, print_conditions(&a2, &conditions))
            }
            Err(code) => (0, format!("FAILED: {}\n", u32::from(code.1))),
        };

        if UPDATE_TESTS {
            if (flags & MEMPOOL_MODE) != 0 {
                if output != last_output {
                    write_back.push_str(&format!("STRICT:\n{output}"));
                }
            } else {
                last_output = output.clone();
                write_back.push_str(&format!("{output}"));
            }
        }

        let mut a1 = make_allocator(flags);
        let conds1 = run_block_generator(
            &mut a1,
            &generator,
            &block_refs,
            11_000_000_000,
            flags | DONT_VALIDATE_SIGNATURE,
            &Signature::default(),
            None,
            &TEST_CONSTANTS,
        );
        let output_pre_hard_fork = match conds1 {
            Ok(mut conditions) => {
                // before the hard fork, the cost of running the genrator +
                // puzzles should never be lower than after the hard-fork
                // but it's likely higher.
                assert!(conditions.cost >= expected_cost);
                // pre-hard fork, we don't have access to per-puzzle costs, so
                // set those to whatever run_block_generator2() produced, to
                // make the check pass
                if let Ok(ref conds2) = conds2 {
                    // update the cost we print here, just to be compatible with
                    // the test cases we have. We've already ensured the cost is
                    // lower
                    conditions.cost = conds2.cost;
                    conditions.execution_cost = conds2.execution_cost;
                    for s in &conds2.spends {
                        for ms in conditions.spends.iter_mut() {
                            if ms.coin_id == s.coin_id {
                                ms.execution_cost = s.execution_cost;
                                break;
                            }
                        }
                    }
                }

                print_conditions(&a1, &conditions)
            }
            Err(code) => {
                format!("FAILED: {}\n", u32::from(code.1))
            }
        };

        if output != output_pre_hard_fork {
            print_diff(&output, &output_pre_hard_fork);
            if !UPDATE_TESTS {
                panic!("run_block_generator 1 and 2 produced a different result!");
            }
        }

        if output != expected {
            print_diff(&output, expected);
            if !UPDATE_TESTS {
                panic!("mismatching generator output");
            }
        }

        // now lets check get_coinspends_for_trusted_block
        let vec_of_slices: Vec<&[u8]> = block_refs.iter().map(std::vec::Vec::as_slice).collect();

        let result = get_coinspends_for_trusted_block(
            &TEST_CONSTANTS,
            &Program::new(generator.clone().into()),
            &vec_of_slices,
            flags,
        );

        let result2 = get_coinspends_with_conditions_for_trusted_block(
            &TEST_CONSTANTS,
            &Program::new(generator.clone().into()),
            &vec_of_slices,
            flags,
        );

        if let Ok(ref conds) = conds2 {
            // if run_block_generator2 is OK then check we're equal
            let coinspends = result.expect("get_coinspends");
            let coinspends2 = result2.expect("get_coinspends_with_conds");
            for (i, spend) in conds.spends.iter().enumerate() {
                let runnable = {
                    let mut a = make_allocator(flags);
                    coinspends[i]
                        .puzzle_reveal
                        .run(
                            &mut a,
                            flags,
                            TEST_CONSTANTS.max_block_cost_klvm,
                            &coinspends[i].solution,
                        )
                        .is_ok()
                };
                assert!(runnable);
                let parent_id = a2.atom(spend.parent_id);
                assert_eq!(
                    parent_id.as_ref(),
                    coinspends[i].coin.parent_coin_info.as_slice()
                );
                let puzhash = a2.atom(spend.puzzle_hash);
                assert_eq!(puzhash.as_ref(), coinspends[i].coin.puzzle_hash.as_slice());
                assert_eq!(spend.coin_amount, coinspends[i].coin.amount);

                // check that we're getting the same info from get_coinspends_with_conditions_for_trusted_block
                assert_eq!(
                    parent_id.as_ref(),
                    coinspends2[i].0.coin.parent_coin_info.as_slice()
                );
                assert_eq!(
                    puzhash.as_ref(),
                    coinspends2[i].0.coin.puzzle_hash.as_slice()
                );
                assert_eq!(spend.coin_amount, coinspends2[i].0.coin.amount);
            }
        }
    }

    if UPDATE_TESTS {
        write(&filename, write_back.into_bytes()).expect("write file");
    }
}