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
use std::fmt;
use std::ops;

use candid::CandidType;
use ciborium::tag::Captured;
use ex3_crypto::sha256;
use ex3_node_error::OtherError;
use ex3_payload_derive::Ex3Payload;
use ex3_serde::{bincode, cbor};
use ic_stable_structures::storable::Bound;
use ic_stable_structures::Storable;
use num_bigint::BigUint;
use serde::de::{Deserializer, SeqAccess, Visitor};
use serde::ser::{SerializeSeq, Serializer};
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;

pub use asset::*;
pub use asset_account_binding::*;
pub use deposit::*;
pub use market::*;
pub use order::*;
pub use secret::*;
pub use transfer::*;
pub use types::*;
pub use wallet_registration::*;
pub use withdrawal::*;

use crate::PublicKey;
use crate::{Nonce, TransactionHash, Version, WalletRegisterId};

mod asset;
mod deposit;
mod market;
mod order;
mod secret;
mod transfer;
mod types;
mod withdrawal;

mod asset_account_binding;
mod wallet_registration;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Transaction {
    // Version of the transaction.
    pub version: Version,
    // Type of transaction.
    pub r#type: TransactionType,
    // Wallet register ID of the sender.
    pub from: WalletRegisterId,
    /// Nonce is a number that is used only once for every transaction per wallet.
    /// If the transaction type is Deposit, Wallet Register, or Reset Main Secret, this field is 0.
    /// Otherwise, this field starts from 1.
    pub nonce: Nonce,
    // Payload information of the transaction.
    pub payload: ByteBuf,
    // Signature of the transaction.
    pub signature: ByteBuf,
}

#[derive(Debug, Clone, PartialEq, Eq, Ex3Payload)]
struct TxData {
    #[index(0)]
    version: u8,
    #[index(1)]
    r#type: BigUint,
    #[index(2)]
    from: BigUint,
    #[index(3)]
    nonce: BigUint,
    #[index(4)]
    payload: ByteBuf,
}

impl Transaction {
    pub fn hash(&self) -> TransactionHash {
        let bytes = bincode::serialize(&(
            &self.version,
            &self.r#type,
            &self.from,
            &self.nonce,
            &self.payload,
        ))
        .unwrap();
        sha256(&bytes)
    }

    // Why use this hash function?
    // Because the wallet registration transaction is a special transaction.
    // It is no public key in the transaction payload, but the public key is in the transaction signature.
    // So we need to use the public key in the transaction signature to calculate the hash value.
    pub fn hash_for_wallet_registration(&self, recovery_public_key: PublicKey) -> TransactionHash {
        let bytes = bincode::serialize(&(
            &self.version,
            &self.r#type,
            &self.from,
            &self.nonce,
            &recovery_public_key,
        ))
        .unwrap();
        sha256(&bytes)
    }

    pub fn tx_data_bytes(&self) -> Vec<u8> {
        let tx_data = TxData {
            version: self.version.encode(),
            r#type: self.r#type.clone().into(),
            from: self.from.clone().into(),
            nonce: self.nonce.clone().into(),
            payload: self.payload.clone(),
        };
        let bytes = cbor::serialize(&tx_data).unwrap();
        bytes
    }

    /// Self-encode the transaction into bytes.
    pub fn encode(&self) -> Vec<u8> {
        let data_bytes = bincode::serialize(&(
            &self.r#type,
            &self.from,
            &self.nonce,
            &self.payload,
            &self.signature,
        ))
        .unwrap();

        let mut bytes = vec![self.version.encode()];
        bytes.extend_from_slice(&data_bytes);
        bytes
    }

    /// Decode the transaction from bytes.
    pub fn decode(bytes: &[u8]) -> Result<Self, OtherError> {
        let version = Version::decode(bytes[0..1].try_into().unwrap())
            .map_err(|_| OtherError::new("failed to decode transaction version".to_string()))?;

        if version != Version::V0 {
            return Err(OtherError::new(
                format!(
                    "unsupported transaction version, expected 0, but {}",
                    version.encode()
                )
                .to_string(),
            ));
        }

        let (r#type, from, nonce, payload, signature) = bincode::deserialize(&bytes[1..]).unwrap();

        Ok(Transaction {
            version,
            r#type,
            from,
            nonce,
            payload,
            signature,
        })
    }
}

#[derive(CandidType, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(transparent)]
pub struct EncodedTransaction(ByteBuf);

impl From<Transaction> for EncodedTransaction {
    fn from(tx: Transaction) -> Self {
        let bytes = tx.encode();
        EncodedTransaction(ByteBuf::from(bytes))
    }
}

impl From<&Transaction> for EncodedTransaction {
    fn from(tx: &Transaction) -> Self {
        let bytes = tx.encode();
        EncodedTransaction(ByteBuf::from(bytes))
    }
}

impl From<EncodedTransaction> for Transaction {
    fn from(tx: EncodedTransaction) -> Self {
        Transaction::decode(tx.0.as_ref()).expect("failed to decode transaction")
    }
}

impl From<&EncodedTransaction> for Transaction {
    fn from(tx: &EncodedTransaction) -> Self {
        Transaction::decode(tx.0.as_ref()).expect("failed to decode transaction")
    }
}

impl ops::Deref for EncodedTransaction {
    type Target = ByteBuf;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Storable for EncodedTransaction {
    fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
        self.0.as_ref().into()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        EncodedTransaction(ByteBuf::from(bytes))
    }

    const BOUND: Bound = Bound::Unbounded;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encode_decode_with_empty_signature() {
        let tx = Transaction {
            version: Version::V0,
            r#type: TransactionType::Deposit,
            from: WalletRegisterId::from(1000000u32),
            nonce: Nonce::from(1u32),
            payload: ByteBuf::from(vec![1u8, 2u8, 3u8]),
            signature: ByteBuf::from(vec![]),
        };

        let bytes = tx.encode();
        let tx2 = Transaction::decode(&bytes).unwrap();
        assert_eq!(tx, tx2);
    }

    #[test]
    fn test_encode_decode_with_non_empty_signature() {
        let tx = Transaction {
            version: Version::V0,
            r#type: TransactionType::Deposit,
            from: WalletRegisterId::from(1000000u32),
            nonce: Nonce::from(1u32),
            payload: ByteBuf::from(vec![1u8, 2u8, 3u8]),
            // 65 bytes
            signature: ByteBuf::from(vec![1u8; 65]),
        };

        let bytes = tx.encode();
        let tx2 = Transaction::decode(&bytes).unwrap();
        assert_eq!(tx, tx2);
    }
}