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
//! Transaction types.
use anyhow::anyhow;
use thiserror::Error;

use crate::{
    crypto::{
        multisig,
        signature::{self, PublicKey, Signature},
    },
    types::{
        address,
        address::{Address, SignatureAddressSpec},
        token,
    },
};

/// Transaction signature domain separation context base.
pub const SIGNATURE_CONTEXT_BASE: &[u8] = b"oasis-runtime-sdk/tx: v0";
/// The latest transaction format version.
pub const LATEST_TRANSACTION_VERSION: u16 = 1;

/// Error.
#[derive(Debug, Error)]
pub enum Error {
    #[error("unsupported version")]
    UnsupportedVersion,
    #[error("malformed transaction: {0}")]
    MalformedTransaction(anyhow::Error),
}

/// A container for data that authenticates a transaction.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
pub enum AuthProof {
    /// For _signature_ authentication.
    #[cbor(rename = "signature")]
    Signature(Signature),
    /// For _multisig_ authentication.
    #[cbor(rename = "multisig")]
    Multisig(multisig::SignatureSetOwned),
    /// A flag to use module-controlled decoding. The string is an encoding scheme name that a
    /// module must handle. The scheme name must not be empty.
    #[cbor(rename = "module")]
    Module(String),
}

/// An unverified signed transaction.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
#[cbor(no_default)]
pub struct UnverifiedTransaction(pub Vec<u8>, pub Vec<AuthProof>);

impl UnverifiedTransaction {
    /// Verify and deserialize the unverified transaction.
    pub fn verify(self) -> Result<Transaction, Error> {
        // Deserialize the inner body.
        let body: Transaction =
            cbor::from_slice(&self.0).map_err(|e| Error::MalformedTransaction(e.into()))?;
        body.validate_basic()?;

        // Basic structure validation.
        if self.1.len() != body.auth_info.signer_info.len() {
            return Err(Error::MalformedTransaction(anyhow!(
                "unexpected number of auth proofs. expected {} but found {}",
                body.auth_info.signer_info.len(),
                self.1.len()
            )));
        }

        // Verify all signatures.
        let ctx = signature::context::get_chain_context_for(SIGNATURE_CONTEXT_BASE);
        let mut public_keys = vec![];
        let mut signatures = vec![];
        for (si, auth_proof) in body.auth_info.signer_info.iter().zip(self.1.iter()) {
            let (mut batch_pks, mut batch_sigs) = si.address_spec.batch(auth_proof)?;
            public_keys.append(&mut batch_pks);
            signatures.append(&mut batch_sigs);
        }
        PublicKey::verify_batch_multisig(&ctx, &self.0, &public_keys, &signatures)
            .map_err(|e| Error::MalformedTransaction(e.into()))?;

        Ok(body)
    }
}

/// Transaction.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
#[cbor(no_default)]
pub struct Transaction {
    #[cbor(rename = "v")]
    pub version: u16,

    pub call: Call,

    #[cbor(rename = "ai")]
    pub auth_info: AuthInfo,
}

impl Transaction {
    /// Perform basic validation on the transaction.
    pub fn validate_basic(&self) -> Result<(), Error> {
        if self.version != LATEST_TRANSACTION_VERSION {
            return Err(Error::UnsupportedVersion);
        }
        if self.auth_info.signer_info.is_empty() {
            return Err(Error::MalformedTransaction(anyhow!(
                "transaction has no signers"
            )));
        }
        Ok(())
    }
}

/// Format used for encoding the call (and output) information.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, cbor::Encode, cbor::Decode)]
#[repr(u8)]
#[cbor(with_default)]
pub enum CallFormat {
    /// Plain text call data.
    #[default]
    Plain = 0,
    /// Encrypted call data using X25519 for key exchange and Deoxys-II for symmetric encryption.
    EncryptedX25519DeoxysII = 1,
}

/// Method call.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
pub struct Call {
    /// Call format.
    #[cbor(optional)]
    pub format: CallFormat,
    /// Method name.
    #[cbor(optional)]
    pub method: String,
    /// Method body.
    pub body: cbor::Value,
    /// Read-only flag.
    ///
    /// A read-only call cannot make any changes to runtime state. Any attempt at modifying state
    /// will result in the call failing.
    #[cbor(optional, rename = "ro")]
    pub read_only: bool,
}

impl Default for Call {
    fn default() -> Self {
        Self {
            format: Default::default(),
            method: Default::default(),
            body: cbor::Value::Simple(cbor::SimpleValue::NullValue),
            read_only: false,
        }
    }
}

/// Transaction authentication information.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct AuthInfo {
    /// Transaction signer information.
    #[cbor(rename = "si")]
    pub signer_info: Vec<SignerInfo>,
    /// Fee payment information.
    pub fee: Fee,
    /// Earliest round when the transaction is valid.
    #[cbor(optional)]
    pub not_before: Option<u64>,
    /// Latest round when the transaction is valid.
    #[cbor(optional)]
    pub not_after: Option<u64>,
}

/// Transaction fee.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct Fee {
    /// Amount of base units paid as fee for transaction processing.
    pub amount: token::BaseUnits,
    /// Maximum amount of gas paid for.
    #[cbor(optional)]
    pub gas: u64,
    /// Maximum amount of emitted consensus messages paid for. Zero means that up to the maximum
    /// number of per-batch messages can be emitted.
    #[cbor(optional)]
    pub consensus_messages: u32,
}

impl Fee {
    /// Calculates gas price from fee amount and gas.
    pub fn gas_price(&self) -> u128 {
        self.amount
            .amount()
            .checked_div(self.gas.into())
            .unwrap_or_default()
    }
}

/// A caller address.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
pub enum CallerAddress {
    #[cbor(rename = "address")]
    Address(Address),
    #[cbor(rename = "eth_address")]
    EthAddress([u8; 20]),
}

impl CallerAddress {
    /// Derives the address.
    pub fn address(&self) -> Address {
        match self {
            CallerAddress::Address(address) => *address,
            CallerAddress::EthAddress(address) => Address::new(
                address::ADDRESS_V0_SECP256K1ETH_CONTEXT,
                address::ADDRESS_V0_VERSION,
                address.as_ref(),
            ),
        }
    }

    /// Maps the caller address to one of the same type but with an all-zero address.
    pub fn zeroized(&self) -> Self {
        match self {
            CallerAddress::Address(_) => CallerAddress::Address(Default::default()),
            CallerAddress::EthAddress(_) => CallerAddress::EthAddress(Default::default()),
        }
    }
}

/// Common information that specifies an address as well as how to authenticate.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
pub enum AddressSpec {
    /// For _signature_ authentication.
    #[cbor(rename = "signature")]
    Signature(SignatureAddressSpec),
    /// For _multisig_ authentication.
    #[cbor(rename = "multisig")]
    Multisig(multisig::Config),

    /// For internal child calls (cannot be serialized/deserialized).
    #[cbor(skip)]
    Internal(CallerAddress),
}

impl AddressSpec {
    /// Derives the address.
    pub fn address(&self) -> Address {
        match self {
            AddressSpec::Signature(spec) => Address::from_sigspec(spec),
            AddressSpec::Multisig(config) => Address::from_multisig(config.clone()),
            AddressSpec::Internal(caller) => caller.address(),
        }
    }

    /// Derives the caller address.
    pub fn caller_address(&self) -> CallerAddress {
        match self {
            AddressSpec::Signature(SignatureAddressSpec::Secp256k1Eth(pk)) => {
                CallerAddress::EthAddress(pk.to_eth_address().try_into().unwrap())
            }
            AddressSpec::Internal(caller) => caller.clone(),
            _ => CallerAddress::Address(self.address()),
        }
    }

    /// Checks that the address specification and the authentication proof are acceptable.
    /// Returns vectors of public keys and signatures for batch verification of included signatures.
    pub fn batch(&self, auth_proof: &AuthProof) -> Result<(Vec<PublicKey>, Vec<Signature>), Error> {
        match (self, auth_proof) {
            (AddressSpec::Signature(spec), AuthProof::Signature(signature)) => {
                Ok((vec![spec.public_key()], vec![signature.clone()]))
            }
            (AddressSpec::Multisig(config), AuthProof::Multisig(signature_set)) => Ok(config
                .batch(signature_set)
                .map_err(|e| Error::MalformedTransaction(e.into()))?),
            (AddressSpec::Signature(_), AuthProof::Multisig(_)) => {
                Err(Error::MalformedTransaction(anyhow!(
                    "transaction signer used a single signature, but auth proof was multisig"
                )))
            }
            (AddressSpec::Multisig(_), AuthProof::Signature(_)) => {
                Err(Error::MalformedTransaction(anyhow!(
                    "transaction signer used multisig, but auth proof was a single signature"
                )))
            }
            (AddressSpec::Internal(_), _) => Err(Error::MalformedTransaction(anyhow!(
                "transaction signer used internal address spec"
            ))),
            (_, AuthProof::Module(_)) => Err(Error::MalformedTransaction(anyhow!(
                "module-controlled decoding flag in auth proof list"
            ))),
        }
    }
}

/// Transaction signer information.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
#[cbor(no_default)]
pub struct SignerInfo {
    pub address_spec: AddressSpec,
    pub nonce: u64,
}

impl SignerInfo {
    /// Create a new signer info from a signature address specification and nonce.
    pub fn new_sigspec(spec: SignatureAddressSpec, nonce: u64) -> Self {
        Self {
            address_spec: AddressSpec::Signature(spec),
            nonce,
        }
    }

    /// Create a new signer info from a multisig configuration and a nonce.
    pub fn new_multisig(config: multisig::Config, nonce: u64) -> Self {
        Self {
            address_spec: AddressSpec::Multisig(config),
            nonce,
        }
    }
}

/// Call result.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
pub enum CallResult {
    #[cbor(rename = "ok")]
    Ok(cbor::Value),

    #[cbor(rename = "fail")]
    Failed {
        module: String,
        code: u32,

        #[cbor(optional)]
        message: String,
    },

    #[cbor(rename = "unknown")]
    Unknown(cbor::Value),
}

impl Default for CallResult {
    fn default() -> Self {
        Self::Unknown(cbor::Value::Simple(cbor::SimpleValue::NullValue))
    }
}

impl CallResult {
    /// Check whether the call result indicates a successful operation or not.
    pub fn is_success(&self) -> bool {
        !matches!(self, CallResult::Failed { .. })
    }
}

#[cfg(any(test, feature = "test"))]
impl CallResult {
    pub fn unwrap(self) -> cbor::Value {
        match self {
            Self::Ok(v) | Self::Unknown(v) => v,
            Self::Failed {
                module,
                code,
                message,
            } => panic!("{module} reported failure with code {code}: {message}"),
        }
    }

    pub fn into_call_result(self) -> Option<crate::module::CallResult> {
        Some(match self {
            Self::Ok(v) => crate::module::CallResult::Ok(v),
            Self::Failed {
                module,
                code,
                message,
            } => crate::module::CallResult::Failed {
                module,
                code,
                message,
            },
            Self::Unknown(_) => return None,
        })
    }
}

#[cfg(test)]
mod test {
    use crate::types::token::{BaseUnits, Denomination};

    use super::*;

    #[test]
    fn test_fee_gas_price() {
        let fee = Fee {
            amount: Default::default(),
            gas: 0,
            consensus_messages: 0,
        };
        assert_eq!(0, fee.gas_price(), "empty fee - gas price should be zero",);

        let fee = Fee {
            amount: Default::default(),
            gas: 100,
            consensus_messages: 0,
        };
        assert_eq!(
            0,
            fee.gas_price(),
            "empty fee amount - gas price should be zero",
        );

        let fee = Fee {
            amount: BaseUnits::new(1_000, Denomination::NATIVE),
            gas: 0,
            consensus_messages: 0,
        };
        assert_eq!(0, fee.gas_price(), "empty fee 0 - gas price should be zero",);

        let fee = Fee {
            amount: BaseUnits::new(1_000, Denomination::NATIVE),
            gas: 10_000,
            consensus_messages: 0,
        };
        assert_eq!(
            0,
            fee.gas_price(),
            "non empty fee - gas price should be zero"
        );

        let fee = Fee {
            amount: BaseUnits::new(1_000, Denomination::NATIVE),
            gas: 500,
            consensus_messages: 0,
        };
        assert_eq!(2, fee.gas_price(), "non empty fee - gas price should match");
    }
}