-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathaccount.go
70 lines (60 loc) · 1.43 KB
/
account.go
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
// Account, AccountState
// Some basic operation about accountState
package core
import (
"blockEmulator/utils"
"bytes"
"crypto/sha256"
"encoding/gob"
"log"
"math/big"
)
type Account struct {
AcAddress utils.Address
PublicKey []byte
}
// AccoutState record the details of an account, it will be saved in status trie
type AccountState struct {
AcAddress utils.Address // this part is not useful, abort
Nonce uint64
Balance *big.Int
StorageRoot []byte // only for smart contract account
CodeHash []byte // only for smart contract account
}
// Reduce the balance of an account
func (as *AccountState) Deduct(val *big.Int) bool {
if as.Balance.Cmp(val) < 0 {
return false
}
as.Balance.Sub(as.Balance, val)
return true
}
// Increase the balance of an account
func (s *AccountState) Deposit(value *big.Int) {
s.Balance.Add(s.Balance, value)
}
// Encode AccountState in order to store in the MPT
func (as *AccountState) Encode() []byte {
var buff bytes.Buffer
encoder := gob.NewEncoder(&buff)
err := encoder.Encode(as)
if err != nil {
log.Panic(err)
}
return buff.Bytes()
}
// Decode AccountState
func DecodeAS(b []byte) *AccountState {
var as AccountState
decoder := gob.NewDecoder(bytes.NewReader(b))
err := decoder.Decode(&as)
if err != nil {
log.Panic(err)
}
return &as
}
// Hash AccountState for computing the MPT Root
func (as *AccountState) Hash() []byte {
h := sha256.Sum256(as.Encode())
return h[:]
}