Skip to main content

heika_transaction/
lock.rs

1//! ロック。catbuffer の `lock_hash/` と `lock_secret/`。
2
3use alloc::vec::Vec;
4
5use heika_core::address::Address;
6use heika_core::hash::Hash256;
7use ripemd::Ripemd160;
8use sha2::Sha256;
9use sha3::{Digest, Sha3_256};
10
11use crate::bounded::BoundedVec;
12use crate::mosaic::UnresolvedMosaic;
13use crate::transfer::UnresolvedAddress;
14use crate::{DecodeError, Reader};
15
16/// アグリゲートボンデッドを送る前に、手数料の担保としてモザイクを預ける。
17#[derive(Clone, Copy, PartialEq, Eq, Debug)]
18pub struct HashLock {
19    pub mosaic: UnresolvedMosaic,
20    /// 預ける期間(ブロック)
21    pub duration: u64,
22    /// アグリゲートボンデッドのハッシュ
23    pub hash: Hash256,
24}
25
26impl HashLock {
27    const SIZE: usize = UnresolvedMosaic::SIZE + 8 + 32;
28
29    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
30        self.mosaic.encode(out);
31        out.extend_from_slice(&self.duration.to_le_bytes());
32        out.extend_from_slice(&self.hash.0);
33    }
34
35    pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
36        let mut reader = Reader::exact(bytes, Self::SIZE)?;
37        Ok(Self {
38            mosaic: UnresolvedMosaic::read(&mut reader),
39            duration: reader.u64(),
40            hash: Hash256(reader.array()),
41        })
42    }
43}
44
45/// シークレットロックとプルーフで、プルーフからシークレットを求めるハッシュ。
46#[derive(Clone, Copy, PartialEq, Eq, Debug)]
47pub enum LockHashAlgorithm {
48    Sha3_256,
49    /// RIPEMD-160(SHA-256)
50    Hash160,
51    /// SHA-256(SHA-256)
52    Hash256,
53}
54
55impl LockHashAlgorithm {
56    /// プルーフからシークレットを求める。catapult の `CalculateHash`。
57    /// RIPEMD-160 の20バイトは、後ろを0で埋めて32バイトにする。
58    pub fn secret(self, proof: &[u8]) -> Hash256 {
59        match self {
60            Self::Sha3_256 => Hash256(Sha3_256::digest(proof).into()),
61            Self::Hash160 => {
62                let mut secret = [0; 32];
63                secret[..20].copy_from_slice(&Ripemd160::digest(Sha256::digest(proof)));
64                Hash256(secret)
65            }
66            Self::Hash256 => Hash256(Sha256::digest(Sha256::digest(proof)).into()),
67        }
68    }
69
70    fn to_byte(self) -> u8 {
71        match self {
72            Self::Sha3_256 => 0,
73            Self::Hash160 => 1,
74            Self::Hash256 => 2,
75        }
76    }
77
78    fn from_byte(byte: u8) -> Result<Self, DecodeError> {
79        match byte {
80            0 => Ok(Self::Sha3_256),
81            1 => Ok(Self::Hash160),
82            2 => Ok(Self::Hash256),
83            _ => Err(DecodeError::InvalidValue {
84                field: "ハッシュの種類",
85                value: byte.into(),
86            }),
87        }
88    }
89}
90
91/// プルーフを示したら受取人に渡るように、モザイクをロックする。
92#[derive(Clone, Copy, PartialEq, Eq, Debug)]
93pub struct SecretLock {
94    pub recipient_address: UnresolvedAddress,
95    pub secret: Hash256,
96    pub mosaic: UnresolvedMosaic,
97    /// ロックする期間(ブロック)
98    pub duration: u64,
99    pub hash_algorithm: LockHashAlgorithm,
100}
101
102impl SecretLock {
103    const SIZE: usize = 24 + 32 + UnresolvedMosaic::SIZE + 8 + 1;
104
105    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
106        out.extend_from_slice(&self.recipient_address.0);
107        out.extend_from_slice(&self.secret.0);
108        self.mosaic.encode(out);
109        out.extend_from_slice(&self.duration.to_le_bytes());
110        out.push(self.hash_algorithm.to_byte());
111    }
112
113    pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
114        let mut reader = Reader::exact(bytes, Self::SIZE)?;
115        Ok(Self {
116            recipient_address: UnresolvedAddress(reader.array()),
117            secret: Hash256(reader.array()),
118            mosaic: UnresolvedMosaic::read(&mut reader),
119            duration: reader.u64(),
120            hash_algorithm: LockHashAlgorithm::from_byte(reader.u8())?,
121        })
122    }
123}
124
125/// プルーフを示して、シークレットロックしたモザイクを受取人に渡す。
126#[derive(Clone, PartialEq, Eq, Debug)]
127pub struct SecretProof {
128    pub recipient_address: UnresolvedAddress,
129    pub secret: Hash256,
130    pub hash_algorithm: LockHashAlgorithm,
131    pub proof: BoundedVec<u8, { u16::MAX as usize }>,
132}
133
134impl SecretProof {
135    /// プルーフより前の部分。受取人、シークレット、プルーフの長さ、ハッシュの種類。
136    const FIXED_SIZE: usize = 24 + 32 + 2 + 1;
137
138    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
139        out.extend_from_slice(&self.recipient_address.0);
140        out.extend_from_slice(&self.secret.0);
141        out.extend_from_slice(&(self.proof.len() as u16).to_le_bytes());
142        out.push(self.hash_algorithm.to_byte());
143        out.extend_from_slice(&self.proof);
144    }
145
146    pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
147        let mut reader = Reader::at_least(bytes, Self::FIXED_SIZE)?;
148        let recipient_address = UnresolvedAddress(reader.array());
149        let secret = Hash256(reader.array());
150        let proof_size = reader.u16() as usize;
151        let hash_algorithm = LockHashAlgorithm::from_byte(reader.u8())?;
152        Ok(Self {
153            recipient_address,
154            secret,
155            hash_algorithm,
156            proof: reader
157                .rest(proof_size)?
158                .to_vec()
159                .try_into()
160                .expect("u16 length"),
161        })
162    }
163}
164
165/// チェーンに記録されたシークレットロックの1件を指すハッシュ。catapult の `CalculateSecretLockInfoHash` で、
166/// シークレットと受取人のアドレスを続けた SHA3-256。受取人は、ネームスペースを解決したあとのアドレス。
167pub fn secret_lock_key(secret: &Hash256, recipient: &Address) -> Hash256 {
168    Hash256(
169        Sha3_256::new()
170            .chain_update(secret.0)
171            .chain_update(recipient.0)
172            .finalize()
173            .into(),
174    )
175}
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use crate::Body;
180    use crate::testing::{decode, round_trip};
181    use crate::transfer::UnresolvedMosaicId;
182
183    fn mosaic() -> UnresolvedMosaic {
184        UnresolvedMosaic {
185            mosaic_id: UnresolvedMosaicId(0x0102),
186            amount: 10,
187        }
188    }
189
190    #[test]
191    fn computes_secrets_from_proofs() {
192        // 空のバイト列のハッシュ。Hash160 はビットコインのアドレスで使う RIPEMD-160(SHA-256) で、後ろを0で埋める
193        let secret = |algorithm: LockHashAlgorithm| algorithm.secret(b"").to_string();
194        assert_eq!(
195            secret(LockHashAlgorithm::Sha3_256),
196            "A7FFC6F8BF1ED76651C14756A061D662F580FF4DE43B49FA82D80A4B80F8434A"
197        );
198        assert_eq!(
199            secret(LockHashAlgorithm::Hash160),
200            "B472A266D0BD89C13706A4132CCFB16F7C3B9FCB000000000000000000000000"
201        );
202        assert_eq!(
203            secret(LockHashAlgorithm::Hash256),
204            "5DF6E0E2761359D30A8275058E299FCC0381534545F55CF43E41983F5D4C9456"
205        );
206    }
207
208    #[test]
209    fn hashes_the_secret_and_the_recipient() {
210        let mut data = vec![0x11; 32];
211        data.extend_from_slice(&[0x98; 24]);
212        assert_eq!(
213            secret_lock_key(&Hash256([0x11; 32]), &Address([0x98; 24])),
214            Hash256(Sha3_256::digest(&data).into())
215        );
216    }
217
218    #[test]
219    fn writes_a_hash_lock_in_the_catbuffer_layout() {
220        let body = round_trip(Body::HashLock(HashLock {
221            mosaic: mosaic(),
222            duration: 480,
223            hash: Hash256([0xAB; 32]),
224        }));
225        assert_eq!(body[..8], 0x0102_u64.to_le_bytes());
226        assert_eq!(body[8..16], 10_u64.to_le_bytes());
227        assert_eq!(body[16..24], 480_u64.to_le_bytes());
228        assert_eq!(body[24..], [0xAB; 32]);
229    }
230
231    #[test]
232    fn rejects_an_undefined_hash_algorithm() {
233        let lock = SecretLock {
234            recipient_address: UnresolvedAddress([0x98; 24]),
235            secret: Hash256([1; 32]),
236            mosaic: mosaic(),
237            duration: 1,
238            hash_algorithm: LockHashAlgorithm::Hash256,
239        };
240        let mut body = round_trip(Body::SecretLock(lock));
241        assert_eq!(body[body.len() - 1], 2);
242        *body.last_mut().unwrap() = 3;
243        assert_eq!(
244            decode(0x4152, &body),
245            Err(DecodeError::InvalidValue {
246                field: "ハッシュの種類",
247                value: 3
248            })
249        );
250    }
251
252    #[test]
253    fn reads_a_proof_of_the_stated_size() {
254        let proof = SecretProof {
255            recipient_address: UnresolvedAddress([0x98; 24]),
256            secret: Hash256([1; 32]),
257            hash_algorithm: LockHashAlgorithm::Hash160,
258            proof: vec![0xEE; 20].try_into().unwrap(),
259        };
260        let body = round_trip(Body::SecretProof(proof));
261        assert_eq!(body[56..59], [20, 0, 1]);
262        assert_eq!(body[59..], [0xEE; 20]);
263        for broken in [&body[..body.len() - 1], &[body.as_slice(), &[0]].concat()] {
264            assert_eq!(decode(0x4252, broken), Err(DecodeError::InvalidBodySize));
265        }
266    }
267}