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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
//! Compiled Executable is simulated CompiledPredicate.
//! This simulate refer to https://github.com/cryptoeconomicslab/gazelle/tree/master/packages/ovm-solidity-generator/src.

use crate::compiled_predicates::*;
use crate::executor::*;
use crate::predicates::*;
use crate::*;

// Compiled Predicate transpiles to this structure.
pub struct CompiledExecutable<'a, Ext: ExternalCall> {
    pub ext: &'a Ext,
    pub payout: AddressOf<Ext>,
    pub code: CompiledPredicate,
    pub constants: BTreeMap<HashOf<Ext>, VarType>,
    pub address_inputs: BTreeMap<HashOf<Ext>, AddressOf<Ext>>,
    pub bytes_inputs: BTreeMap<HashOf<Ext>, Vec<u8>>,
}

impl<Ext: ExternalCall> CompiledPredicateInterface<AddressOf<Ext>> for CompiledExecutable<'_, Ext> {
    fn payout_contract_address(&self) -> AddressOf<Ext> {
        self.payout.clone()
    }

    /// @dev Validates a child node of the property in game tree.
    fn is_valid_challenge(
        &self,
        inputs: Vec<Vec<u8>>,
        challenge_inputs: Vec<Vec<u8>>,
        challenge: Property<AddressOf<Ext>>,
    ) -> ExecResult<AddressOf<Ext>> {
        require_with_message!(
            Ext::hash_of(&self.get_child(inputs, challenge_inputs)?) == Ext::hash_of(&challenge),
            "_challenge must be valud child of game tree"
        );
        Ok(true)
    }

    /// @dev get valid child property of game tree with challenge_inputs
    fn get_child(
        &self,
        inputs: Vec<Vec<u8>>,
        challenge_input: Vec<Vec<u8>>,
    ) -> ExecResultTOf<Property<AddressOf<Ext>>, Ext> {
        require!(inputs.len() > 1);
        if Ext::is_label(&inputs[0]) {
            let intermediate = self.resolve_intermediate(&self.code.entry_point)?;
            return self.get_child_intermediate(intermediate, &inputs, &challenge_input);
        }
        let input_0 = &Ext::get_input_value(&inputs[0]);
        let sub_inputs = Ext::sub_array(&inputs, 1, inputs.len());

        let intermediate = self.resolve_intermediate(&input_0)?;
        return self.get_child_intermediate(intermediate, &sub_inputs, &challenge_input);
    }

    fn decide(&self, inputs: Vec<Vec<u8>>, witness: Vec<Vec<u8>>) -> ExecResult<AddressOf<Ext>> {
        // println!("decide inputs: {:?}", inputs);
        // println!("decide witness:{:?}", witness);
        if !Ext::is_label(&inputs[0]) {
            return Err(ExecError::Unimplemented);
        }
        let input_0 = &Ext::get_input_value(&inputs[0]);
        let sub_inputs = Ext::sub_array(&inputs, 1, inputs.len());
        let intermediate = self.resolve_intermediate(&input_0)?;
        self.decide_intermediate(&intermediate, &sub_inputs, &witness)
    }

    fn decide_true(
        &self,
        inputs: Vec<Vec<u8>>,
        witness: Vec<Vec<u8>>,
    ) -> ExecResult<AddressOf<Ext>> {
        self.decide(inputs, witness)
    }

    fn decide_with_witness(
        &self,
        inputs: Vec<Vec<u8>>,
        witness: Vec<Vec<u8>>,
    ) -> ExecResult<AddressOf<Ext>> {
        let result = self.decide(inputs.clone(), witness)?;
        require_with_message!(result, "must be true");
        let property = Property {
            predicate_address: self.ext.ext_address(),
            inputs: inputs,
        };
        self.ext
            .ext_set_predicate_decision(self.ext.ext_get_property_id(&property), true)
    }
}

impl<Ext: ExternalCall> CompiledExecutable<'_, Ext> {
    // decide_** --------------------------------------
    fn decide_intermediate(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        witness: &Vec<Vec<u8>>,
    ) -> ExecResult<AddressOf<Ext>> {
        // println!("decide_intermediate inter    : {:?}", inter);
        // println!("decide_intermediate inputs   : {:?}", inputs);
        // println!("decide_intermediate witness  : {:?}", witness);

        let input_property_list = Self::get_input_property_list(inter, inputs)?;
        let input_property_list_child_list =
            Self::get_input_property_list_child_list(inter, &input_property_list)?;

        match &inter.connective {
            LogicalConnective::And => self.decide_and(
                inter,
                inputs,
                witness,
                &input_property_list,
                &input_property_list_child_list,
            ),
            LogicalConnective::ThereExistsSuchThat => self.decide_there_exists_such_that(
                inter,
                inputs,
                witness,
                &input_property_list,
                &input_property_list_child_list,
            ),
            LogicalConnective::Or => self.decide_or(
                inter,
                inputs,
                witness,
                &input_property_list,
                &input_property_list_child_list,
            ),
            _ => Ok(false),
        }
    }

    fn decide_and(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        witness: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResult<AddressOf<Ext>> {
        require!(witness.len() >= inter.inputs.len());
        for (i, item) in inter.inputs.iter().enumerate() {
            if let AtomicPropositionOrPlaceholder::AtomicProposition(item) = item {
                if item.is_compiled.unwrap_or(false) {
                    let child_inputs = self.construct_inputs(
                        item,
                        &witness[0],
                        inputs,
                        input_property,
                        input_property_list_child_list,
                    )?;
                    require!(self.decide(child_inputs, Ext::bytes_to_bytes_array(&witness[i])?)?);
                }
                return self.decide_property(
                    item,
                    inputs,
                    witness,
                    input_property,
                    input_property_list_child_list,
                    &Ext::bytes_to_bytes_array(&witness[i])?,
                );
            }
        }
        Ok(true)
    }

    fn decide_there_exists_such_that(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        witness: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResult<AddressOf<Ext>> {
        require!(inter.inputs.len() > 2);
        let inner_property = match &inter.inputs[2] {
            AtomicPropositionOrPlaceholder::AtomicProposition(x) => x,
            _ => return Ok(true),
        };
        if inner_property.is_compiled.unwrap_or(false) {
            let child_inputs = self.construct_inputs(
                inner_property,
                &witness[0],
                inputs,
                input_property,
                input_property_list_child_list,
            )?;
            require!(self.decide(child_inputs, Ext::sub_array(&witness, 1, witness.len()))?);
        } else {
            require!(self.decide_property(
                inner_property,
                inputs,
                witness,
                input_property,
                input_property_list_child_list,
                &Ext::sub_array(&witness, 1, witness.len() as usize),
            )?);
        }
        Ok(true)
    }

    fn decide_or(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        witness: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResult<AddressOf<Ext>> {
        let or_index = Ext::bytes_to_u128(&witness[0])?;
        for (index, item) in inter.inputs.iter().enumerate() {
            if or_index as usize == index {
                if let AtomicPropositionOrPlaceholder::AtomicProposition(item) = item {
                    if item.is_compiled.unwrap_or(false) {
                        let child_inputs = self.construct_inputs(
                            item,
                            &witness[0],
                            inputs,
                            input_property,
                            input_property_list_child_list,
                        )?;
                        require!(
                            self.decide(child_inputs, Ext::sub_array(witness, 1, witness.len()))?
                        );
                    } else {
                        return self.decide_property(
                            item,
                            inputs,
                            witness,
                            input_property,
                            input_property_list_child_list,
                            &Ext::sub_array(witness, 1, witness.len()),
                        );
                    }
                }
            }
        }
        Ok(true)
    }

    fn decide_property(
        &self,
        inter: &AtomicProposition,
        inputs: &Vec<Vec<u8>>,
        witness: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
        child_witnesses: &Vec<Vec<u8>>,
    ) -> ExecResult<AddressOf<Ext>> {
        if let PredicateCall::InputPredicateCall(call) = &inter.predicate {
            require!(inputs.len() > (call.source.input_index - 1) as usize);
            if inter.inputs.len() == 0 {
                require!(self.ext.ext_is_decided(&Ext::bytes_to_property(
                    &inputs[(call.source.input_index - 1) as usize]
                )?));
            } else {
                let input_predicate_property =
                    Ext::bytes_to_property(&inputs[(call.source.input_index - 1) as usize])?;
                let mut new_inputs = input_predicate_property.inputs.clone();
                if let CompiledInput::NormalInput(normal_input) = &inter.inputs[0] {
                    require!(inputs.len() > (normal_input.input_index - 1) as usize);
                    new_inputs.push(inputs[(normal_input.input_index - 1) as usize].clone());
                    let result = self.ext.ext_call(
                        &input_predicate_property.predicate_address,
                        PredicateCallInputs::CompiledPredicate(
                            CompiledPredicateCallInputs::Decide {
                                inputs: new_inputs,
                                witness: child_witnesses.clone(),
                            },
                        ),
                    )?;
                    require_with_message!(
                        Ext::bytes_to_bool(&result)?,
                        "InputPredicate must be true"
                    );
                }
            }
        } else if let PredicateCall::VariablePredicateCall(_) = &inter.predicate {
            // TODO: executable
            // require_with_message!(
            //     self.ext
            //         .ext_is_decided(&Ext::bytes_to_property(&challenge_input)),
            //     "VariablePredicate must be true"
            // );
            return Ok(true);
        } else {
            let new_inputs = self.construct_inputs(
                inter,
                &witness[0],
                inputs,
                input_property,
                input_property_list_child_list,
            )?;
            if let PredicateCall::CompiledPredicateCall(_call) = &inter.predicate {
                // This is for predicates dynamic linking.
                let source = Self::get_source_str_from_inter(&inter.predicate)?;
                let result = self.ext.ext_call(
                    &self.get_address_variable(&source)?,
                    PredicateCallInputs::CompiledPredicate(CompiledPredicateCallInputs::Decide {
                        inputs: new_inputs,
                        witness: child_witnesses.clone(),
                    }),
                )?;
                require_with_message!(
                    Ext::bytes_to_bool(&result)?,
                    "CompiledPredicate(property.predicate.source) must be true"
                );
            } else {
                let source = Self::get_source_str_from_inter(&inter.predicate)?;
                let result = self.ext.ext_call(
                    &self.get_address_variable(&source)?,
                    PredicateCallInputs::AtomicPredicate(AtomicPredicateCallInputs::Decide {
                        inputs: new_inputs,
                    }),
                )?;
                require_with_message!(
                    Ext::bytes_to_bool(&result)?,
                    "CompiledPredicate(property.predicate.source) must be true"
                );
            }
        }
        Ok(true)
    }

    // get_child_** --------------------------------------
    fn get_child_intermediate(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        challenge_inputs: &Vec<Vec<u8>>,
    ) -> ExecResultTOf<PropertyOf<Ext>, Ext> {
        // println!("get_child_intermediate inter    : {:?}", inter);
        // println!("get_child_intermediate inputs   : {:?}", inputs);
        // println!("get_child_intermediate challenge: {:?}", challenge_inputs);
        let input_property_list = Self::get_input_property_list(inter, inputs)?;
        let input_property_list_child_list =
            Self::get_input_property_list_child_list(inter, &input_property_list)?;

        match &inter.connective {
            LogicalConnective::And => self.get_child_and(
                inter,
                inputs,
                challenge_inputs,
                &input_property_list,
                &input_property_list_child_list,
            ),
            LogicalConnective::ForAllSuchThat => self.get_child_for_all_such_that(
                inter,
                inputs,
                challenge_inputs,
                &input_property_list,
                &input_property_list_child_list,
            ),
            LogicalConnective::Not => self.get_child_not(
                inter,
                inputs,
                challenge_inputs,
                &input_property_list,
                &input_property_list_child_list,
            ),
            LogicalConnective::Or => self.get_child_or(
                inter,
                inputs,
                challenge_inputs,
                &input_property_list,
                &input_property_list_child_list,
            ),
            LogicalConnective::ThereExistsSuchThat => self.get_child_there_exists_such_that(
                inter,
                inputs,
                challenge_inputs,
                &input_property_list,
                &input_property_list_child_list,
            ),
        }
    }

    fn get_child_and(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        challenge_inputs: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResultTOf<PropertyOf<Ext>, Ext> {
        let challenge_input: usize = Ext::bytes_to_u128(&challenge_inputs[0])? as usize;
        require!(inter.inputs.len() > challenge_input as usize);
        let item = &inter.inputs[challenge_input];
        match item {
            AtomicPropositionOrPlaceholder::AtomicProposition(item) => {
                if item.is_compiled.unwrap_or(false) {
                    require!(item.inputs.len() > 1);
                    let child_inputs = self.construct_inputs(
                        &item,
                        &challenge_inputs[0],
                        inputs,
                        input_property,
                        input_property_list_child_list,
                    )?;
                    return self.get_child(
                        child_inputs,
                        Ext::sub_array(challenge_inputs, 1, challenge_inputs.len()),
                    );
                } else if let PredicateCall::CompiledPredicateCall(pred) = &item.predicate {
                    let child_inputs = self.construct_inputs(
                        &item,
                        &challenge_inputs[0],
                        inputs,
                        input_property,
                        input_property_list_child_list,
                    )?;
                    let ret = self.ext.ext_call(
                        &self.get_address_variable(&pred.source)?,
                        PredicateCallInputs::CompiledPredicate(
                            CompiledPredicateCallInputs::GetChild {
                                inputs: child_inputs,
                                challenge_input: Ext::sub_array(
                                    challenge_inputs,
                                    1,
                                    challenge_inputs.len(),
                                ),
                            },
                        ),
                    )?;
                    return Ok(Ext::bytes_to_property(&ret)?);
                } else {
                    let not_inputs = vec![self
                        .construct_property(
                            &item,
                            false,
                            inputs,
                            challenge_inputs,
                            input_property,
                            input_property_list_child_list,
                        )?
                        .encode()];
                    Ok(Property {
                        predicate_address: Ext::not_address(),
                        inputs: not_inputs,
                    })
                }
            }
            _ => Err(ExecError::Unexpected {
                msg: "get_child_and must be AtomicProposition.",
            }),
        }
    }

    fn get_child_for_all_such_that(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        challenge_inputs: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResultTOf<PropertyOf<Ext>, Ext> {
        require!(inter.inputs.len() > 2);
        // let quantifier = &inter.inputs[0];
        let inner_property = &inter.inputs[2];
        match inner_property {
            AtomicPropositionOrPlaceholder::AtomicProposition(inner_property) => {
                if inner_property.is_compiled.unwrap_or(false) {
                    let child_inputs = self.construct_inputs(
                        inner_property,
                        &challenge_inputs[0],
                        inputs,
                        input_property,
                        input_property_list_child_list,
                    )?;
                    self.get_child(
                        child_inputs,
                        Ext::sub_array(challenge_inputs, 1, challenge_inputs.len()),
                    )
                } else {
                    let not_inputs = vec![self
                        .construct_property(
                            inner_property,
                            false,
                            inputs,
                            challenge_inputs,
                            input_property,
                            input_property_list_child_list,
                        )?
                        .encode()];
                    Ok(Property {
                        predicate_address: Ext::not_address(),
                        inputs: not_inputs,
                    })
                }
            }
            _ => Err(ExecError::Unexpected {
                msg: "get_child_for_all_such_that must be AtomicProposition.",
            }),
        }
    }

    fn get_child_not(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        challenge_inputs: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResultTOf<PropertyOf<Ext>, Ext> {
        let inner_property = &inter.inputs[0];
        if let AtomicPropositionOrPlaceholder::AtomicProposition(inner_property) = inner_property {
            return self.construct_property(
                inner_property,
                false,
                inputs,
                challenge_inputs,
                input_property,
                input_property_list_child_list,
            );
        }
        Err(ExecError::Unexpected {
            msg: "get_child_not must be AtomicProposition.",
        })
    }

    fn get_child_there_exists_such_that(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        challenge_inputs: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResultTOf<PropertyOf<Ext>, Ext> {
        if let AtomicPropositionOrPlaceholder::AtomicProposition(inner_property) = &inter.inputs[2]
        {
            if let AtomicPropositionOrPlaceholder::Placeholder(property_input_1) = &inter.inputs[1]
            {
                let not_input =
                    self.construct_property(
                        inner_property,
                        Ext::bytes_to_bool(&mut &self.get_bytes_variable(
                            &Ext::prefix_variable(&property_input_1.encode()),
                        )?)?,
                        inputs,
                        challenge_inputs,
                        input_property,
                        input_property_list_child_list,
                    )?;
                let for_all_such_that_inputs = vec![
                    vec![],
                    property_input_1.encode(),
                    Property {
                        predicate_address: Ext::not_address(),
                        inputs: vec![not_input.encode()],
                    }
                    .encode(),
                ];
                return Ok(Property {
                    predicate_address: Ext::for_all_address(),
                    inputs: for_all_such_that_inputs,
                });
            }
        }
        Err(ExecError::Unexpected {
            msg: "get_child_there_exists_such_that must be inter.inputs[1] is Placeholder, inter.inputs[2] is AtomicProposition.",
        })
    }

    fn get_child_or(
        &self,
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
        challenge_inputs: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResultTOf<PropertyOf<Ext>, Ext> {
        let inputs = inter
            .inputs
            .iter()
            .map(|item| {
                if let AtomicPropositionOrPlaceholder::AtomicProposition(item) = &item {
                    if let PredicateCall::CompiledPredicateCall(_) = &item.predicate {
                        // not (compiled predicate)
                        let not_inputs = vec![self
                            .construct_property(
                                item,
                                false,
                                inputs,
                                challenge_inputs,
                                input_property,
                                input_property_list_child_list,
                            )?
                            .encode()];
                        return Ok(Property {
                            predicate_address: Ext::not_address(),
                            inputs: not_inputs,
                        }
                        .encode());
                    } else {
                        // The valid challenge of "p1 ∨ p2" is "¬(p1) ∧ ¬(p2)".
                        // If p1 is "¬(p1_1)", the valid challenge is "p1_1 ∧ ¬(p2)",
                        //   then returning getChild of "¬(p1_1)" here.
                        let child_inputs = self.construct_inputs(
                            item,
                            &challenge_inputs[0],
                            inputs,
                            input_property,
                            input_property_list_child_list,
                        )?;
                        return Ok(self
                            .get_child(child_inputs, challenge_inputs.clone())?
                            .encode());
                    }
                }
                Err(ExecError::Unexpected {
                    msg: "get_child_or must be all inter.inputs AtomicProposition.",
                })
            })
            .collect::<Result<Vec<Vec<u8>>, _>>()?;
        Ok(Property {
            predicate_address: Ext::and_address(),
            inputs: inputs,
        })
    }

    // helper -----------------------------------------------
    fn resolve_intermediate(
        &self,
        name: &Vec<u8>,
    ) -> ExecResultTOf<&IntermediateCompiledPredicate, Ext> {
        if let Some(index) = self
            .code
            .contracts
            .iter()
            .position(|inter| &inter.name == name)
        {
            return Ok(&self.code.contracts[index]);
        }
        Err(ExecError::Require {
            msg: "Required error by: resolve_intermediate",
        })
    }

    fn get_input_property_list(
        inter: &IntermediateCompiledPredicate,
        inputs: &Vec<Vec<u8>>,
    ) -> ExecResultTOf<Vec<PropertyOf<Ext>>, Ext> {
        Ok(inter
            .property_inputs
            .iter()
            .map(|property_input| {
                Ext::bytes_to_property(&inputs[(property_input.input_index - 1) as usize])
            })
            .collect::<Result<Vec<PropertyOf<Ext>>, _>>()?)
    }

    fn get_input_property_list_child_list(
        inter: &IntermediateCompiledPredicate,
        input_property: &Vec<PropertyOf<Ext>>,
    ) -> ExecResultTOf<Vec<BTreeMap<i8, PropertyOf<Ext>>>, Ext> {
        inter
            .property_inputs
            .iter()
            .map(|property_input| {
                let mut ret = BTreeMap::new();
                if property_input.children.len() > 0 {
                    require!(
                        input_property[property_input.input_index as usize]
                            .inputs
                            .len()
                            > property_input.children[0] as usize
                    );
                    ret.insert(
                        property_input.children[0].clone(),
                        Ext::bytes_to_property(
                            &input_property[property_input.input_index as usize].inputs
                                [property_input.children[0] as usize],
                        )?,
                    );
                }
                Ok(ret)
            })
            .collect::<Result<Vec<BTreeMap<i8, PropertyOf<Ext>>>, _>>()
    }

    fn construct_inputs(
        &self,
        property: &AtomicProposition,
        witness: &Vec<u8>,
        inputs: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResultTOf<Vec<Vec<u8>>, Ext> {
        property
            .inputs
            .iter()
            .map(|input| {
                self.construct_input(
                    input,
                    witness,
                    inputs,
                    input_property,
                    input_property_list_child_list,
                )
            })
            .collect()
    }

    fn construct_input(
        &self,
        compiled_input: &CompiledInput,
        witness: &Vec<u8>,
        inputs: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResultTOf<Vec<u8>, Ext> {
        match compiled_input {
            CompiledInput::ConstantInput(inp) => Ok(inp.name.clone()),
            CompiledInput::LabelInput(inp) => {
                Ok(Ext::prefix_label(&self.get_bytes_variable(&inp.label)?))
            }
            CompiledInput::NormalInput(inp) => {
                if inp.children.len() == 1 {
                    require!(input_property.len() > inp.input_index as usize);
                    let input_property_input = &input_property[inp.input_index as usize];
                    if inp.children[0] >= 0 {
                        require!(input_property_input.inputs.len() > inp.children[0] as usize);
                        return Ok(input_property_input.inputs[inp.children[0] as usize].clone());
                    } else {
                        return Ok(input_property_input.predicate_address.encode());
                    }
                } else if inp.children.len() == 2 {
                    require!(input_property_list_child_list.len() > inp.input_index as usize);
                    let input_child_list = input_property_list_child_list[inp.input_index as usize]
                        .get(&inp.children[0])
                        .ok_or(ExecError::Require {
                            msg: "invalid index children[0]",
                        })?;
                    if inp.children[1] >= 0 {
                        return Ok(input_child_list.inputs[inp.children[1] as usize].clone());
                    } else {
                        return Ok(input_child_list.predicate_address.encode());
                    }
                }
                require!(inputs.len() > (inp.input_index - 1) as usize);
                Ok(inputs[(inp.input_index - 1) as usize].clone())
            }
            CompiledInput::VariableInput(_) => Ok(witness.clone()),
            CompiledInput::SelfInput(_) => Ok(self.ext.ext_address().encode()),
        }
    }

    fn construct_property(
        &self,
        property: &AtomicProposition,
        free_variable: bool,
        inputs: &Vec<Vec<u8>>,
        challenge_inputs: &Vec<Vec<u8>>,
        input_property: &Vec<PropertyOf<Ext>>,
        input_property_list_child_list: &Vec<BTreeMap<i8, PropertyOf<Ext>>>,
    ) -> ExecResultTOf<PropertyOf<Ext>, Ext> {
        match &property.predicate {
            PredicateCall::InputPredicateCall(call) => {
                require!(inputs.len() > (call.source.input_index - 1) as usize);
                if property.inputs.len() == 0 {
                    return Ext::bytes_to_property(&inputs[(call.source.input_index - 1) as usize]);
                }
                require!(inputs.len() > (call.source.input_index - 1) as usize);
                require!(challenge_inputs.len() > 0);
                let input_predicate_property: PropertyOf<Ext> =
                    Ext::bytes_to_property(&inputs[(call.source.input_index - 1) as usize])?;
                let mut child_inputs_of = input_predicate_property.inputs;
                child_inputs_of.push(self.construct_input(
                    &property.inputs[0],
                    &challenge_inputs[0],
                    inputs,
                    input_property,
                    input_property_list_child_list,
                )?);
                Ok(Property {
                    predicate_address: input_predicate_property.predicate_address,
                    inputs: child_inputs_of,
                })
            }
            PredicateCall::VariablePredicateCall(_) => {
                if property.inputs.len() == 0 {
                    require!(challenge_inputs.len() > 0);
                    return Ext::bytes_to_property(&challenge_inputs[0]);
                }

                let input_predicate_property: PropertyOf<Ext> =
                    Ext::bytes_to_property(&challenge_inputs[0])?;
                let mut child_inputs_of = input_predicate_property.inputs;
                let property_inputs_input_index =
                    Self::get_input_index_from_atomic_proposition(&property.inputs[0])?;
                child_inputs_of.push(inputs[(property_inputs_input_index - 1) as usize].clone());
                Ok(Property {
                    predicate_address: input_predicate_property.predicate_address,
                    inputs: child_inputs_of,
                })
            }
            _ => {
                let witness = if free_variable {
                    self.get_bytes_variable(&b"freeVariable".to_vec())?
                } else {
                    challenge_inputs[0].clone()
                };
                let child_inputs_of = self.construct_inputs(
                    property,
                    &witness,
                    inputs,
                    input_property,
                    input_property_list_child_list,
                )?;
                if property.is_compiled.unwrap_or(false) {
                    return Ok(Property {
                        predicate_address: self.ext.ext_address(),
                        inputs: child_inputs_of,
                    });
                }
                let predicate_address = self
                    .get_address_variable(&Self::get_source_str_from_inter(&property.predicate)?)?;
                Ok(PropertyOf::<Ext> {
                    predicate_address,
                    inputs: child_inputs_of,
                })
            }
        }
    }

    fn get_bytes_variable(&self, key: &Vec<u8>) -> ExecResultTOf<Vec<u8>, Ext> {
        if let Some(ret) = self.bytes_inputs.get(&Ext::hash_of(&key)) {
            return Ok(ret.clone());
        }
        Err(ExecError::Require {
            msg: "invalid bytes variable name.",
        })
    }

    fn get_address_variable(&self, key: &Vec<u8>) -> ExecResultTOf<AddressOf<Ext>, Ext> {
        // println!("get_address_variable: {}", key);
        if let Some(ret) = self.address_inputs.get(&Ext::hash_of(key)) {
            return Ok(ret.clone());
        }
        if let Some(ret) = Ext::vec_to_address(key) {
            return Ok(ret);
        }
        Err(ExecError::Require {
            msg: "invalid address a variable name.",
        })
    }

    fn get_source_str_from_inter(predicate: &PredicateCall) -> ExecResultTOf<Vec<u8>, Ext> {
        match predicate {
            PredicateCall::AtomicPredicateCall(predicate) => Ok(predicate.source.clone()),
            PredicateCall::CompiledPredicateCall(predicate) => Ok(predicate.source.clone()),
            _ => Err(ExecError::Unexpected {
                msg: "The intermediate must have source as bytes string.",
            }),
        }
    }

    fn get_input_index_from_atomic_proposition(
        compiled_input: &CompiledInput,
    ) -> ExecResultTOf<u8, Ext> {
        match compiled_input {
            CompiledInput::NormalInput(normal) => Ok(normal.input_index),
            _ => Err(ExecError::Unexpected {
                msg: "The atomic proposition must have NormalInput and input_index.",
            }),
        }
    }
}