github.com/turingchain2020/turingchain@v1.1.21/executor/plugin_fee.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package executor 6 7 import "github.com/turingchain2020/turingchain/types" 8 9 func init() { 10 RegisterPlugin("fee", &feePlugin{}) 11 } 12 13 type feePlugin struct { 14 pluginBase 15 } 16 17 func (p *feePlugin) CheckEnable(executor *executor, enable bool) (kvs []*types.KeyValue, ok bool, err error) { 18 return nil, true, nil 19 } 20 21 func (p *feePlugin) ExecLocal(executor *executor, data *types.BlockDetail) ([]*types.KeyValue, error) { 22 fee := &types.TotalFee{} 23 for i := 0; i < len(data.Block.Txs); i++ { 24 tx := data.Block.Txs[i] 25 fee.Fee += tx.Fee 26 fee.TxCount++ 27 } 28 kv, err := saveFee(executor, fee, data.Block.ParentHash, data.Block.Hash(executor.api.GetConfig())) 29 if err != nil { 30 return nil, err 31 } 32 return []*types.KeyValue{kv}, err 33 } 34 35 func (p *feePlugin) ExecDelLocal(executor *executor, data *types.BlockDetail) ([]*types.KeyValue, error) { 36 kv, err := delFee(executor, data.Block.Hash(executor.api.GetConfig())) 37 if err != nil { 38 return nil, err 39 } 40 return []*types.KeyValue{kv}, err 41 } 42 43 func saveFee(ex *executor, fee *types.TotalFee, parentHash, hash []byte) (*types.KeyValue, error) { 44 totalFee := &types.TotalFee{} 45 totalFeeBytes, err := ex.localDB.Get(types.TotalFeeKey(parentHash)) 46 if err == nil { 47 err = types.Decode(totalFeeBytes, totalFee) 48 if err != nil { 49 return nil, err 50 } 51 } else if err != types.ErrNotFound { 52 return nil, err 53 } 54 totalFee.Fee += fee.Fee 55 totalFee.TxCount += fee.TxCount 56 return &types.KeyValue{Key: types.TotalFeeKey(hash), Value: types.Encode(totalFee)}, nil 57 } 58 59 func delFee(ex *executor, hash []byte) (*types.KeyValue, error) { 60 return &types.KeyValue{Key: types.TotalFeeKey(hash)}, nil 61 }