chia-protocol 0.46.0

Chia network protocol message types
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
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
use chia_sha2::Sha256;
use chia_streamable_macro::streamable;

use crate::Bytes;
use crate::Bytes32;
use crate::Coin;
use crate::EndOfSubSlotBundle;
use crate::Program;
use crate::RewardChainBlock;
use crate::VDFProof;
use crate::{Foliage, FoliageTransactionBlock, TransactionsInfo};
use chia_traits::Streamable;
use chia_traits::chia_error::{Error, Result};
use std::io::Cursor;

// Similar to ProofOfSpace, we use unused bits in the Option<> prefix byte
// for transactions_generator to encode a version flag. Bit 1 (0b10) indicates
// the "raw bytes" format where the generator is serialized as length-prefixed
// bytes (like Bytes) instead of a self-describing CLVM Program, and
// transactions_generator_ref_list is omitted entirely.
#[streamable(no_streamable)]
pub struct FullBlock {
    finished_sub_slots: Vec<EndOfSubSlotBundle>,
    reward_chain_block: RewardChainBlock,
    challenge_chain_sp_proof: Option<VDFProof>, // # If not first sp in sub-slot
    challenge_chain_ip_proof: VDFProof,
    reward_chain_sp_proof: Option<VDFProof>, // # If not first sp in sub-slot
    reward_chain_ip_proof: VDFProof,
    infused_challenge_chain_ip_proof: Option<VDFProof>, // # Iff deficit < 4
    foliage: Foliage,                                   // # Reward chain foliage data
    foliage_transaction_block: Option<FoliageTransactionBlock>, // # Reward chain foliage data (tx block)
    transactions_info: Option<TransactionsInfo>, // Reward chain foliage data (tx block additional)
    transactions_generator: Option<Program>,     // Program that generates transactions
    transactions_generator_ref_list: Vec<u32>, // List of block heights of previous generators referenced in this block

    // Raw generator bytes, only used when version == 1. Mutually exclusive
    // with transactions_generator and transactions_generator_ref_list.
    transactions_generator_buffer: Option<Vec<u8>>,

    // 0 = legacy format (Program serialization + ref_list)
    // 1 = raw bytes format (length-prefixed bytes, ref_list omitted)
    version: u8,
}

impl Streamable for FullBlock {
    fn update_digest(&self, digest: &mut Sha256) {
        self.finished_sub_slots.update_digest(digest);
        self.reward_chain_block.update_digest(digest);
        self.challenge_chain_sp_proof.update_digest(digest);
        self.challenge_chain_ip_proof.update_digest(digest);
        self.reward_chain_sp_proof.update_digest(digest);
        self.reward_chain_ip_proof.update_digest(digest);
        self.infused_challenge_chain_ip_proof.update_digest(digest);
        self.foliage.update_digest(digest);
        self.foliage_transaction_block.update_digest(digest);
        self.transactions_info.update_digest(digest);

        if self.version == 0 {
            self.transactions_generator.update_digest(digest);
            self.transactions_generator_ref_list.update_digest(digest);
        } else if self.version == 1 {
            match &self.transactions_generator_buffer {
                None => {
                    0b10_u8.update_digest(digest);
                }
                Some(buf) => {
                    0b11_u8.update_digest(digest);
                    (buf.len() as u32).update_digest(digest);
                    digest.update(buf);
                }
            }
        } else {
            panic!("version field must be 0 or 1, but it's {}", self.version);
        }
    }

    fn stream(&self, out: &mut Vec<u8>) -> Result<()> {
        self.finished_sub_slots.stream(out)?;
        self.reward_chain_block.stream(out)?;
        self.challenge_chain_sp_proof.stream(out)?;
        self.challenge_chain_ip_proof.stream(out)?;
        self.reward_chain_sp_proof.stream(out)?;
        self.reward_chain_ip_proof.stream(out)?;
        self.infused_challenge_chain_ip_proof.stream(out)?;
        self.foliage.stream(out)?;
        self.foliage_transaction_block.stream(out)?;
        self.transactions_info.stream(out)?;

        if self.version == 0 {
            self.transactions_generator.stream(out)?;
            self.transactions_generator_ref_list.stream(out)?;
        } else if self.version == 1 {
            match &self.transactions_generator_buffer {
                None => {
                    0b10_u8.stream(out)?;
                }
                Some(buf) => {
                    0b11_u8.stream(out)?;
                    (buf.len() as u32).stream(out)?;
                    out.extend_from_slice(buf);
                }
            }
        } else {
            return Err(Error::InvalidFullBlock);
        }
        Ok(())
    }

    fn parse<const TRUSTED: bool>(input: &mut Cursor<&[u8]>) -> Result<Self> {
        let finished_sub_slots = <Vec<EndOfSubSlotBundle> as Streamable>::parse::<TRUSTED>(input)?;
        let reward_chain_block = <RewardChainBlock as Streamable>::parse::<TRUSTED>(input)?;
        let challenge_chain_sp_proof = <Option<VDFProof> as Streamable>::parse::<TRUSTED>(input)?;
        let challenge_chain_ip_proof = <VDFProof as Streamable>::parse::<TRUSTED>(input)?;
        let reward_chain_sp_proof = <Option<VDFProof> as Streamable>::parse::<TRUSTED>(input)?;
        let reward_chain_ip_proof = <VDFProof as Streamable>::parse::<TRUSTED>(input)?;
        let infused_challenge_chain_ip_proof =
            <Option<VDFProof> as Streamable>::parse::<TRUSTED>(input)?;
        let foliage = <Foliage as Streamable>::parse::<TRUSTED>(input)?;
        let foliage_transaction_block =
            <Option<FoliageTransactionBlock> as Streamable>::parse::<TRUSTED>(input)?;
        let transactions_info = <Option<TransactionsInfo> as Streamable>::parse::<TRUSTED>(input)?;

        let prefix = <u8 as Streamable>::parse::<TRUSTED>(input)?;
        let version = prefix >> 1;
        let has_generator = (prefix & 1) != 0;

        if version == 0 {
            let transactions_generator = if has_generator {
                Some(<Program as Streamable>::parse::<TRUSTED>(input)?)
            } else {
                None
            };
            let transactions_generator_ref_list =
                <Vec<u32> as Streamable>::parse::<TRUSTED>(input)?;

            Ok(FullBlock {
                finished_sub_slots,
                reward_chain_block,
                challenge_chain_sp_proof,
                challenge_chain_ip_proof,
                reward_chain_sp_proof,
                reward_chain_ip_proof,
                infused_challenge_chain_ip_proof,
                foliage,
                foliage_transaction_block,
                transactions_info,
                transactions_generator,
                transactions_generator_ref_list,
                transactions_generator_buffer: None,
                version,
            })
        } else if version == 1 {
            let transactions_generator_buffer = if has_generator {
                let bytes = <Bytes as Streamable>::parse::<TRUSTED>(input)?;
                Some(bytes.into_inner())
            } else {
                None
            };

            Ok(FullBlock {
                finished_sub_slots,
                reward_chain_block,
                challenge_chain_sp_proof,
                challenge_chain_ip_proof,
                reward_chain_sp_proof,
                reward_chain_ip_proof,
                infused_challenge_chain_ip_proof,
                foliage,
                foliage_transaction_block,
                transactions_info,
                transactions_generator: None,
                transactions_generator_ref_list: vec![],
                transactions_generator_buffer,
                version,
            })
        } else {
            Err(Error::InvalidFullBlock)
        }
    }
}

impl FullBlock {
    pub fn prev_header_hash(&self) -> Bytes32 {
        self.foliage.prev_block_hash
    }

    pub fn header_hash(&self) -> Bytes32 {
        self.foliage.hash().into()
    }

    pub fn is_transaction_block(&self) -> bool {
        self.foliage.foliage_transaction_block_hash.is_some()
    }

    pub fn total_iters(&self) -> u128 {
        self.reward_chain_block.total_iters
    }

    pub fn height(&self) -> u32 {
        self.reward_chain_block.height
    }

    pub fn weight(&self) -> u128 {
        self.reward_chain_block.weight
    }

    pub fn get_included_reward_coins(&self) -> Vec<Coin> {
        if let Some(ti) = &self.transactions_info {
            ti.reward_claims_incorporated.clone()
        } else {
            vec![]
        }
    }

    pub fn is_fully_compactified(&self) -> bool {
        for sub_slot in &self.finished_sub_slots {
            if sub_slot.proofs.challenge_chain_slot_proof.witness_type != 0
                || !sub_slot
                    .proofs
                    .challenge_chain_slot_proof
                    .normalized_to_identity
            {
                return false;
            }
            if let Some(proof) = &sub_slot.proofs.infused_challenge_chain_slot_proof {
                if proof.witness_type != 0 || !proof.normalized_to_identity {
                    return false;
                }
            }
        }

        if let Some(proof) = &self.challenge_chain_sp_proof {
            if proof.witness_type != 0 || !proof.normalized_to_identity {
                return false;
            }
        }
        self.challenge_chain_ip_proof.witness_type == 0
            && self.challenge_chain_ip_proof.normalized_to_identity
    }
}

#[cfg(feature = "py-bindings")]
use chia_traits::ChiaToPython;
#[cfg(feature = "py-bindings")]
use pyo3::prelude::*;

#[cfg(feature = "py-bindings")]
#[pymethods]
impl FullBlock {
    #[getter]
    #[pyo3(name = "prev_header_hash")]
    fn py_prev_header_hash(&self) -> Bytes32 {
        self.prev_header_hash()
    }

    #[getter]
    #[pyo3(name = "header_hash")]
    fn py_header_hash(&self) -> Bytes32 {
        self.header_hash()
    }

    #[pyo3(name = "is_transaction_block")]
    fn py_is_transaction_block(&self) -> bool {
        self.is_transaction_block()
    }

    #[getter]
    #[pyo3(name = "total_iters")]
    fn py_total_iters<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
        ChiaToPython::to_python(&self.total_iters(), py)
    }

    #[getter]
    #[pyo3(name = "height")]
    fn py_height<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
        ChiaToPython::to_python(&self.height(), py)
    }

    #[getter]
    #[pyo3(name = "weight")]
    fn py_weight<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
        ChiaToPython::to_python(&self.weight(), py)
    }

    #[pyo3(name = "get_included_reward_coins")]
    fn py_get_included_reward_coins(&self) -> Vec<Coin> {
        self.get_included_reward_coins()
    }

    #[pyo3(name = "is_fully_compactified")]
    fn py_is_fully_compactified(&self) -> bool {
        self.is_fully_compactified()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ClassgroupElement, FoliageBlockData, PoolTarget, ProofOfSpace, VDFInfo};
    use chia_bls::{G1Element, G2Element};

    fn make_vdf_proof() -> VDFProof {
        VDFProof::new(0, Bytes::default(), false)
    }

    fn make_vdf_info() -> VDFInfo {
        VDFInfo::new(Bytes32::default(), 1, ClassgroupElement::default())
    }

    fn make_proof_of_space() -> ProofOfSpace {
        ProofOfSpace::new(
            Bytes32::default(),
            Some(G1Element::default()),
            None,
            G1Element::default(),
            0,
            0,
            0,
            0,
            32,
            Bytes::from(vec![0x80]),
        )
    }

    fn make_reward_chain_block() -> RewardChainBlock {
        RewardChainBlock::new(
            1,
            0,
            1,
            0,
            Bytes32::default(),
            make_proof_of_space(),
            None,
            G2Element::default(),
            make_vdf_info(),
            None,
            G2Element::default(),
            make_vdf_info(),
            None,
            None,
            false,
        )
    }

    fn make_foliage() -> Foliage {
        let pool_target = PoolTarget::new(Bytes32::default(), 0);
        let foliage_block_data = FoliageBlockData::new(
            Bytes32::default(),
            pool_target,
            Some(G2Element::default()),
            Bytes32::default(),
            Bytes32::default(),
        );
        Foliage::new(
            Bytes32::default(),
            Bytes32::default(),
            foliage_block_data,
            G2Element::default(),
            None,
            None,
        )
    }

    fn make_v0_block(generator: Option<Program>, ref_list: Vec<u32>) -> FullBlock {
        FullBlock::new(
            vec![],
            make_reward_chain_block(),
            None,
            make_vdf_proof(),
            None,
            make_vdf_proof(),
            None,
            make_foliage(),
            None,
            None,
            generator,
            ref_list,
            None,
            0,
        )
    }

    fn make_v1_block(buffer: Option<Vec<u8>>) -> FullBlock {
        FullBlock::new(
            vec![],
            make_reward_chain_block(),
            None,
            make_vdf_proof(),
            None,
            make_vdf_proof(),
            None,
            make_foliage(),
            None,
            None,
            None,
            vec![],
            buffer,
            1,
        )
    }

    #[test]
    fn v0_no_generator_roundtrip() {
        let block = make_v0_block(None, vec![]);
        let buf = block.to_bytes().unwrap();
        let block2 = FullBlock::parse::<false>(&mut Cursor::new(&buf)).unwrap();

        assert_eq!(block2.version, 0);
        assert!(block2.transactions_generator.is_none());
        assert!(block2.transactions_generator_ref_list.is_empty());
        assert!(block2.transactions_generator_buffer.is_none());
        assert_eq!(block2.to_bytes().unwrap(), buf);
    }

    #[test]
    fn v0_with_generator_roundtrip() {
        let generator = Program::from(vec![0xff, 0x01, 0x80]);
        let block = make_v0_block(Some(generator.clone()), vec![100, 200]);
        let buf = block.to_bytes().unwrap();
        let block2 = FullBlock::parse::<false>(&mut Cursor::new(&buf)).unwrap();

        assert_eq!(block2.version, 0);
        assert_eq!(
            block2.transactions_generator.as_ref().unwrap().as_ref(),
            generator.as_ref()
        );
        assert_eq!(block2.transactions_generator_ref_list, vec![100, 200]);
        assert!(block2.transactions_generator_buffer.is_none());
        assert_eq!(block2.to_bytes().unwrap(), buf);
    }

    #[test]
    fn v1_no_generator_roundtrip() {
        let block = make_v1_block(None);
        let buf = block.to_bytes().unwrap();
        let block2 = FullBlock::parse::<false>(&mut Cursor::new(&buf)).unwrap();

        assert_eq!(block2.version, 1);
        assert!(block2.transactions_generator.is_none());
        assert!(block2.transactions_generator_ref_list.is_empty());
        assert!(block2.transactions_generator_buffer.is_none());
        assert_eq!(block2.to_bytes().unwrap(), buf);
    }

    #[test]
    fn v1_with_buffer_roundtrip() {
        let raw = vec![0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe];
        let block = make_v1_block(Some(raw.clone()));
        let buf = block.to_bytes().unwrap();
        let block2 = FullBlock::parse::<false>(&mut Cursor::new(&buf)).unwrap();

        assert_eq!(block2.version, 1);
        assert!(block2.transactions_generator.is_none());
        assert!(block2.transactions_generator_ref_list.is_empty());
        assert_eq!(block2.transactions_generator_buffer.as_ref().unwrap(), &raw);
        assert_eq!(block2.to_bytes().unwrap(), buf);
    }

    #[test]
    fn v0_prefix_byte_encoding() {
        let block_none = make_v0_block(None, vec![]);
        let buf_none = block_none.to_bytes().unwrap();

        let block_some = make_v0_block(Some(Program::from(vec![0x80])), vec![]);
        let buf_some = block_some.to_bytes().unwrap();

        let prefix_offset = buf_none
            .iter()
            .zip(buf_some.iter())
            .position(|(a, b)| a != b)
            .unwrap();

        assert_eq!(buf_none[prefix_offset], 0b00);
        assert_eq!(buf_some[prefix_offset], 0b01);
    }

    #[test]
    fn v1_prefix_byte_encoding() {
        let block_none = make_v1_block(None);
        let buf_none = block_none.to_bytes().unwrap();

        let block_some = make_v1_block(Some(vec![0x80]));
        let buf_some = block_some.to_bytes().unwrap();

        let prefix_offset = buf_none
            .iter()
            .zip(buf_some.iter())
            .position(|(a, b)| a != b)
            .unwrap();

        assert_eq!(buf_none[prefix_offset], 0b10);
        assert_eq!(buf_some[prefix_offset], 0b11);
    }

    #[test]
    fn v1_generator_has_length_prefix() {
        let raw = vec![0xca, 0xfe, 0xba, 0xbe];
        let block = make_v1_block(Some(raw.clone()));
        let buf = block.to_bytes().unwrap();

        let block_empty = make_v1_block(None);
        let buf_empty = block_empty.to_bytes().unwrap();

        let prefix_offset = buf
            .iter()
            .zip(buf_empty.iter())
            .position(|(a, b)| a != b)
            .unwrap();

        assert_eq!(buf[prefix_offset], 0b11);
        let len = u32::from_be_bytes(
            buf[prefix_offset + 1..prefix_offset + 5]
                .try_into()
                .unwrap(),
        );
        assert_eq!(len as usize, raw.len());
        assert_eq!(&buf[prefix_offset + 5..prefix_offset + 5 + raw.len()], &raw);
        assert_eq!(prefix_offset + 5 + raw.len(), buf.len());
    }

    #[test]
    fn v1_omits_ref_list() {
        let block_v0 = make_v0_block(Some(Program::from(vec![0x80])), vec![42]);
        let buf_v0 = block_v0.to_bytes().unwrap();

        let block_v1 = make_v1_block(Some(vec![0x80]));
        let buf_v1 = block_v1.to_bytes().unwrap();

        // v0: 1 (prefix) + 1 (program "80") + 4 (ref_list count) + 4 (one u32) = 10 tail bytes
        // v1: 1 (prefix) + 4 (length) + 1 (data) = 6 tail bytes
        assert!(buf_v1.len() < buf_v0.len());
    }

    #[test]
    fn v0_and_v1_same_hash_fields_before_generator() {
        let block_v0 = make_v0_block(None, vec![]);
        let block_v1 = make_v1_block(None);

        assert_eq!(block_v0.header_hash(), block_v1.header_hash());
    }

    #[test]
    fn v1_unvalidated_buffer_roundtrips() {
        let garbage = vec![0xff; 1000];
        let block = make_v1_block(Some(garbage.clone()));
        let buf = block.to_bytes().unwrap();
        let block2 = FullBlock::parse::<false>(&mut Cursor::new(&buf)).unwrap();
        assert_eq!(block2.transactions_generator_buffer.unwrap(), garbage);
    }

    // The version flag is packed into the transactions_generator Option prefix
    // byte. Only bit 0 (the Option flag) and bit 1 (the version) carry
    // meaning. The high bits (2..=7) must be rejected, matching the strictness
    // of a plain Option<> prefix in earlier protocol versions where this byte
    // could only ever be 0 or 1.
    #[test]
    fn high_prefix_bits_rejected() {
        let v0_none = make_v0_block(None, vec![]).to_bytes().unwrap();
        let v0_some = make_v0_block(Some(Program::from(vec![0x80])), vec![])
            .to_bytes()
            .unwrap();
        let offset = v0_none
            .iter()
            .zip(v0_some.iter())
            .position(|(a, b)| a != b)
            .unwrap();
        assert_eq!(v0_none[offset], 0b00);

        let v1_none = make_v1_block(None).to_bytes().unwrap();
        assert_eq!(v1_none[offset], 0b10);

        for valid in [&v0_none, &v1_none] {
            for bit in 2..8u8 {
                let mut buf = valid.clone();
                buf[offset] |= 1 << bit;
                let err = FullBlock::parse::<false>(&mut Cursor::new(&buf))
                    .expect_err("high prefix bit must be rejected");
                assert_eq!(err, Error::InvalidFullBlock);
            }
        }
    }
}