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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

use crate::{bytes::Bytes, hash::KECCAK_EMPTY};
use cfx_types::{
    address_util::AddressUtil, Address, AddressSpaceUtil, AddressWithSpace,
    Space, H256, U256,
};
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
use rlp_derive::{RlpDecodable, RlpEncodable};
use serde_derive::{Deserialize, Serialize};

use std::{
    fmt,
    ops::{Deref, DerefMut},
    sync::Arc,
};

#[derive(Debug, PartialEq, Clone)]
pub enum AddressSpace {
    Builtin,
    User,
    Contract,
}

#[derive(Debug, PartialEq, Clone)]
pub enum AccountError {
    ReservedAddressSpace(Address),
    AddressSpaceMismatch(Address, AddressSpace),
    InvalidRlp(DecoderError),
}

#[derive(
    Clone,
    Debug,
    RlpDecodable,
    RlpEncodable,
    Ord,
    PartialOrd,
    Eq,
    PartialEq,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "camelCase")]
pub struct DepositInfo {
    /// This is the number of tokens in this deposit.
    pub amount: U256,
    /// This is the timestamp when this deposit happened, measured in the
    /// number of past blocks. It will be used to calculate
    /// the service charge.
    pub deposit_time: U256,
    /// This is the accumulated interest rate when this deposit happened.
    pub accumulated_interest_rate: U256,
}

#[derive(
    Clone,
    Debug,
    RlpDecodable,
    RlpEncodable,
    Ord,
    PartialOrd,
    Eq,
    PartialEq,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "camelCase")]
pub struct VoteStakeInfo {
    /// This is the number of tokens should be locked before
    /// `unlock_block_number`.
    pub amount: U256,
    /// This is the timestamp when the vote right will be invalid, measured in
    /// the number of past blocks.
    pub unlock_block_number: U256,
}

#[derive(Clone, Debug, Default, Ord, PartialOrd, Eq, PartialEq)]
pub struct DepositList(pub Vec<DepositInfo>);

impl Encodable for DepositList {
    fn rlp_append(&self, s: &mut RlpStream) { s.append_list(&self.0); }
}

impl Decodable for DepositList {
    fn decode(d: &Rlp) -> Result<Self, DecoderError> {
        let deposit_vec = d.as_list()?;
        Ok(DepositList(deposit_vec))
    }
}

impl Deref for DepositList {
    type Target = Vec<DepositInfo>;

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

impl DerefMut for DepositList {
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}

#[derive(Clone, Debug, Default, Ord, PartialOrd, Eq, PartialEq)]
pub struct VoteStakeList(pub Vec<VoteStakeInfo>);

impl Encodable for VoteStakeList {
    fn rlp_append(&self, s: &mut RlpStream) { s.append_list(&self.0); }
}

impl Decodable for VoteStakeList {
    fn decode(d: &Rlp) -> Result<Self, DecoderError> {
        let vote_vec = d.as_list()?;
        Ok(VoteStakeList(vote_vec))
    }
}

impl Deref for VoteStakeList {
    type Target = Vec<VoteStakeInfo>;

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

impl DerefMut for VoteStakeList {
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}

impl VoteStakeList {
    pub fn withdrawable_staking_balance(
        &self, staking_balance: U256, block_number: u64,
    ) -> U256 {
        let block_number: U256 = block_number.into();
        if !self.is_empty() {
            // Find first index whose `unlock_block_number` is greater than
            // timestamp and all entries before the index could be
            // ignored.
            let idx = self
                .binary_search_by(|vote_info| {
                    vote_info.unlock_block_number.cmp(&(block_number + 1))
                })
                .unwrap_or_else(|x| x);
            if idx == self.len() {
                staking_balance
            } else {
                staking_balance - self[idx].amount
            }
        } else {
            staking_balance
        }
    }

    pub fn remove_expired_vote_stake_info(&mut self, block_number: u64) {
        let block_number: U256 = block_number.into();
        if !self.is_empty() && self[0].unlock_block_number <= block_number {
            // Find first index whose `unlock_block_number` is greater than
            // timestamp and all entries before the index could be
            // removed.
            let idx = self
                .binary_search_by(|vote_info| {
                    vote_info.unlock_block_number.cmp(&(block_number + 1))
                })
                .unwrap_or_else(|x| x);
            self.0 = self.split_off(idx)
        }
    }

    pub fn vote_lock(&mut self, amount: U256, unlock_block_number: u64) {
        let unlock_block_number: U256 = unlock_block_number.into();
        let mut updated = false;
        let mut updated_index = 0;
        match self.binary_search_by(|vote_info| {
            vote_info.unlock_block_number.cmp(&unlock_block_number)
        }) {
            Ok(index) => {
                if amount > self[index].amount {
                    self[index].amount = amount;
                    updated = true;
                    updated_index = index;
                }
            }
            Err(index) => {
                if index >= self.len() || self[index].amount < amount {
                    self.insert(
                        index,
                        VoteStakeInfo {
                            amount,
                            unlock_block_number,
                        },
                    );
                    updated = true;
                    updated_index = index;
                }
            }
        }
        if updated {
            let rest = self.split_off(updated_index);
            while !self.is_empty()
                && self.last().unwrap().amount <= rest[0].amount
            {
                self.pop();
            }
            self.extend_from_slice(&rest);
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct CodeInfo {
    pub code: Arc<Bytes>,
    pub owner: Address,
}

impl CodeInfo {
    #[inline]
    pub fn code_size(&self) -> usize { self.code.len() }
}

impl Encodable for CodeInfo {
    fn rlp_append(&self, stream: &mut RlpStream) {
        stream.begin_list(2).append(&*self.code).append(&self.owner);
    }
}

impl Decodable for CodeInfo {
    fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
        Ok(Self {
            code: Arc::new(rlp.val_at(0)?),
            owner: rlp.val_at(1)?,
        })
    }
}

#[derive(
    Clone,
    Debug,
    Ord,
    PartialOrd,
    Eq,
    PartialEq,
    Default,
    RlpDecodable,
    RlpEncodable,
)]
pub struct StoragePoints {
    pub unused: U256,
    pub used: U256,
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Default)]
pub struct SponsorInfo {
    /// This is the address of the sponsor for gas cost of the contract.
    pub sponsor_for_gas: Address,
    /// This is the address of the sponsor for collateral of the contract.
    pub sponsor_for_collateral: Address,
    /// This is the upper bound of sponsor gas cost per tx.
    pub sponsor_gas_bound: U256,
    /// This is the amount of tokens sponsor for gas cost to the contract.
    pub sponsor_balance_for_gas: U256,
    /// This is the amount of tokens sponsor for collateral to the contract.
    pub sponsor_balance_for_collateral: U256,
    /// This is the storage point introduced in CIP-107
    pub storage_points: Option<StoragePoints>,
}

impl SponsorInfo {
    pub fn unused_storage_points(&self) -> U256 {
        self.storage_points
            .as_ref()
            .map_or(U256::zero(), |x| x.unused)
    }
}

impl Encodable for SponsorInfo {
    fn rlp_append(&self, s: &mut RlpStream) {
        match &self.storage_points {
            None => {
                s.begin_list(5);
                s.append(&self.sponsor_for_gas);
                s.append(&self.sponsor_for_collateral);
                s.append(&self.sponsor_gas_bound);
                s.append(&self.sponsor_balance_for_gas);
                s.append(&self.sponsor_balance_for_collateral);
            }
            Some(points) => {
                s.begin_list(6);
                s.append(&self.sponsor_for_gas);
                s.append(&self.sponsor_for_collateral);
                s.append(&self.sponsor_gas_bound);
                s.append(&self.sponsor_balance_for_gas);
                s.append(&self.sponsor_balance_for_collateral);
                s.append(points);
            }
        }
    }
}

impl Decodable for SponsorInfo {
    fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
        match rlp.item_count()? {
            5 => Ok(SponsorInfo {
                sponsor_for_gas: rlp.val_at(0)?,
                sponsor_for_collateral: rlp.val_at(1)?,
                sponsor_gas_bound: rlp.val_at(2)?,
                sponsor_balance_for_gas: rlp.val_at(3)?,
                sponsor_balance_for_collateral: rlp.val_at(4)?,
                storage_points: None,
            }),
            6 => Ok(SponsorInfo {
                sponsor_for_gas: rlp.val_at(0)?,
                sponsor_for_collateral: rlp.val_at(1)?,
                sponsor_gas_bound: rlp.val_at(2)?,
                sponsor_balance_for_gas: rlp.val_at(3)?,
                sponsor_balance_for_collateral: rlp.val_at(4)?,
                storage_points: Some(rlp.val_at(5)?),
            }),
            _ => Err(DecoderError::RlpInvalidLength),
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct Account {
    /// This field is not part of Account data, but kept for convenience. It
    /// should be rarely used except for debugging.
    address_local_info: AddressWithSpace,
    pub balance: U256,
    pub nonce: U256,
    pub code_hash: H256,
    /// This is the number of tokens used in staking.
    pub staking_balance: U256,
    /// This is the number of tokens used as collateral for storage, which will
    /// be returned to balance if the storage is released.
    pub collateral_for_storage: U256,
    /// This is the accumulated interest return.
    pub accumulated_interest_return: U256,
    /// This is the address of the administrator of the contract.
    pub admin: Address,
    /// This is the sponsor information of the contract.
    pub sponsor_info: SponsorInfo,
}

/// Defined for Rlp serialization/deserialization.
#[derive(RlpEncodable, RlpDecodable)]
pub struct BasicAccount {
    pub balance: U256,
    pub nonce: U256,
    /// This is the number of tokens used in staking.
    pub staking_balance: U256,
    /// This is the number of tokens used as collateral for storage, which will
    /// be returned to balance if the storage is released.
    pub collateral_for_storage: U256,
    /// This is the accumulated interest return.
    pub accumulated_interest_return: U256,
}

/// Defined for Rlp serialization/deserialization.
#[derive(RlpEncodable, RlpDecodable)]
pub struct ContractAccount {
    pub balance: U256,
    pub nonce: U256,
    pub code_hash: H256,
    /// This is the number of tokens used in staking.
    pub staking_balance: U256,
    /// This is the number of tokens used as collateral for storage, which will
    /// be returned to balance if the storage is released.
    pub collateral_for_storage: U256,
    /// This is the accumulated interest return.
    pub accumulated_interest_return: U256,
    /// This is the address of the administrator of the contract.
    pub admin: Address,
    /// This is the sponsor information of the contract.
    pub sponsor_info: SponsorInfo,
}

#[derive(RlpEncodable, RlpDecodable)]
pub struct EthereumAccount {
    pub balance: U256,
    pub nonce: U256,
    pub code_hash: H256,
}

impl Account {
    pub fn address(&self) -> &AddressWithSpace { &self.address_local_info }

    pub fn set_address(&mut self, address: AddressWithSpace) {
        self.address_local_info = address;
    }

    pub fn new_empty(address: &AddressWithSpace) -> Account {
        Self::new_empty_with_balance(address, &U256::from(0), &U256::from(0))
    }

    pub fn new_empty_with_balance(
        address: &AddressWithSpace, balance: &U256, nonce: &U256,
    ) -> Account {
        Self {
            address_local_info: *address,
            balance: *balance,
            nonce: *nonce,
            code_hash: KECCAK_EMPTY,
            staking_balance: 0.into(),
            collateral_for_storage: 0.into(),
            accumulated_interest_return: 0.into(),
            admin: Address::zero(),
            sponsor_info: Default::default(),
        }
    }

    fn from_basic_account(address: Address, a: BasicAccount) -> Self {
        Self {
            address_local_info: address.with_native_space(),
            balance: a.balance,
            nonce: a.nonce,
            code_hash: KECCAK_EMPTY,
            staking_balance: a.staking_balance,
            collateral_for_storage: a.collateral_for_storage,
            accumulated_interest_return: a.accumulated_interest_return,
            admin: Address::zero(),
            sponsor_info: Default::default(),
        }
    }

    pub fn from_contract_account(address: Address, a: ContractAccount) -> Self {
        Self {
            address_local_info: address.with_native_space(),
            balance: a.balance,
            nonce: a.nonce,
            code_hash: a.code_hash,
            staking_balance: a.staking_balance,
            collateral_for_storage: a.collateral_for_storage,
            accumulated_interest_return: a.accumulated_interest_return,
            admin: a.admin,
            sponsor_info: a.sponsor_info,
        }
    }

    fn from_ethereum_account(address: Address, a: EthereumAccount) -> Self {
        let address = address.with_evm_space();
        Self {
            address_local_info: address,
            balance: a.balance,
            nonce: a.nonce,
            code_hash: a.code_hash,
            ..Self::new_empty(&address)
        }
    }

    pub fn to_basic_account(&self) -> BasicAccount {
        assert_eq!(self.address_local_info.space, Space::Native);
        BasicAccount {
            balance: self.balance,
            nonce: self.nonce,
            staking_balance: self.staking_balance,
            collateral_for_storage: self.collateral_for_storage,
            accumulated_interest_return: self.accumulated_interest_return,
        }
    }

    pub fn to_contract_account(&self) -> ContractAccount {
        assert_eq!(self.address_local_info.space, Space::Native);
        ContractAccount {
            balance: self.balance,
            nonce: self.nonce,
            code_hash: self.code_hash,
            staking_balance: self.staking_balance,
            collateral_for_storage: self.collateral_for_storage,
            accumulated_interest_return: self.accumulated_interest_return,
            admin: self.admin,
            sponsor_info: self.sponsor_info.clone(),
        }
    }

    pub fn to_evm_account(&self) -> EthereumAccount {
        assert_eq!(self.address_local_info.space, Space::Ethereum);
        assert!(self.staking_balance.is_zero());
        assert!(self.collateral_for_storage.is_zero());
        assert!(self.accumulated_interest_return.is_zero());
        assert!(self.admin.is_zero());
        assert_eq!(self.sponsor_info, Default::default());
        EthereumAccount {
            balance: self.balance,
            nonce: self.nonce,
            code_hash: self.code_hash,
        }
    }

    pub fn new_from_rlp(
        address: Address, rlp: &Rlp,
    ) -> Result<Self, AccountError> {
        let account = match rlp.item_count()? {
            8 => Self::from_contract_account(
                address,
                ContractAccount::decode(rlp)?,
            ),
            5 => Self::from_basic_account(address, BasicAccount::decode(rlp)?),
            3 => Self::from_ethereum_account(
                address,
                EthereumAccount::decode(rlp)?,
            ),
            _ => {
                return Err(AccountError::InvalidRlp(
                    DecoderError::RlpIncorrectListLen,
                ));
            }
        };
        Ok(account)
    }
}

impl Encodable for Account {
    fn rlp_append(&self, stream: &mut RlpStream) {
        if self.address_local_info.space == Space::Ethereum {
            stream.append_internal(&self.to_evm_account());
            return;
        }

        // After CIP-80, an address started by 0x8 is still stored as
        // contract format in underlying db, even if it may be a normal address.
        // In order to achieve backward compatible.
        //
        // It is impossible to have an all-zero hash value. But some previous
        // bug make one of the genesis accounts has all zero genesis hash.
        if self.code_hash != KECCAK_EMPTY && !self.code_hash.is_zero()
            || self.address_local_info.address.is_contract_address()
        {
            // A contract address can hold balance before its initialization
            // as a recipient of a simple transaction.
            // So we always determine how to serialize by the address type bits.
            stream.append_internal(&self.to_contract_account());
        } else {
            stream.append_internal(&self.to_basic_account());
        }
    }
}

impl From<DecoderError> for AccountError {
    fn from(err: DecoderError) -> Self { AccountError::InvalidRlp(err) }
}

impl fmt::Display for AccountError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let msg = match self {
            AccountError::ReservedAddressSpace(address) => {
                format!("Address space is reserved for {:?}", address)
            }
            AccountError::AddressSpaceMismatch(address, address_space) => {
                format!(
                    "Address {:?} not in address space {:?}",
                    address, address_space
                )
            }
            AccountError::InvalidRlp(err) => {
                format!("Transaction has invalid RLP structure: {}.", err)
            }
        };

        f.write_fmt(format_args!("Account error ({})", msg))
    }
}

impl std::error::Error for AccountError {
    fn description(&self) -> &str { "Account error" }
}

#[cfg(test)]
fn test_random_account(
    type_bit: Option<u8>, non_empty_hash: bool, contract_type: bool,
) {
    let mut address = Address::random();
    address.set_address_type_bits(type_bit.unwrap_or(0x40));

    let admin = Address::random();
    let sponsor_info = SponsorInfo {
        sponsor_for_gas: Address::random(),
        sponsor_for_collateral: Address::random(),
        sponsor_balance_for_gas: U256::from(123),
        sponsor_balance_for_collateral: U256::from(124),
        sponsor_gas_bound: U256::from(2),
        storage_points: None,
    };

    let code_hash = if non_empty_hash {
        H256::random()
    } else {
        KECCAK_EMPTY
    };

    let account = if contract_type {
        Account::from_contract_account(
            address,
            ContractAccount {
                balance: 1000.into(),
                nonce: 123.into(),
                code_hash,
                staking_balance: 10000000.into(),
                collateral_for_storage: 23.into(),
                accumulated_interest_return: 456.into(),
                admin,
                sponsor_info,
            },
        )
    } else {
        Account::from_basic_account(
            address,
            BasicAccount {
                balance: 1000.into(),
                nonce: 123.into(),
                staking_balance: 10000000.into(),
                collateral_for_storage: 23.into(),
                accumulated_interest_return: 456.into(),
            },
        )
    };
    assert_eq!(
        account,
        Account::new_from_rlp(
            account.address_local_info.address,
            &Rlp::new(&account.rlp_bytes()),
        )
        .unwrap()
    );
}

#[test]
fn test_account_serde() {
    // Original normal address
    test_random_account(Some(0x10), false, false);
    // Original contract address
    test_random_account(Some(0x80), true, true);
    // Uninitialized contract address && new normal address
    test_random_account(Some(0x80), false, true);

    // New normal address
    test_random_account(None, false, false);
    test_random_account(Some(0x80), false, false);

    test_random_account(None, true, true);
    test_random_account(Some(0x80), true, true);
}