Skip to main content

heika_transaction/
restriction.rs

1//! 制限。catbuffer の `restriction_account/` と `restriction_mosaic/`。
2
3use alloc::vec::Vec;
4
5use heika_core::address::Address;
6use heika_core::hash::Hash256;
7use sha3::{Digest, Sha3_256};
8
9use crate::bounded::BoundedVec;
10use crate::mosaic::MosaicId;
11use crate::transfer::{UnresolvedAddress, UnresolvedMosaicId};
12use crate::{DecodeError, Reader};
13
14/// アカウントの制限の種類と向き。catbuffer の `AccountRestrictionFlags`。
15#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
16pub struct AccountRestrictionFlags(u16);
17
18impl AccountRestrictionFlags {
19    /// アドレスで制限する
20    pub const ADDRESS: Self = Self(0x0001);
21    /// モザイクで制限する
22    pub const MOSAIC_ID: Self = Self(0x0002);
23    /// トランザクションの種類で制限する
24    pub const TRANSACTION_TYPE: Self = Self(0x0004);
25    /// 送る側を制限する。なければ受け取る側
26    pub const OUTGOING: Self = Self(0x4000);
27    /// 並べたものを拒む。なければ並べたものだけを許す
28    pub const BLOCK: Self = Self(0x8000);
29    const ALL: u16 = 0xC007;
30
31    /// 定義されていないビットが立っていれば `None`。
32    /// どの組み合わせを受け付けるかは catapult の `AccountRestrictionFlagsValidator` が決めるので、ここでは確かめない。
33    pub fn from_bits(bits: u16) -> Option<Self> {
34        (bits & !Self::ALL == 0).then_some(Self(bits))
35    }
36
37    pub fn bits(self) -> u16 {
38        self.0
39    }
40
41    pub fn contains(self, other: Self) -> bool {
42        self.0 & other.0 == other.0
43    }
44}
45
46impl core::ops::BitOr for AccountRestrictionFlags {
47    type Output = Self;
48
49    fn bitor(self, other: Self) -> Self {
50        Self(self.0 | other.0)
51    }
52}
53
54/// アカウントの制限に並べられる値。アドレス、モザイクの ID、トランザクションの種類。
55pub(crate) trait AccountRestrictionValue: Copy {
56    const SIZE: usize;
57    fn encode(&self, out: &mut Vec<u8>);
58    fn read(reader: &mut Reader) -> Self;
59}
60
61impl AccountRestrictionValue for UnresolvedAddress {
62    const SIZE: usize = 24;
63
64    fn encode(&self, out: &mut Vec<u8>) {
65        out.extend_from_slice(&self.0);
66    }
67
68    fn read(reader: &mut Reader) -> Self {
69        Self(reader.array())
70    }
71}
72
73impl AccountRestrictionValue for UnresolvedMosaicId {
74    const SIZE: usize = 8;
75
76    fn encode(&self, out: &mut Vec<u8>) {
77        out.extend_from_slice(&self.0.to_le_bytes());
78    }
79
80    fn read(reader: &mut Reader) -> Self {
81        Self(reader.u64())
82    }
83}
84
85/// トランザクションの種類。catbuffer の `TransactionType`。
86#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
87pub struct TransactionType(pub u16);
88
89impl AccountRestrictionValue for TransactionType {
90    const SIZE: usize = 2;
91
92    fn encode(&self, out: &mut Vec<u8>) {
93        out.extend_from_slice(&self.0.to_le_bytes());
94    }
95
96    fn read(reader: &mut Reader) -> Self {
97        Self(reader.u16())
98    }
99}
100
101/// アカウントの制限を足す、または外す。並べる値の型だけが違う3種類に共通。
102#[derive(Clone, PartialEq, Eq, Debug)]
103pub struct AccountRestriction<T> {
104    pub restriction_flags: AccountRestrictionFlags,
105    pub restriction_additions: BoundedVec<T, { u8::MAX as usize }>,
106    pub restriction_deletions: BoundedVec<T, { u8::MAX as usize }>,
107}
108
109impl<T: Copy> AccountRestriction<T> {
110    /// 値の並びより前の部分。フラグ、足す数と外す数、予約。
111    const FIXED_SIZE: usize = 2 + 1 + 1 + 4;
112
113    pub(crate) fn encode(&self, out: &mut Vec<u8>)
114    where
115        T: AccountRestrictionValue,
116    {
117        out.extend_from_slice(&self.restriction_flags.0.to_le_bytes());
118        out.push(self.restriction_additions.len() as u8);
119        out.push(self.restriction_deletions.len() as u8);
120        out.extend_from_slice(&[0; 4]);
121        for value in self
122            .restriction_additions
123            .iter()
124            .chain(&*self.restriction_deletions)
125        {
126            value.encode(out);
127        }
128    }
129
130    pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError>
131    where
132        T: AccountRestrictionValue,
133    {
134        let mut reader = Reader::at_least(bytes, Self::FIXED_SIZE)?;
135        let flags = reader.u16();
136        let restriction_flags =
137            AccountRestrictionFlags::from_bits(flags).ok_or(DecodeError::InvalidValue {
138                field: "アカウントの制限のフラグ",
139                value: flags.into(),
140            })?;
141        let additions_count = reader.u8() as usize;
142        let deletions_count = reader.u8() as usize;
143        if reader.u32() != 0 {
144            return Err(DecodeError::NonZeroReserved);
145        }
146        reader.expect_remaining((additions_count + deletions_count) * T::SIZE)?;
147        let mut read = |count| {
148            (0..count)
149                .map(|_| T::read(&mut reader))
150                .collect::<Vec<_>>()
151                .try_into()
152                .expect("u8 count")
153        };
154        let restriction_additions = read(additions_count);
155        let restriction_deletions = read(deletions_count);
156        Ok(Self {
157            restriction_flags,
158            restriction_additions,
159            restriction_deletions,
160        })
161    }
162}
163
164/// モザイクの制限で、アドレスの値と比べ方。
165#[derive(Clone, Copy, PartialEq, Eq, Debug)]
166pub enum MosaicRestrictionType {
167    /// 制限しない。制限を外すときに使う
168    None,
169    Eq,
170    Ne,
171    Lt,
172    Le,
173    Gt,
174    Ge,
175}
176
177impl MosaicRestrictionType {
178    fn to_byte(self) -> u8 {
179        match self {
180            Self::None => 0,
181            Self::Eq => 1,
182            Self::Ne => 2,
183            Self::Lt => 3,
184            Self::Le => 4,
185            Self::Gt => 5,
186            Self::Ge => 6,
187        }
188    }
189
190    fn from_byte(byte: u8) -> Result<Self, DecodeError> {
191        Ok(match byte {
192            0 => Self::None,
193            1 => Self::Eq,
194            2 => Self::Ne,
195            3 => Self::Lt,
196            4 => Self::Le,
197            5 => Self::Gt,
198            6 => Self::Ge,
199            _ => {
200                return Err(DecodeError::InvalidValue {
201                    field: "モザイクの制限の比べ方",
202                    value: byte.into(),
203                });
204            }
205        })
206    }
207}
208
209/// モザイクの制限で、アドレスごとの値を決める。
210#[derive(Clone, Copy, PartialEq, Eq, Debug)]
211pub struct MosaicAddressRestriction {
212    pub mosaic_id: UnresolvedMosaicId,
213    pub restriction_key: u64,
214    pub previous_restriction_value: u64,
215    pub new_restriction_value: u64,
216    pub target_address: UnresolvedAddress,
217}
218
219impl MosaicAddressRestriction {
220    const SIZE: usize = 8 + 8 + 8 + 8 + 24;
221
222    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
223        out.extend_from_slice(&self.mosaic_id.0.to_le_bytes());
224        out.extend_from_slice(&self.restriction_key.to_le_bytes());
225        out.extend_from_slice(&self.previous_restriction_value.to_le_bytes());
226        out.extend_from_slice(&self.new_restriction_value.to_le_bytes());
227        out.extend_from_slice(&self.target_address.0);
228    }
229
230    pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
231        let mut reader = Reader::exact(bytes, Self::SIZE)?;
232        Ok(Self {
233            mosaic_id: UnresolvedMosaicId(reader.u64()),
234            restriction_key: reader.u64(),
235            previous_restriction_value: reader.u64(),
236            new_restriction_value: reader.u64(),
237            target_address: UnresolvedAddress(reader.array()),
238        })
239    }
240}
241
242/// モザイクの制限で、モザイク全体の条件を決める。
243#[derive(Clone, Copy, PartialEq, Eq, Debug)]
244pub struct MosaicGlobalRestriction {
245    pub mosaic_id: UnresolvedMosaicId,
246    /// 条件を借りてくるモザイク。0なら `mosaic_id` 自身
247    pub reference_mosaic_id: UnresolvedMosaicId,
248    pub restriction_key: u64,
249    pub previous_restriction_value: u64,
250    pub new_restriction_value: u64,
251    pub previous_restriction_type: MosaicRestrictionType,
252    pub new_restriction_type: MosaicRestrictionType,
253}
254
255impl MosaicGlobalRestriction {
256    const SIZE: usize = 8 + 8 + 8 + 8 + 8 + 1 + 1;
257
258    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
259        out.extend_from_slice(&self.mosaic_id.0.to_le_bytes());
260        out.extend_from_slice(&self.reference_mosaic_id.0.to_le_bytes());
261        out.extend_from_slice(&self.restriction_key.to_le_bytes());
262        out.extend_from_slice(&self.previous_restriction_value.to_le_bytes());
263        out.extend_from_slice(&self.new_restriction_value.to_le_bytes());
264        out.push(self.previous_restriction_type.to_byte());
265        out.push(self.new_restriction_type.to_byte());
266    }
267
268    pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
269        let mut reader = Reader::exact(bytes, Self::SIZE)?;
270        Ok(Self {
271            mosaic_id: UnresolvedMosaicId(reader.u64()),
272            reference_mosaic_id: UnresolvedMosaicId(reader.u64()),
273            restriction_key: reader.u64(),
274            previous_restriction_value: reader.u64(),
275            new_restriction_value: reader.u64(),
276            previous_restriction_type: MosaicRestrictionType::from_byte(reader.u8())?,
277            new_restriction_type: MosaicRestrictionType::from_byte(reader.u8())?,
278        })
279    }
280}
281
282/// 文字列からモザイクの制限のキーを作る。公式の SDK の `mosaic_restriction_generate_key` と同じく、
283/// SHA3-256 の先頭8バイトをリトルエンディアンで読む。メタデータのキーと違い、最上位ビットは立てない。
284pub fn mosaic_restriction_key(text: &str) -> u64 {
285    let hash = Sha3_256::digest(text.as_bytes());
286    u64::from_le_bytes(hash[..8].try_into().expect("8 of 32 bytes"))
287}
288
289/// チェーンに記録されたモザイクの制限の1件を指すハッシュ。catapult の `CreateMosaicRestrictionEntryKey` で、
290/// モザイクの ID とアドレスを続けた SHA3-256。モザイク全体の制限なら、アドレスを24バイトの0にする。
291/// ID とアドレスは、ネームスペースを解決したあとのもの。
292pub fn mosaic_restriction_entry_key(mosaic_id: MosaicId, address: Option<&Address>) -> Hash256 {
293    let address = address.map_or([0; 24], |address| address.0);
294    Hash256(
295        Sha3_256::new()
296            .chain_update(mosaic_id.0.to_le_bytes())
297            .chain_update(address)
298            .finalize()
299            .into(),
300    )
301}
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use crate::Body;
306    use crate::testing::{decode, round_trip};
307
308    fn restriction<T>(flags: AccountRestrictionFlags, additions: Vec<T>) -> AccountRestriction<T> {
309        AccountRestriction {
310            restriction_flags: flags,
311            restriction_additions: additions.try_into().unwrap(),
312            restriction_deletions: Vec::new().try_into().unwrap(),
313        }
314    }
315
316    #[test]
317    fn makes_restriction_keys_without_setting_the_high_bit() {
318        // FIPS 202 の SHA3-256 の例。空の文字列のハッシュは A7FFC6F8BF1ED766 で始まる
319        assert_eq!(mosaic_restriction_key(""), 0x66D7_1EBF_F8C6_FFA7);
320        // "abc" のハッシュは 3A985DA74FE225B2 で始まる
321        assert_eq!(mosaic_restriction_key("abc"), 0xB225_E24F_A75D_983A);
322    }
323
324    #[test]
325    fn hashes_the_mosaic_id_and_the_address() {
326        let mut data = 0x0102_u64.to_le_bytes().to_vec();
327        data.extend_from_slice(&[0x98; 24]);
328        assert_eq!(
329            mosaic_restriction_entry_key(MosaicId(0x0102), Some(&Address([0x98; 24]))),
330            Hash256(Sha3_256::digest(&data).into())
331        );
332        // モザイク全体の制限は、アドレスが0の制限と同じキーになる
333        assert_eq!(
334            mosaic_restriction_entry_key(MosaicId(0x0102), None),
335            mosaic_restriction_entry_key(MosaicId(0x0102), Some(&Address([0; 24])))
336        );
337    }
338
339    #[test]
340    fn writes_each_kind_of_value() {
341        let address = round_trip(Body::AccountAddressRestriction(restriction(
342            AccountRestrictionFlags::ADDRESS | AccountRestrictionFlags::BLOCK,
343            vec![UnresolvedAddress([0x98; 24])],
344        )));
345        assert_eq!(address[..8], [0x01, 0x80, 1, 0, 0, 0, 0, 0]);
346        assert_eq!(address[8..], [0x98; 24]);
347
348        let mosaic = round_trip(Body::AccountMosaicRestriction(restriction(
349            AccountRestrictionFlags::MOSAIC_ID,
350            vec![UnresolvedMosaicId(7)],
351        )));
352        assert_eq!(mosaic[8..], 7_u64.to_le_bytes());
353
354        let operation = round_trip(Body::AccountOperationRestriction(restriction(
355            AccountRestrictionFlags::TRANSACTION_TYPE | AccountRestrictionFlags::OUTGOING,
356            vec![TransactionType(0x4154), TransactionType(0x4252)],
357        )));
358        assert_eq!(operation[..2], [0x04, 0x40]);
359        assert_eq!(operation[8..], [0x54, 0x41, 0x52, 0x42]);
360    }
361
362    #[test]
363    fn rejects_undefined_flags_and_reserved_bytes() {
364        let body = round_trip(Body::AccountAddressRestriction(restriction(
365            AccountRestrictionFlags::ADDRESS,
366            vec![],
367        )));
368        // Sentinel(0x0008)は catapult の中だけで使い、トランザクションには書けない
369        let mut flags = body.clone();
370        flags[0] = 0x09;
371        assert_eq!(
372            decode(0x4150, &flags),
373            Err(DecodeError::InvalidValue {
374                field: "アカウントの制限のフラグ",
375                value: 0x09
376            })
377        );
378        let mut reserved = body;
379        reserved[7] = 1;
380        assert_eq!(decode(0x4150, &reserved), Err(DecodeError::NonZeroReserved));
381    }
382
383    #[test]
384    fn rejects_an_undefined_mosaic_restriction_type() {
385        let restriction = MosaicGlobalRestriction {
386            mosaic_id: UnresolvedMosaicId(1),
387            reference_mosaic_id: UnresolvedMosaicId(0),
388            restriction_key: 2,
389            previous_restriction_value: 3,
390            new_restriction_value: 4,
391            previous_restriction_type: MosaicRestrictionType::None,
392            new_restriction_type: MosaicRestrictionType::Ge,
393        };
394        let mut body = round_trip(Body::MosaicGlobalRestriction(restriction));
395        assert_eq!(body[40..], [0, 6]);
396        body[41] = 7;
397        assert_eq!(
398            decode(0x4151, &body),
399            Err(DecodeError::InvalidValue {
400                field: "モザイクの制限の比べ方",
401                value: 7
402            })
403        );
404
405        let address = round_trip(Body::MosaicAddressRestriction(MosaicAddressRestriction {
406            mosaic_id: UnresolvedMosaicId(1),
407            restriction_key: 2,
408            previous_restriction_value: 3,
409            new_restriction_value: 4,
410            target_address: UnresolvedAddress([0x98; 24]),
411        }));
412        assert_eq!(address[32..], [0x98; 24]);
413    }
414}