1use alloc::vec::Vec;
22use core::fmt;
23
24use heika_core::address::Address;
25use heika_core::hash::Hash256;
26use heika_core::merkle;
27use heika_transaction::{MosaicId, NamespaceId, UnresolvedAddress, UnresolvedMosaicId};
28use sha3::{Digest, Sha3_256};
29
30use reader::Reader;
31
32const RECEIPT_HEADER_SIZE: usize = 4 + 2 + 2;
34
35const STATEMENT_VERSION: u16 = 1;
37
38const TRANSACTION_GROUP: u16 = 0xE143;
40
41#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
46pub struct ReceiptSource {
47 pub primary_id: u32,
48 pub secondary_id: u32,
49}
50
51impl ReceiptSource {
52 const SIZE: usize = 4 + 4;
53
54 fn encode(&self, out: &mut Vec<u8>) {
55 out.extend_from_slice(&self.primary_id.to_le_bytes());
56 out.extend_from_slice(&self.secondary_id.to_le_bytes());
57 }
58
59 fn read(reader: &mut Reader) -> Result<Self, StatementDecodeError> {
60 Ok(Self {
61 primary_id: reader.u32()?,
62 secondary_id: reader.u32()?,
63 })
64 }
65}
66
67#[derive(Clone, Copy, PartialEq, Eq, Debug)]
69pub struct Mosaic {
70 pub mosaic_id: MosaicId,
71 pub amount: u64,
72}
73
74impl Mosaic {
75 fn encode(&self, out: &mut Vec<u8>) {
76 out.extend_from_slice(&self.mosaic_id.0.to_le_bytes());
77 out.extend_from_slice(&self.amount.to_le_bytes());
78 }
79
80 fn read(reader: &mut Reader) -> Result<Self, StatementDecodeError> {
81 Ok(Self {
82 mosaic_id: MosaicId(reader.u64()?),
83 amount: reader.u64()?,
84 })
85 }
86}
87
88#[derive(Clone, Copy, PartialEq, Eq, Debug)]
90pub struct BalanceTransfer {
91 pub mosaic: Mosaic,
92 pub sender_address: Address,
93 pub recipient_address: Address,
94}
95
96#[derive(Clone, Copy, PartialEq, Eq, Debug)]
98pub struct BalanceChange {
99 pub mosaic: Mosaic,
100 pub target_address: Address,
101}
102
103#[derive(Clone, Copy, PartialEq, Eq, Debug)]
105pub struct Receipt {
106 pub version: u16,
107 pub body: ReceiptBody,
108}
109
110#[derive(Clone, Copy, PartialEq, Eq, Debug)]
112pub enum ReceiptBody {
113 MosaicRentalFee(BalanceTransfer),
115 NamespaceRentalFee(BalanceTransfer),
117 HarvestFee(BalanceChange),
119 LockHashCompleted(BalanceChange),
121 LockHashExpired(BalanceChange),
123 LockSecretCompleted(BalanceChange),
125 LockSecretExpired(BalanceChange),
127 LockHashCreated(BalanceChange),
129 LockSecretCreated(BalanceChange),
131 MosaicExpired(MosaicId),
133 NamespaceExpired(NamespaceId),
135 NamespaceDeleted(NamespaceId),
137 Inflation(Mosaic),
139}
140
141impl ReceiptBody {
142 pub fn receipt_type(&self) -> u16 {
144 match self {
145 Self::MosaicRentalFee(_) => 0x124D,
146 Self::NamespaceRentalFee(_) => 0x134E,
147 Self::HarvestFee(_) => 0x2143,
148 Self::LockHashCompleted(_) => 0x2248,
149 Self::LockHashExpired(_) => 0x2348,
150 Self::LockSecretCompleted(_) => 0x2252,
151 Self::LockSecretExpired(_) => 0x2352,
152 Self::LockHashCreated(_) => 0x3148,
153 Self::LockSecretCreated(_) => 0x3152,
154 Self::MosaicExpired(_) => 0x414D,
155 Self::NamespaceExpired(_) => 0x414E,
156 Self::NamespaceDeleted(_) => 0x424E,
157 Self::Inflation(_) => 0x5143,
158 }
159 }
160
161 fn encode(&self, out: &mut Vec<u8>) {
162 match self {
163 Self::MosaicRentalFee(transfer) | Self::NamespaceRentalFee(transfer) => {
164 transfer.mosaic.encode(out);
165 out.extend_from_slice(&transfer.sender_address.0);
166 out.extend_from_slice(&transfer.recipient_address.0);
167 }
168 Self::HarvestFee(change)
169 | Self::LockHashCompleted(change)
170 | Self::LockHashExpired(change)
171 | Self::LockSecretCompleted(change)
172 | Self::LockSecretExpired(change)
173 | Self::LockHashCreated(change)
174 | Self::LockSecretCreated(change) => {
175 change.mosaic.encode(out);
176 out.extend_from_slice(&change.target_address.0);
177 }
178 Self::MosaicExpired(id) => out.extend_from_slice(&id.0.to_le_bytes()),
179 Self::NamespaceExpired(id) | Self::NamespaceDeleted(id) => {
180 out.extend_from_slice(&id.0.to_le_bytes())
181 }
182 Self::Inflation(mosaic) => mosaic.encode(out),
183 }
184 }
185
186 fn decode(receipt_type: u16, reader: &mut Reader) -> Result<Self, StatementDecodeError> {
187 let transfer = |reader: &mut Reader| -> Result<_, StatementDecodeError> {
188 Ok(BalanceTransfer {
189 mosaic: Mosaic::read(reader)?,
190 sender_address: Address(reader.array()?),
191 recipient_address: Address(reader.array()?),
192 })
193 };
194 let change = |reader: &mut Reader| -> Result<_, StatementDecodeError> {
195 Ok(BalanceChange {
196 mosaic: Mosaic::read(reader)?,
197 target_address: Address(reader.array()?),
198 })
199 };
200 Ok(match receipt_type {
201 0x124D => Self::MosaicRentalFee(transfer(reader)?),
202 0x134E => Self::NamespaceRentalFee(transfer(reader)?),
203 0x2143 => Self::HarvestFee(change(reader)?),
204 0x2248 => Self::LockHashCompleted(change(reader)?),
205 0x2348 => Self::LockHashExpired(change(reader)?),
206 0x2252 => Self::LockSecretCompleted(change(reader)?),
207 0x2352 => Self::LockSecretExpired(change(reader)?),
208 0x3148 => Self::LockHashCreated(change(reader)?),
209 0x3152 => Self::LockSecretCreated(change(reader)?),
210 0x414D => Self::MosaicExpired(MosaicId(reader.u64()?)),
211 0x414E => Self::NamespaceExpired(NamespaceId(reader.u64()?)),
212 0x424E => Self::NamespaceDeleted(NamespaceId(reader.u64()?)),
213 0x5143 => Self::Inflation(Mosaic::read(reader)?),
214 other => return Err(StatementDecodeError::UnknownReceiptType(other)),
215 })
216 }
217}
218
219impl Receipt {
220 pub fn to_bytes(&self) -> Vec<u8> {
221 let mut body = Vec::new();
222 self.body.encode(&mut body);
223 let mut bytes = Vec::with_capacity(RECEIPT_HEADER_SIZE + body.len());
224 bytes.extend_from_slice(&((RECEIPT_HEADER_SIZE + body.len()) as u32).to_le_bytes());
225 bytes.extend_from_slice(&self.version.to_le_bytes());
226 bytes.extend_from_slice(&self.body.receipt_type().to_le_bytes());
227 bytes.extend_from_slice(&body);
228 bytes
229 }
230
231 pub fn from_bytes(bytes: &[u8]) -> Result<Self, StatementDecodeError> {
233 let mut reader = Reader(bytes);
234 let receipt = Self::read(&mut reader)?;
235 reader.finish()?;
236 Ok(receipt)
237 }
238
239 fn read(reader: &mut Reader) -> Result<Self, StatementDecodeError> {
240 let size = reader.u32()? as usize;
241 let rest = size
242 .checked_sub(4)
243 .ok_or(StatementDecodeError::InvalidReceiptSize(size))?;
244 let mut body = Reader(reader.take(rest)?);
245 let version = body.u16()?;
246 let receipt_type = body.u16()?;
247 let receipt = Self {
248 version,
249 body: ReceiptBody::decode(receipt_type, &mut body).map_err(|error| match error {
250 StatementDecodeError::TooShort => StatementDecodeError::InvalidReceiptSize(size),
251 error => error,
252 })?,
253 };
254 if !body.0.is_empty() {
255 return Err(StatementDecodeError::InvalidReceiptSize(size));
256 }
257 Ok(receipt)
258 }
259}
260
261#[derive(Clone, PartialEq, Eq, Debug)]
263pub struct TransactionStatement {
264 pub source: ReceiptSource,
265 pub receipts: Vec<Receipt>,
267}
268
269impl TransactionStatement {
270 pub fn hash(&self) -> Hash256 {
273 let mut hasher = Sha3_256::new();
274 hasher.update(STATEMENT_VERSION.to_le_bytes());
275 hasher.update(TRANSACTION_GROUP.to_le_bytes());
276 let mut source = Vec::with_capacity(ReceiptSource::SIZE);
277 self.source.encode(&mut source);
278 hasher.update(source);
279 for receipt in &self.receipts {
280 hasher.update(&receipt.to_bytes()[4..]);
281 }
282 Hash256(hasher.finalize().into())
283 }
284
285 pub fn to_bytes(&self) -> Vec<u8> {
286 let mut bytes = Vec::new();
287 self.encode(&mut bytes);
288 bytes
289 }
290
291 pub fn from_bytes(bytes: &[u8]) -> Result<Self, StatementDecodeError> {
292 let mut reader = Reader(bytes);
293 let statement = Self::read(&mut reader)?;
294 reader.finish()?;
295 Ok(statement)
296 }
297
298 fn encode(&self, out: &mut Vec<u8>) {
299 self.source.encode(out);
300 out.extend_from_slice(&(self.receipts.len() as u32).to_le_bytes());
301 for receipt in &self.receipts {
302 out.extend_from_slice(&receipt.to_bytes());
303 }
304 }
305
306 fn read(reader: &mut Reader) -> Result<Self, StatementDecodeError> {
307 let source = ReceiptSource::read(reader)?;
308 let count = reader.u32()?;
309 let receipts = (0..count)
310 .map(|_| Receipt::read(reader))
311 .collect::<Result<_, _>>()?;
312 Ok(Self { source, receipts })
313 }
314}
315
316pub trait Resolved: Copy + private::Sealed {
318 type Unresolved: Copy + Eq + fmt::Debug;
320 const RECEIPT_TYPE: u16;
322}
323
324impl Resolved for Address {
325 type Unresolved = UnresolvedAddress;
326 const RECEIPT_TYPE: u16 = 0xF143;
327}
328
329impl Resolved for MosaicId {
330 type Unresolved = UnresolvedMosaicId;
331 const RECEIPT_TYPE: u16 = 0xF243;
332}
333
334mod private {
335 use super::*;
336
337 pub trait Sealed: Sized {
339 fn encode_resolved(&self, out: &mut Vec<u8>);
340 fn read_resolved(reader: &mut Reader) -> Result<Self, StatementDecodeError>;
341 fn encode_unresolved(unresolved: &<Self as Resolved>::Unresolved, out: &mut Vec<u8>)
342 where
343 Self: Resolved;
344 fn read_unresolved(
345 reader: &mut Reader,
346 ) -> Result<<Self as Resolved>::Unresolved, StatementDecodeError>
347 where
348 Self: Resolved;
349 }
350
351 impl Sealed for Address {
352 fn encode_resolved(&self, out: &mut Vec<u8>) {
353 out.extend_from_slice(&self.0);
354 }
355
356 fn read_resolved(reader: &mut Reader) -> Result<Self, StatementDecodeError> {
357 Ok(Self(reader.array()?))
358 }
359
360 fn encode_unresolved(unresolved: &UnresolvedAddress, out: &mut Vec<u8>) {
361 out.extend_from_slice(&unresolved.0);
362 }
363
364 fn read_unresolved(reader: &mut Reader) -> Result<UnresolvedAddress, StatementDecodeError> {
365 Ok(UnresolvedAddress(reader.array()?))
366 }
367 }
368
369 impl Sealed for MosaicId {
370 fn encode_resolved(&self, out: &mut Vec<u8>) {
371 out.extend_from_slice(&self.0.to_le_bytes());
372 }
373
374 fn read_resolved(reader: &mut Reader) -> Result<Self, StatementDecodeError> {
375 Ok(Self(reader.u64()?))
376 }
377
378 fn encode_unresolved(unresolved: &UnresolvedMosaicId, out: &mut Vec<u8>) {
379 out.extend_from_slice(&unresolved.0.to_le_bytes());
380 }
381
382 fn read_unresolved(
383 reader: &mut Reader,
384 ) -> Result<UnresolvedMosaicId, StatementDecodeError> {
385 Ok(UnresolvedMosaicId(reader.u64()?))
386 }
387 }
388}
389
390#[derive(Clone, Copy, PartialEq, Eq, Debug)]
392pub struct ResolutionEntry<R> {
393 pub source: ReceiptSource,
394 pub resolved: R,
395}
396
397#[derive(Clone, PartialEq, Eq, Debug)]
399pub struct ResolutionStatement<R: Resolved> {
400 pub unresolved: R::Unresolved,
401 pub entries: Vec<ResolutionEntry<R>>,
403}
404
405pub type AddressResolutionStatement = ResolutionStatement<Address>;
407pub type MosaicResolutionStatement = ResolutionStatement<MosaicId>;
409
410impl<R: Resolved> ResolutionStatement<R> {
411 pub fn hash(&self) -> Hash256 {
414 let mut data = Vec::new();
415 data.extend_from_slice(&STATEMENT_VERSION.to_le_bytes());
416 data.extend_from_slice(&R::RECEIPT_TYPE.to_le_bytes());
417 self.encode_entries(&mut data);
418 Hash256(Sha3_256::digest(&data).into())
419 }
420
421 pub fn to_bytes(&self) -> Vec<u8> {
422 let mut bytes = Vec::new();
423 self.encode(&mut bytes);
424 bytes
425 }
426
427 pub fn from_bytes(bytes: &[u8]) -> Result<Self, StatementDecodeError> {
428 let mut reader = Reader(bytes);
429 let statement = Self::read(&mut reader)?;
430 reader.finish()?;
431 Ok(statement)
432 }
433
434 fn encode_entries(&self, out: &mut Vec<u8>) {
436 R::encode_unresolved(&self.unresolved, out);
437 for entry in &self.entries {
438 entry.source.encode(out);
439 entry.resolved.encode_resolved(out);
440 }
441 }
442
443 fn encode(&self, out: &mut Vec<u8>) {
444 R::encode_unresolved(&self.unresolved, out);
445 out.extend_from_slice(&(self.entries.len() as u32).to_le_bytes());
446 for entry in &self.entries {
447 entry.source.encode(out);
448 entry.resolved.encode_resolved(out);
449 }
450 }
451
452 fn read(reader: &mut Reader) -> Result<Self, StatementDecodeError> {
453 let unresolved = R::read_unresolved(reader)?;
454 let count = reader.u32()?;
455 let entries = (0..count)
456 .map(|_| {
457 Ok(ResolutionEntry {
458 source: ReceiptSource::read(reader)?,
459 resolved: R::read_resolved(reader)?,
460 })
461 })
462 .collect::<Result<_, _>>()?;
463 Ok(Self {
464 unresolved,
465 entries,
466 })
467 }
468}
469
470#[derive(Clone, PartialEq, Eq, Debug, Default)]
472pub struct BlockStatement {
473 pub transaction_statements: Vec<TransactionStatement>,
475 pub address_resolution_statements: Vec<AddressResolutionStatement>,
477 pub mosaic_resolution_statements: Vec<MosaicResolutionStatement>,
479}
480
481impl BlockStatement {
482 pub fn merkle_hash(&self) -> Hash256 {
486 let leaves: Vec<_> = self
487 .transaction_statements
488 .iter()
489 .map(TransactionStatement::hash)
490 .chain(
491 self.address_resolution_statements
492 .iter()
493 .map(ResolutionStatement::hash),
494 )
495 .chain(
496 self.mosaic_resolution_statements
497 .iter()
498 .map(ResolutionStatement::hash),
499 )
500 .collect();
501 merkle::root(&leaves)
502 }
503
504 pub fn to_bytes(&self) -> Vec<u8> {
505 let mut bytes = Vec::new();
506 bytes.extend_from_slice(&(self.transaction_statements.len() as u32).to_le_bytes());
507 for statement in &self.transaction_statements {
508 statement.encode(&mut bytes);
509 }
510 bytes.extend_from_slice(&(self.address_resolution_statements.len() as u32).to_le_bytes());
511 for statement in &self.address_resolution_statements {
512 statement.encode(&mut bytes);
513 }
514 bytes.extend_from_slice(&(self.mosaic_resolution_statements.len() as u32).to_le_bytes());
515 for statement in &self.mosaic_resolution_statements {
516 statement.encode(&mut bytes);
517 }
518 bytes
519 }
520
521 pub fn from_bytes(bytes: &[u8]) -> Result<Self, StatementDecodeError> {
523 let mut reader = Reader(bytes);
524 let transaction_statements = read_all(&mut reader, TransactionStatement::read)?;
525 let address_resolution_statements = read_all(&mut reader, ResolutionStatement::read)?;
526 let mosaic_resolution_statements = read_all(&mut reader, ResolutionStatement::read)?;
527 reader.finish()?;
528 Ok(Self {
529 transaction_statements,
530 address_resolution_statements,
531 mosaic_resolution_statements,
532 })
533 }
534}
535
536fn read_all<T>(
537 reader: &mut Reader,
538 read: impl Fn(&mut Reader) -> Result<T, StatementDecodeError>,
539) -> Result<Vec<T>, StatementDecodeError> {
540 let count = reader.u32()?;
541 (0..count).map(|_| read(reader)).collect()
542}
543
544mod reader {
545 use super::StatementDecodeError;
546
547 pub struct Reader<'a>(pub &'a [u8]);
549
550 impl<'a> Reader<'a> {
551 pub fn take(&mut self, size: usize) -> Result<&'a [u8], StatementDecodeError> {
552 if self.0.len() < size {
553 return Err(StatementDecodeError::TooShort);
554 }
555 let (head, rest) = self.0.split_at(size);
556 self.0 = rest;
557 Ok(head)
558 }
559
560 pub fn array<const N: usize>(&mut self) -> Result<[u8; N], StatementDecodeError> {
561 Ok(self.take(N)?.try_into().expect("N bytes"))
562 }
563
564 pub fn u16(&mut self) -> Result<u16, StatementDecodeError> {
565 self.array().map(u16::from_le_bytes)
566 }
567
568 pub fn u32(&mut self) -> Result<u32, StatementDecodeError> {
569 self.array().map(u32::from_le_bytes)
570 }
571
572 pub fn u64(&mut self) -> Result<u64, StatementDecodeError> {
573 self.array().map(u64::from_le_bytes)
574 }
575
576 pub fn finish(self) -> Result<(), StatementDecodeError> {
577 if self.0.is_empty() {
578 Ok(())
579 } else {
580 Err(StatementDecodeError::TrailingBytes(self.0.len()))
581 }
582 }
583 }
584}
585
586#[derive(Debug, Clone, PartialEq, Eq)]
587pub enum StatementDecodeError {
588 TooShort,
590 TrailingBytes(usize),
592 InvalidReceiptSize(usize),
594 UnknownReceiptType(u16),
596}
597
598impl fmt::Display for StatementDecodeError {
599 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
600 match self {
601 Self::TooShort => f.write_str("ステートメントが途中で切れています"),
602 Self::TrailingBytes(count) => {
603 write!(f, "ステートメントの後ろに {count} バイト余っています")
604 }
605 Self::InvalidReceiptSize(size) => {
606 write!(
607 f,
608 "レシートのサイズ {size} が、種類から決まる大きさと合いません"
609 )
610 }
611 Self::UnknownReceiptType(receipt_type) => {
612 write!(f, "種類 0x{receipt_type:04X} のレシートは知りません")
613 }
614 }
615 }
616}
617
618impl core::error::Error for StatementDecodeError {}
619
620#[cfg(test)]
621mod tests {
622 use super::*;
623
624 fn mosaic() -> Mosaic {
625 Mosaic {
626 mosaic_id: MosaicId(0x6BED_913F_A202_23F8),
627 amount: 1_000_000,
628 }
629 }
630
631 fn harvest_fee() -> Receipt {
632 Receipt {
633 version: 1,
634 body: ReceiptBody::HarvestFee(BalanceChange {
635 mosaic: mosaic(),
636 target_address: Address([0x68; 24]),
637 }),
638 }
639 }
640
641 fn inflation() -> Receipt {
642 Receipt {
643 version: 1,
644 body: ReceiptBody::Inflation(mosaic()),
645 }
646 }
647
648 fn source(primary_id: u32, secondary_id: u32) -> ReceiptSource {
649 ReceiptSource {
650 primary_id,
651 secondary_id,
652 }
653 }
654
655 fn sha3(parts: &[&[u8]]) -> Hash256 {
656 let mut hasher = Sha3_256::new();
657 for part in parts {
658 hasher.update(part);
659 }
660 Hash256(hasher.finalize().into())
661 }
662
663 #[test]
664 fn writes_the_receipt_header() {
665 let bytes = harvest_fee().to_bytes();
666 assert_eq!(bytes.len(), 8 + 16 + 24);
667 assert_eq!(bytes[..8], [48, 0, 0, 0, 1, 0, 0x43, 0x21]);
668 assert_eq!(Receipt::from_bytes(&bytes), Ok(harvest_fee()));
669 }
670
671 #[test]
672 fn refuses_receipts_whose_size_does_not_fit_the_type() {
673 let mut bytes = inflation().to_bytes();
674 bytes[6..8].copy_from_slice(&0x2143_u16.to_le_bytes());
676 assert_eq!(
677 Receipt::from_bytes(&bytes),
678 Err(StatementDecodeError::InvalidReceiptSize(24))
679 );
680 let mut bytes = harvest_fee().to_bytes();
681 bytes[6..8].copy_from_slice(&0x5143_u16.to_le_bytes());
682 assert_eq!(
683 Receipt::from_bytes(&bytes),
684 Err(StatementDecodeError::InvalidReceiptSize(48))
685 );
686 bytes[6..8].copy_from_slice(&0xE143_u16.to_le_bytes());
687 assert_eq!(
688 Receipt::from_bytes(&bytes),
689 Err(StatementDecodeError::UnknownReceiptType(0xE143))
690 );
691 assert_eq!(
692 Receipt::from_bytes(&[3, 0, 0, 0]),
693 Err(StatementDecodeError::InvalidReceiptSize(3))
694 );
695 assert_eq!(
696 Receipt::from_bytes(&inflation().to_bytes()[..20]),
697 Err(StatementDecodeError::TooShort)
698 );
699 }
700
701 #[test]
702 fn hashes_a_transaction_statement_with_a_group_header() {
703 let statement = TransactionStatement {
704 source: source(0, 0),
705 receipts: vec![harvest_fee(), inflation()],
706 };
707 let expected = sha3(&[
709 &[1, 0, 0x43, 0xE1],
710 &[0; 8],
711 &harvest_fee().to_bytes()[4..],
712 &inflation().to_bytes()[4..],
713 ]);
714 assert_eq!(statement.hash(), expected);
715 assert_eq!(
716 TransactionStatement::from_bytes(&statement.to_bytes()),
717 Ok(statement)
718 );
719 }
720
721 #[test]
722 fn hashes_resolution_statements_with_their_own_type() {
723 let address = AddressResolutionStatement {
724 unresolved: UnresolvedAddress([0x69; 24]),
725 entries: vec![ResolutionEntry {
726 source: source(1, 2),
727 resolved: Address([0x68; 24]),
728 }],
729 };
730 let expected = sha3(&[
731 &[1, 0, 0x43, 0xF1],
732 &[0x69; 24],
733 &[1, 0, 0, 0, 2, 0, 0, 0],
734 &[0x68; 24],
735 ]);
736 assert_eq!(address.hash(), expected);
737
738 let mosaic = MosaicResolutionStatement {
739 unresolved: UnresolvedMosaicId(0xE74B_99BA_41F4_AFEE),
740 entries: vec![ResolutionEntry {
741 source: source(1, 0),
742 resolved: MosaicId(0x6BED_913F_A202_23F8),
743 }],
744 };
745 let expected = sha3(&[
746 &[1, 0, 0x43, 0xF2],
747 &0xE74B_99BA_41F4_AFEE_u64.to_le_bytes(),
748 &[1, 0, 0, 0, 0, 0, 0, 0],
749 &0x6BED_913F_A202_23F8_u64.to_le_bytes(),
750 ]);
751 assert_eq!(mosaic.hash(), expected);
752 }
753
754 #[test]
755 fn merkle_hash_puts_transactions_then_addresses_then_mosaics() {
756 let transaction = TransactionStatement {
757 source: source(0, 0),
758 receipts: vec![harvest_fee()],
759 };
760 let address = AddressResolutionStatement {
761 unresolved: UnresolvedAddress([0x69; 24]),
762 entries: Vec::new(),
763 };
764 let mosaic = MosaicResolutionStatement {
765 unresolved: UnresolvedMosaicId(0xE74B_99BA_41F4_AFEE),
766 entries: Vec::new(),
767 };
768 let statement = BlockStatement {
769 transaction_statements: vec![transaction.clone()],
770 address_resolution_statements: vec![address.clone()],
771 mosaic_resolution_statements: vec![mosaic.clone()],
772 };
773 assert_eq!(
774 statement.merkle_hash(),
775 merkle::root(&[transaction.hash(), address.hash(), mosaic.hash()])
776 );
777 assert_eq!(
778 BlockStatement::from_bytes(&statement.to_bytes()),
779 Ok(statement)
780 );
781 assert_eq!(BlockStatement::default().merkle_hash(), Hash256([0; 32]));
783 assert_eq!(BlockStatement::default().to_bytes(), [0; 12]);
784 }
785
786 #[test]
787 fn refuses_trailing_bytes() {
788 let mut bytes = BlockStatement::default().to_bytes();
789 bytes.push(0);
790 assert_eq!(
791 BlockStatement::from_bytes(&bytes),
792 Err(StatementDecodeError::TrailingBytes(1))
793 );
794 }
795}