forked from 33cn/plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tokendb.go
470 lines (408 loc) · 14.1 KB
/
tokendb.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
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
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"fmt"
"strings"
"github.com/33cn/chain33/account"
dbm "github.com/33cn/chain33/common/db"
"github.com/33cn/chain33/system/dapp"
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/token/types"
)
type tokenDB struct {
token pty.Token
}
func newTokenDB(preCreate *pty.TokenPreCreate, creator string, height int64) *tokenDB {
t := &tokenDB{}
t.token.Name = preCreate.GetName()
t.token.Symbol = preCreate.GetSymbol()
t.token.Introduction = preCreate.GetIntroduction()
t.token.Total = preCreate.GetTotal()
t.token.Price = preCreate.GetPrice()
//token可以由自己进行创建,也可以通过委托给其他地址进行创建
t.token.Owner = preCreate.GetOwner()
t.token.Creator = creator
t.token.Status = pty.TokenStatusPreCreated
if types.IsDappFork(height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) {
t.token.Category = preCreate.Category
}
return t
}
func (t *tokenDB) save(db dbm.KV, key []byte) {
set := t.getKVSet(key)
for i := 0; i < len(set); i++ {
db.Set(set[i].GetKey(), set[i].Value)
}
}
func (t *tokenDB) getLogs(ty int32, status int32) []*types.ReceiptLog {
var log []*types.ReceiptLog
value := types.Encode(&pty.ReceiptToken{Symbol: t.token.Symbol, Owner: t.token.Owner, Status: t.token.Status})
log = append(log, &types.ReceiptLog{Ty: ty, Log: value})
return log
}
//key:mavl-create-token-addr-xxx or mavl-token-xxx <-----> value:token
func (t *tokenDB) getKVSet(key []byte) (kvset []*types.KeyValue) {
value := types.Encode(&t.token)
kvset = append(kvset, &types.KeyValue{Key: key, Value: value})
return kvset
}
func getTokenFromDB(db dbm.KV, symbol string, owner string) (*pty.Token, error) {
key := calcTokenAddrKeyS(symbol, owner)
value, err := db.Get(key)
if err != nil {
// not found old key
key = calcTokenAddrNewKeyS(symbol, owner)
value, err = db.Get(key)
if err != nil {
return nil, err
}
}
var token pty.Token
if err = types.Decode(value, &token); err != nil {
tokenlog.Error("getTokenFromDB", "Fail to decode types.token for key", string(key), "err info is", err)
return nil, err
}
return &token, nil
}
type tokenAction struct {
coinsAccount *account.DB
db dbm.KV
txhash []byte
fromaddr string
toaddr string
blocktime int64
height int64
execaddr string
}
func newTokenAction(t *token, toaddr string, tx *types.Transaction) *tokenAction {
hash := tx.Hash()
fromaddr := tx.From()
return &tokenAction{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr, toaddr,
t.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer))}
}
func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt, error) {
tokenlog.Debug("preCreate")
if token == nil {
return nil, types.ErrInvalidParam
}
if len(token.GetName()) > pty.TokenNameLenLimit {
return nil, pty.ErrTokenNameLen
} else if len(token.GetIntroduction()) > pty.TokenIntroLenLimit {
return nil, pty.ErrTokenIntroLen
} else if len(token.GetSymbol()) > pty.TokenSymbolLenLimit {
return nil, pty.ErrTokenSymbolLen
} else if token.GetTotal() > types.MaxTokenBalance || token.GetTotal() <= 0 {
return nil, pty.ErrTokenTotalOverflow
}
if !types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) {
if token.Category != 0 {
return nil, types.ErrNotSupport
}
}
if !validSymbolWithHeight([]byte(token.GetSymbol()), action.height) {
tokenlog.Error("token precreate ", "symbol need be upper", token.GetSymbol())
return nil, pty.ErrTokenSymbolUpper
}
if checkTokenExist(token.GetSymbol(), action.db) {
return nil, pty.ErrTokenExist
}
if checkTokenHasPrecreate(token.GetSymbol(), token.GetOwner(), pty.TokenStatusPreCreated, action.db) {
return nil, pty.ErrTokenHavePrecreated
}
if types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenBlackListX) {
found, err := inBlacklist(token.GetSymbol(), blacklist, action.db)
if err != nil {
return nil, err
}
if found {
return nil, pty.ErrTokenBlacklist
}
}
var logs []*types.ReceiptLog
var kv []*types.KeyValue
if types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenPriceX) && token.GetPrice() == 0 {
// pay for create token offline
} else {
receipt, err := action.coinsAccount.ExecFrozen(action.fromaddr, action.execaddr, token.GetPrice())
if err != nil {
tokenlog.Error("token precreate ", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", token.GetTotal())
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
}
tokendb := newTokenDB(token, action.fromaddr, action.height)
var statuskey []byte
var key []byte
if types.IsFork(action.height, "ForkExecKey") {
statuskey = calcTokenStatusNewKeyS(tokendb.token.Symbol, tokendb.token.Owner, pty.TokenStatusPreCreated)
key = calcTokenAddrNewKeyS(tokendb.token.Symbol, tokendb.token.Owner)
} else {
statuskey = calcTokenStatusKey(tokendb.token.Symbol, tokendb.token.Owner, pty.TokenStatusPreCreated)
key = calcTokenAddrKeyS(tokendb.token.Symbol, tokendb.token.Owner)
}
tokendb.save(action.db, statuskey)
tokendb.save(action.db, key)
logs = append(logs, tokendb.getLogs(pty.TyLogPreCreateToken, pty.TokenStatusPreCreated)...)
kv = append(kv, tokendb.getKVSet(key)...)
kv = append(kv, tokendb.getKVSet(statuskey)...)
//tokenlog.Info("func token preCreate", "token:", tokendb.token.Symbol, "owner:", tokendb.token.Owner,
// "key:", key, "key string", string(key), "value:", tokendb.getKVSet(key)[0].Value)
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
func (action *tokenAction) finishCreate(tokenFinish *pty.TokenFinishCreate) (*types.Receipt, error) {
tokenlog.Debug("finishCreate")
if tokenFinish == nil {
return nil, types.ErrInvalidParam
}
token, err := getTokenFromDB(action.db, tokenFinish.GetSymbol(), tokenFinish.GetOwner())
if err != nil || token.Status != pty.TokenStatusPreCreated {
return nil, pty.ErrTokenNotPrecreated
}
approverValid := false
for _, approver := range conf.GStrList("tokenApprs") {
if approver == action.fromaddr {
approverValid = true
break
}
}
hasPriv, ok := validFinisher(action.fromaddr, action.db)
if (ok != nil || !hasPriv) && !approverValid {
return nil, pty.ErrTokenCreatedApprover
}
var logs []*types.ReceiptLog
var kv []*types.KeyValue
if types.IsDappFork(action.height, pty.TokenX, "ForkTokenPrice") && token.GetPrice() == 0 {
// pay for create token offline
} else {
//将之前冻结的资金转账到fund合约账户中
receiptForCoin, err := action.coinsAccount.ExecTransferFrozen(token.Creator, action.toaddr, action.execaddr, token.Price)
if err != nil {
tokenlog.Error("token finishcreate ", "addr", action.fromaddr, "execaddr", action.execaddr, "token", token.Symbol)
return nil, err
}
logs = append(logs, receiptForCoin.Logs...)
kv = append(kv, receiptForCoin.KV...)
}
//创建token类型的账户,同时需要创建的额度存入
tokenAccount, err := account.NewAccountDB("token", tokenFinish.GetSymbol(), action.db)
if err != nil {
return nil, err
}
tokenlog.Debug("finishCreate", "token.Owner", token.Owner, "token.GetTotal()", token.GetTotal())
receiptForToken, err := tokenAccount.GenesisInit(token.Owner, token.GetTotal())
if err != nil {
return nil, err
}
//更新token的状态为已经创建
token.Status = pty.TokenStatusCreated
tokendb := &tokenDB{*token}
var key []byte
if types.IsFork(action.height, "ForkExecKey") {
key = calcTokenAddrNewKeyS(tokendb.token.Symbol, tokendb.token.Owner)
} else {
key = calcTokenAddrKeyS(tokendb.token.Symbol, tokendb.token.Owner)
}
tokendb.save(action.db, key)
logs = append(logs, receiptForToken.Logs...)
logs = append(logs, tokendb.getLogs(pty.TyLogFinishCreateToken, pty.TokenStatusCreated)...)
kv = append(kv, receiptForToken.KV...)
kv = append(kv, tokendb.getKVSet(key)...)
key = calcTokenKey(tokendb.token.Symbol)
//因为该token已经被创建,需要保存一个全局的token,防止其他用户再次创建
tokendb.save(action.db, key)
kv = append(kv, tokendb.getKVSet(key)...)
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
func (action *tokenAction) revokeCreate(tokenRevoke *pty.TokenRevokeCreate) (*types.Receipt, error) {
if tokenRevoke == nil {
return nil, types.ErrInvalidParam
}
token, err := getTokenFromDB(action.db, tokenRevoke.GetSymbol(), tokenRevoke.GetOwner())
if err != nil {
tokenlog.Error("token revokeCreate ", "Can't get token form db for token", tokenRevoke.GetSymbol())
return nil, pty.ErrTokenNotPrecreated
}
if token.Status != pty.TokenStatusPreCreated {
tokenlog.Error("token revokeCreate ", "token's status should be precreated to be revoked for token", tokenRevoke.GetSymbol())
return nil, pty.ErrTokenCanotRevoked
}
//确认交易发起者的身份,token的发起人可以撤销该项token的创建
//token的owner允许撤销交易
if action.fromaddr != token.Owner && action.fromaddr != token.Creator {
tokenlog.Error("tprocTokenRevokeCreate, different creator/owner vs actor of this revoke",
"action.fromaddr", action.fromaddr, "creator", token.Creator, "owner", token.Owner)
return nil, pty.ErrTokenRevoker
}
var logs []*types.ReceiptLog
var kv []*types.KeyValue
if types.IsDappFork(action.height, pty.TokenX, pty.ForkTokenPriceX) && token.GetPrice() == 0 {
// pay for create token offline
} else {
//解锁之前冻结的资金
receipt, err := action.coinsAccount.ExecActive(token.Creator, action.execaddr, token.Price)
if err != nil {
tokenlog.Error("token revokeCreate error ", "error info", err, "creator addr", token.Creator, "execaddr", action.execaddr, "token", token.Symbol)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
}
token.Status = pty.TokenStatusCreateRevoked
tokendb := &tokenDB{*token}
var key []byte
if types.IsFork(action.height, "ForkExecKey") {
key = calcTokenAddrNewKeyS(tokendb.token.Symbol, tokendb.token.Owner)
} else {
key = calcTokenAddrKeyS(tokendb.token.Symbol, tokendb.token.Owner)
}
tokendb.save(action.db, key)
logs = append(logs, tokendb.getLogs(pty.TyLogRevokeCreateToken, pty.TokenStatusCreateRevoked)...)
kv = append(kv, tokendb.getKVSet(key)...)
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
func checkTokenExist(token string, db dbm.KV) bool {
_, err := db.Get(calcTokenKey(token))
return err == nil
}
func checkTokenHasPrecreate(token, owner string, status int32, db dbm.KV) bool {
_, err := db.Get(calcTokenAddrKeyS(token, owner))
if err == nil {
return true
}
_, err = db.Get(calcTokenAddrNewKeyS(token, owner))
return err == nil
}
func validFinisher(addr string, db dbm.KV) (bool, error) {
return validOperator(addr, finisherKey, db)
}
func getManageKey(key string, db dbm.KV) ([]byte, error) {
manageKey := types.ManageKey(key)
value, err := db.Get([]byte(manageKey))
if err != nil {
tokenlog.Info("tokendb", "get db key", "not found manageKey", "key", manageKey)
return getConfigKey(key, db)
}
return value, nil
}
func getConfigKey(key string, db dbm.KV) ([]byte, error) {
configKey := types.ConfigKey(key)
value, err := db.Get([]byte(configKey))
if err != nil {
tokenlog.Info("tokendb", "get db key", "not found configKey", "key", configKey)
return nil, err
}
return value, nil
}
func validOperator(addr, key string, db dbm.KV) (bool, error) {
value, err := getManageKey(key, db)
if err != nil {
tokenlog.Info("tokendb", "get db key", "not found", "key", key)
return false, err
}
if value == nil {
tokenlog.Info("tokendb", "get db key", " found nil value", "key", key)
return false, nil
}
var item types.ConfigItem
err = types.Decode(value, &item)
if err != nil {
tokenlog.Error("tokendb", "get db key", err)
return false, err // types.ErrBadConfigValue
}
for _, op := range item.GetArr().Value {
if op == addr {
return true, nil
}
}
return false, nil
}
func calcTokenAssetsKey(addr string) []byte {
return []byte(fmt.Sprintf(tokenAssetsPrefix+"%s", addr))
}
func getTokenAssetsKey(addr string, db dbm.KVDB) (*types.ReplyStrings, error) {
key := calcTokenAssetsKey(addr)
value, err := db.Get(key)
if err != nil && err != types.ErrNotFound {
tokenlog.Error("tokendb", "GetTokenAssetsKey", err)
return nil, err
}
var assets types.ReplyStrings
if err == types.ErrNotFound {
return &assets, nil
}
err = types.Decode(value, &assets)
if err != nil {
tokenlog.Error("tokendb", "GetTokenAssetsKey", err)
return nil, err
}
return &assets, nil
}
// AddTokenToAssets 添加个人资产列表
func AddTokenToAssets(addr string, db dbm.KVDB, symbol string) []*types.KeyValue {
tokenAssets, err := getTokenAssetsKey(addr, db)
if err != nil {
return nil
}
if tokenAssets == nil {
tokenAssets = &types.ReplyStrings{}
}
var found = false
for _, sym := range tokenAssets.Datas {
if sym == symbol {
found = true
break
}
}
if !found {
tokenAssets.Datas = append(tokenAssets.Datas, symbol)
}
var kv []*types.KeyValue
kv = append(kv, &types.KeyValue{Key: calcTokenAssetsKey(addr), Value: types.Encode(tokenAssets)})
return kv
}
func inBlacklist(symbol, key string, db dbm.KV) (bool, error) {
found, err := validOperator(symbol, key, db)
return found, err
}
func isUpperChar(a byte) bool {
res := (a <= 'Z' && a >= 'A')
return res
}
func isDigit(a byte) bool {
return (a <= '9' && a >= '0')
}
func validSymbolForkBadTokenSymbol(cs []byte) bool {
for _, c := range cs {
if !isUpperChar(c) {
return false
}
}
return true
}
func validSymbolForkTokenSymbolWithNumber(cs []byte) bool {
for _, c := range cs {
if !isUpperChar(c) && !isDigit(c) {
return false
}
}
return true
}
func validSymbolOriginal(cs []byte) bool {
symbol := string(cs)
upSymbol := strings.ToUpper(symbol)
return upSymbol == symbol
}
func validSymbolWithHeight(cs []byte, height int64) bool {
if types.IsDappFork(height, pty.TokenX, pty.ForkTokenSymbolWithNumberX) {
return validSymbolForkTokenSymbolWithNumber(cs)
} else if types.IsDappFork(height, pty.TokenX, pty.ForkBadTokenSymbolX) {
return validSymbolForkBadTokenSymbol(cs)
}
return validSymbolOriginal(cs)
}