-
Notifications
You must be signed in to change notification settings - Fork 11
/
appstate.go
396 lines (342 loc) · 10.7 KB
/
appstate.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
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
package conchapp
import (
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/blockchainworkers/conch/crypto"
"github.com/blockchainworkers/conch/libs/log"
"github.com/jmoiron/sqlx"
"math/big"
"sync"
)
// AccountState means current account's info
type AccountState struct {
sync.RWMutex
accounts map[string]*Account
log log.Logger
db *sqlx.DB
isDirty bool
}
// NewAccountState return AccountState inst
func NewAccountState(db *sqlx.DB, log log.Logger) *AccountState {
return &AccountState{
accounts: make(map[string]*Account),
log: log,
db: db,
isDirty: false,
}
}
// LoadAccount get account from cache or db
func (as *AccountState) LoadAccount(address string) (*Account, error) {
as.RLock()
defer as.RUnlock()
if k, ok := as.accounts[address]; ok {
return k, nil
}
// try load from db
acc, err := as.selectAccount(address)
if err == nil {
as.accounts[address] = acc
}
return acc, err
}
func (as *AccountState) selectAccount(addr string) (*Account, error) {
sqlStr := "select amount from funds where address = ?"
var amount string
err := as.db.QueryRowx(sqlStr, addr).Scan(&amount)
if err == sql.ErrNoRows {
return &Account{Address: addr, Amount: new(big.Int).SetInt64(0)}, nil
}
if err != nil {
return nil, err
}
acc := Account{Address: addr, Amount: big.NewInt(0)}
acc.Amount.SetString(amount, 0)
return &acc, nil
}
// UpdateAccountCache update account in memory
func (as *AccountState) UpdateAccountCache(acc *Account) {
as.RLock()
defer as.RUnlock()
as.accounts[acc.Address] = acc
as.isDirty = true
}
//SyncToDisk cache to disk
func (as *AccountState) SyncToDisk() error {
if !as.isDirty {
return nil
}
if len(as.accounts) == 0 {
return nil
}
sqlStr := "replace into funds(address, amount) values "
for _, val := range as.accounts {
sqlStr = sqlStr + fmt.Sprintf(" ('%s', '%s'),", val.Address, val.Amount.String())
}
sqlStr = sqlStr[0 : len(sqlStr)-1]
_, err := as.db.Exec(sqlStr)
as.accounts = make(map[string]*Account)
return err
}
//Account ...
type Account struct {
Address string
Amount *big.Int
}
// NewAccount return account inst
func NewAccount(addr, amount string) *Account {
am := big.NewInt(0)
am.SetString(amount, 0)
return &Account{Address: addr, Amount: am}
}
// TxState means current tx's info
type TxState struct {
sync.RWMutex
Txs Transactions
log log.Logger
db *sqlx.DB
}
// NewTxState txstate inst
func NewTxState(db *sqlx.DB, log log.Logger) *TxState {
return &TxState{
Txs: Transactions{},
log: log,
db: db,
}
}
// UpdateTx append tx
func (txState *TxState) UpdateTx(tx *Transaction) {
txState.Lock()
defer txState.Unlock()
txState.log.Error("one tx has been executed.......")
txState.Txs = txState.Txs.AppendTx(tx)
}
// SyncToDisk write tx to db
func (txState *TxState) SyncToDisk(height int64) (hashRoot string, err error) {
if txState.Txs.Len() == 0 {
return txState.Txs.HashRoot(), nil
}
sqlStr := "replace into transaction_records(id, sender, receiver, amount, input, expired, time_stamp, nonce, ref_block_num, block_num, sign) values "
for _, val := range txState.Txs {
sqlStr = sqlStr + fmt.Sprintf(" ('%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%d', '%d', '%s'),",
val.TxID(), val.Sender, val.Receiver, val.Value, val.Input, val.ExpiredNum, val.TimeStamp, val.Nonce, val.RefBlockNum, height, val.Sign)
}
sqlStr = sqlStr[0 : len(sqlStr)-1]
_, err = txState.db.Exec(sqlStr)
// merkle tree
hashRoot = txState.Txs.HashRoot()
// new trans for next commit
txState.RLock()
txState.Txs = Transactions{}
txState.RUnlock()
return
}
//QueryTxsByAccount query account related tx
func (txState *TxState) QueryTxsByAccount(account string, start, offset int64) Transactions {
var txs Transactions
// id, sender, receiver, amount, input, expired, time_stamp, nonce, ref_block_num, block_num, sign
sqlStr := "select id, sender, receiver, amount, input, expired, time_stamp, nonce, ref_block_num from transaction_records where sender=? or receiver=? limit ?, ?;"
rows, err := txState.db.Queryx(sqlStr, account, account, start, offset)
if err != nil {
txState.log.Error("query txs by account failed", "err", err.Error())
return txs
}
for rows.Next() {
var tmp Transaction
rows.Scan(&tmp.ID, &tmp.Sender, &tmp.Receiver, &tmp.Value, &tmp.Input, &tmp.ExpiredNum, &tmp.TimeStamp, &tmp.Nonce, &tmp.RefBlockNum)
txs = append(txs, &tmp)
}
return txs
}
//QueryTxByID query tx by id
func (txState *TxState) QueryTxByID(id string) Transaction {
var tx Transaction
// id, sender, receiver, amount, input, expired, time_stamp, nonce, ref_block_num, block_num, sign
sqlStr := "select id, sender, receiver, amount, input, expired, time_stamp, nonce, ref_block_num from transaction_records where id=? ;"
row := txState.db.QueryRowx(sqlStr, id)
err := row.Scan(&tx.ID, &tx.Sender, &tx.Receiver, &tx.Value, &tx.Input, &tx.ExpiredNum, &tx.TimeStamp, &tx.Nonce, &tx.RefBlockNum)
if err == sql.ErrNoRows {
return tx
}
if err != nil {
txState.log.Error("query txs by id failed", "err", err.Error())
}
return tx
}
// TxRepState means current tx receipt's info
type TxRepState struct {
sync.RWMutex
Txreps TransactionReceipts
log log.Logger
db *sqlx.DB
}
// NewTxRepState tx receipt inst
func NewTxRepState(db *sqlx.DB, log log.Logger) *TxRepState {
return &TxRepState{
Txreps: TransactionReceipts{},
log: log,
db: db,
}
}
// UpdateTxRep append tx
func (txrSt *TxRepState) UpdateTxRep(tr *TransactionReceipt) {
txrSt.Lock()
defer txrSt.Unlock()
txrSt.Txreps = txrSt.Txreps.AppendTxrp(tr)
}
// SyncToDisk write tx to db
func (txrSt *TxRepState) SyncToDisk(height int64) (hashRoot string, err error) {
if txrSt.Txreps.Len() == 0 {
return txrSt.Txreps.HashRoot(), nil
}
// id | status | fee | block_num | tx_hash | log
sqlStr := "replace into transaction_receipts (id, status, fee, block_num, tx_hash, log) values "
for _, val := range txrSt.Txreps {
sqlStr = sqlStr + fmt.Sprintf(" ('%s', '%d', '%s', '%d', '%s', '%s'),",
string(val.ID()), val.Status, val.Fee.String(), height, val.TxHash, val.Log)
}
sqlStr = sqlStr[0 : len(sqlStr)-1]
_, err = txrSt.db.Exec(sqlStr)
// merkle tree
hashRoot = txrSt.Txreps.HashRoot()
// new trans for next commit
txrSt.RLock()
txrSt.Txreps = TransactionReceipts{}
txrSt.RUnlock()
return
}
// HeaderState appheader state
type HeaderState struct {
CurBlockNum int64 `json:"cur_block_num"`
CurBlockHash string `json:"cur_block_hash"`
CurAPPHash string `json:"cur_app_hash"`
TimeStamp int64 `json:"time_stamp"`
Fee *big.Int
db *sqlx.DB
log log.Logger
}
// LoadHeaderState from db load header
func (hdSt *HeaderState) LoadHeaderState() error {
sqlStr := "select content from state where id=1"
var text string
err := hdSt.db.QueryRowx(sqlStr).Scan(&text)
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
return json.Unmarshal([]byte(text), hdSt)
}
// SyncToDisk to db
func (hdSt *HeaderState) SyncToDisk() error {
dat, err := json.Marshal(hdSt)
if err != nil {
return err
}
sqlStr := fmt.Sprintf("replace into state (id, content) values ('%d', '%s')", 1, string(dat))
_, err = hdSt.db.Exec(sqlStr)
return err
}
// BlockState current app block state
type BlockState struct {
APPHash string
TxRoot string
TxRepRoot string
BlockHash string
BlockNum int64
TimeStamp int64
db *sqlx.DB
log log.Logger
}
// NewBlockState block state instance
func NewBlockState(db *sqlx.DB, log log.Logger) *BlockState {
return &BlockState{db: db, log: log}
}
//Hash return apphash
func (bs *BlockState) Hash() string {
code := fmt.Sprintf("block_hash=%s&block_num=%d&tx_root=%s&receipt_root=%s&time_stamp=%d",
bs.BlockHash, bs.BlockNum, bs.TxRoot, bs.TxRepRoot, bs.TimeStamp)
// bs.log.Error("show blk code ", "code", code)
dat := []byte(code)
buf := make([]byte, base64.StdEncoding.EncodedLen(len(dat)))
base64.StdEncoding.Encode(buf, dat)
bs.APPHash = hex.EncodeToString(crypto.Sha256(buf))
return bs.APPHash
}
// SyncToDisk to db
func (bs *BlockState) SyncToDisk() error {
hash := bs.Hash()
//apphash | block_hash | block_num | tx_root | receipt_root | time_stamp
sqlStr := fmt.Sprintf(`replace into block_records (apphash, block_hash, block_num, tx_root, receipt_root, time_stamp) values
('%s', '%s', '%d', '%s', '%s', '%d' )`, hash, bs.BlockHash, bs.BlockNum, bs.TxRoot, bs.TxRepRoot, bs.TimeStamp)
_, err := bs.db.Exec(sqlStr)
return err
}
// APPState state set
type APPState struct {
HeadSt *HeaderState
AccoutSt *AccountState
TxSt *TxState
TxRepSt *TxRepState
BlkSt *BlockState
DB *sqlx.DB
}
//NewAPPState return app state init db (if db is not exist create the database and tables)
func NewAPPState(db *sqlx.DB, log log.Logger) *APPState {
return &APPState{
HeadSt: &HeaderState{db: db, log: log, Fee: big.NewInt(0)},
AccoutSt: NewAccountState(db, log),
TxSt: NewTxState(db, log),
TxRepSt: NewTxRepState(db, log),
BlkSt: NewBlockState(db, log),
DB: db,
}
}
// Commit commit an state return apphash, err
func (appSt *APPState) Commit() (string, error) {
// 1. iter tx
// 2. exec tx and update transaction receipt then update account
// 3. all transaction have been exec ? then goto 1.
// 4. sync to db
vm := NewVMActuator(appSt)
for iter := range appSt.TxSt.Txs {
if err := vm.ExecuteTx(appSt.TxSt.Txs[iter]); err != nil {
appSt.TxSt.log.Error("execurate transaction failed", "err", err.Error())
}
}
// sync account state
if err := appSt.AccoutSt.SyncToDisk(); err != nil {
appSt.AccoutSt.log.Error("account state sync faild ", "err", err.Error())
}
// sync tx state
txRoot, err := appSt.TxSt.SyncToDisk(appSt.HeadSt.CurBlockNum)
if err != nil {
appSt.TxSt.log.Error("tx state sync faild ", "err", err.Error())
}
// sync tx receipt state
txrepRoot, err := appSt.TxRepSt.SyncToDisk(appSt.HeadSt.CurBlockNum)
if err != nil {
appSt.TxRepSt.log.Error("tx receipt state sync faild ", "err", err.Error())
}
// upadte block state
appSt.BlkSt.BlockHash = appSt.HeadSt.CurBlockHash
appSt.BlkSt.BlockNum = appSt.HeadSt.CurBlockNum
appSt.BlkSt.TxRoot = txRoot
appSt.BlkSt.TxRepRoot = txrepRoot
appSt.BlkSt.TimeStamp = appSt.HeadSt.TimeStamp
if err := appSt.BlkSt.SyncToDisk(); err != nil {
appSt.BlkSt.log.Error("block state sync faild ", "err", err.Error())
}
appSt.BlkSt.log.Info("show blockinfo", "blocknum", appSt.BlkSt.BlockNum, "txroot", appSt.BlkSt.TxRoot, "txreproot", appSt.BlkSt.TxRepRoot,
"blockhash", appSt.BlkSt.BlockHash, "apphash", appSt.BlkSt.Hash(), "time", appSt.BlkSt.TimeStamp)
// todo:: all tx's fee need be processed
appSt.HeadSt.CurAPPHash = appSt.BlkSt.APPHash
// sync state
if err := appSt.HeadSt.SyncToDisk(); err != nil {
appSt.HeadSt.log.Error("header state sync faild ", "err", err.Error())
}
return appSt.HeadSt.CurAPPHash, nil
}