diff --git a/account/client.go b/account/client.go index ea1295afc..e8a950f01 100644 --- a/account/client.go +++ b/account/client.go @@ -10,6 +10,7 @@ import ( "crypto/sha256" "errors" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math/rand" "os" "sort" @@ -19,7 +20,6 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" pg "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/utils" "github.com/elastos/Elastos.ELA/utils/signal" @@ -105,7 +105,7 @@ func Open(path string, password []byte) (*Client, error) { return client, nil } -func (cl *Client) Sign(txn *types.Transaction) (*types.Transaction, error) { +func (cl *Client) Sign(txn *transactions.BaseTransaction) (*transactions.BaseTransaction, error) { var signedPrograms []*pg.Program for _, program := range txn.Programs { // Get sign type @@ -421,7 +421,7 @@ func (cl *Client) HandleInterrupt() { } } -func SignBySigner(txn *types.Transaction, acc *Account) ([]byte, error) { +func SignBySigner(txn *transactions.BaseTransaction, acc *Account) ([]byte, error) { buf := new(bytes.Buffer) if err := txn.SerializeUnsigned(buf); err != nil { return nil, err @@ -433,7 +433,7 @@ func SignBySigner(txn *types.Transaction, acc *Account) ([]byte, error) { return signature, nil } -func SignStandardTransaction(txn *types.Transaction, program *pg.Program, +func SignStandardTransaction(txn *transactions.BaseTransaction, program *pg.Program, accounts map[common.Uint160]*Account) (*pg.Program, error) { code := program.Code acct, ok := accounts[*common.ToCodeHash(code)] @@ -459,7 +459,7 @@ func SignStandardTransaction(txn *types.Transaction, program *pg.Program, return signedProgram, nil } -func SignMultiSignTransaction(txn *types.Transaction, program *pg.Program, +func SignMultiSignTransaction(txn *transactions.BaseTransaction, program *pg.Program, accounts map[common.Uint160]*Account) (*pg.Program, error) { code := program.Code param := program.Parameter diff --git a/benchmark/common/tx/fixamontassigner.go b/benchmark/common/tx/fixamontassigner.go index b2b130f46..6835d2713 100644 --- a/benchmark/common/tx/fixamontassigner.go +++ b/benchmark/common/tx/fixamontassigner.go @@ -10,9 +10,9 @@ import ( "github.com/elastos/Elastos.ELA/benchmark/common/utils" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" + "github.com/elastos/Elastos.ELA/core/types/transactions" ) const ( @@ -21,10 +21,10 @@ const ( type fixAmountAssigner struct { account *account.Account - utxo *types.UTXO + utxo *common2.UTXO } -func (a *fixAmountAssigner) SignAndChange(tx *types.Transaction) error { +func (a *fixAmountAssigner) SignAndChange(tx *transactions.BaseTransaction) error { tx.Inputs = []*common2.Input{ { Previous: common2.OutPoint{ diff --git a/benchmark/common/tx/interface.go b/benchmark/common/tx/interface.go index 7dd1018e9..e66ee39f5 100644 --- a/benchmark/common/tx/interface.go +++ b/benchmark/common/tx/interface.go @@ -7,8 +7,8 @@ package tx import ( "github.com/elastos/Elastos.ELA/account" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" ) type AssignerType byte @@ -19,11 +19,11 @@ const ( ) type Generator interface { - Generate() *types.Transaction + Generate() *transactions.BaseTransaction } type Assigner interface { - SignAndChange(tx *types.Transaction) error + SignAndChange(tx *transactions.BaseTransaction) error } func NewGenerator(txType common2.TxType, ac ...*account.Account) Generator { @@ -36,7 +36,7 @@ func NewGenerator(txType common2.TxType, ac ...*account.Account) Generator { } func NewAssigner(assignerType AssignerType, ac *account.Account, - utxo *types.UTXO) Assigner { + utxo *common2.UTXO) Assigner { switch assignerType { case NoChanges: return &noChangesEvenAssigner{account: ac, utxo: utxo} diff --git a/benchmark/common/tx/nochangesevenassigner.go b/benchmark/common/tx/nochangesevenassigner.go index 0cb6964d8..1c6bc1348 100644 --- a/benchmark/common/tx/nochangesevenassigner.go +++ b/benchmark/common/tx/nochangesevenassigner.go @@ -9,8 +9,8 @@ import ( "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/benchmark/common/utils" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" ) const ( @@ -19,10 +19,10 @@ const ( type noChangesEvenAssigner struct { account *account.Account - utxo *types.UTXO + utxo *common2.UTXO } -func (a *noChangesEvenAssigner) SignAndChange(tx *types.Transaction) error { +func (a *noChangesEvenAssigner) SignAndChange(tx *transactions.BaseTransaction) error { tx.Inputs = []*common2.Input{ { Previous: common2.OutPoint{ diff --git a/benchmark/common/tx/transferasset.go b/benchmark/common/tx/transferasset.go index b62d02f7b..cd64b4d4d 100644 --- a/benchmark/common/tx/transferasset.go +++ b/benchmark/common/tx/transferasset.go @@ -9,10 +9,10 @@ import ( "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/benchmark/common/utils" "github.com/elastos/Elastos.ELA/common/config" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" + "github.com/elastos/Elastos.ELA/core/types/transactions" ) const ( @@ -23,8 +23,8 @@ type transferAssetGenerator struct { account []*account.Account } -func (g *transferAssetGenerator) Generate() *types.Transaction { - txn := &types.Transaction{ +func (g *transferAssetGenerator) Generate() *transactions.BaseTransaction { + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, PayloadVersion: 0, diff --git a/benchmark/common/utils/sign.go b/benchmark/common/utils/sign.go index f5c5bc0f7..6cd3853ab 100644 --- a/benchmark/common/utils/sign.go +++ b/benchmark/common/utils/sign.go @@ -9,10 +9,10 @@ import ( "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/transactions" ) -func SignStandardTx(tx *types.Transaction, ac *account.Account) (err error) { +func SignStandardTx(tx *transactions.BaseTransaction, ac *account.Account) (err error) { accounts := map[common.Uint160]*account.Account{} accounts[ac.ProgramHash.ToCodeHash()] = ac diff --git a/benchmark/tools/generator/chain/datagen.go b/benchmark/tools/generator/chain/datagen.go index 5bcd4076f..c01321df6 100644 --- a/benchmark/tools/generator/chain/datagen.go +++ b/benchmark/tools/generator/chain/datagen.go @@ -9,6 +9,8 @@ import ( "bytes" "errors" "fmt" + common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "io/ioutil" "math" "os" @@ -98,7 +100,7 @@ func (g *DataGen) Generate(height uint32) (err error) { } func (g *DataGen) fastProcess(height uint32) (err error) { - var txs []*types.Transaction + var txs []*transactions.BaseTransaction if txs, err = g.generateTxs(height); err != nil { return } @@ -120,7 +122,7 @@ func (g *DataGen) fastProcess(height uint32) (err error) { } func (g *DataGen) normalProcess(height uint32) (err error) { - var txs []*types.Transaction + var txs []*transactions.BaseTransaction if txs, err = g.generateTxs(height); err != nil { return } @@ -142,7 +144,7 @@ func (g *DataGen) normalProcess(height uint32) (err error) { } func (g *DataGen) minimalProcess(height uint32) (err error) { - var txs []*types.Transaction + var txs []*transactions.BaseTransaction if txs, err = g.generateTxs(height); err != nil { return } @@ -174,7 +176,7 @@ func (g *DataGen) countProcess(counter *TimeCounter, action func()) { } func (g *DataGen) generateTxs( - height uint32) (txs []*types.Transaction, err error) { + height uint32) (txs []*transactions.BaseTransaction, err error) { if g.pressure { return g.txRepo.GeneratePressureTxs(height, g.pressureTxSize) } else { @@ -183,7 +185,7 @@ func (g *DataGen) generateTxs( } func (g *DataGen) generateBlock( - txs []*types.Transaction) (block *types.Block, err error) { + txs []*transactions.BaseTransaction) (block *types.Block, err error) { g.countProcess(g.addToTxPoolCount, func() { for _, v := range txs { if err = g.txPool.AppendToTxPool(v); err != nil { @@ -273,7 +275,7 @@ func FromTxRepository(dataDir string, interrupt <-chan struct{}, if initFoundationUTXO { fundTx := chainParams.GenesisBlock.Transactions[0] - repo.SetFoundationUTXO(&types.UTXO{ + repo.SetFoundationUTXO(&common2.UTXO{ TxID: fundTx.Hash(), Index: 0, Value: fundTx.Outputs[0].Value, diff --git a/benchmark/tools/generator/chain/txrepository.go b/benchmark/tools/generator/chain/txrepository.go index 185784bb0..1ac810e58 100644 --- a/benchmark/tools/generator/chain/txrepository.go +++ b/benchmark/tools/generator/chain/txrepository.go @@ -6,13 +6,13 @@ package chain import ( + "github.com/elastos/Elastos.ELA/core/types/transactions" "io" "math/rand" "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/benchmark/common/tx" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/crypto" ) @@ -21,9 +21,9 @@ type TxRepository struct { params *GenerationParams accountKeys []common.Uint168 accounts map[common.Uint168]*account.Account - utxos map[common.Uint168][]types.UTXO + utxos map[common.Uint168][]common2.UTXO foundation *account.Account - foundationUTXO types.UTXO + foundationUTXO common2.UTXO } func (r *TxRepository) Params() *GenerationParams { @@ -34,19 +34,19 @@ func (r *TxRepository) GetFoundationAccount() *account.Account { return r.foundation } -func (r *TxRepository) SetFoundationUTXO(utxo *types.UTXO) { +func (r *TxRepository) SetFoundationUTXO(utxo *common2.UTXO) { r.foundationUTXO = *utxo } func (r *TxRepository) GeneratePressureTxs( - height uint32, size int) (txs []*types.Transaction, err error) { + height uint32, size int) (txs []*transactions.BaseTransaction, err error) { if height <= r.params.PrepareStartHeight { return } totalTxSize := 0 - var txn *types.Transaction - txs = make([]*types.Transaction, 0) + var txn *transactions.BaseTransaction + txs = make([]*transactions.BaseTransaction, 0) for { txn, err = r.generateTx() if err != nil { @@ -66,7 +66,7 @@ func (r *TxRepository) GeneratePressureTxs( } func (r *TxRepository) GenerateTxs( - height uint32) (txs []*types.Transaction, err error) { + height uint32) (txs []*transactions.BaseTransaction, err error) { if height <= r.params.PrepareStartHeight { return } @@ -74,8 +74,8 @@ func (r *TxRepository) GenerateTxs( refCount := r.calculateRefCount(height) // tx consume UTXOs - var txn *types.Transaction - txs = make([]*types.Transaction, 0, refCount+1) + var txn *transactions.BaseTransaction + txs = make([]*transactions.BaseTransaction, 0, refCount+1) for i := uint32(0); i < refCount; i++ { txn, err = r.generateTx() if err != nil { @@ -209,9 +209,9 @@ func (r *TxRepository) Deserialize(reader io.Reader) (err error) { if length, err = common.ReadVarUint(reader, 0); err != nil { return } - var utxo types.UTXO + var utxo common2.UTXO var utxoCount uint64 - r.utxos = make(map[common.Uint168][]types.UTXO, length) + r.utxos = make(map[common.Uint168][]common2.UTXO, length) for i := uint64(0); i < length; i++ { if err = key.Deserialize(reader); err != nil { return @@ -220,7 +220,7 @@ func (r *TxRepository) Deserialize(reader io.Reader) (err error) { if utxoCount, err = common.ReadVarUint(reader, 0); err != nil { return } - utxos := make([]types.UTXO, 0, utxoCount) + utxos := make([]common2.UTXO, 0, utxoCount) for j := uint64(0); j < utxoCount; j++ { if err = utxo.Deserialize(reader); err != nil { return @@ -248,30 +248,30 @@ func (r *TxRepository) deserializeAccount( return account.NewAccountWithPrivateKey(priBuf) } -func (r *TxRepository) updateByAllocateFundTx(allocTx *types.Transaction) { +func (r *TxRepository) updateByAllocateFundTx(allocTx *transactions.BaseTransaction) { r.appendUTXOs(allocTx, len(allocTx.Outputs)-1) - r.foundationUTXO = types.UTXO{ + r.foundationUTXO = common2.UTXO{ TxID: allocTx.Hash(), Index: uint16(len(allocTx.Outputs) - 1), Value: allocTx.Outputs[len(allocTx.Outputs)-1].Value, } } -func (r *TxRepository) updateUTXOs(txns []*types.Transaction) { +func (r *TxRepository) updateUTXOs(txns []*transactions.BaseTransaction) { for _, txn := range txns { r.appendUTXOs(txn, 0) } } -func (r *TxRepository) appendUTXOs(txn *types.Transaction, utxoCount int) { +func (r *TxRepository) appendUTXOs(txn *transactions.BaseTransaction, utxoCount int) { for i, o := range txn.Outputs { if utxoCount != 0 && i >= utxoCount { break } addr := o.ProgramHash - utxo := types.UTXO{ + utxo := common2.UTXO{ TxID: txn.Hash(), Index: uint16(i), Value: o.Value, @@ -279,13 +279,13 @@ func (r *TxRepository) appendUTXOs(txn *types.Transaction, utxoCount int) { if _, ok := r.utxos[addr]; ok { r.utxos[addr] = append(r.utxos[addr], utxo) } else { - r.utxos[addr] = []types.UTXO{utxo} + r.utxos[addr] = []common2.UTXO{utxo} } } } func (r *TxRepository) allocateFromFoundation(inCount uint32) ( - transaction *types.Transaction, err error) { + transaction *transactions.BaseTransaction, err error) { accounts := make([]*account.Account, 0, inCount) for i := uint32(0); i < inCount; i++ { ac := r.randomAccount() @@ -299,7 +299,7 @@ func (r *TxRepository) allocateFromFoundation(inCount uint32) ( return } -func (r *TxRepository) generateTx() (txn *types.Transaction, err error) { +func (r *TxRepository) generateTx() (txn *transactions.BaseTransaction, err error) { outAccount := r.randomAccount() // todo generate tx by random tx types later generator := tx.NewGenerator(common2.TransferAsset, outAccount) @@ -317,7 +317,7 @@ func (r *TxRepository) randomAccount() *account.Account { return r.accounts[r.accountKeys[index]] } -func (r *TxRepository) consumeRandomUTXO(ac *account.Account) types.UTXO { +func (r *TxRepository) consumeRandomUTXO(ac *account.Account) common2.UTXO { utxos := r.utxos[ac.ProgramHash] index := rand.Int63n(int64(len(utxos))) result := utxos[index] @@ -335,7 +335,7 @@ func NewTxRepository(params *GenerationParams) (result *TxRepository, params: params, accountKeys: []common.Uint168{}, accounts: map[common.Uint168]*account.Account{}, - utxos: map[common.Uint168][]types.UTXO{}, + utxos: map[common.Uint168][]common2.UTXO{}, } var ac *account.Account diff --git a/benchmark/tools/generator/chain/txrepository_test.go b/benchmark/tools/generator/chain/txrepository_test.go index 1bb3e6084..66cbed225 100644 --- a/benchmark/tools/generator/chain/txrepository_test.go +++ b/benchmark/tools/generator/chain/txrepository_test.go @@ -7,14 +7,13 @@ package chain import ( "bytes" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "math" "math/rand" "testing" "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" - "github.com/stretchr/testify/assert" ) @@ -36,7 +35,7 @@ func randomTxRepository() *TxRepository { foundationUTXO: randomUTXO(), foundation: randomAccount(), accounts: map[common.Uint168]*account.Account{}, - utxos: map[common.Uint168][]types.UTXO{}, + utxos: map[common.Uint168][]common2.UTXO{}, } for i := 0; i < 5; i++ { @@ -44,7 +43,7 @@ func randomTxRepository() *TxRepository { result.accountKeys = append(result.accountKeys, *key) result.accounts[*key] = randomAccount() - utxos := make([]types.UTXO, 0, 5) + utxos := make([]common2.UTXO, 0, 5) for j := 0; j < 5; j++ { utxos = append(utxos, randomUTXO()) } @@ -90,7 +89,7 @@ func txRepositoriesEqual(first, second *TxRepository) bool { return true } -func utxosEqual(first, second *types.UTXO) bool { +func utxosEqual(first, second *common2.UTXO) bool { return first.Index == second.Index && first.Value == second.Value && first.TxID.IsEqual(second.TxID) } @@ -120,8 +119,8 @@ func randomUint256() *common.Uint256 { return result } -func randomUTXO() types.UTXO { - return types.UTXO{ +func randomUTXO() common2.UTXO { + return common2.UTXO{ TxID: *randomUint256(), Index: uint16(rand.Int31n(math.MaxUint16)), Value: common.Fixed64(rand.Int63()), diff --git a/benchmark/tools/generator/chain/utils.go b/benchmark/tools/generator/chain/utils.go index 9cbdf225d..df5e1a9ec 100644 --- a/benchmark/tools/generator/chain/utils.go +++ b/benchmark/tools/generator/chain/utils.go @@ -6,6 +6,7 @@ package chain import ( + "github.com/elastos/Elastos.ELA/core/types/transactions" "sort" "time" @@ -95,7 +96,7 @@ func newGenesisBlock(ac *account.Account) *types.Block { []byte{77, 101, 130, 33, 7, 252, 253, 82}) genesisTime, _ := time.Parse(time.RFC3339, "2017-12-22T10:00:00Z") - coinBase := types.Transaction{ + coinBase := transactions.BaseTransaction{ Version: 0, TxType: common2.CoinBase, PayloadVersion: payload.CoinBaseVersion, @@ -134,7 +135,7 @@ func newGenesisBlock(ac *account.Account) *types.Block { Nonce: 2083236893, Height: 0, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ &coinBase, { TxType: common2.RegisterAsset, @@ -157,7 +158,7 @@ func newGenesisBlock(ac *account.Account) *types.Block { } func quickGenerateBlock(pow *pow.Service, prevHash *common.Uint256, - txs []*types.Transaction, minerAddr string, params *config.Params, + txs []*transactions.BaseTransaction, minerAddr string, params *config.Params, height uint32) (*types.Block, error) { coinBaseTx, err := pow.CreateCoinbaseTx(minerAddr, height) if err != nil { @@ -176,14 +177,14 @@ func quickGenerateBlock(pow *pow.Service, prevHash *common.Uint256, msgBlock := &types.Block{ Header: header, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, } msgBlock.Transactions = append(msgBlock.Transactions, coinBaseTx) totalTxsSize := coinBaseTx.GetSize() txCount := 1 totalTxFee := common.Fixed64(0) - isHighPriority := func(tx *types.Transaction) bool { + isHighPriority := func(tx *transactions.BaseTransaction) bool { if tx.IsIllegalTypeTx() || tx.IsInactiveArbitrators() || tx.IsSideChainPowTx() || tx.IsUpdateVersion() || tx.IsActivateProducerTx() { diff --git a/benchmark/tools/inputcounter/calculator/singleinputoutput.go b/benchmark/tools/inputcounter/calculator/singleinputoutput.go index da9c971b4..63a0dd7dc 100644 --- a/benchmark/tools/inputcounter/calculator/singleinputoutput.go +++ b/benchmark/tools/inputcounter/calculator/singleinputoutput.go @@ -9,12 +9,12 @@ import ( "github.com/elastos/Elastos.ELA/account" "github.com/elastos/Elastos.ELA/benchmark/common/tx" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" ) type singleInputOutput struct { - protoTx *types.Transaction + protoTx *transactions.BaseTransaction } func (s *singleInputOutput) initialSize() uint64 { @@ -32,7 +32,7 @@ func newSingleInputOutput() (*singleInputOutput, error) { }, err } -func createSingleInputOutputTx() (*types.Transaction, error) { +func createSingleInputOutputTx() (*transactions.BaseTransaction, error) { acc, err := account.NewAccount() if err != nil { return nil, err @@ -41,7 +41,7 @@ func createSingleInputOutputTx() (*types.Transaction, error) { generator := tx.NewGenerator(common2.TransferAsset, acc) txn := generator.Generate() - utxo := types.UTXO{ + utxo := common2.UTXO{ TxID: common.Uint256{}, Index: 0, Value: 100000000, diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index f924a6170..9e055d24b 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -11,6 +11,8 @@ import ( "errors" "fmt" "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math/big" "os" "path/filepath" @@ -327,9 +329,9 @@ func (b *BlockChain) InitCheckpoint(interrupt <-chan struct{}, return err } -func (b *BlockChain) createTransaction(pd Payload, txType common.TxType, +func (b *BlockChain) createTransaction(pd interfaces.Payload, txType common.TxType, fromAddress Uint168, fee Fixed64, lockedUntil uint32, - utxos []*UTXO, outputs ...*common.OutputInfo) (*Transaction, error) { + utxos []*common.UTXO, outputs ...*common.OutputInfo) (*transactions.BaseTransaction, error) { // check output if len(outputs) == 0 { return nil, errors.New("invalid transaction target") @@ -346,7 +348,7 @@ func (b *BlockChain) createTransaction(pd Payload, txType common.TxType, return nil, err } txOutputs = append(txOutputs, changeOutputs...) - return &Transaction{ + return &transactions.BaseTransaction{ Version: common.TxVersion09, TxType: txType, Payload: pd, @@ -378,8 +380,8 @@ func (b *BlockChain) createNormalOutputs(outputs []*common.OutputInfo, fee Fixed return txOutputs, totalAmount, nil } -func (b *BlockChain) getUTXOsFromAddress(address Uint168) ([]*UTXO, Fixed64, error) { - var utxoSlice []*UTXO +func (b *BlockChain) getUTXOsFromAddress(address Uint168) ([]*common.UTXO, Fixed64, error) { + var utxoSlice []*common.UTXO var lockedAmount Fixed64 utxos, err := b.db.GetFFLDB().GetUTXO(&address) if err != nil { @@ -409,7 +411,7 @@ func (b *BlockChain) getUTXOsFromAddress(address Uint168) ([]*UTXO, Fixed64, err } func (b *BlockChain) createInputs(fromAddress Uint168, - totalAmount Fixed64, utxos []*UTXO) ([]*common.Input, []*common.Output, error) { + totalAmount Fixed64, utxos []*common.UTXO) ([]*common.Input, []*common.Output, error) { var txInputs []*common.Input var changeOutputs []*common.Output for _, utxo := range utxos { @@ -448,7 +450,7 @@ func (b *BlockChain) createInputs(fromAddress Uint168, return txInputs, changeOutputs, nil } -func (b *BlockChain) CreateCRCAppropriationTransaction() (*Transaction, Fixed64, error) { +func (b *BlockChain) CreateCRCAppropriationTransaction() (*transactions.BaseTransaction, Fixed64, error) { utxos, lockedAmount, err := b.getUTXOsFromAddress(b.chainParams.CRAssetsAddress) if err != nil { return nil, 0, err @@ -467,7 +469,7 @@ func (b *BlockChain) CreateCRCAppropriationTransaction() (*Transaction, Fixed64, outputs := []*common.OutputInfo{{b.chainParams.CRExpensesAddress, appropriationAmount}} - var tx *Transaction + var tx *transactions.BaseTransaction tx, err = b.createTransaction(&payload.CRCAppropriation{}, common.CRCAppropriation, b.chainParams.CRAssetsAddress, Fixed64(0), uint32(0), utxos, outputs...) if err != nil { @@ -477,7 +479,7 @@ func (b *BlockChain) CreateCRCAppropriationTransaction() (*Transaction, Fixed64, } func (b *BlockChain) CreateCRRealWithdrawTransaction( - withdrawTransactionHashes []Uint256, outputs []*common.OutputInfo) (*Transaction, error) { + withdrawTransactionHashes []Uint256, outputs []*common.OutputInfo) (*transactions.BaseTransaction, error) { utxos, _, err := b.getUTXOsFromAddress(b.chainParams.CRExpensesAddress) if err != nil { return nil, err @@ -492,7 +494,7 @@ func (b *BlockChain) CreateCRRealWithdrawTransaction( } txFee := b.chainParams.RealWithdrawSingleFee * Fixed64(len(withdrawTransactionHashes)) - var tx *Transaction + var tx *transactions.BaseTransaction tx, err = b.createTransaction(wPayload, common.CRCProposalRealWithdraw, b.chainParams.CRExpensesAddress, txFee, uint32(0), utxos, outputs...) if err != nil { @@ -501,7 +503,7 @@ func (b *BlockChain) CreateCRRealWithdrawTransaction( return tx, nil } -func (b *BlockChain) CreateCRAssetsRectifyTransaction() (*Transaction, error) { +func (b *BlockChain) CreateCRAssetsRectifyTransaction() (*transactions.BaseTransaction, error) { utxos, _, err := b.getUTXOsFromAddress(b.chainParams.CRAssetsAddress) if err != nil { return nil, err @@ -528,7 +530,7 @@ func (b *BlockChain) CreateCRAssetsRectifyTransaction() (*Transaction, error) { outputs := []*common.OutputInfo{{b.chainParams.CRAssetsAddress, rectifyAmount}} - var tx *Transaction + var tx *transactions.BaseTransaction tx, err = b.createTransaction(&payload.CRAssetsRectify{}, common.CRAssetsRectify, b.chainParams.CRAssetsAddress, b.chainParams.RectifyTxFee, uint32(0), utxos, outputs...) if err != nil { diff --git a/blockchain/blockvalidator.go b/blockchain/blockvalidator.go index 71c09efc6..69792e255 100644 --- a/blockchain/blockvalidator.go +++ b/blockchain/blockvalidator.go @@ -9,6 +9,7 @@ import ( "bytes" "errors" "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "math/big" "strconv" @@ -237,7 +238,7 @@ func checkDuplicateTx(block *Block) error { return nil } -func RecordCRCProposalAmount(usedAmount *Fixed64, txn *Transaction) { +func RecordCRCProposalAmount(usedAmount *Fixed64, txn *transactions.BaseTransaction) { proposal, ok := txn.Payload.(*payload.CRCProposal) if !ok { return @@ -360,7 +361,7 @@ func CheckProofOfWork(header *Header, powLimit *big.Int) error { return nil } -func IsFinalizedTransaction(msgTx *Transaction, blockHeight uint32) bool { +func IsFinalizedTransaction(msgTx *transactions.BaseTransaction, blockHeight uint32) bool { // Lock time of zero means the transaction is finalized. lockTime := msgTx.LockTime if lockTime == 0 { @@ -383,7 +384,7 @@ func IsFinalizedTransaction(msgTx *Transaction, blockHeight uint32) bool { return true } -func GetTxFee(tx *Transaction, assetId Uint256, references map[*common.Input]common.Output) Fixed64 { +func GetTxFee(tx *transactions.BaseTransaction, assetId Uint256, references map[*common.Input]common.Output) Fixed64 { feeMap, err := GetTxFeeMap(tx, references) if err != nil { return 0 @@ -392,7 +393,7 @@ func GetTxFee(tx *Transaction, assetId Uint256, references map[*common.Input]com return feeMap[assetId] } -func GetTxFeeMap(tx *Transaction, references map[*common.Input]common.Output) (map[Uint256]Fixed64, error) { +func GetTxFeeMap(tx *transactions.BaseTransaction, references map[*common.Input]common.Output) (map[Uint256]Fixed64, error) { feeMap := make(map[Uint256]Fixed64) var inputs = make(map[Uint256]Fixed64) var outputs = make(map[Uint256]Fixed64) @@ -431,7 +432,7 @@ func GetTxFeeMap(tx *Transaction, references map[*common.Input]common.Output) (m return feeMap, nil } -func (b *BlockChain) checkCoinbaseTransactionContext(blockHeight uint32, coinbase *Transaction, totalTxFee Fixed64) error { +func (b *BlockChain) checkCoinbaseTransactionContext(blockHeight uint32, coinbase *transactions.BaseTransaction, totalTxFee Fixed64) error { // main version >= H2 if blockHeight >= b.chainParams.PublicDPOSHeight { totalReward := totalTxFee + b.chainParams.GetBlockReward(blockHeight) @@ -463,7 +464,7 @@ func (b *BlockChain) checkCoinbaseTransactionContext(blockHeight uint32, coinbas return nil } -func checkCoinbaseArbitratorsReward(coinbase *Transaction) error { +func checkCoinbaseArbitratorsReward(coinbase *transactions.BaseTransaction) error { rewards := DefaultLedger.Arbitrators.GetArbitersRoundReward() if len(rewards) != len(coinbase.Outputs)-2 { return errors.New("coinbase output count not match") diff --git a/blockchain/blockvalidator_test.go b/blockchain/blockvalidator_test.go index 157d9087f..023e5d1de 100644 --- a/blockchain/blockvalidator_test.go +++ b/blockchain/blockvalidator_test.go @@ -9,6 +9,7 @@ import ( "bytes" "encoding/hex" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "math/rand" "path/filepath" @@ -164,7 +165,7 @@ func TestCheckCoinbaseArbitratorsReward(t *testing.T) { totalTopProducersReward := dposTotalReward - totalBlockConfirmReward individualBlockConfirmReward := common.Fixed64(math.Floor(totalBlockConfirmReward / float64(5))) rewardPerVote := totalTopProducersReward / float64(totalVotesInRound) - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: 0, TxType: common2.CoinBase, } @@ -200,7 +201,7 @@ func TestCRDuplicateTx(t *testing.T) { TestRegisterCR := func(t *testing.T) { OneRegisterCRTest := func() { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) registerCRTxPointer := generateRegisterCR(code, cid, nickname) block.Transactions = append(block.Transactions, registerCRTxPointer) err := checkDuplicateTx(&block) @@ -210,7 +211,7 @@ func TestCRDuplicateTx(t *testing.T) { TwoRegisterCRTest := func() { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) registerCRTxPointer := generateRegisterCR(code, cid, nickname) block.Transactions = append(block.Transactions, registerCRTxPointer) block.Transactions = append(block.Transactions, registerCRTxPointer) @@ -224,7 +225,7 @@ func TestCRDuplicateTx(t *testing.T) { TestUpdateCR := func(t *testing.T) { OneUpdateCRTest := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) updateCRPointer := generateUpdateCR(code, cid, nickname) block.Transactions = append(block.Transactions, updateCRPointer) err := checkDuplicateTx(&block) @@ -234,7 +235,7 @@ func TestCRDuplicateTx(t *testing.T) { TwoUpdateCRTest := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) updateCRPointer := generateUpdateCR(code, cid, nickname) block.Transactions = append(block.Transactions, updateCRPointer) block.Transactions = append(block.Transactions, updateCRPointer) @@ -248,7 +249,7 @@ func TestCRDuplicateTx(t *testing.T) { TestUnregisterCR := func(t *testing.T) { OneUnregisterCR := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) unregisterCRPointer := generateUnregisterCR(code) block.Transactions = append(block.Transactions, unregisterCRPointer) err := checkDuplicateTx(&block) @@ -258,7 +259,7 @@ func TestCRDuplicateTx(t *testing.T) { TwoUnregisterCR := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) unregisterCRPointer := generateUnregisterCR(code) block.Transactions = append(block.Transactions, unregisterCRPointer) block.Transactions = append(block.Transactions, unregisterCRPointer) @@ -271,7 +272,7 @@ func TestCRDuplicateTx(t *testing.T) { OneRegisterOneUpdate := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) registerCRTxPointer := generateRegisterCR(code, cid, nickname) updateCRPointer := generateUpdateCR(code, cid, nickname) block.Transactions = append(block.Transactions, registerCRTxPointer) @@ -283,7 +284,7 @@ func TestCRDuplicateTx(t *testing.T) { OneRegisterOneUnregister := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) registerCRTxPointer := generateRegisterCR(code, cid, nickname) unregisterCRPointer := generateUnregisterCR(code) block.Transactions = append(block.Transactions, registerCRTxPointer) @@ -294,7 +295,7 @@ func TestCRDuplicateTx(t *testing.T) { OneRegisterOneUnregister(t) OneUpdateOneUnregister := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) updateCRPointer := generateUpdateCR(code, cid, nickname) unregisterCRPointer := generateUnregisterCR(code) block.Transactions = append(block.Transactions, updateCRPointer) @@ -310,7 +311,7 @@ func TestProducerDuplicateTx(t *testing.T) { TestRegisterProducer := func(t *testing.T) { OneRegisterProducerTest := func() { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) registerProducerTxPointer := generateRegisterProducer() block.Transactions = append(block.Transactions, registerProducerTxPointer) err := checkDuplicateTx(&block) @@ -320,7 +321,7 @@ func TestProducerDuplicateTx(t *testing.T) { TwoRegisterProducerTest := func() { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) registerProducerTxPointer := generateRegisterProducer() block.Transactions = append(block.Transactions, registerProducerTxPointer) block.Transactions = append(block.Transactions, registerProducerTxPointer) @@ -333,7 +334,7 @@ func TestProducerDuplicateTx(t *testing.T) { TestUpdateProducer := func(t *testing.T) { OneUpdateProducerTest := func() { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) updateProducerTxPointer := generateUpdateProducer() block.Transactions = append(block.Transactions, updateProducerTxPointer) err := checkDuplicateTx(&block) @@ -343,7 +344,7 @@ func TestProducerDuplicateTx(t *testing.T) { TwoUpdateProducerTest := func() { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) updateProducerTxPointer := generateUpdateProducer() block.Transactions = append(block.Transactions, updateProducerTxPointer) block.Transactions = append(block.Transactions, updateProducerTxPointer) @@ -356,7 +357,7 @@ func TestProducerDuplicateTx(t *testing.T) { TestCancelProducer := func(t *testing.T) { OneCancelProducerTest := func() { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) cancelProducerTxPointer := generateCancelProducer() block.Transactions = append(block.Transactions, cancelProducerTxPointer) err := checkDuplicateTx(&block) @@ -366,7 +367,7 @@ func TestProducerDuplicateTx(t *testing.T) { TwoCancelProducerTest := func() { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) cancelProducerTxPointer := generateCancelProducer() block.Transactions = append(block.Transactions, cancelProducerTxPointer) block.Transactions = append(block.Transactions, cancelProducerTxPointer) @@ -379,7 +380,7 @@ func TestProducerDuplicateTx(t *testing.T) { OneRegisterOneUpdate := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) registerProducerTxPointer := generateRegisterProducer() updateProducerTxPointer := generateUpdateProducer() block.Transactions = append(block.Transactions, registerProducerTxPointer) @@ -391,7 +392,7 @@ func TestProducerDuplicateTx(t *testing.T) { OneRegisterOneCancel := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) registerProducerTxPointer := generateRegisterProducer() cancelProducerTxPointer := generateCancelProducer() block.Transactions = append(block.Transactions, registerProducerTxPointer) @@ -402,7 +403,7 @@ func TestProducerDuplicateTx(t *testing.T) { OneRegisterOneCancel(t) OneUpdateOneCancel := func(t *testing.T) { var block types.Block - block.Transactions = make([]*types.Transaction, 0) + block.Transactions = make([]*transactions.BaseTransaction, 0) updateProducerTxPointer := generateUpdateProducer() cancelProducerTxPointer := generateCancelProducer() block.Transactions = append(block.Transactions, updateProducerTxPointer) @@ -413,10 +414,10 @@ func TestProducerDuplicateTx(t *testing.T) { OneUpdateOneCancel(t) } -func generateRegisterProducer() *types.Transaction { +func generateRegisterProducer() *transactions.BaseTransaction { publicKeyStr1 := "03c77af162438d4b7140f8544ad6523b9734cca9c7a62476d54ed5d1bddc7a39c3" publicKey1, _ := common.HexStringToBytes(publicKeyStr1) - return &types.Transaction{ + return &transactions.BaseTransaction{ TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ OwnerPublicKey: publicKey1, @@ -429,10 +430,10 @@ func generateRegisterProducer() *types.Transaction { } } -func generateUpdateProducer() *types.Transaction { +func generateUpdateProducer() *transactions.BaseTransaction { publicKeyStr1 := "03c77af162438d4b7140f8544ad6523b9734cca9c7a62476d54ed5d1bddc7a39c3" publicKey1, _ := common.HexStringToBytes(publicKeyStr1) - return &types.Transaction{ + return &transactions.BaseTransaction{ TxType: common2.UpdateProducer, Payload: &payload.ProducerInfo{ OwnerPublicKey: publicKey1, @@ -445,10 +446,10 @@ func generateUpdateProducer() *types.Transaction { } } -func generateCancelProducer() *types.Transaction { +func generateCancelProducer() *transactions.BaseTransaction { publicKeyStr1 := "03c77af162438d4b7140f8544ad6523b9734cca9c7a62476d54ed5d1bddc7a39c3" publicKey1, _ := common.HexStringToBytes(publicKeyStr1) - return &types.Transaction{ + return &transactions.BaseTransaction{ TxType: common2.CancelProducer, Payload: &payload.ProcessProducer{ OwnerPublicKey: publicKey1, @@ -457,8 +458,8 @@ func generateCancelProducer() *types.Transaction { } func generateRegisterCR(code []byte, cid common.Uint168, - nickname string) *types.Transaction { - return &types.Transaction{ + nickname string) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.RegisterCR, Payload: &payload.CRInfo{ Code: code, @@ -469,8 +470,8 @@ func generateRegisterCR(code []byte, cid common.Uint168, } func generateUpdateCR(code []byte, cid common.Uint168, - nickname string) *types.Transaction { - return &types.Transaction{ + nickname string) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.UpdateCR, Payload: &payload.CRInfo{ Code: code, @@ -480,8 +481,8 @@ func generateUpdateCR(code []byte, cid common.Uint168, } } -func generateUnregisterCR(code []byte) *types.Transaction { - return &types.Transaction{ +func generateUnregisterCR(code []byte) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.UnregisterCR, Payload: &payload.UnregisterCR{ CID: *getCID(code), diff --git a/blockchain/chainstore.go b/blockchain/chainstore.go index 85cfd337d..8785b9e00 100644 --- a/blockchain/chainstore.go +++ b/blockchain/chainstore.go @@ -10,6 +10,7 @@ import ( "encoding/hex" "errors" "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "path/filepath" "sync" "sync/atomic" @@ -64,7 +65,7 @@ func (c *ChainStore) CleanSmallCrossTransferTx(txHash Uint256) error { return c.levelDB.Delete(key.Bytes()) } -func (c *ChainStore) SaveSmallCrossTransferTx(tx *Transaction) error { +func (c *ChainStore) SaveSmallCrossTransferTx(tx *transactions.BaseTransaction) error { buf := new(bytes.Buffer) tx.Serialize(buf) var key bytes.Buffer @@ -74,13 +75,13 @@ func (c *ChainStore) SaveSmallCrossTransferTx(tx *Transaction) error { return nil } -func (c *ChainStore) GetSmallCrossTransferTxs() ([]*Transaction, error) { +func (c *ChainStore) GetSmallCrossTransferTxs() ([]*transactions.BaseTransaction, error) { Iter := c.levelDB.NewIterator(SMALL_CROSS_TRANSFER_RPEFIX) - txs := make([]*Transaction, 0) + txs := make([]*transactions.BaseTransaction, 0) for Iter.Next() { val := Iter.Value() r := bytes.NewReader(val) - tx := new(Transaction) + tx := new(transactions.BaseTransaction) if err := tx.Deserialize(r); err != nil { return nil, err } @@ -128,7 +129,7 @@ func (c *ChainStore) IsSidechainReturnDepositTxHashDuplicate(sidechainReturnDepo return c.GetFFLDB().IsSideChainReturnDepositExist(&sidechainReturnDepositTxHash) } -func (c *ChainStore) IsDoubleSpend(txn *Transaction) bool { +func (c *ChainStore) IsDoubleSpend(txn *transactions.BaseTransaction) bool { if len(txn.Inputs) == 0 { return false } @@ -162,7 +163,7 @@ func (c *ChainStore) RollbackBlock(b *Block, node *BlockNode, return err } -func (c *ChainStore) GetTransaction(txID Uint256) (*Transaction, uint32, error) { +func (c *ChainStore) GetTransaction(txID Uint256) (*transactions.BaseTransaction, uint32, error) { return c.fflDB.GetTransaction(txID) } @@ -170,7 +171,7 @@ func (c *ChainStore) GetProposalDraftDataByDraftHash(draftHash *Uint256) ([]byte return c.fflDB.GetProposalDraftDataByDraftHash(draftHash) } -func (c *ChainStore) GetTxReference(tx *Transaction) (map[*common.Input]*common.Output, error) { +func (c *ChainStore) GetTxReference(tx *transactions.BaseTransaction) (map[*common.Input]*common.Output, error) { if tx.TxType == common.RegisterAsset { return nil, nil } diff --git a/blockchain/chainstoreffldb.go b/blockchain/chainstoreffldb.go index 6039d23ee..6480a38f6 100644 --- a/blockchain/chainstoreffldb.go +++ b/blockchain/chainstoreffldb.go @@ -9,6 +9,7 @@ import ( "bytes" "errors" "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "os" "path/filepath" "sync" @@ -132,7 +133,7 @@ func (c *ChainStoreFFLDB) Close() error { return c.db.Close() } -func ProcessProposalDraftData(dbTx database.Tx, Transactions []*Transaction) (err error) { +func ProcessProposalDraftData(dbTx database.Tx, Transactions []*transactions.BaseTransaction) (err error) { //var err error for _, tx := range Transactions { switch tx.TxType { @@ -164,7 +165,7 @@ func ProcessProposalDraftData(dbTx database.Tx, Transactions []*Transaction) (er return err } -func RollbackProcessProposalDraftData(dbTx database.Tx, Transactions []*Transaction) (err error) { +func RollbackProcessProposalDraftData(dbTx database.Tx, Transactions []*transactions.BaseTransaction) (err error) { //var err error for _, tx := range Transactions { switch tx.TxType { @@ -451,7 +452,7 @@ func (c *ChainStoreFFLDB) GetProposalDraftDataByDraftHash(hash *Uint256) ([]byte return draftData, err } -func (c *ChainStoreFFLDB) GetTransaction(txID Uint256) (*Transaction, uint32, error) { +func (c *ChainStoreFFLDB) GetTransaction(txID Uint256) (*transactions.BaseTransaction, uint32, error) { return c.indexManager.FetchTx(txID) } @@ -463,7 +464,7 @@ func (c *ChainStoreFFLDB) GetUnspent(txID Uint256) ([]uint16, error) { return c.indexManager.FetchUnspent(txID) } -func (c *ChainStoreFFLDB) GetUTXO(programHash *Uint168) ([]*UTXO, error) { +func (c *ChainStoreFFLDB) GetUTXO(programHash *Uint168) ([]*common.UTXO, error) { return c.indexManager.FetchUTXO(programHash) } diff --git a/blockchain/indexers/common.go b/blockchain/indexers/common.go index d19ddcb1a..7cf4eb934 100644 --- a/blockchain/indexers/common.go +++ b/blockchain/indexers/common.go @@ -16,6 +16,8 @@ package indexers import ( "encoding/binary" "errors" + common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" @@ -59,13 +61,13 @@ type IndexManager interface { // FetchTx retrieval a transaction and a block hash where it // located by transaction hash - FetchTx(txID common.Uint256) (*types.Transaction, uint32, error) + FetchTx(txID common.Uint256) (*transactions.BaseTransaction, uint32, error) // FetchUnspent retrieval the unspent set of transaction by its hash FetchUnspent(txID common.Uint256) ([]uint16, error) // FetchUTXO retrieval the utxo set of a account address - FetchUTXO(programHash *common.Uint168) ([]*types.UTXO, error) + FetchUTXO(programHash *common.Uint168) ([]*common2.UTXO, error) // IsTx3Exist use to find if tx3 exist in db IsTx3Exist(txHash *common.Uint256) bool @@ -104,7 +106,7 @@ type Indexer interface { type ITxStore interface { // FetchTx retrieval a transaction and a block hash where it // located by transaction hash - FetchTx(txID common.Uint256) (*types.Transaction, uint32, error) + FetchTx(txID common.Uint256) (*transactions.BaseTransaction, uint32, error) } // AssertError identifies an error that indicates an internal code consistency diff --git a/blockchain/indexers/manager.go b/blockchain/indexers/manager.go index 14ac092ef..586309955 100644 --- a/blockchain/indexers/manager.go +++ b/blockchain/indexers/manager.go @@ -12,6 +12,8 @@ package indexers import ( "bytes" "fmt" + common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" @@ -472,7 +474,7 @@ func (m *Manager) DisconnectBlock(dbTx database.Tx, block *types.Block) error { return nil } -func (m *Manager) FetchTx(txID common.Uint256) (*types.Transaction, uint32, error) { +func (m *Manager) FetchTx(txID common.Uint256) (*transactions.BaseTransaction, uint32, error) { return m.txStore.FetchTx(txID) } @@ -490,8 +492,8 @@ func (m *Manager) FetchUnspent(txID common.Uint256) ([]uint16, error) { return indexes, nil } -func (m *Manager) FetchUTXO(programHash *common.Uint168) ([]*types.UTXO, error) { - var utxos []*types.UTXO +func (m *Manager) FetchUTXO(programHash *common.Uint168) ([]*common2.UTXO, error) { + var utxos []*common2.UTXO err := m.db.View(func(dbTx database.Tx) error { var err error utxos, err = dbFetchUtxoIndexEntry(dbTx, programHash) diff --git a/blockchain/indexers/returndepositindex_test.go b/blockchain/indexers/returndepositindex_test.go index d076d2010..0f992c7e6 100644 --- a/blockchain/indexers/returndepositindex_test.go +++ b/blockchain/indexers/returndepositindex_test.go @@ -6,6 +6,7 @@ package indexers import ( + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -30,7 +31,7 @@ var ( DepositTransactionHash: returnDepositHash, }, } - tx5 = &types.Transaction{ + tx5 = &transactions.BaseTransaction{ TxType: common2.ReturnSideChainDepositCoin, PayloadVersion: 0, Inputs: []*common2.Input{}, @@ -39,7 +40,7 @@ var ( testReturnDepositIndexBlock = &types.Block{ Header: types.Header{}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ tx5, }, } diff --git a/blockchain/indexers/tx3index_test.go b/blockchain/indexers/tx3index_test.go index 21a700e4f..4786f32d3 100644 --- a/blockchain/indexers/tx3index_test.go +++ b/blockchain/indexers/tx3index_test.go @@ -6,6 +6,7 @@ package indexers import ( + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -21,7 +22,7 @@ import ( var ( tx3Hash = common.Uint256{1, 2, 3} - tx4 = &types.Transaction{ + tx4 = &transactions.BaseTransaction{ TxType: common2.WithdrawFromSideChain, PayloadVersion: 0, Payload: &payload.WithdrawFromSideChain{ @@ -35,7 +36,7 @@ var ( testTx3IndexBlock = &types.Block{ Header: types.Header{}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ tx4, }, } diff --git a/blockchain/indexers/txcache.go b/blockchain/indexers/txcache.go index e0b9a65e5..590362a67 100644 --- a/blockchain/indexers/txcache.go +++ b/blockchain/indexers/txcache.go @@ -6,12 +6,12 @@ package indexers import ( + "github.com/elastos/Elastos.ELA/core/types/transactions" "io" "sync" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" - "github.com/elastos/Elastos.ELA/core/types" ) const ( @@ -24,7 +24,7 @@ const ( type TxInfo struct { blockHeight uint32 - txn *types.Transaction + txn *transactions.BaseTransaction } func (t *TxInfo) Serialize(w io.Writer) (err error) { @@ -40,7 +40,7 @@ func (t *TxInfo) Deserialize(r io.Reader) (err error) { if err != nil { return } - var txn types.Transaction + var txn transactions.BaseTransaction err = txn.Deserialize(r) if err != nil { return @@ -93,7 +93,7 @@ func (t *TxCache) Deserialize(r io.Reader) (err error) { return nil } -func (t *TxCache) setTxn(height uint32, txn *types.Transaction) { +func (t *TxCache) setTxn(height uint32, txn *transactions.BaseTransaction) { if t.params.NodeProfileStrategy == config.MemoryFirst.String() { return diff --git a/blockchain/indexers/txindex.go b/blockchain/indexers/txindex.go index d03f3f4d5..72d2159b6 100644 --- a/blockchain/indexers/txindex.go +++ b/blockchain/indexers/txindex.go @@ -14,6 +14,7 @@ import ( "bytes" "errors" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/log" @@ -296,7 +297,7 @@ func dbRemoveTxIndexEntries(dbTx database.Tx, block *types.Block) error { // dbFetchTx looks up the passed transaction hash in the transaction index and // loads it from the database. -func dbFetchTx(dbTx database.Tx, hash *common.Uint256) (*types.Transaction, *common.Uint256, error) { +func dbFetchTx(dbTx database.Tx, hash *common.Uint256) (*transactions.BaseTransaction, *common.Uint256, error) { // Look up the location of the transaction. blockRegion, err := dbFetchTxIndexEntry(dbTx, hash) if err != nil { @@ -313,7 +314,7 @@ func dbFetchTx(dbTx database.Tx, hash *common.Uint256) (*types.Transaction, *com } // Deserialize the transaction. - var txn types.Transaction + var txn transactions.BaseTransaction err = txn.Deserialize(bytes.NewReader(txBytes)) if err != nil { return nil, &common.EmptyHash, err diff --git a/blockchain/indexers/unspentindex.go b/blockchain/indexers/unspentindex.go index cac936f15..3aa2db788 100644 --- a/blockchain/indexers/unspentindex.go +++ b/blockchain/indexers/unspentindex.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" @@ -242,12 +243,12 @@ func (idx *UnspentIndex) DisconnectBlock(dbTx database.Tx, block *types.Block) e return nil } -func (idx *UnspentIndex) FetchTx(txID common.Uint256) (*types.Transaction, uint32, error) { +func (idx *UnspentIndex) FetchTx(txID common.Uint256) (*transactions.BaseTransaction, uint32, error) { if txnInfo := idx.txCache.getTxn(txID); txnInfo != nil { return txnInfo.txn, txnInfo.blockHeight, nil } - var txn *types.Transaction + var txn *transactions.BaseTransaction var height uint32 err := idx.db.View(func(dbTx database.Tx) error { var err error diff --git a/blockchain/indexers/unspentindex_test.go b/blockchain/indexers/unspentindex_test.go index 87cd70156..e1088399f 100644 --- a/blockchain/indexers/unspentindex_test.go +++ b/blockchain/indexers/unspentindex_test.go @@ -6,6 +6,7 @@ package indexers import ( + "github.com/elastos/Elastos.ELA/core/types/transactions" "os" "path/filepath" "testing" @@ -31,7 +32,7 @@ var ( unspentIndexReferIndex1 = uint16(1) unspentIndexReferIndex2 = uint16(2) unspentIndexReferIndex3 = uint16(3) - unspentIndexCoinbase = &types.Transaction{ + unspentIndexCoinbase = &transactions.BaseTransaction{ TxType: common2.CoinBase, Payload: new(payload.CoinBase), Inputs: nil, @@ -44,7 +45,7 @@ var ( }, }, } - testUnspentIndexTx1 = &types.Transaction{ + testUnspentIndexTx1 = &transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: new(payload.TransferAsset), Inputs: []*common2.Input{ @@ -64,7 +65,7 @@ var ( }, }, } - testUnspentIndexTx2 = &types.Transaction{ + testUnspentIndexTx2 = &transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: new(payload.TransferAsset), Inputs: []*common2.Input{ @@ -84,7 +85,7 @@ var ( }, }, } - testUnspentIndexTx3 = &types.Transaction{ + testUnspentIndexTx3 = &transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: new(payload.TransferAsset), Inputs: []*common2.Input{ @@ -106,14 +107,14 @@ var ( } unspentIndexBlock = &types.Block{ Header: types.Header{}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ unspentIndexCoinbase, testUnspentIndexTx1, testUnspentIndexTx2, testUnspentIndexTx3, }, } - testUnspentIndexTx4 = &types.Transaction{ + testUnspentIndexTx4 = &transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: new(payload.TransferAsset), Inputs: []*common2.Input{ @@ -136,13 +137,13 @@ var ( }, }, } - testUnspentIndexTx5 = &types.Transaction{ + testUnspentIndexTx5 = &transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: new(payload.TransferAsset), Inputs: []*common2.Input{}, Outputs: []*common2.Output{}, } - unspentIndexCoinbase2 = &types.Transaction{ + unspentIndexCoinbase2 = &transactions.BaseTransaction{ TxType: common2.CoinBase, Payload: new(payload.CoinBase), Inputs: nil, @@ -157,7 +158,7 @@ var ( } unspentIndexBlock2 = &types.Block{ Header: types.Header{}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ unspentIndexCoinbase2, testUnspentIndexTx4, testUnspentIndexTx5, @@ -188,10 +189,10 @@ func TestUnspentIndexInit(t *testing.T) { assert.NoError(t, err) err = dbPutUnspentIndexEntry(dbTx, &unspentIndexReferTx3, []uint16{unspentIndexReferIndex3}) assert.NoError(t, err) - //testUnspentIndex.txCache.setTxn(1, &types.Transaction{ + //testUnspentIndex.txCache.setTxn(1, &types.BaseTransaction{ // LockTime: 10, //}) - //testUnspentIndex.txCache.setTxn(1, &types.Transaction{ + //testUnspentIndex.txCache.setTxn(1, &types.BaseTransaction{ // LockTime: 20, //}) diff --git a/blockchain/indexers/utxoindex.go b/blockchain/indexers/utxoindex.go index 4eaa6eba9..1c3bf16c3 100644 --- a/blockchain/indexers/utxoindex.go +++ b/blockchain/indexers/utxoindex.go @@ -9,6 +9,7 @@ import ( "bytes" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/database" ) @@ -26,7 +27,7 @@ var ( // dbPutUtxoIndexEntry uses an existing database transaction to update the // index of utxo. func dbPutUtxoIndexEntry(dbTx database.Tx, programHash *common.Uint168, - height uint32, utxos []*types.UTXO) error { + height uint32, utxos []*common2.UTXO) error { utxoIndex := dbTx.Metadata().Bucket(utxoIndexKey) programHashIndex, err := utxoIndex.CreateBucketIfNotExists(programHash.Bytes()) if err != nil { @@ -53,13 +54,13 @@ func dbPutUtxoIndexEntry(dbTx database.Tx, programHash *common.Uint168, // utxos. When there is no entry for the provided hash, nil will be returned // for the both the index and the error. func dbFetchUtxoIndexEntry(dbTx database.Tx, programHash *common.Uint168) ( - []*types.UTXO, error) { + []*common2.UTXO, error) { // Load the record from the database and return now if it doesn't exist. programHashIndex := dbTx.Metadata().Bucket(utxoIndexKey).Bucket(programHash.Bytes()) if programHashIndex == nil { return nil, nil } - utxos := make([]*types.UTXO, 0) + utxos := make([]*common2.UTXO, 0) err := programHashIndex.ForEach(func(height, serializedData []byte) error { if len(serializedData) == 0 { return nil @@ -71,7 +72,7 @@ func dbFetchUtxoIndexEntry(dbTx database.Tx, programHash *common.Uint168) ( return err } for i := 0; i < int(count); i++ { - var utxo types.UTXO + var utxo common2.UTXO if err := utxo.Deserialize(r); err != nil { return err } @@ -90,7 +91,7 @@ func dbFetchUtxoIndexEntry(dbTx database.Tx, programHash *common.Uint168) ( // utxos. When there is no entry for the provided hash, nil will be returned // for the both the index and the error. func dbFetchUtxoIndexEntryByHeight(dbTx database.Tx, programHash *common.Uint168, - height uint32) ([]*types.UTXO, error) { + height uint32) ([]*common2.UTXO, error) { // Load the record from the database and return now if it doesn't exist. utxoIndex := dbTx.Metadata().Bucket(utxoIndexKey) programHashIndex, err := utxoIndex.CreateBucketIfNotExists(programHash.Bytes()) @@ -111,9 +112,9 @@ func dbFetchUtxoIndexEntryByHeight(dbTx database.Tx, programHash *common.Uint168 if err != nil { return nil, err } - utxos := make([]*types.UTXO, 0, count) + utxos := make([]*common2.UTXO, 0, count) for i := 0; i < int(count); i++ { - var utxo types.UTXO + var utxo common2.UTXO if err := utxo.Deserialize(r); err != nil { return nil, err } @@ -166,7 +167,7 @@ func (idx *UtxoIndex) Create(dbTx database.Tx) error { // // This is part of the Indexer interface. func (idx *UtxoIndex) ConnectBlock(dbTx database.Tx, block *types.Block) error { - utxoMap := make(map[common.Uint168]map[uint32][]*types.UTXO) + utxoMap := make(map[common.Uint168]map[uint32][]*common2.UTXO) for _, txn := range block.Transactions { // output process for i, output := range txn.Outputs { @@ -174,7 +175,7 @@ func (idx *UtxoIndex) ConnectBlock(dbTx database.Tx, block *types.Block) error { continue } if _, ok := utxoMap[output.ProgramHash]; !ok { - utxoMap[output.ProgramHash] = make(map[uint32][]*types.UTXO) + utxoMap[output.ProgramHash] = make(map[uint32][]*common2.UTXO) } utxos, ok := utxoMap[output.ProgramHash][block.Height] if !ok { @@ -185,7 +186,7 @@ func (idx *UtxoIndex) ConnectBlock(dbTx database.Tx, block *types.Block) error { return err } } - utxos = append(utxos, &types.UTXO{TxID: txn.Hash(), Index: uint16(i), + utxos = append(utxos, &common2.UTXO{TxID: txn.Hash(), Index: uint16(i), Value: output.Value}) utxoMap[output.ProgramHash][block.Height] = utxos } @@ -201,7 +202,7 @@ func (idx *UtxoIndex) ConnectBlock(dbTx database.Tx, block *types.Block) error { referOutput := referTx.Outputs[input.Previous.Index] // find the spent items and remove it if _, ok := utxoMap[referOutput.ProgramHash]; !ok { - utxoMap[referOutput.ProgramHash] = make(map[uint32][]*types.UTXO) + utxoMap[referOutput.ProgramHash] = make(map[uint32][]*common2.UTXO) } utxos, ok := utxoMap[referOutput.ProgramHash][height] if !ok { @@ -242,14 +243,14 @@ func (idx *UtxoIndex) ConnectBlock(dbTx database.Tx, block *types.Block) error { // // This is part of the Indexer interface. func (idx *UtxoIndex) DisconnectBlock(dbTx database.Tx, block *types.Block) error { - utxoMap := make(map[common.Uint168]map[uint32][]*types.UTXO) + utxoMap := make(map[common.Uint168]map[uint32][]*common2.UTXO) for _, txn := range block.Transactions { // output process for _, output := range txn.Outputs { if _, ok := utxoMap[output.ProgramHash]; !ok { - utxoMap[output.ProgramHash] = make(map[uint32][]*types.UTXO) + utxoMap[output.ProgramHash] = make(map[uint32][]*common2.UTXO) } - utxoMap[output.ProgramHash][block.Height] = []*types.UTXO{} + utxoMap[output.ProgramHash][block.Height] = []*common2.UTXO{} } // inputs process @@ -266,7 +267,7 @@ func (idx *UtxoIndex) DisconnectBlock(dbTx database.Tx, block *types.Block) erro continue } if _, ok := utxoMap[referOutput.ProgramHash]; !ok { - utxoMap[referOutput.ProgramHash] = make(map[uint32][]*types.UTXO) + utxoMap[referOutput.ProgramHash] = make(map[uint32][]*common2.UTXO) } utxos, ok := utxoMap[referOutput.ProgramHash][height] if !ok { @@ -275,7 +276,7 @@ func (idx *UtxoIndex) DisconnectBlock(dbTx database.Tx, block *types.Block) erro return err } } - utxos = append(utxos, &types.UTXO{ + utxos = append(utxos, &common2.UTXO{ TxID: input.Previous.TxID, Index: input.Previous.Index, Value: referOutput.Value, diff --git a/blockchain/indexers/utxoindex_test.go b/blockchain/indexers/utxoindex_test.go index d74cd2158..2178af08b 100644 --- a/blockchain/indexers/utxoindex_test.go +++ b/blockchain/indexers/utxoindex_test.go @@ -8,6 +8,7 @@ package indexers import ( "errors" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -28,7 +29,7 @@ var ( referRecipient2, _ = common.Uint168FromAddress("EKnWs1jyNdhzH65UST8qMo8ZpQrTpXGnLH") // refer tx hash: 160da301e49617c037ae9b630919af52b8ac458202cd64558af7e0dcc753e307 - testUtxoIndexReferTx = &types.Transaction{ + testUtxoIndexReferTx = &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, PayloadVersion: 0, @@ -72,7 +73,7 @@ var ( LockTime: 5, } recipient1, _ = common.Uint168FromAddress("EQr9qjiXGF2y7YMtDCHtHNewZynakbDzF7") - testUtxoIndexTx1 = &types.Transaction{ + testUtxoIndexTx1 = &transactions.BaseTransaction{ TxType: common2.CoinBase, Payload: new(payload.CoinBase), Inputs: nil, @@ -88,7 +89,7 @@ var ( }, } recipient2, _ = common.Uint168FromAddress("EWQfnxDhXQ4vHjncuAG5si2zpbKR79CjLp") - testUtxoIndexTx2 = &types.Transaction{ + testUtxoIndexTx2 = &transactions.BaseTransaction{ TxType: common2.TransferAsset, PayloadVersion: 0, Payload: &payload.TransferAsset{}, @@ -134,7 +135,7 @@ var ( Header: types.Header{ Height: 200, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ testUtxoIndexTx1, testUtxoIndexTx2, }, @@ -146,11 +147,11 @@ var ( ) type TestTxStore struct { - transactions map[common.Uint256]*types.Transaction + transactions map[common.Uint256]*transactions.BaseTransaction heights map[common.Uint256]uint32 } -func (s *TestTxStore) FetchTx(txID common.Uint256) (*types.Transaction, +func (s *TestTxStore) FetchTx(txID common.Uint256) (*transactions.BaseTransaction, uint32, error) { txn, exist := s.transactions[txID] if exist { @@ -159,7 +160,7 @@ func (s *TestTxStore) FetchTx(txID common.Uint256) (*types.Transaction, return nil, 0, errors.New("leveldb: not found") } -func (s *TestTxStore) SetTx(txn *types.Transaction, height uint32) { +func (s *TestTxStore) SetTx(txn *transactions.BaseTransaction, height uint32) { s.transactions[txn.Hash()] = txn s.heights[txn.Hash()] = height } @@ -170,7 +171,7 @@ func (s *TestTxStore) RemoveTx(txID common.Uint256) { func NewTestTxStore() *TestTxStore { var db TestTxStore - db.transactions = make(map[common.Uint256]*types.Transaction) + db.transactions = make(map[common.Uint256]*transactions.BaseTransaction) db.heights = make(map[common.Uint256]uint32) return &db } @@ -194,21 +195,21 @@ func TestUTXOIndexInit(t *testing.T) { assert.NoError(t, err) // initialize test utxo - utxos1 := make([]*types.UTXO, 0) - utxos2 := make([]*types.UTXO, 0) + utxos1 := make([]*common2.UTXO, 0) + utxos2 := make([]*common2.UTXO, 0) for i, output := range testUtxoIndexReferTx.Outputs { if output.Value == 0 { continue } if output.ProgramHash.IsEqual(*referRecipient1) { - utxos1 = append(utxos1, &types.UTXO{ + utxos1 = append(utxos1, &common2.UTXO{ TxID: testUtxoIndexReferTx.Hash(), Index: uint16(i), Value: output.Value, }) } if output.ProgramHash.IsEqual(*referRecipient2) { - utxos2 = append(utxos2, &types.UTXO{ + utxos2 = append(utxos2, &common2.UTXO{ TxID: testUtxoIndexReferTx.Hash(), Index: uint16(i), Value: output.Value, @@ -227,7 +228,7 @@ func TestUTXOIndexInit(t *testing.T) { utxos1, err = dbFetchUtxoIndexEntryByHeight(dbTx, referRecipient1, referHeight) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{ + assert.Equal(t, []*common2.UTXO{ { TxID: testUtxoIndexReferTx.Hash(), Index: 1, @@ -236,7 +237,7 @@ func TestUTXOIndexInit(t *testing.T) { }, utxos1) utxos2, err = dbFetchUtxoIndexEntryByHeight(dbTx, referRecipient2, referHeight) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{ + assert.Equal(t, []*common2.UTXO{ { TxID: testUtxoIndexReferTx.Hash(), Index: 2, @@ -264,10 +265,10 @@ func TestUtxoIndex_ConnectBlock(t *testing.T) { // input items should be removed from db inputUtxo1, err := dbFetchUtxoIndexEntry(dbTx, referRecipient1) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{}, inputUtxo1) + assert.Equal(t, []*common2.UTXO{}, inputUtxo1) inputUtxo2, err := dbFetchUtxoIndexEntry(dbTx, referRecipient2) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{ + assert.Equal(t, []*common2.UTXO{ { TxID: testUtxoIndexReferTx.Hash(), Index: 3, @@ -278,7 +279,7 @@ func TestUtxoIndex_ConnectBlock(t *testing.T) { // output items should be added in db outputUtxo1, err := dbFetchUtxoIndexEntry(dbTx, recipient1) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{ + assert.Equal(t, []*common2.UTXO{ { TxID: testUtxoIndexTx1.Hash(), Index: 0, @@ -297,7 +298,7 @@ func TestUtxoIndex_ConnectBlock(t *testing.T) { }, outputUtxo1) outputUtxo2, err := dbFetchUtxoIndexEntry(dbTx, recipient2) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{ + assert.Equal(t, []*common2.UTXO{ { TxID: testUtxoIndexTx2.Hash(), Index: 1, @@ -317,7 +318,7 @@ func TestUtxoIndex_DisconnectBlock(t *testing.T) { // input items should be added to db utxos1, err := dbFetchUtxoIndexEntry(dbTx, referRecipient1) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{ + assert.Equal(t, []*common2.UTXO{ { TxID: testUtxoIndexReferTx.Hash(), Index: 1, @@ -326,7 +327,7 @@ func TestUtxoIndex_DisconnectBlock(t *testing.T) { }, utxos1) utxos2, err := dbFetchUtxoIndexEntry(dbTx, referRecipient2) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{ + assert.Equal(t, []*common2.UTXO{ { TxID: testUtxoIndexReferTx.Hash(), Index: 3, @@ -342,10 +343,10 @@ func TestUtxoIndex_DisconnectBlock(t *testing.T) { // output items should be removed from db outputUtxo1, err := dbFetchUtxoIndexEntry(dbTx, recipient1) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{}, outputUtxo1) + assert.Equal(t, []*common2.UTXO{}, outputUtxo1) outputUtxo2, err := dbFetchUtxoIndexEntry(dbTx, recipient2) assert.NoError(t, err) - assert.Equal(t, []*types.UTXO{}, outputUtxo2) + assert.Equal(t, []*common2.UTXO{}, outputUtxo2) return nil }) diff --git a/blockchain/ledger.go b/blockchain/ledger.go index ed097bc4b..2564707a4 100644 --- a/blockchain/ledger.go +++ b/blockchain/ledger.go @@ -7,6 +7,7 @@ package blockchain import ( "errors" + "github.com/elastos/Elastos.ELA/core/types/transactions" "strconv" . "github.com/elastos/Elastos.ELA/common" @@ -29,7 +30,7 @@ type Ledger struct { } //check weather the transaction contains the doubleSpend. -func (l *Ledger) IsDoubleSpend(Tx *Transaction) bool { +func (l *Ledger) IsDoubleSpend(Tx *transactions.BaseTransaction) bool { return DefaultLedger.Store.IsDoubleSpend(Tx) } @@ -56,7 +57,7 @@ func (l *Ledger) GetBlockWithHash(hash Uint256) (*Block, error) { } //Get transaction with hash. -func (l *Ledger) GetTransactionWithHash(hash Uint256) (*Transaction, error) { +func (l *Ledger) GetTransactionWithHash(hash Uint256) (*transactions.BaseTransaction, error) { tx, _, err := l.Store.GetTransaction(hash) if err != nil { return nil, errors.New("[Ledger],GetTransactionWithHash failed with hash=" + hash.String()) diff --git a/blockchain/ledgerstore.go b/blockchain/ledgerstore.go index ba6747dca..723709266 100644 --- a/blockchain/ledgerstore.go +++ b/blockchain/ledgerstore.go @@ -7,6 +7,7 @@ package blockchain import ( "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "time" "github.com/elastos/Elastos.ELA/blockchain/indexers" @@ -22,15 +23,15 @@ type IChainStore interface { SaveBlock(b *Block, node *BlockNode, confirm *payload.Confirm, medianTimePast time.Time) error - IsDoubleSpend(tx *Transaction) bool + IsDoubleSpend(tx *transactions.BaseTransaction) bool GetConfirm(hash Uint256) (*payload.Confirm, error) RollbackBlock(b *Block, node *BlockNode, confirm *payload.Confirm, medianTimePast time.Time) error - GetTransaction(txID Uint256) (*Transaction, uint32, error) - GetTxReference(tx *Transaction) (map[*common.Input]*common.Output, error) + GetTransaction(txID Uint256) (*transactions.BaseTransaction, uint32, error) + GetTxReference(tx *transactions.BaseTransaction) (map[*common.Input]*common.Output, error) SetHeight(height uint32) GetHeight() uint32 @@ -41,8 +42,8 @@ type IChainStore interface { GetProposalDraftDataByDraftHash(draftHash *Uint256) ([]byte, error) - SaveSmallCrossTransferTx(tx *Transaction) error - GetSmallCrossTransferTxs() ([]*Transaction, error) + SaveSmallCrossTransferTx(tx *transactions.BaseTransaction) error + GetSmallCrossTransferTxs() ([]*transactions.BaseTransaction, error) GetSmallCrossTransferTx() ([]string, error) CleanSmallCrossTransferTx(txHash Uint256) error @@ -80,7 +81,7 @@ type IFFLDBChainStore interface { IsBlockInStore(hash *Uint256) bool // Get a transaction by transaction hash. - GetTransaction(txID Uint256) (*Transaction, uint32, error) + GetTransaction(txID Uint256) (*transactions.BaseTransaction, uint32, error) // InitIndex use to initialize the index manager. InitIndex(chain indexers.IChain, interrupt <-chan struct{}) error @@ -89,7 +90,7 @@ type IFFLDBChainStore interface { GetUnspent(txID Uint256) ([]uint16, error) // Get utxo by program hash. - GetUTXO(programHash *Uint168) ([]*UTXO, error) + GetUTXO(programHash *Uint168) ([]*common.UTXO, error) // IsTx3Exist use to find if tx3 exist in db. IsTx3Exist(txHash *Uint256) bool diff --git a/blockchain/txvalidator.go b/blockchain/txvalidator.go index 0dc7e8cd6..a7db1a403 100644 --- a/blockchain/txvalidator.go +++ b/blockchain/txvalidator.go @@ -11,6 +11,8 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "math/big" "sort" @@ -55,8 +57,8 @@ const ( ) type TransactionChecker interface { - CheckTransactionSanity(blockHeight uint32, txn *Transaction) elaerr.ELAError - CheckTransactionContext(blockHeight uint32, txn *Transaction, + CheckTransactionSanity(blockHeight uint32, txn *transactions.BaseTransaction) elaerr.ELAError + CheckTransactionContext(blockHeight uint32, txn *transactions.BaseTransaction, proposalsUsedAmount common.Fixed64, timeStamp uint32) ( map[*common2.Input]common2.Output, elaerr.ELAError) } @@ -67,7 +69,7 @@ type BaseChecker struct { // CheckTransactionSanity verifies received single transaction func (b *BlockChain) CheckTransactionSanity(blockHeight uint32, - txn *Transaction) elaerr.ELAError { + txn *transactions.BaseTransaction) elaerr.ELAError { if err := b.checkTxHeightVersion(txn, blockHeight); err != nil { log.Warn("[CheckTxHeightVersion],", err) return elaerr.Simple(elaerr.ErrTxHeightVersion, err) @@ -113,7 +115,7 @@ func (b *BlockChain) CheckTransactionSanity(blockHeight uint32, // CheckTransactionContext verifies a transaction with history transaction in ledger func (b *BlockChain) CheckTransactionContext(blockHeight uint32, - txn *Transaction, proposalsUsedAmount common.Fixed64, timeStamp uint32) ( + tx interfaces.Transaction, proposalsUsedAmount common.Fixed64, timeStamp uint32) ( map[*common2.Input]common2.Output, elaerr.ELAError) { //if err := b.checkTxHeightVersion(txn, blockHeight); err != nil { @@ -148,16 +150,9 @@ func (b *BlockChain) CheckTransactionContext(blockHeight uint32, // return nil, nil //} - para := &payload.CheckParameters{ - Version: txn.Version, - TxType: txn.TxType, - PayloadVersion: txn.PayloadVersion, - Attributes: txn.Attributes, - Inputs: txn.Inputs, - Outputs: txn.Outputs, - LockTime: txn.LockTime, - Programs: txn.Programs, - TxHash: txn.Hash(), + para := &interfaces.CheckParameters{ + Transaction: tx, + // todo 函数指针初始化 BlockHeight: blockHeight, CRCommitteeStartHeight: b.chainParams.CRCommitteeStartHeight, @@ -167,11 +162,13 @@ func (b *BlockChain) CheckTransactionContext(blockHeight uint32, FoundationAddress: b.chainParams.Foundation, } - references, contextErr := txn.Payload.ContextCheck(para) + references, contextErr := tx.ContextCheck(para) if contextErr != nil { return nil, contextErr } + txn := tx.(*transactions.BaseTransaction) + // //references, err := b.UTXOCache.GetTxReference(txn) //if err != nil { @@ -650,7 +647,7 @@ func checkDestructionAddress(references map[*common2.Input]common2.Output) error return nil } -func (b *BlockChain) checkInvalidUTXO(txn *Transaction) error { +func (b *BlockChain) checkInvalidUTXO(txn *transactions.BaseTransaction) error { currentHeight := DefaultLedger.Blockchain.GetHeight() for _, input := range txn.Inputs { referTxn, err := b.UTXOCache.GetTransaction(input.Previous.TxID) @@ -670,7 +667,7 @@ func (b *BlockChain) checkInvalidUTXO(txn *Transaction) error { } //validate the transaction of duplicate UTXO input -func checkTransactionInput(txn *Transaction) error { +func checkTransactionInput(txn *transactions.BaseTransaction) error { if txn.IsCoinBaseTx() { if len(txn.Inputs) != 1 { return errors.New("coinbase must has only one input") @@ -714,7 +711,7 @@ func checkTransactionInput(txn *Transaction) error { return nil } -func (b *BlockChain) checkCRCProposalWithdrawOutput(txn *Transaction) error { +func (b *BlockChain) checkCRCProposalWithdrawOutput(txn *transactions.BaseTransaction) error { withdrawPayload, ok := txn.Payload.(*payload.CRCProposalWithdraw) if !ok { return errors.New("checkCRCProposalWithdrawOutput invalid payload") @@ -727,7 +724,7 @@ func (b *BlockChain) checkCRCProposalWithdrawOutput(txn *Transaction) error { return nil } -func (b *BlockChain) checkTransactionOutput(txn *Transaction, +func (b *BlockChain) checkTransactionOutput(txn *transactions.BaseTransaction, blockHeight uint32) error { if len(txn.Outputs) > math.MaxUint16 { return errors.New("output count should not be greater than 65535(MaxUint16)") @@ -930,7 +927,7 @@ func checkOutputPayload(txType common2.TxType, output *common2.Output) error { return output.Payload.Validate() } -func checkTransactionUTXOLock(txn *Transaction, references map[*common2.Input]common2.Output) error { +func checkTransactionUTXOLock(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { for input, output := range references { if output.OutputLock == 0 { @@ -947,7 +944,7 @@ func checkTransactionUTXOLock(txn *Transaction, references map[*common2.Input]co return nil } -func checkTransactionDepositUTXO(txn *Transaction, references map[*common2.Input]common2.Output) error { +func checkTransactionDepositUTXO(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { for _, output := range references { if contract.GetPrefixType(output.ProgramHash) == contract.PrefixDeposit { if !txn.IsReturnDepositCoin() && !txn.IsReturnCRDepositCoinTx() { @@ -965,7 +962,7 @@ func checkTransactionDepositUTXO(txn *Transaction, references map[*common2.Input return nil } -func checkTransactionDepositOutpus(bc *BlockChain, txn *Transaction) error { +func checkTransactionDepositOutpus(bc *BlockChain, txn *transactions.BaseTransaction) error { for _, output := range txn.Outputs { if contract.GetPrefixType(output.ProgramHash) == contract.PrefixDeposit { if txn.IsRegisterProducerTx() || txn.IsRegisterCRTx() || @@ -987,7 +984,7 @@ func checkTransactionDepositOutpus(bc *BlockChain, txn *Transaction) error { return nil } -func checkTransactionSize(txn *Transaction) error { +func checkTransactionSize(txn *transactions.BaseTransaction) error { size := txn.GetSize() if size <= 0 || size > int(pact.MaxBlockContextSize) { return fmt.Errorf("Invalid transaction size: %d bytes", size) @@ -996,7 +993,7 @@ func checkTransactionSize(txn *Transaction) error { return nil } -func checkAssetPrecision(txn *Transaction) error { +func checkAssetPrecision(txn *transactions.BaseTransaction) error { for _, output := range txn.Outputs { if !checkAmountPrecise(output.Value, config.ELAPrecision) { return errors.New("the precision of asset is incorrect") @@ -1005,7 +1002,7 @@ func checkAssetPrecision(txn *Transaction) error { return nil } -func (b *BlockChain) getTransactionFee(tx *Transaction, +func (b *BlockChain) getTransactionFee(tx *transactions.BaseTransaction, references map[*common2.Input]common2.Output) common.Fixed64 { var outputValue common.Fixed64 var inputValue common.Fixed64 @@ -1026,7 +1023,7 @@ func (b *BlockChain) isSmallThanMinTransactionFee(fee common.Fixed64) bool { return false } -func (b *BlockChain) checkTransactionFee(tx *Transaction, references map[*common2.Input]common2.Output) error { +func (b *BlockChain) checkTransactionFee(tx *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { fee := b.getTransactionFee(tx, references) if b.isSmallThanMinTransactionFee(fee) { return fmt.Errorf("transaction fee not enough") @@ -1039,7 +1036,7 @@ func (b *BlockChain) checkTransactionFee(tx *Transaction, references map[*common return nil } -func (b *BlockChain) checkAttributeProgram(tx *Transaction, +func (b *BlockChain) checkAttributeProgram(tx *transactions.BaseTransaction, blockHeight uint32) error { switch tx.TxType { case common2.CoinBase: @@ -1126,7 +1123,7 @@ func (b *BlockChain) checkAttributeProgram(tx *Transaction, return nil } -func checkTransactionSignature(tx *Transaction, references map[*common2.Input]common2.Output) error { +func checkTransactionSignature(tx *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { programHashes, err := GetTxProgramHashes(tx, references) if (tx.IsCRCProposalWithdrawTx() && tx.PayloadVersion == payload.CRCProposalWithdrawDefault) || tx.IsCRAssetsRectifyTx() || tx.IsCRCProposalRealWithdrawTx() || tx.IsNextTurnDPOSInfoTx() { @@ -1149,7 +1146,7 @@ func checkAmountPrecise(amount common.Fixed64, precision byte) bool { return amount.IntValue()%int64(math.Pow(10, float64(8-precision))) == 0 } -func (b *BlockChain) checkTransactionPayload(txn *Transaction) error { +func (b *BlockChain) checkTransactionPayload(txn *transactions.BaseTransaction) error { switch pld := txn.Payload.(type) { case *payload.RegisterAsset: if pld.Asset.Precision < payload.MinPrecision || pld.Asset.Precision > payload.MaxPrecision { @@ -1194,7 +1191,7 @@ func (b *BlockChain) checkTransactionPayload(txn *Transaction) error { return nil } -func checkSchnorrWithdrawFromSidechain(txn *Transaction, pld *payload.WithdrawFromSideChain) error { +func checkSchnorrWithdrawFromSidechain(txn *transactions.BaseTransaction, pld *payload.WithdrawFromSideChain) error { var pxArr []*big.Int var pyArr []*big.Int for _, index := range pld.Signers { @@ -1230,7 +1227,7 @@ func checkSchnorrWithdrawFromSidechain(txn *Transaction, pld *payload.WithdrawFr } // validate the transaction of duplicate sidechain transaction -func checkDuplicateSidechainTx(txn *Transaction) error { +func checkDuplicateSidechainTx(txn *transactions.BaseTransaction) error { if txn.IsWithdrawFromSideChainTx() { witPayload := txn.Payload.(*payload.WithdrawFromSideChain) existingHashs := make(map[common.Uint256]struct{}) @@ -1244,7 +1241,7 @@ func checkDuplicateSidechainTx(txn *Transaction) error { return nil } -func (b *BlockChain) checkPOWConsensusTransaction(txn *Transaction, references map[*common2.Input]common2.Output) error { +func (b *BlockChain) checkPOWConsensusTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { if b.state.GetConsensusAlgorithm() != state.POW { return nil } @@ -1302,7 +1299,7 @@ func (b *BlockChain) checkPOWConsensusTransaction(txn *Transaction, references m } // validate the type of transaction is allowed or not at current height. -func (b *BlockChain) checkTxHeightVersion(txn *Transaction, blockHeight uint32) error { +func (b *BlockChain) checkTxHeightVersion(txn *transactions.BaseTransaction, blockHeight uint32) error { switch txn.TxType { case common2.RevertToPOW, common2.RevertToDPOS: if blockHeight < b.chainParams.RevertToPOWStartHeight { @@ -1444,7 +1441,7 @@ func (b *BlockChain) checkTxHeightVersion(txn *Transaction, blockHeight uint32) return nil } -func CheckSideChainPowConsensus(txn *Transaction, arbitrator []byte) error { +func CheckSideChainPowConsensus(txn *transactions.BaseTransaction, arbitrator []byte) error { payloadSideChainPow, ok := txn.Payload.(*payload.SideChainPow) if !ok { return errors.New("side mining transaction has invalid payload") @@ -1473,7 +1470,7 @@ func CheckSideChainPowConsensus(txn *Transaction, arbitrator []byte) error { return nil } -func (b *BlockChain) checkWithdrawFromSideChainTransaction(txn *Transaction, references map[*common2.Input]common2.Output, height uint32) error { +func (b *BlockChain) checkWithdrawFromSideChainTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output, height uint32) error { if txn.PayloadVersion == payload.WithdrawFromSideChainVersion { return b.checkWithdrawFromSideChainTransactionV0(txn, references, height) @@ -1486,7 +1483,7 @@ func (b *BlockChain) checkWithdrawFromSideChainTransaction(txn *Transaction, ref return errors.New("invalid payload version") } -func (b *BlockChain) checkWithdrawFromSideChainTransactionV1(txn *Transaction, references map[*common2.Input]common2.Output, height uint32) error { +func (b *BlockChain) checkWithdrawFromSideChainTransactionV1(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output, height uint32) error { for _, output := range txn.Outputs { if output.Type != common2.OTWithdrawFromSideChain { continue @@ -1541,7 +1538,7 @@ func (b *BlockChain) checkWithdrawFromSideChainTransactionV1(txn *Transaction, r return nil } -func (b *BlockChain) checkWithdrawFromSideChainTransactionV0(txn *Transaction, references map[*common2.Input]common2.Output, height uint32) error { +func (b *BlockChain) checkWithdrawFromSideChainTransactionV0(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output, height uint32) error { witPayload, ok := txn.Payload.(*payload.WithdrawFromSideChain) if !ok { return errors.New("Invalid withdraw from side chain payload type") @@ -1601,7 +1598,7 @@ func (b *BlockChain) checkWithdrawFromSideChainTransactionV0(txn *Transaction, r return nil } -func (b *BlockChain) checkWithdrawFromSideChainTransactionV2(txn *Transaction, references map[*common2.Input]common2.Output) error { +func (b *BlockChain) checkWithdrawFromSideChainTransactionV2(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { pld, ok := txn.Payload.(*payload.WithdrawFromSideChain) if !ok { return errors.New("Invalid withdraw from side chain payload type") @@ -1657,7 +1654,7 @@ func (b *BlockChain) checkCrossChainArbitrators(publicKeys [][]byte) error { return nil } -func (b *BlockChain) checkTransferCrossChainAssetTransaction(txn *Transaction, references map[*common2.Input]common2.Output, +func (b *BlockChain) checkTransferCrossChainAssetTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output, blockHeight uint32) error { if txn.PayloadVersion > payload.TransferCrossChainVersionV1 { return errors.New("invalid payload version") @@ -1667,7 +1664,7 @@ func (b *BlockChain) checkTransferCrossChainAssetTransaction(txn *Transaction, r return b.checkTransferCrossChainAssetTransactionV0(txn, references) } -func (b *BlockChain) checkTransferCrossChainAssetTransactionV1(txn *Transaction, references map[*common2.Input]common2.Output, +func (b *BlockChain) checkTransferCrossChainAssetTransactionV1(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output, blockHeight uint32) error { if txn.Version < common2.TxVersion09 { return errors.New("invalid transaction version") @@ -1713,7 +1710,7 @@ func (b *BlockChain) checkTransferCrossChainAssetTransactionV1(txn *Transaction, return nil } -func (b *BlockChain) checkTransferCrossChainAssetTransactionV0(txn *Transaction, references map[*common2.Input]common2.Output) error { +func (b *BlockChain) checkTransferCrossChainAssetTransactionV0(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { payloadObj, ok := txn.Payload.(*payload.TransferCrossChainAsset) if !ok { return errors.New("Invalid transfer cross chain asset payload type") @@ -1812,7 +1809,7 @@ func (b *BlockChain) ConvertToArbitersStr(arbiters [][]byte) []string { return arbitersStr } -func (b *BlockChain) checkCustomIDResultTransaction(txn *Transaction) error { +func (b *BlockChain) checkCustomIDResultTransaction(txn *transactions.BaseTransaction) error { if !DefaultLedger.Committee.IsCustomIDResultNeeded() { return errors.New("should not have custom ID result transaction") } @@ -1837,7 +1834,7 @@ func (b *BlockChain) checkCustomIDResultTransaction(txn *Transaction) error { return nil } -func (b *BlockChain) checkNextTurnDPOSInfoTransaction(txn *Transaction) error { +func (b *BlockChain) checkNextTurnDPOSInfoTransaction(txn *transactions.BaseTransaction) error { nextTurnDPOSInfo, ok := txn.Payload.(*payload.NextTurnDPOSInfo) if !ok { return errors.New("invalid NextTurnDPOSInfo payload") @@ -1858,7 +1855,7 @@ func (b *BlockChain) checkNextTurnDPOSInfoTransaction(txn *Transaction) error { return nil } -func (b *BlockChain) checkRegisterProducerTransaction(txn *Transaction) error { +func (b *BlockChain) checkRegisterProducerTransaction(txn *transactions.BaseTransaction) error { info, ok := txn.Payload.(*payload.ProducerInfo) if !ok { return errors.New("invalid payload") @@ -1957,7 +1954,7 @@ func (b *BlockChain) checkRegisterProducerTransaction(txn *Transaction) error { return nil } -func (b *BlockChain) checkProcessProducer(txn *Transaction) ( +func (b *BlockChain) checkProcessProducer(txn *transactions.BaseTransaction) ( *state.Producer, error) { processProducer, ok := txn.Payload.(*payload.ProcessProducer) if !ok { @@ -2005,7 +2002,7 @@ func (b *BlockChain) checkActivateProducerSignature(activateProducer *payload.Ac return nil } -func (b *BlockChain) checkCancelProducerTransaction(txn *Transaction) error { +func (b *BlockChain) checkCancelProducerTransaction(txn *transactions.BaseTransaction) error { producer, err := b.checkProcessProducer(txn) if err != nil { return err @@ -2019,7 +2016,7 @@ func (b *BlockChain) checkCancelProducerTransaction(txn *Transaction) error { return nil } -func (b *BlockChain) checkActivateProducerTransaction(txn *Transaction, +func (b *BlockChain) checkActivateProducerTransaction(txn *transactions.BaseTransaction, height uint32) error { activateProducer, ok := txn.Payload.(*payload.ActivateProducer) @@ -2104,7 +2101,7 @@ func (b *BlockChain) checkActivateProducerTransaction(txn *Transaction, return nil } -func (b *BlockChain) checkUpdateProducerTransaction(txn *Transaction) error { +func (b *BlockChain) checkUpdateProducerTransaction(txn *transactions.BaseTransaction) error { info, ok := txn.Payload.(*payload.ProducerInfo) if !ok { return errors.New("invalid payload") @@ -2190,7 +2187,7 @@ func getDIDFromCode(code []byte) (*common.Uint168, error) { } } -func (b *BlockChain) checkRegisterCRTransaction(txn *Transaction, +func (b *BlockChain) checkRegisterCRTransaction(txn *transactions.BaseTransaction, blockHeight uint32) error { info, ok := txn.Payload.(*payload.CRInfo) if !ok { @@ -2290,7 +2287,7 @@ func (b *BlockChain) checkRegisterCRTransaction(txn *Transaction, return nil } -func (b *BlockChain) checkUpdateCRTransaction(txn *Transaction, +func (b *BlockChain) checkUpdateCRTransaction(txn *transactions.BaseTransaction, blockHeight uint32) error { info, ok := txn.Payload.(*payload.CRInfo) if !ok { @@ -2360,7 +2357,7 @@ func (b *BlockChain) checkUpdateCRTransaction(txn *Transaction, return nil } -func (b *BlockChain) checkCRCProposalReviewTransaction(txn *Transaction, +func (b *BlockChain) checkCRCProposalReviewTransaction(txn *transactions.BaseTransaction, blockHeight uint32) error { crcProposalReview, ok := txn.Payload.(*payload.CRCProposalReview) if !ok { @@ -2434,7 +2431,7 @@ func getDiDFromPublicKey(publicKey []byte) (*common.Uint168, error) { } } -func (b *BlockChain) checkCRCProposalWithdrawTransaction(txn *Transaction, +func (b *BlockChain) checkCRCProposalWithdrawTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output, blockHeight uint32) error { if txn.PayloadVersion == payload.CRCProposalWithdrawDefault { @@ -2520,7 +2517,7 @@ func (b *BlockChain) checkCRCProposalWithdrawTransaction(txn *Transaction, return checkCRTransactionSignature(withdrawPayload.Signature, code, signedBuf.Bytes()) } -func (b *BlockChain) checkCRCProposalTrackingTransaction(txn *Transaction, +func (b *BlockChain) checkCRCProposalTrackingTransaction(txn *transactions.BaseTransaction, blockHeight uint32) error { cptPayload, ok := txn.Payload.(*payload.CRCProposalTracking) if !ok { @@ -2586,7 +2583,7 @@ func (b *BlockChain) checkCRCProposalTrackingTransaction(txn *Transaction, return result } -func (b *BlockChain) checkCRCAppropriationTransaction(txn *Transaction, +func (b *BlockChain) checkCRCAppropriationTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { // Check if current session has appropriated. if !b.crCommittee.IsAppropriationNeeded() { @@ -2627,7 +2624,7 @@ func (b *BlockChain) checkCRCAppropriationTransaction(txn *Transaction, return nil } -func (b *BlockChain) checkCRCProposalRealWithdrawTransaction(txn *Transaction, +func (b *BlockChain) checkCRCProposalRealWithdrawTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { crcRealWithdraw, ok := txn.Payload.(*payload.CRCProposalRealWithdraw) if !ok { @@ -2688,7 +2685,7 @@ func (b *BlockChain) checkCRCProposalRealWithdrawTransaction(txn *Transaction, return nil } -func (b *BlockChain) checkCRAssetsRectifyTransaction(txn *Transaction, +func (b *BlockChain) checkCRAssetsRectifyTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output) error { // Inputs count should be less than or equal to MaxCRAssetsAddressUTXOCount if len(txn.Inputs) > int(b.chainParams.MaxCRAssetsAddressUTXOCount) { @@ -2731,7 +2728,7 @@ func (b *BlockChain) checkCRAssetsRectifyTransaction(txn *Transaction, return nil } -func (b *BlockChain) checkReturnSideChainDepositTransaction(txn *Transaction) error { +func (b *BlockChain) checkReturnSideChainDepositTransaction(txn *transactions.BaseTransaction) error { _, ok := txn.Payload.(*payload.ReturnSideChainDepositCoin) if !ok { return errors.New("invalid payload") @@ -2814,7 +2811,7 @@ func (b *BlockChain) checkReturnSideChainDepositTransaction(txn *Transaction) er return nil } -func (b *BlockChain) checkRevertToPOWTransaction(txn *Transaction, blockHeight uint32, timeStamp uint32) error { +func (b *BlockChain) checkRevertToPOWTransaction(txn *transactions.BaseTransaction, blockHeight uint32, timeStamp uint32) error { p, ok := txn.Payload.(*payload.RevertToPOW) if !ok { return errors.New("invalid payload") @@ -2853,7 +2850,7 @@ func (b *BlockChain) checkRevertToPOWTransaction(txn *Transaction, blockHeight u return nil } -func (b *BlockChain) checkCRCouncilMemberClaimNodeTransaction(txn *Transaction) error { +func (b *BlockChain) checkCRCouncilMemberClaimNodeTransaction(txn *transactions.BaseTransaction) error { manager, ok := txn.Payload.(*payload.CRCouncilMemberClaimNode) if !ok { return errors.New("invalid payload") @@ -3142,7 +3139,7 @@ func (b *BlockChain) checkSecretaryGeneralSignature( return nil } -func (b *BlockChain) checkUnRegisterCRTransaction(txn *Transaction, +func (b *BlockChain) checkUnRegisterCRTransaction(txn *transactions.BaseTransaction, blockHeight uint32) error { info, ok := txn.Payload.(*payload.UnregisterCR) if !ok { @@ -3654,7 +3651,7 @@ func (b *BlockChain) checkNormalOrELIPProposal(proposal *payload.CRCProposal, pr return b.checkOwnerAndCRCouncilMemberSign(proposal, crCouncilMember.Info.Code, PayloadVersion) } -func (b *BlockChain) checkCRCProposalTransaction(txn *Transaction, +func (b *BlockChain) checkCRCProposalTransaction(txn *transactions.BaseTransaction, blockHeight uint32, proposalsUsedAmount common.Fixed64) error { proposal, ok := txn.Payload.(*payload.CRCProposal) if !ok { @@ -3798,7 +3795,7 @@ func (b *BlockChain) additionalProducerInfoCheck( return nil } -func (b *BlockChain) checkReturnDepositCoinTransaction(txn *Transaction, +func (b *BlockChain) checkReturnDepositCoinTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output, currentHeight uint32) error { var inputValue common.Fixed64 @@ -3844,7 +3841,7 @@ func (b *BlockChain) checkReturnDepositCoinTransaction(txn *Transaction, return nil } -func (b *BlockChain) checkReturnCRDepositCoinTransaction(txn *Transaction, +func (b *BlockChain) checkReturnCRDepositCoinTransaction(txn *transactions.BaseTransaction, references map[*common2.Input]common2.Output, currentHeight uint32) error { var inputValue common.Fixed64 @@ -3897,7 +3894,7 @@ func (b *BlockChain) checkReturnCRDepositCoinTransaction(txn *Transaction, return nil } -func (b *BlockChain) checkIllegalProposalsTransaction(txn *Transaction) error { +func (b *BlockChain) checkIllegalProposalsTransaction(txn *transactions.BaseTransaction) error { p, ok := txn.Payload.(*payload.DPOSIllegalProposals) if !ok { return errors.New("invalid payload") @@ -3910,7 +3907,7 @@ func (b *BlockChain) checkIllegalProposalsTransaction(txn *Transaction) error { return CheckDPOSIllegalProposals(p) } -func (b *BlockChain) checkIllegalVotesTransaction(txn *Transaction) error { +func (b *BlockChain) checkIllegalVotesTransaction(txn *transactions.BaseTransaction) error { p, ok := txn.Payload.(*payload.DPOSIllegalVotes) if !ok { return errors.New("invalid payload") @@ -3923,7 +3920,7 @@ func (b *BlockChain) checkIllegalVotesTransaction(txn *Transaction) error { return CheckDPOSIllegalVotes(p) } -func (b *BlockChain) checkIllegalBlocksTransaction(txn *Transaction) error { +func (b *BlockChain) checkIllegalBlocksTransaction(txn *transactions.BaseTransaction) error { p, ok := txn.Payload.(*payload.DPOSIllegalBlocks) if !ok { return errors.New("invalid payload") @@ -3937,7 +3934,7 @@ func (b *BlockChain) checkIllegalBlocksTransaction(txn *Transaction) error { } func (b *BlockChain) checkInactiveArbitratorsTransaction( - txn *Transaction) error { + txn *transactions.BaseTransaction) error { if b.state.SpecialTxExists(txn) { return errors.New("tx already exists") @@ -3946,12 +3943,12 @@ func (b *BlockChain) checkInactiveArbitratorsTransaction( return CheckInactiveArbitrators(txn) } -func CheckRevertToDPOSTransaction(txn *Transaction) error { +func CheckRevertToDPOSTransaction(txn *transactions.BaseTransaction) error { return checkArbitratorsSignatures(txn.Programs[0]) } func (b *BlockChain) checkRevertToDPOSTransaction( - blockHeight uint32, txn *Transaction) error { + blockHeight uint32, txn *transactions.BaseTransaction) error { p, ok := txn.Payload.(*payload.RevertToDPOS) if !ok { return errors.New("invalid payload.RevertToDPOS") @@ -3974,7 +3971,7 @@ func (b *BlockChain) checkRevertToDPOSTransaction( return CheckRevertToDPOSTransaction(txn) } -func (b *BlockChain) checkUpdateVersionTransaction(txn *Transaction) error { +func (b *BlockChain) checkUpdateVersionTransaction(txn *transactions.BaseTransaction) error { payload, ok := txn.Payload.(*payload.UpdateVersion) if !ok { return errors.New("invalid payload") @@ -3988,7 +3985,7 @@ func (b *BlockChain) checkUpdateVersionTransaction(txn *Transaction) error { return checkCRCArbitratorsSignatures(txn.Programs[0]) } -func (b *BlockChain) checkSidechainIllegalEvidenceTransaction(txn *Transaction) error { +func (b *BlockChain) checkSidechainIllegalEvidenceTransaction(txn *transactions.BaseTransaction) error { p, ok := txn.Payload.(*payload.SidechainIllegalData) if !ok { return errors.New("invalid payload") @@ -4036,7 +4033,7 @@ func CheckSidechainIllegalEvidence(p *payload.SidechainIllegalData) error { return nil } -func CheckInactiveArbitrators(txn *Transaction) error { +func CheckInactiveArbitrators(txn *transactions.BaseTransaction) error { p, ok := txn.Payload.(*payload.InactiveArbitrators) if !ok { return errors.New("invalid payload") diff --git a/blockchain/txvalidator_specailtx_test.go b/blockchain/txvalidator_specailtx_test.go index 5faf76274..b6abb6568 100644 --- a/blockchain/txvalidator_specailtx_test.go +++ b/blockchain/txvalidator_specailtx_test.go @@ -7,6 +7,7 @@ package blockchain import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math/rand" "path/filepath" "strconv" @@ -680,7 +681,7 @@ func (s *txValidatorSpecialTxTestSuite) TestCheckInactiveArbitrators() { p := &payload.InactiveArbitrators{ Sponsor: randomPublicKey(), } - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Payload: p, Programs: []*program.Program{ { @@ -759,7 +760,7 @@ func (s *txValidatorSpecialTxTestSuite) TestCheckInactiveArbitrators() { } func (s *txValidatorSpecialTxTestSuite) TestCheckUpdateVersion() { - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Programs: []*program.Program{ { Code: randomPublicKey(), diff --git a/blockchain/txvalidator_test.go b/blockchain/txvalidator_test.go index 94f5e230a..6a0996823 100644 --- a/blockchain/txvalidator_test.go +++ b/blockchain/txvalidator_test.go @@ -14,6 +14,7 @@ import ( "encoding/hex" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" mrand "math/rand" "net" @@ -112,13 +113,13 @@ func (s *txValidatorTestSuite) TestCheckTxHeightVersion() { blockHeight3 := s.Chain.chainParams.RegisterCRByDIDHeight // check height version of registerCR transaction. - registerCR := &types.Transaction{TxType: common2.RegisterCR} + registerCR := &transactions.BaseTransaction{TxType: common2.RegisterCR} err := s.Chain.checkTxHeightVersion(registerCR, blockHeight1) s.EqualError(err, "not support RegisterCR transaction before CRVotingStartHeight") err = s.Chain.checkTxHeightVersion(registerCR, blockHeight2) s.NoError(err) - registerCR2 := &types.Transaction{TxType: common2.RegisterCR, + registerCR2 := &transactions.BaseTransaction{TxType: common2.RegisterCR, PayloadVersion: payload.CRInfoDIDVersion} err = s.Chain.checkTxHeightVersion(registerCR2, blockHeight1) s.EqualError(err, "not support RegisterCR transaction before CRVotingStartHeight") @@ -126,28 +127,28 @@ func (s *txValidatorTestSuite) TestCheckTxHeightVersion() { s.NoError(err) // check height version of updateCR transaction. - updateCR := &types.Transaction{TxType: common2.UpdateCR} + updateCR := &transactions.BaseTransaction{TxType: common2.UpdateCR} err = s.Chain.checkTxHeightVersion(updateCR, blockHeight1) s.EqualError(err, "not support UpdateCR transaction before CRVotingStartHeight") err = s.Chain.checkTxHeightVersion(updateCR, blockHeight2) s.NoError(err) // check height version of unregister transaction. - unregisterCR := &types.Transaction{TxType: common2.UnregisterCR} + unregisterCR := &transactions.BaseTransaction{TxType: common2.UnregisterCR} err = s.Chain.checkTxHeightVersion(unregisterCR, blockHeight1) s.EqualError(err, "not support UnregisterCR transaction before CRVotingStartHeight") err = s.Chain.checkTxHeightVersion(unregisterCR, blockHeight2) s.NoError(err) // check height version of unregister transaction. - returnCoin := &types.Transaction{TxType: common2.ReturnCRDepositCoin} + returnCoin := &transactions.BaseTransaction{TxType: common2.ReturnCRDepositCoin} err = s.Chain.checkTxHeightVersion(returnCoin, blockHeight1) s.EqualError(err, "not support ReturnCRDepositCoin transaction before CRVotingStartHeight") err = s.Chain.checkTxHeightVersion(returnCoin, blockHeight2) s.NoError(err) // check height version of vote CR. - voteCR := &types.Transaction{ + voteCR := &transactions.BaseTransaction{ Version: 0x09, TxType: common2.TransferAsset, Outputs: []*common2.Output{ @@ -337,7 +338,7 @@ func (s *txValidatorTestSuite) TestCheckTransactionOutput() { config.DefaultParams.PublicDPOSHeight = originHeight // new sideChainPow - tx = &types.Transaction{ + tx = &transactions.BaseTransaction{ TxType: 0x05, Outputs: []*common2.Output{ { @@ -447,7 +448,7 @@ func (s *txValidatorTestSuite) TestCheckAttributeProgram() { func (s *txValidatorTestSuite) TestCheckTransactionPayload() { // normal - tx := new(types.Transaction) + tx := new(transactions.BaseTransaction) payload := &payload.RegisterAsset{ Asset: payload.Asset{ Name: "ELA", @@ -481,7 +482,7 @@ func (s *txValidatorTestSuite) TestCheckDuplicateSidechainTx() { hash2, _ := common.Uint256FromBytes(hashBytes2) // 1. Generate the ill withdraw transaction which have duplicate sidechain tx - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.WithdrawFromSideChain txn.Payload = &payload.WithdrawFromSideChain{ BlockHeight: 100, @@ -500,7 +501,7 @@ func (s *txValidatorTestSuite) TestCheckDuplicateSidechainTx() { func (s *txValidatorTestSuite) TestCheckTransactionBalance() { // WithdrawFromSideChain will pass check in any condition - tx := new(types.Transaction) + tx := new(transactions.BaseTransaction) tx.TxType = common2.WithdrawFromSideChain // single output @@ -551,7 +552,7 @@ func (s *txValidatorTestSuite) TestCheckTransactionBalance() { func (s *txValidatorTestSuite) TestCheckSideChainPowConsensus() { // 1. Generate a side chain pow transaction - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.SideChainPow txn.Payload = &payload.SideChainPow{ SideBlockHash: common.Uint256{1, 1, 1}, @@ -609,7 +610,7 @@ func (s *txValidatorTestSuite) TestCheckRegisterProducerTransaction() { errPublicKeyStr := "02b611f07341d5ddce51b5c4366aca7b889cfe0993bd63fd4" errPublicKey, _ := common.HexStringToBytes(errPublicKeyStr) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.RegisterProducer rpPayload := &payload.ProducerInfo{ OwnerPublicKey: publicKey1, @@ -1071,7 +1072,7 @@ func (s *txValidatorTestSuite) TestCheckUpdateProducerTransaction() { errPublicKeyStr := "02b611f07341d5ddce51b5c4366aca7b889cfe0993bd63fd4" errPublicKey, _ := common.HexStringToBytes(errPublicKeyStr) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.RegisterProducer registerPayload := &payload.ProducerInfo{ OwnerPublicKey: publicKey1, @@ -1110,7 +1111,7 @@ func (s *txValidatorTestSuite) TestCheckUpdateProducerTransaction() { CreateCRAppropriationTransaction: s.Chain.CreateCRCAppropriationTransaction, }) block := &types.Block{ - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ txn, }, Header: types.Header{Height: s.CurrentHeight}, @@ -1187,7 +1188,7 @@ func (s *txValidatorTestSuite) TestCheckCancelProducerTransaction() { errPublicKeyStr := "02b611f07341d5ddce51b5c4366aca7b889cfe0993bd63fd4" errPublicKey, _ := common.HexStringToBytes(errPublicKeyStr) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CancelProducer cancelPayload := &payload.ProcessProducer{ OwnerPublicKey: publicKey1, @@ -1214,7 +1215,7 @@ func (s *txValidatorTestSuite) TestCheckActivateProducerTransaction() { errPublicKeyStr := "02b611f07341d5ddce51b5c4366aca7b889cfe0993bd63fd4" errPublicKey, _ := common.HexStringToBytes(errPublicKeyStr) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.ActivateProducer activatePayload := &payload.ActivateProducer{ NodePublicKey: publicKey1, @@ -1445,7 +1446,7 @@ func getCID(code []byte) *common.Uint168 { } func (s *txValidatorTestSuite) getRegisterCRTx(publicKeyStr, privateKeyStr, - nickName string, payloadVersion byte, did *common.Uint168) *types.Transaction { + nickName string, payloadVersion byte, did *common.Uint168) *transactions.BaseTransaction { publicKeyStr1 := publicKeyStr privateKeyStr1 := privateKeyStr @@ -1458,7 +1459,7 @@ func (s *txValidatorTestSuite) getRegisterCRTx(publicKeyStr, privateKeyStr, hash1, _ := contract.PublicKeyToDepositProgramHash(publicKey1) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.RegisterCR txn.Version = common2.TxVersion09 txn.PayloadVersion = payloadVersion @@ -1493,7 +1494,7 @@ func (s *txValidatorTestSuite) getRegisterCRTx(publicKeyStr, privateKeyStr, } func (s *txValidatorTestSuite) getMultiSigRegisterCRTx( - publicKeyStrs, privateKeyStrs []string, nickName string) *types.Transaction { + publicKeyStrs, privateKeyStrs []string, nickName string) *transactions.BaseTransaction { var publicKeys []*crypto.PublicKey for _, publicKeyStr := range publicKeyStrs { @@ -1510,7 +1511,7 @@ func (s *txValidatorTestSuite) getMultiSigRegisterCRTx( ctDeposit, _ := contract.CreateDepositContractByCode(multiCode) deposit := ctDeposit.ToProgramHash() - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.RegisterCR txn.Version = common2.TxVersion09 crInfoPayload := &payload.CRInfo{ @@ -1546,7 +1547,7 @@ func (s *txValidatorTestSuite) getMultiSigRegisterCRTx( return txn } -func (s *txValidatorTestSuite) getUpdateCRTx(publicKeyStr, privateKeyStr, nickName string) *types.Transaction { +func (s *txValidatorTestSuite) getUpdateCRTx(publicKeyStr, privateKeyStr, nickName string) *transactions.BaseTransaction { publicKeyStr1 := publicKeyStr privateKeyStr1 := privateKeyStr @@ -1555,7 +1556,7 @@ func (s *txValidatorTestSuite) getUpdateCRTx(publicKeyStr, privateKeyStr, nickNa ct1, _ := contract.CreateCRIDContractByCode(code1) cid1 := ct1.ToProgramHash() - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.UpdateCR txn.Version = common2.TxVersion09 crInfoPayload := &payload.CRInfo{ @@ -1580,7 +1581,7 @@ func (s *txValidatorTestSuite) getUpdateCRTx(publicKeyStr, privateKeyStr, nickNa return txn } -func (s *txValidatorTestSuite) getUnregisterCRTx(publicKeyStr, privateKeyStr string) *types.Transaction { +func (s *txValidatorTestSuite) getUnregisterCRTx(publicKeyStr, privateKeyStr string) *transactions.BaseTransaction { publicKeyStr1 := publicKeyStr privateKeyStr1 := privateKeyStr @@ -1588,7 +1589,7 @@ func (s *txValidatorTestSuite) getUnregisterCRTx(publicKeyStr, privateKeyStr str code1 := getCodeByPubKeyStr(publicKeyStr1) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.UnregisterCR txn.Version = common2.TxVersion09 unregisterCRPayload := &payload.UnregisterCR{ @@ -1616,7 +1617,7 @@ func (s *txValidatorTestSuite) getCRMember(publicKeyStr, privateKeyStr, nickName code1 := getCodeByPubKeyStr(publicKeyStr1) did1, _ := getDIDFromCode(code1) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.RegisterCR txn.Version = common2.TxVersion09 crInfoPayload := payload.CRInfo{ @@ -1637,7 +1638,7 @@ func (s *txValidatorTestSuite) getCRMember(publicKeyStr, privateKeyStr, nickName } func (s *txValidatorTestSuite) getSecretaryGeneralCRCProposalTx(ownerPublicKeyStr, ownerPrivateKeyStr, - crPublicKeyStr, crPrivateKeyStr, secretaryPublicKeyStr, secretaryPrivateKeyStr string) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr, secretaryPublicKeyStr, secretaryPrivateKeyStr string) *transactions.BaseTransaction { ownerPublicKey, _ := common.HexStringToBytes(ownerPublicKeyStr) ownerPrivateKey, _ := common.HexStringToBytes(ownerPrivateKeyStr) @@ -1650,7 +1651,7 @@ func (s *txValidatorTestSuite) getSecretaryGeneralCRCProposalTx(ownerPublicKeySt crCode := getCodeByPubKeyStr(crPublicKeyStr) draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 @@ -1690,7 +1691,7 @@ func (s *txValidatorTestSuite) getSecretaryGeneralCRCProposalTx(ownerPublicKeySt } func (s *txValidatorTestSuite) getCRCProposalTx(publicKeyStr, privateKeyStr, - crPublicKeyStr, crPrivateKeyStr string) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr string) *transactions.BaseTransaction { publicKey1, _ := common.HexStringToBytes(publicKeyStr) privateKey1, _ := common.HexStringToBytes(privateKeyStr) @@ -1699,7 +1700,7 @@ func (s *txValidatorTestSuite) getCRCProposalTx(publicKeyStr, privateKeyStr, code2 := getCodeByPubKeyStr(crPublicKeyStr) draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 @@ -1776,7 +1777,7 @@ func (s *txValidatorTestSuite) createSpecificStatusProposal(publicKey1, publicKe } func (s *txValidatorTestSuite) getCRCCloseProposalTxWithHash(publicKeyStr, privateKeyStr, - crPublicKeyStr, crPrivateKeyStr string, closeProposalHash common.Uint256) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr string, closeProposalHash common.Uint256) *transactions.BaseTransaction { draftData := randomBytes(10) privateKey1, _ := common.HexStringToBytes(privateKeyStr) @@ -1788,7 +1789,7 @@ func (s *txValidatorTestSuite) getCRCCloseProposalTxWithHash(publicKeyStr, priva //did2, _ := getDIDFromCode(code2) //draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 CRCouncilMemberDID, _ := getDIDFromCode(code2) @@ -1819,14 +1820,14 @@ func (s *txValidatorTestSuite) getCRCCloseProposalTxWithHash(publicKeyStr, priva } func (s *txValidatorTestSuite) getCRCRegisterSideChainProposalTx(publicKeyStr, privateKeyStr, - crPublicKeyStr, crPrivateKeyStr string) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr string) *transactions.BaseTransaction { normalPrivateKey, _ := common.HexStringToBytes(privateKeyStr) normalPublicKey, _ := common.HexStringToBytes(publicKeyStr) crPrivateKey, _ := common.HexStringToBytes(crPrivateKeyStr) draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 CRCouncilMemberDID, _ := getDIDFromCode(getCodeByPubKeyStr(crPublicKeyStr)) @@ -1864,7 +1865,7 @@ func (s *txValidatorTestSuite) getCRCRegisterSideChainProposalTx(publicKeyStr, p } func (s *txValidatorTestSuite) getCRCCloseProposalTx(publicKeyStr, privateKeyStr, - crPublicKeyStr, crPrivateKeyStr string) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr string) *transactions.BaseTransaction { privateKey1, _ := common.HexStringToBytes(privateKeyStr) @@ -1874,7 +1875,7 @@ func (s *txValidatorTestSuite) getCRCCloseProposalTx(publicKeyStr, privateKeyStr //did2, _ := getDIDFromCode(code2) draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 CRCouncilMemberDID, _ := getDIDFromCode(code2) @@ -1916,7 +1917,7 @@ func randomName(length int) string { } func (s *txValidatorTestSuite) getCRCReceivedCustomIDProposalTx(publicKeyStr, privateKeyStr, - crPublicKeyStr, crPrivateKeyStr string, receivedList []string) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr string, receivedList []string) *transactions.BaseTransaction { privateKey1, _ := common.HexStringToBytes(privateKeyStr) publicKey1, _ := common.HexStringToBytes(publicKeyStr) @@ -1927,7 +1928,7 @@ func (s *txValidatorTestSuite) getCRCReceivedCustomIDProposalTx(publicKeyStr, pr //did2, _ := getDIDFromCode(code2) draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 CRCouncilMemberDID, _ := getDIDFromCode(code2) @@ -1959,7 +1960,7 @@ func (s *txValidatorTestSuite) getCRCReceivedCustomIDProposalTx(publicKeyStr, pr } func (s *txValidatorTestSuite) getCRCReservedCustomIDProposalTx(publicKeyStr, privateKeyStr, - crPublicKeyStr, crPrivateKeyStr string) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr string) *transactions.BaseTransaction { privateKey1, _ := common.HexStringToBytes(privateKeyStr) @@ -1969,7 +1970,7 @@ func (s *txValidatorTestSuite) getCRCReservedCustomIDProposalTx(publicKeyStr, pr //did2, _ := getDIDFromCode(code2) draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 CRCouncilMemberDID, _ := getDIDFromCode(code2) @@ -2186,7 +2187,7 @@ func (s *txValidatorTestSuite) getCRCProposalTrackingTx( proposalHash common.Uint256, stage uint8, ownerPublicKeyStr, ownerPrivateKeyStr, newownerpublickeyStr, newownerprivatekeyStr, - sgPublicKeyStr, sgPrivateKeyStr string) *types.Transaction { + sgPublicKeyStr, sgPrivateKeyStr string) *transactions.BaseTransaction { ownerPublicKey, _ := common.HexStringToBytes(ownerPublicKeyStr) ownerPrivateKey, _ := common.HexStringToBytes(ownerPrivateKeyStr) @@ -2198,7 +2199,7 @@ func (s *txValidatorTestSuite) getCRCProposalTrackingTx( documentData := randomBytes(10) opinionHash := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposalTracking txn.Version = common2.TxVersion09 cPayload := &payload.CRCProposalTracking{ @@ -2313,8 +2314,8 @@ func (s *txValidatorTestSuite) TestCheckCRCAppropriationTransaction() { } func (s *txValidatorTestSuite) getCRCAppropriationTx(input *common2.Input, - output1 *common2.Output, output2 *common2.Output) *types.Transaction { - txn := new(types.Transaction) + output1 *common2.Output, output2 *common2.Output) *transactions.BaseTransaction { + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCAppropriation txn.Version = common2.TxVersion09 cPayload := &payload.CRCAppropriation{} @@ -2326,8 +2327,8 @@ func (s *txValidatorTestSuite) getCRCAppropriationTx(input *common2.Input, } func (s *txValidatorTestSuite) getCRCProposalRealWithdrawTx(input *common2.Input, - hashes []common.Uint256, outputs []*common2.Output) *types.Transaction { - txn := new(types.Transaction) + hashes []common.Uint256, outputs []*common2.Output) *transactions.BaseTransaction { + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposalRealWithdraw txn.Version = common2.TxVersion09 cPayload := &payload.CRCProposalRealWithdraw{WithdrawTransactionHashes: hashes} @@ -2408,7 +2409,7 @@ func (s *txValidatorTestSuite) TestCheckUpdateCRTransaction() { CreateCRAppropriationTransaction: s.Chain.CreateCRCAppropriationTransaction, }) block := &types.Block{ - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, }, @@ -2621,7 +2622,7 @@ func (s *txValidatorTestSuite) TestCheckUnregisterCRTransaction() { CreateCRAppropriationTransaction: s.Chain.CreateCRCAppropriationTransaction, }) block := &types.Block{ - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn, }, Header: types.Header{Height: s.CurrentHeight}, @@ -2659,11 +2660,11 @@ func (s *txValidatorTestSuite) TestCheckUnregisterCRTransaction() { } func (s *txValidatorTestSuite) getCRCProposalReviewTx(crPublicKeyStr, - crPrivateKeyStr string) *types.Transaction { + crPrivateKeyStr string) *transactions.BaseTransaction { privateKey1, _ := common.HexStringToBytes(crPrivateKeyStr) code := getCodeByPubKeyStr(crPublicKeyStr) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposalReview txn.Version = common2.TxVersion09 did, _ := getDIDFromCode(code) @@ -2754,13 +2755,12 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalReviewTransaction() { func (s *txValidatorTestSuite) getCRCProposalWithdrawTx(crPublicKeyStr, crPrivateKeyStr string, recipient, - commitee *common.Uint168, recipAmout, commiteAmout common.Fixed64, payloadVersion byte) *types. - Transaction { + commitee *common.Uint168, recipAmout, commiteAmout common.Fixed64, payloadVersion byte) *transactions.BaseTransaction { privateKey1, _ := common.HexStringToBytes(crPrivateKeyStr) pkBytes, _ := common.HexStringToBytes(crPublicKeyStr) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposalWithdraw txn.Version = common2.TxVersionDefault var crcProposalWithdraw *payload.CRCProposalWithdraw @@ -2978,7 +2978,7 @@ func (s *txValidatorTestSuite) TestCheckCRCProposalWithdrawTransaction() { } func (s *txValidatorTestSuite) getCRChangeProposalOwnerProposalTx(publicKeyStr, privateKeyStr, - crPublicKeyStr, crPrivateKeyStr, newOwnerPublicKeyStr string, targetHash common.Uint256) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr, newOwnerPublicKeyStr string, targetHash common.Uint256) *transactions.BaseTransaction { privateKey, _ := common.HexStringToBytes(privateKeyStr) crPrivateKey, _ := common.HexStringToBytes(crPrivateKeyStr) @@ -2987,7 +2987,7 @@ func (s *txValidatorTestSuite) getCRChangeProposalOwnerProposalTx(publicKeyStr, newOwnerPublicKey, _ := common.HexStringToBytes(newOwnerPublicKeyStr) draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 @@ -3026,7 +3026,7 @@ func (s *txValidatorTestSuite) TestGenrateTxFromRawTxStr() { return } - var tx types.Transaction + var tx transactions.BaseTransaction reader := bytes.NewReader(data) err2 := tx.Deserialize(reader) if err2 != nil { @@ -3061,7 +3061,7 @@ func (s *txValidatorTestSuite) TestGenerateRawTransactionStr() { if err2 != nil { fmt.Println("HexStringToBytes err2", err2) } - var txn2 types.Transaction + var txn2 transactions.BaseTransaction reader2 := bytes.NewReader(data) err2 = txn2.Deserialize(reader2) if err2 != nil { @@ -3406,7 +3406,7 @@ func (s *txValidatorTestSuite) TestCheckStringField() { func (s *txValidatorTestSuite) TestCheckTransactionDepositUTXO() { references := make(map[*common2.Input]common2.Output) input := &common2.Input{} - var txn types.Transaction + var txn transactions.BaseTransaction // Use the deposit UTXO in a TransferAsset transaction depositHash, _ := common.Uint168FromAddress("DVgnDnVfPVuPa2y2E4JitaWjWgRGJDuyrD") @@ -3466,7 +3466,7 @@ func (s *txValidatorTestSuite) TestCheckReturnDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ { TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ @@ -3493,7 +3493,7 @@ func (s *txValidatorTestSuite) TestCheckReturnDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) s.CurrentHeight++ } @@ -3507,7 +3507,7 @@ func (s *txValidatorTestSuite) TestCheckReturnDepositCoinTransaction() { } code1, _ := contract.CreateStandardRedeemScript(pk) - rdTx := &types.Transaction{ + rdTx := &transactions.BaseTransaction{ TxType: common2.ReturnCRDepositCoin, Payload: &payload.ReturnDepositCoin{}, Programs: []*program.Program{ @@ -3527,7 +3527,7 @@ func (s *txValidatorTestSuite) TestCheckReturnDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ { TxType: common2.CancelProducer, Payload: &payload.ProcessProducer{ @@ -3560,7 +3560,7 @@ func (s *txValidatorTestSuite) TestCheckReturnDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) // check a return deposit coin transaction with wrong output amount. @@ -3599,7 +3599,7 @@ func (s *txValidatorTestSuite) TestCheckReturnCRDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ { TxType: common2.RegisterCR, Payload: &payload.CRInfo{ @@ -3625,7 +3625,7 @@ func (s *txValidatorTestSuite) TestCheckReturnCRDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) s.CurrentHeight++ } @@ -3637,7 +3637,7 @@ func (s *txValidatorTestSuite) TestCheckReturnCRDepositCoinTransaction() { Value: common.Fixed64(5000 * 100000000), } - rdTx := &types.Transaction{ + rdTx := &transactions.BaseTransaction{ TxType: common2.ReturnCRDepositCoin, Payload: &payload.ReturnDepositCoin{}, Programs: []*program.Program{ @@ -3654,7 +3654,7 @@ func (s *txValidatorTestSuite) TestCheckReturnCRDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ { TxType: common2.UnregisterCR, Payload: &payload.UnregisterCR{ @@ -3676,7 +3676,7 @@ func (s *txValidatorTestSuite) TestCheckReturnCRDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) // check a return cr deposit coin transaction with wrong code in voting period. @@ -3706,7 +3706,7 @@ func (s *txValidatorTestSuite) TestCheckReturnCRDepositCoinTransaction() { Header: types.Header{ Height: s.CurrentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ rdTx, }, }, nil) @@ -3843,7 +3843,7 @@ func (s *txValidatorTestSuite) TestCheckVoteOutputs() { CreateCRAppropriationTransaction: s.Chain.CreateCRCAppropriationTransaction, }) block := &types.Block{ - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -4281,7 +4281,7 @@ func (s *txValidatorTestSuite) TestCreateCRCAppropriationTransaction() { txOutputs = append(txOutputs, &txOutPutNew) } - txn := &types.Transaction{ + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, @@ -4297,7 +4297,7 @@ func (s *txValidatorTestSuite) TestCreateCRCAppropriationTransaction() { txOutputCoinBase.Value = common.Fixed64(500) txOutputCoinBase.OutputLock = uint32(100) txOutputs = append(txOutputs, &txOutputCoinBase) - txnCoinBase := &types.Transaction{ + txnCoinBase := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.CoinBase, Payload: &payload.TransferAsset{}, @@ -4308,7 +4308,7 @@ func (s *txValidatorTestSuite) TestCreateCRCAppropriationTransaction() { LockTime: 0, } block := &types.Block{ - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ txn, txnCoinBase, }, @@ -4329,8 +4329,8 @@ func TestTxValidatorSuite(t *testing.T) { } func newCoinBaseTransaction(coinBasePayload *payload.CoinBase, - currentHeight uint32) *types.Transaction { - return &types.Transaction{ + currentHeight uint32) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ Version: 0, TxType: common2.CoinBase, PayloadVersion: payload.CoinBaseVersion, @@ -4350,7 +4350,7 @@ func newCoinBaseTransaction(coinBasePayload *payload.CoinBase, } } -func (a *txValidatorTestSuite) createNextTurnDPOSInfoTransaction(crcArbiters, normalDPOSArbiters [][]byte) *types.Transaction { +func (a *txValidatorTestSuite) createNextTurnDPOSInfoTransaction(crcArbiters, normalDPOSArbiters [][]byte) *transactions.BaseTransaction { var nextTurnDPOSInfo payload.NextTurnDPOSInfo for _, v := range crcArbiters { @@ -4359,7 +4359,7 @@ func (a *txValidatorTestSuite) createNextTurnDPOSInfoTransaction(crcArbiters, no for _, v := range normalDPOSArbiters { nextTurnDPOSInfo.DPOSPublicKeys = append(nextTurnDPOSInfo.DPOSPublicKeys, v) } - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.NextTurnDPOSInfo, Payload: &nextTurnDPOSInfo, diff --git a/blockchain/utxocache.go b/blockchain/utxocache.go index ff787db2a..ebfe10090 100644 --- a/blockchain/utxocache.go +++ b/blockchain/utxocache.go @@ -9,11 +9,11 @@ import ( "container/list" "errors" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sync" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" - "github.com/elastos/Elastos.ELA/core/types" ) const ( @@ -25,7 +25,7 @@ var ( ) type IUTXOCacheStore interface { - GetTransaction(txID common.Uint256) (*types.Transaction, uint32, error) + GetTransaction(txID common.Uint256) (*transactions.BaseTransaction, uint32, error) } type UTXOCache struct { @@ -34,7 +34,7 @@ type UTXOCache struct { db IUTXOCacheStore inputs *list.List reference map[common2.Input]common2.Output - txCache map[common.Uint256]*types.Transaction + txCache map[common.Uint256]*transactions.BaseTransaction } func (up *UTXOCache) insertReference(input *common2.Input, output *common2.Output) { @@ -52,7 +52,7 @@ func (up *UTXOCache) insertReference(input *common2.Input, output *common2.Outpu up.reference[*input] = *output } -func (up *UTXOCache) GetTxReference(tx *types.Transaction) (map[*common2.Input]common2.Output, error) { +func (up *UTXOCache) GetTxReference(tx *transactions.BaseTransaction) (map[*common2.Input]common2.Output, error) { up.Lock() defer up.Unlock() @@ -77,14 +77,14 @@ func (up *UTXOCache) GetTxReference(tx *types.Transaction) (map[*common2.Input]c return result, nil } -func (up *UTXOCache) GetTransaction(txID common.Uint256) (*types.Transaction, error) { +func (up *UTXOCache) GetTransaction(txID common.Uint256) (*transactions.BaseTransaction, error) { up.Lock() defer up.Unlock() return up.getTransaction(txID) } -func (up *UTXOCache) insertTransaction(txID common.Uint256, tx *types.Transaction) { +func (up *UTXOCache) insertTransaction(txID common.Uint256, tx *transactions.BaseTransaction) { if len(up.txCache) > maxReferenceSize { for k := range up.txCache { delete(up.txCache, k) @@ -98,7 +98,7 @@ func (up *UTXOCache) insertTransaction(txID common.Uint256, tx *types.Transactio up.txCache[txID] = tx } -func (up *UTXOCache) getTransaction(txID common.Uint256) (*types.Transaction, error) { +func (up *UTXOCache) getTransaction(txID common.Uint256) (*transactions.BaseTransaction, error) { prevTx, exist := up.txCache[txID] if !exist { var err error @@ -116,7 +116,7 @@ func (up *UTXOCache) CleanTxCache() { up.Lock() defer up.Unlock() - up.txCache = make(map[common.Uint256]*types.Transaction) + up.txCache = make(map[common.Uint256]*transactions.BaseTransaction) } func (up *UTXOCache) CleanCache() { @@ -125,7 +125,7 @@ func (up *UTXOCache) CleanCache() { up.inputs.Init() up.reference = make(map[common2.Input]common2.Output) - up.txCache = make(map[common.Uint256]*types.Transaction) + up.txCache = make(map[common.Uint256]*transactions.BaseTransaction) } func NewUTXOCache(db IUTXOCacheStore, params *config.Params) *UTXOCache { @@ -137,6 +137,6 @@ func NewUTXOCache(db IUTXOCacheStore, params *config.Params) *UTXOCache { db: db, inputs: list.New(), reference: make(map[common2.Input]common2.Output), - txCache: make(map[common.Uint256]*types.Transaction), + txCache: make(map[common.Uint256]*transactions.BaseTransaction), } } diff --git a/blockchain/utxocache_test.go b/blockchain/utxocache_test.go index 55c4f0add..cf7f92dbb 100644 --- a/blockchain/utxocache_test.go +++ b/blockchain/utxocache_test.go @@ -8,11 +8,11 @@ package blockchain import ( "errors" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" @@ -26,7 +26,7 @@ var ( utxoCache *UTXOCache // refer tx hash: 160da301e49617c037ae9b630919af52b8ac458202cd64558af7e0dcc753e307 - referTx = &types.Transaction{ + referTx = &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, PayloadVersion: 0, @@ -51,7 +51,7 @@ var ( LockTime: 5, } - spendTx = &types.Transaction{ + spendTx = &transactions.BaseTransaction{ Inputs: []*common2.Input{ { Previous: common2.OutPoint{ @@ -65,7 +65,7 @@ var ( ) type UtxoCacheDB struct { - transactions map[common.Uint256]*types.Transaction + transactions map[common.Uint256]*transactions.BaseTransaction } func init() { @@ -73,7 +73,7 @@ func init() { } func (s *UtxoCacheDB) GetTransaction(txID common.Uint256) ( - *types.Transaction, uint32, error) { + *transactions.BaseTransaction, uint32, error) { txn, exist := s.transactions[txID] if exist { return txn, 0, nil @@ -81,7 +81,7 @@ func (s *UtxoCacheDB) GetTransaction(txID common.Uint256) ( return nil, 0, errors.New("leveldb: not found") } -func (s *UtxoCacheDB) SetTransaction(txn *types.Transaction) { +func (s *UtxoCacheDB) SetTransaction(txn *transactions.BaseTransaction) { s.transactions[txn.Hash()] = txn } @@ -91,7 +91,7 @@ func (s *UtxoCacheDB) RemoveTransaction(txID common.Uint256) { func NewUtxoCacheDB() *UtxoCacheDB { var db UtxoCacheDB - db.transactions = make(map[common.Uint256]*types.Transaction) + db.transactions = make(map[common.Uint256]*transactions.BaseTransaction) return &db } diff --git a/blockchain/validation.go b/blockchain/validation.go index 309f4a33e..9d3e4e6e3 100644 --- a/blockchain/validation.go +++ b/blockchain/validation.go @@ -9,12 +9,12 @@ import ( "crypto/sha256" "errors" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sort" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" . "github.com/elastos/Elastos.ELA/core/contract/program" - . "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/crypto" ) @@ -69,9 +69,9 @@ func RunPrograms(data []byte, programHashes []common.Uint168, programs []*Progra return nil } -func GetTxProgramHashes(tx *Transaction, references map[*common2.Input]common2.Output) ([]common.Uint168, error) { +func GetTxProgramHashes(tx *transactions.BaseTransaction, references map[*common2.Input]common2.Output) ([]common.Uint168, error) { if tx == nil { - return nil, errors.New("[Transaction],GetProgramHashes transaction is nil") + return nil, errors.New("[BaseTransaction],GetProgramHashes transaction is nil") } hashes := make([]common.Uint168, 0) uniqueHashes := make([]common.Uint168, 0) @@ -84,7 +84,7 @@ func GetTxProgramHashes(tx *Transaction, references map[*common2.Input]common2.O if attribute.Usage == common2.Script { dataHash, err := common.Uint168FromBytes(attribute.Data) if err != nil { - return nil, errors.New("[Transaction], GetProgramHashes err") + return nil, errors.New("[BaseTransaction], GetProgramHashes err") } hashes = append(hashes, *dataHash) } diff --git a/blockchain/validation_test.go b/blockchain/validation_test.go index 314501846..a1fdd32f6 100644 --- a/blockchain/validation_test.go +++ b/blockchain/validation_test.go @@ -10,6 +10,7 @@ import ( "crypto/rand" "encoding/hex" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math/big" math "math/rand" "sort" @@ -18,7 +19,6 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" @@ -88,7 +88,7 @@ func (a *multiAccount) Sign(data []byte) ([]byte, error) { } func TestCheckCheckSigSignature(t *testing.T) { - var tx *types.Transaction + var tx *transactions.BaseTransaction tx = buildTx() data := getData(tx) @@ -122,7 +122,7 @@ func TestCheckCheckSigSignature(t *testing.T) { } func TestCheckMultiSigSignature(t *testing.T) { - var tx *types.Transaction + var tx *transactions.BaseTransaction tx = buildTx() data := getData(tx) @@ -291,7 +291,7 @@ func TestSchnorrRunProgramsOrigin(t *testing.T) { publicKey1, _ := crypto.DecodePoint(pk[:]) fmt.Println(publicKey1) //var err error - var tx *types.Transaction + var tx *transactions.BaseTransaction //var acts []act var hashes []common.Uint168 var programs []*program.Program @@ -525,7 +525,7 @@ func TestAggregateSignatures(t *testing.T) { func TestSchnorrRunPrograms(t *testing.T) { var err error - var tx *types.Transaction + var tx *transactions.BaseTransaction var hashes []common.Uint168 var programs []*program.Program var acts []act @@ -566,7 +566,7 @@ func TestSchnorrRunPrograms(t *testing.T) { func TestRunPrograms(t *testing.T) { var err error - var tx *types.Transaction + var tx *transactions.BaseTransaction var acts []act var hashes []common.Uint168 var programs []*program.Program @@ -779,8 +779,8 @@ func newMultiAccount(num int, t *testing.T) *multiAccount { return ma } -func buildTx() *types.Transaction { - tx := new(types.Transaction) +func buildTx() *transactions.BaseTransaction { + tx := new(transactions.BaseTransaction) tx.TxType = common2.TransferAsset tx.Payload = new(payload.TransferAsset) tx.Inputs = randomInputs() @@ -820,7 +820,7 @@ func randomOutputs() []*common2.Output { return outputs } -func getData(tx *types.Transaction) []byte { +func getData(tx *transactions.BaseTransaction) []byte { buf := new(bytes.Buffer) tx.SerializeUnsigned(buf) return buf.Bytes() diff --git a/blockchain/weight.go b/blockchain/weight.go index 5843227e1..907669674 100644 --- a/blockchain/weight.go +++ b/blockchain/weight.go @@ -13,6 +13,7 @@ package blockchain import ( "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/btcsuite/btcd/wire" ) @@ -67,7 +68,7 @@ func GetBlockWeight(blk *types.Block) int64 { // transactions's serialized size without any witness data scaled // proportionally by the WitnessScaleFactor, and the transaction's serialized // size including any witness data. -func GetTransactionWeight(tx *types.Transaction) int64 { +func GetTransactionWeight(tx *transactions.BaseTransaction) int64 { baseSize := tx.SerializeSizeStripped() return int64(baseSize) } diff --git a/cmd/common/flags.go b/cmd/common/flags.go index 6afbbb380..a7e00101a 100644 --- a/cmd/common/flags.go +++ b/cmd/common/flags.go @@ -34,7 +34,7 @@ var ( Usage: "public key list of multi signature address, separate public keys with comma `,`", } - // Transaction flags + // BaseTransaction flags TransactionFromFlag = cli.StringFlag{ Name: "from", Usage: "the sender `
` of the transaction", diff --git a/cmd/info/info.go b/cmd/info/info.go index 3bfb990bc..3d4df3fd1 100644 --- a/cmd/info/info.go +++ b/cmd/info/info.go @@ -153,7 +153,7 @@ func NewCommand() *cli.Command { Usage: "Get raw transaction by transaction hash", Action: func(c *cli.Context) error { if c.NArg() < 1 { - cmdcom.PrintErrorMsg("Missing argument. Transaction hash expected.") + cmdcom.PrintErrorMsg("Missing argument. BaseTransaction hash expected.") cli.ShowCommandHelpAndExit(c, "getrawtransaction", 1) } param := c.Args().First() diff --git a/cmd/script/api/api.go b/cmd/script/api/api.go index 8f82b69e0..f300ee16d 100644 --- a/cmd/script/api/api.go +++ b/cmd/script/api/api.go @@ -61,7 +61,7 @@ func outputTx(L *lua.LState) int { os.Exit(1) } haveSign, needSign, _ := crypto.GetSignStatus(txn.Programs[0].Code, txn.Programs[0].Parameter) - fmt.Println("[", haveSign, "/", needSign, "] Transaction was successfully signed") + fmt.Println("[", haveSign, "/", needSign, "] BaseTransaction was successfully signed") wallet.OutputTx(haveSign, needSign, txn) return 0 diff --git a/cmd/script/api/dposmanager.go b/cmd/script/api/dposmanager.go index 6bce767e3..3a5ab6afb 100644 --- a/cmd/script/api/dposmanager.go +++ b/cmd/script/api/dposmanager.go @@ -8,6 +8,7 @@ package api import ( "encoding/json" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "strconv" "time" @@ -193,7 +194,7 @@ func dposManagerCheckLastRelay(L *lua.LState) int { result := false switch t { case relayTx: - if relayedTx, ok := m.Peer.GetLastRelay().(*types.Transaction); ok { + if relayedTx, ok := m.Peer.GetLastRelay().(*transactions.BaseTransaction); ok { if tx := checkTransaction(L, 3); tx != nil { result = tx.Hash().IsEqual(relayedTx.Hash()) } diff --git a/cmd/script/api/mock/peer.go b/cmd/script/api/mock/peer.go index 132fd81f5..98983f8b4 100644 --- a/cmd/script/api/mock/peer.go +++ b/cmd/script/api/mock/peer.go @@ -7,6 +7,7 @@ package mock import ( "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "time" "github.com/elastos/Elastos.ELA/blockchain" @@ -51,7 +52,7 @@ func (n *peerMock) DumpRelays(level uint32) string { case 0: for _, v := range n.relayList { if m, ok := v.(*msg.Tx); ok { - tx := m.Serializable.(*types.Transaction) + tx := m.Serializable.(*transactions.BaseTransaction) result += fmt.Sprintf("[transaction]: type=%s", tx.TxType.Name()) } else if m, ok := v.(*msg.Block); ok { diff --git a/cmd/script/api/txtype.go b/cmd/script/api/txtype.go index da7553c2f..4216467a6 100644 --- a/cmd/script/api/txtype.go +++ b/cmd/script/api/txtype.go @@ -11,13 +11,14 @@ import ( "encoding/json" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" + "github.com/elastos/Elastos.ELA/core/types/transactions" "os" cmdcom "github.com/elastos/Elastos.ELA/cmd/common" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" pg "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/servers" @@ -54,7 +55,7 @@ func newTransaction(L *lua.LState) int { ud := L.CheckUserData(4) lockTime := uint32(L.ToInt(5)) - var pload types.Payload + var pload interfaces.Payload switch ud.Value.(type) { case *payload.CoinBase: pload, _ = ud.Value.(*payload.CoinBase) @@ -107,7 +108,7 @@ func newTransaction(L *lua.LState) int { os.Exit(1) } - txn := &types.Transaction{ + txn := &transactions.BaseTransaction{ Version: common2.TransactionVersion(version), TxType: txType, PayloadVersion: payloadVersion, @@ -138,7 +139,7 @@ func fromFile(L *lua.LState) int { os.Exit(1) } - var txn types.Transaction + var txn transactions.BaseTransaction err = txn.Deserialize(bytes.NewReader(txData)) if err != nil { fmt.Println("deserialize transaction failed") @@ -153,13 +154,13 @@ func fromFile(L *lua.LState) int { return 1 } -// Checks whether the first lua argument is a *LUserData with *Transaction and returns this *Transaction. -func checkTransaction(L *lua.LState, idx int) *types.Transaction { +// Checks whether the first lua argument is a *LUserData with *BaseTransaction and returns this *BaseTransaction. +func checkTransaction(L *lua.LState, idx int) *transactions.BaseTransaction { ud := L.CheckUserData(idx) - if v, ok := ud.Value.(*types.Transaction); ok { + if v, ok := ud.Value.(*transactions.BaseTransaction); ok { return v } - L.ArgError(1, "Transaction expected") + L.ArgError(1, "BaseTransaction expected") return nil } diff --git a/cmd/wallet/common.go b/cmd/wallet/common.go index d3483bbe0..f255baab1 100644 --- a/cmd/wallet/common.go +++ b/cmd/wallet/common.go @@ -13,6 +13,7 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "io" "os" "strings" @@ -21,7 +22,6 @@ import ( cmdcom "github.com/elastos/Elastos.ELA/cmd/common" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/servers" "github.com/elastos/Elastos.ELA/utils/http" @@ -178,7 +178,7 @@ func getAddressBalance(address string) (common.Fixed64, common.Fixed64, error) { return availableAmount, lockedAmount, nil } -func OutputTx(haveSign, needSign int, txn *types.Transaction) error { +func OutputTx(haveSign, needSign int, txn *transactions.BaseTransaction) error { // Serialise transaction content buf := new(bytes.Buffer) err := txn.Serialize(buf) @@ -198,7 +198,7 @@ func OutputTx(haveSign, needSign int, txn *types.Transaction) error { fileName := "to_be_signed" // Create transaction file name if haveSign == 0 && needSign > 0 { - // Transaction created do nothing + // BaseTransaction created do nothing } else if needSign > haveSign { fileName = fmt.Sprint(fileName, "_", haveSign, "_of_", needSign) } else if needSign == haveSign { @@ -216,7 +216,7 @@ func OutputTx(haveSign, needSign int, txn *types.Transaction) error { return err } - var tx types.Transaction + var tx transactions.BaseTransaction txBytes, _ := hex.DecodeString(content) if err := tx.Deserialize(bytes.NewReader(txBytes)); err != nil { return err diff --git a/cmd/wallet/transaction.go b/cmd/wallet/transaction.go index e75aff2e9..561de1422 100644 --- a/cmd/wallet/transaction.go +++ b/cmd/wallet/transaction.go @@ -9,13 +9,13 @@ import ( "bytes" "errors" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "os" "strings" "github.com/elastos/Elastos.ELA/account" cmdcom "github.com/elastos/Elastos.ELA/cmd/common" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/utils/http" @@ -24,7 +24,7 @@ import ( var txCommand = []cli.Command{ { - Category: "Transaction", + Category: "BaseTransaction", Name: "buildtx", Usage: "Build a transaction", Description: "use --to --amount --fee to create a transaction", @@ -42,7 +42,7 @@ var txCommand = []cli.Command{ Action: buildTx, }, { - Category: "Transaction", + Category: "BaseTransaction", Name: "signtx", Usage: "Sign a transaction", Description: "use --file or --hex to specify the transaction file path or content", @@ -55,7 +55,7 @@ var txCommand = []cli.Command{ Action: signTx, }, { - Category: "Transaction", + Category: "BaseTransaction", Name: "sendtx", Usage: "Send a transaction", Description: "use --file or --hex to specify the transaction file path or content", @@ -66,7 +66,7 @@ var txCommand = []cli.Command{ Action: sendTx, }, { - Category: "Transaction", + Category: "BaseTransaction", Name: "showtx", Usage: "Show info of raw transaction", Flags: []cli.Flag{ @@ -213,7 +213,7 @@ func signTx(c *cli.Context) error { return errors.New("decode transaction content failed") } - var txn types.Transaction + var txn transactions.BaseTransaction err = txn.Deserialize(bytes.NewReader(rawData)) if err != nil { return errors.New("deserialize transaction failed") @@ -237,7 +237,7 @@ func signTx(c *cli.Context) error { } haveSign, needSign, _ = crypto.GetSignStatus(txn.Programs[0].Code, txn.Programs[0].Parameter) - fmt.Println("[", haveSign, "/", needSign, "] Transaction was successfully signed") + fmt.Println("[", haveSign, "/", needSign, "] BaseTransaction was successfully signed") OutputTx(haveSign, needSign, txnSigned) @@ -279,7 +279,7 @@ func showTx(c *cli.Context) error { if err != nil { return err } - var txn types.Transaction + var txn transactions.BaseTransaction if err := txn.Deserialize(bytes.NewReader(txBytes)); err != nil { return err } diff --git a/cmd/wallet/txbuilder.go b/cmd/wallet/txbuilder.go index 8a56757dc..14f474a39 100644 --- a/cmd/wallet/txbuilder.go +++ b/cmd/wallet/txbuilder.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "math/rand" "os" @@ -21,7 +22,6 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract" pg "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" @@ -101,7 +101,7 @@ func CreateTransaction(c *cli.Context) error { } } - var txn *types.Transaction + var txn *transactions.BaseTransaction txn, err = createTransaction(walletPath, from, *fee, uint32(outputLock), uint32(txLock), outputs...) if err != nil { @@ -269,7 +269,7 @@ func createVoteOutputs(output *OutputInfo, candidateList []string) ([]*common2.O } func createTransaction(walletPath string, from string, fee common.Fixed64, outputLock uint32, - txLock uint32, outputs ...*OutputInfo) (*types.Transaction, error) { + txLock uint32, outputs ...*OutputInfo) (*transactions.BaseTransaction, error) { // check output if len(outputs) == 0 { return nil, errors.New("invalid transaction target") @@ -308,7 +308,7 @@ func createTransaction(walletPath string, from string, fee common.Fixed64, outpu Code: redeemScript, Parameter: nil, } - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, @@ -373,7 +373,7 @@ func CreateActivateProducerTransaction(c *cli.Context) error { } apPayload.Signature = signature - txn := &types.Transaction{ + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.ActivateProducer, Payload: apPayload, @@ -474,7 +474,7 @@ func CreateCRCProposalWithdrawTransaction(c *cli.Context) error { } txOutputs = append(txOutputs, changeOutputs...) - txn := &types.Transaction{ + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.CRCProposalWithdraw, Payload: crcProposalWithdraw, @@ -559,7 +559,7 @@ func CreateVoteTransaction(c *cli.Context) error { Parameter: nil, } - txn := &types.Transaction{ + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, @@ -622,7 +622,7 @@ func CreateCrossChainTransaction(c *cli.Context) error { } func createCrossChainTransaction(walletPath string, from string, fee common.Fixed64, lockedUntil uint32, - crossChainOutputs ...*CrossChainOutput) (*types.Transaction, error) { + crossChainOutputs ...*CrossChainOutput) (*transactions.BaseTransaction, error) { // check output if len(crossChainOutputs) == 0 { return nil, errors.New("invalid transaction target") @@ -677,7 +677,7 @@ func createCrossChainTransaction(walletPath string, from string, fee common.Fixe Parameter: nil, } - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferCrossChainAsset, Payload: payload, diff --git a/common/config/params.go b/common/config/params.go index f4e894ea4..decf42d6d 100644 --- a/common/config/params.go +++ b/common/config/params.go @@ -7,6 +7,7 @@ package config import ( common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "math/big" "time" @@ -26,7 +27,7 @@ var ( zeroHash = common.Uint256{} // elaAsset is the transaction that create and register the ELA coin. - elaAsset = types.Transaction{ + elaAsset = transactions.BaseTransaction{ TxType: common2.RegisterAsset, PayloadVersion: 0, Payload: &payload.RegisterAsset{ @@ -805,7 +806,7 @@ func (p *Params) newRewardPerBlock(targetTimePerBlock time.Duration, height uint // The genesis block goes different because the foundation address in each // network is different. func GenesisBlock(foundation *common.Uint168) *types.Block { - coinBase := types.Transaction{ + coinBase := transactions.BaseTransaction{ Version: 0, TxType: common2.CoinBase, PayloadVersion: payload.CoinBaseVersion, @@ -844,7 +845,7 @@ func GenesisBlock(foundation *common.Uint168) *types.Block { Nonce: 2083236893, Height: 0, }, - Transactions: []*types.Transaction{&coinBase, &elaAsset}, + Transactions: []*transactions.BaseTransaction{&coinBase, &elaAsset}, } } diff --git a/core/types/block.go b/core/types/block.go index 10ce55d4f..a338269e9 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -8,6 +8,7 @@ package types import ( "bytes" "errors" + "github.com/elastos/Elastos.ELA/core/types/transactions" "io" "github.com/elastos/Elastos.ELA/common" @@ -26,7 +27,7 @@ type TxLoc struct { type Block struct { Header - Transactions []*Transaction + Transactions []*transactions.BaseTransaction } func (b *Block) Serialize(w io.Writer) error { @@ -55,7 +56,7 @@ func (b *Block) Deserialize(r io.Reader) error { return errors.New("Block item transactions count deserialize failed.") } for i := uint32(0); i < count; i++ { - transaction := new(Transaction) + transaction := new(transactions.BaseTransaction) if err := transaction.Deserialize(r); err != nil { return errors.New("Block item transaction deserialize failed, " + err.Error()) } @@ -83,11 +84,11 @@ func (b *Block) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) { // Deserialize each transaction while keeping track of its location // within the byte stream. - b.Transactions = make([]*Transaction, 0, txCount) + b.Transactions = make([]*transactions.BaseTransaction, 0, txCount) txLocs := make([]TxLoc, txCount) for i := uint32(0); i < txCount; i++ { txLocs[i].TxStart = fullLen - r.Len() - tx := Transaction{} + tx := transactions.BaseTransaction{} err := tx.Deserialize(r) if err != nil { return nil, err diff --git a/core/types/common/attribute.go b/core/types/common/attribute.go index f698e88f0..4e2ddebbf 100644 --- a/core/types/common/attribute.go +++ b/core/types/common/attribute.go @@ -68,13 +68,13 @@ func NewAttribute(u AttributeUsage, d []byte) Attribute { func (attr *Attribute) Serialize(w io.Writer) error { if err := common.WriteUint8(w, byte(attr.Usage)); err != nil { - return errors.New("Transaction attribute Usage serialization error.") + return errors.New("BaseTransaction attribute Usage serialization error.") } if !IsValidAttributeType(attr.Usage) { return errors.New("[Attribute error] Serialize Unsupported attribute Description.") } if err := common.WriteVarBytes(w, attr.Data); err != nil { - return errors.New("Transaction attribute Data serialization error.") + return errors.New("BaseTransaction attribute Data serialization error.") } return nil } @@ -82,7 +82,7 @@ func (attr *Attribute) Serialize(w io.Writer) error { func (attr *Attribute) Deserialize(r io.Reader) error { val, err := common.ReadBytes(r, 1) if err != nil { - return errors.New("Transaction attribute Usage deserialization error.") + return errors.New("BaseTransaction attribute Usage deserialization error.") } attr.Usage = AttributeUsage(val[0]) if !IsValidAttributeType(attr.Usage) { @@ -91,7 +91,7 @@ func (attr *Attribute) Deserialize(r io.Reader) error { attr.Data, err = common.ReadVarBytes(r, common.MaxVarStringLength, "attribute data") if err != nil { - return errors.New("Transaction attribute Data deserialization error.") + return errors.New("BaseTransaction attribute Data deserialization error.") } return nil } diff --git a/core/types/output_test.go b/core/types/common/output_test.go similarity index 82% rename from core/types/output_test.go rename to core/types/common/output_test.go index 8d0427182..cec27d34a 100644 --- a/core/types/output_test.go +++ b/core/types/common/output_test.go @@ -3,14 +3,13 @@ // license that can be found in the LICENSE file. // -package types +package common import ( "bytes" "testing" "github.com/elastos/Elastos.ELA/common" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" ) @@ -25,12 +24,12 @@ var ( func TestOutput_Serialize(t *testing.T) { // C0 - output := common2.Output{ + output := Output{ AssetID: *assetID, Value: 100000, OutputLock: 0, ProgramHash: *recipient, - Type: common2.OTVote, + Type: OTVote, Payload: &outputpayload.VoteOutput{ Version: 0, Contents: []outputpayload.VoteContent{ @@ -45,7 +44,7 @@ func TestOutput_Serialize(t *testing.T) { } buf := new(bytes.Buffer) - if err := output.Serialize(buf, common2.TxVersion09); err != nil { + if err := output.Serialize(buf, TxVersion09); err != nil { t.Error("output serialize failed") } @@ -60,13 +59,13 @@ func TestOutput_Deserialize(t *testing.T) { outputBytes, _ := common.HexStringToBytes(OUTPUTHEX) outputBuf := bytes.NewBuffer(outputBytes) - var output common2.Output - if err := output.Deserialize(outputBuf, common2.TxVersion09); err != nil { + var output Output + if err := output.Deserialize(outputBuf, TxVersion09); err != nil { t.Error("output deserialize failed") } buf := new(bytes.Buffer) - if err := output.Serialize(buf, common2.TxVersion09); err != nil { + if err := output.Serialize(buf, TxVersion09); err != nil { t.Error("output serialize failed") } diff --git a/core/types/utxo.go b/core/types/common/utxo.go similarity index 98% rename from core/types/utxo.go rename to core/types/common/utxo.go index adc0f891f..b6711ef33 100644 --- a/core/types/utxo.go +++ b/core/types/common/utxo.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // -package types +package common import ( "bytes" diff --git a/core/types/interfaces/basetransaction.go b/core/types/interfaces/basetransaction.go new file mode 100644 index 000000000..f249fb41e --- /dev/null +++ b/core/types/interfaces/basetransaction.go @@ -0,0 +1,26 @@ +// Copyright (c) 2017-2021 The Elastos Foundation +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. +// + +package interfaces + +import ( + "github.com/elastos/Elastos.ELA/common" + "io" +) + +type Transaction interface { + PayloadChecker + + + + String() string + Serialize(w io.Writer) error + SerializeUnsigned(w io.Writer) error + Deserialize(r io.Reader) error + DeserializeUnsigned(r io.Reader) error + GetSize() int + Hash() common.Uint256 + +} diff --git a/core/types/interfaces/payload.go b/core/types/interfaces/payload.go new file mode 100644 index 000000000..27f3e8a11 --- /dev/null +++ b/core/types/interfaces/payload.go @@ -0,0 +1,22 @@ +// Copyright (c) 2017-2021 The Elastos Foundation +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. +// + +package interfaces + +import ( + "io" +) + +// Payload define the func for loading the payload data +// base on payload type which have different structure +type Payload interface { + // Get payload data + Data(version byte) []byte + + Serialize(w io.Writer, version byte) error + + Deserialize(r io.Reader, version byte) error + +} diff --git a/core/types/payload/payloadcheckerinterface.go b/core/types/interfaces/payloadcheckerinterface.go similarity index 97% rename from core/types/payload/payloadcheckerinterface.go rename to core/types/interfaces/payloadcheckerinterface.go index 8c965b309..470c74bdb 100644 --- a/core/types/payload/payloadcheckerinterface.go +++ b/core/types/interfaces/payloadcheckerinterface.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // -package payload +package interfaces import ( "github.com/elastos/Elastos.ELA/common" diff --git a/core/types/payload/payloadcheckerparameter.go b/core/types/interfaces/payloadcheckerparameter.go similarity index 53% rename from core/types/payload/payloadcheckerparameter.go rename to core/types/interfaces/payloadcheckerparameter.go index b595d5a5e..5083558c9 100644 --- a/core/types/payload/payloadcheckerparameter.go +++ b/core/types/interfaces/payloadcheckerparameter.go @@ -3,25 +3,15 @@ // license that can be found in the LICENSE file. // -package payload +package interfaces import ( "github.com/elastos/Elastos.ELA/common" - pg "github.com/elastos/Elastos.ELA/core/contract/program" - common2 "github.com/elastos/Elastos.ELA/core/types/common" ) type CheckParameters struct { // transaction - Version common2.TransactionVersion - TxType common2.TxType - PayloadVersion byte - Attributes []*common2.Attribute - Inputs []*common2.Input - Outputs []*common2.Output - LockTime uint32 - Programs []*pg.Program - TxHash common.Uint256 + Transaction Transaction // others BlockHeight uint32 diff --git a/core/types/payload/ReturnSideChainDepositCoin.go b/core/types/payload/ReturnSideChainDepositCoin.go index d00b1f96b..75683f08c 100644 --- a/core/types/payload/ReturnSideChainDepositCoin.go +++ b/core/types/payload/ReturnSideChainDepositCoin.go @@ -14,8 +14,6 @@ const ReturnSideChainDepositCoinVersion byte = 0x00 const ReturnSideChainDepositCoinVersionV1 byte = 0x01 type ReturnSideChainDepositCoin struct { - DefaultChecker - // schnorr Signers []uint8 } @@ -59,18 +57,3 @@ func (s *ReturnSideChainDepositCoin) Deserialize(r io.Reader, version byte) erro } return nil } - -// -//// todo add description -//func (a *ReturnSideChainDepositCoin) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *ReturnSideChainDepositCoin) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/activateproducer.go b/core/types/payload/activateproducer.go index dc4f754f6..ee9f43a42 100644 --- a/core/types/payload/activateproducer.go +++ b/core/types/payload/activateproducer.go @@ -19,8 +19,6 @@ const ( ) type ActivateProducer struct { - DefaultChecker - NodePublicKey []byte Signature []byte } diff --git a/core/types/payload/asset.go b/core/types/payload/asset.go index cff10e47f..5c0e29fc4 100644 --- a/core/types/payload/asset.go +++ b/core/types/payload/asset.go @@ -35,8 +35,6 @@ const ( //registered asset will be assigned to contract address type Asset struct { - DefaultChecker - Name string Description string Precision byte diff --git a/core/types/payload/coinbase.go b/core/types/payload/coinbase.go index 201d7120a..229145955 100644 --- a/core/types/payload/coinbase.go +++ b/core/types/payload/coinbase.go @@ -6,13 +6,8 @@ package payload import ( - "errors" - "fmt" - common2 "github.com/elastos/Elastos.ELA/core/types/common" "io" - elaerr "github.com/elastos/Elastos.ELA/errors" - "github.com/elastos/Elastos.ELA/common" ) @@ -24,8 +19,6 @@ const ( const CoinBaseVersion byte = 0x04 type CoinBase struct { - DefaultChecker - Content []byte } @@ -43,52 +36,3 @@ func (a *CoinBase) Deserialize(r io.Reader, version byte) error { a.Content = temp return err } - -// todo add description -func (a *CoinBase) SpecialCheck(para *CheckParameters) (elaerr.ELAError, bool) { - // todo special check, all check witch used isCoinbase function, need to move here. - if para.BlockHeight >= para.CRCommitteeStartHeight { - if para.ConsensusAlgorithm == 0x01 { - if !para.Outputs[0].ProgramHash.IsEqual(para.DestroyELAAddress) { - return elaerr.Simple(elaerr.ErrTxInvalidOutput, - errors.New("first output address should be "+ - "DestroyAddress in POW consensus algorithm")), true - } - } else { - if !para.Outputs[0].ProgramHash.IsEqual(para.CRAssetsAddress) { - return elaerr.Simple(elaerr.ErrTxInvalidOutput, - errors.New("first output address should be CR assets address")), true - } - } - } else if !para.Outputs[0].ProgramHash.IsEqual(para.FoundationAddress) { - return elaerr.Simple(elaerr.ErrTxInvalidOutput, - errors.New("first output address should be foundation address")), true - } - - fmt.Println("CoinBase self check") - return nil, true -} - -func (a *CoinBase) ContextCheck(para *CheckParameters) (map[*common2.Input]common2.Output, elaerr.ELAError) { - - if err := a.CheckTxHeightVersion(para); err != nil { - return nil, elaerr.Simple(elaerr.ErrTxHeightVersion, nil) - } - - //// check if duplicated with transaction in ledger - //if exist := b.db.IsTxHashDuplicate(txn.Hash()); exist { - // log.Warn("[CheckTransactionContext] duplicate transaction check failed.") - // return nil, elaerr.Simple(elaerr.ErrTxDuplicate, nil) - //} - if exist := a.IsTxHashDuplicate(para.TxHash); exist { - //log.Warn("[CheckTransactionContext] duplicate transaction check failed.") - return nil, elaerr.Simple(elaerr.ErrTxDuplicate, nil) - } - - firstErr, end := a.SpecialCheck(para) - if end { - return nil, firstErr - } - - return nil, nil -} diff --git a/core/types/payload/coinbase_test.go b/core/types/payload/coinbase_test.go index ec0432631..5ac128178 100644 --- a/core/types/payload/coinbase_test.go +++ b/core/types/payload/coinbase_test.go @@ -5,71 +5,64 @@ package payload -import ( - "testing" - - "github.com/elastos/Elastos.ELA/common" - common2 "github.com/elastos/Elastos.ELA/core/types/common" -) - -func TestCoinBase_FunctionRewrite(t *testing.T) { - var para = &CheckParameters{ - Version: 0, - TxType: 0, - PayloadVersion: 0, - Attributes: nil, - Inputs: []*common2.Input{ - { - Previous: common2.OutPoint{ - TxID: common.Uint256{1}, - Index: 0, - }, - Sequence: 0, - }, - }, - Outputs: []*common2.Output{ - { - AssetID: common.Uint256{2}, - Value: 100, - OutputLock: 0, - ProgramHash: common.Uint168{}, - Type: 0, - Payload: nil, - }, - }, - LockTime: 0, - Programs: nil, - TxHash: common.Uint256{}, - BlockHeight: 0, - CRCommitteeStartHeight: 0, - ConsensusAlgorithm: 0, - DestroyELAAddress: common.Uint168{}, - CRAssetsAddress: common.Uint168{}, - FoundationAddress: common.Uint168{}, - } // self check - payload := CoinBase{ - DefaultChecker: DefaultChecker{ - IsTxHashDuplicateFunction: func(txhash common.Uint256) bool { return false }, - GetTxReferenceFunction: func(para *CheckParameters) (map[*common2.Input]common2.Output, error) { - result := make(map[*common2.Input]common2.Output) - return result, nil - }, - }, - } - payload.ContextCheck(para) - payload.SpecialCheck(para) - - // default check - payload2 := Confirm{ - DefaultChecker: DefaultChecker{ - IsTxHashDuplicateFunction: func(txhash common.Uint256) bool { return false }, - GetTxReferenceFunction: func(para *CheckParameters) (map[*common2.Input]common2.Output, error) { - result := make(map[*common2.Input]common2.Output) - return result, nil - }, - }, - } - payload2.ContextCheck(para) - payload2.SpecialCheck(para) - -} +//func TestCoinBase_FunctionRewrite(t *testing.T) { +// var para = &interfaces.CheckParameters{ +// Version: 0, +// TxType: 0, +// PayloadVersion: 0, +// Attributes: nil, +// Inputs: []*common2.Input{ +// { +// Previous: common2.OutPoint{ +// TxID: common.Uint256{1}, +// Index: 0, +// }, +// Sequence: 0, +// }, +// }, +// Outputs: []*common2.Output{ +// { +// AssetID: common.Uint256{2}, +// Value: 100, +// OutputLock: 0, +// ProgramHash: common.Uint168{}, +// Type: 0, +// Payload: nil, +// }, +// }, +// LockTime: 0, +// Programs: nil, +// TxHash: common.Uint256{}, +// BlockHeight: 0, +// CRCommitteeStartHeight: 0, +// ConsensusAlgorithm: 0, +// DestroyELAAddress: common.Uint168{}, +// CRAssetsAddress: common.Uint168{}, +// FoundationAddress: common.Uint168{}, +// } // self check +// payload := CoinBase{ +// DefaultChecker: DefaultChecker{ +// IsTxHashDuplicateFunction: func(txhash common.Uint256) bool { return false }, +// GetTxReferenceFunction: func(para *interfaces.CheckParameters) (map[*common2.Input]common2.Output, error) { +// result := make(map[*common2.Input]common2.Output) +// return result, nil +// }, +// }, +// } +// payload.ContextCheck(para) +// payload.SpecialCheck(para) +// +// // default check +// payload2 := Confirm{ +// DefaultChecker: DefaultChecker{ +// IsTxHashDuplicateFunction: func(txhash common.Uint256) bool { return false }, +// GetTxReferenceFunction: func(para *interfaces.CheckParameters) (map[*common2.Input]common2.Output, error) { +// result := make(map[*common2.Input]common2.Output) +// return result, nil +// }, +// }, +// } +// payload2.ContextCheck(para) +// payload2.SpecialCheck(para) +// +//} diff --git a/core/types/payload/confirm.go b/core/types/payload/confirm.go index a5be1f4ad..6ed4e5e98 100644 --- a/core/types/payload/confirm.go +++ b/core/types/payload/confirm.go @@ -12,8 +12,6 @@ import ( ) type Confirm struct { - DefaultChecker - Proposal DPOSProposal Votes []DPOSProposalVote } diff --git a/core/types/payload/crassetsrectify.go b/core/types/payload/crassetsrectify.go index 24bd31d94..a69ecb148 100644 --- a/core/types/payload/crassetsrectify.go +++ b/core/types/payload/crassetsrectify.go @@ -12,7 +12,6 @@ import ( const CRAssetsRectifyVersion byte = 0x00 type CRAssetsRectify struct { - DefaultChecker } func (p *CRAssetsRectify) Data(version byte) []byte { diff --git a/core/types/payload/crcappropriation.go b/core/types/payload/crcappropriation.go index 403472343..bb1f5e76b 100644 --- a/core/types/payload/crcappropriation.go +++ b/core/types/payload/crcappropriation.go @@ -12,7 +12,6 @@ import ( const CRCAppropriationVersion byte = 0x00 type CRCAppropriation struct { - DefaultChecker } func (p *CRCAppropriation) Data(version byte) []byte { diff --git a/core/types/payload/crcproposal.go b/core/types/payload/crcproposal.go index 7625bba03..df0607d9f 100644 --- a/core/types/payload/crcproposal.go +++ b/core/types/payload/crcproposal.go @@ -139,8 +139,6 @@ type Budget struct { } type CRCProposal struct { - DefaultChecker - // The type of current CR Council proposal. ProposalType CRCProposalType @@ -1646,7 +1644,7 @@ func (p *CRCProposalInfo) Deserialize(r io.Reader, version byte) error { return errors.New("failed to deserialize Recipient") } - if p.NewOwnerPublicKey, err = common.ReadVarBytes(r, crypto.NegativeBigLength, "owner"); err != nil{ + if p.NewOwnerPublicKey, err = common.ReadVarBytes(r, crypto.NegativeBigLength, "owner"); err != nil { return errors.New("failed to deserialize NewOwnerPublicKey") } @@ -1672,18 +1670,3 @@ func (p *CRCProposalInfo) Deserialize(r io.Reader, version byte) error { } return nil } - -// -//// todo add description -//func (a *CRCProposal) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *CRCProposal) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/crcproposalrealwithdraw.go b/core/types/payload/crcproposalrealwithdraw.go index dff201f39..028791bba 100644 --- a/core/types/payload/crcproposalrealwithdraw.go +++ b/core/types/payload/crcproposalrealwithdraw.go @@ -16,8 +16,6 @@ import ( const CRCProposalRealWithdrawVersion byte = 0x00 type CRCProposalRealWithdraw struct { - DefaultChecker - // Hash of the proposal to withdrawal ela. WithdrawTransactionHashes []common.Uint256 } @@ -66,18 +64,3 @@ func (p *CRCProposalRealWithdraw) Deserialize(r io.Reader, version byte) error { return nil } - -// -//// todo add description -//func (a *CRCProposalRealWithdraw) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *CRCProposalRealWithdraw) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/crcproposalreview.go b/core/types/payload/crcproposalreview.go index 78005e5ae..78352c78b 100644 --- a/core/types/payload/crcproposalreview.go +++ b/core/types/payload/crcproposalreview.go @@ -47,8 +47,6 @@ func (v VoteResult) Name() string { } type CRCProposalReview struct { - DefaultChecker - ProposalHash common.Uint256 VoteResult VoteResult OpinionHash common.Uint256 @@ -138,17 +136,3 @@ func (a *CRCProposalReview) DeserializeUnsigned(r io.Reader, version byte) error } return nil } -// -//// todo add description -//func (a *CRCProposalReview) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *CRCProposalReview) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/crcproposaltracking.go b/core/types/payload/crcproposaltracking.go index 22b31cf8c..4834b03de 100644 --- a/core/types/payload/crcproposaltracking.go +++ b/core/types/payload/crcproposaltracking.go @@ -76,7 +76,6 @@ const ( ) type CRCProposalTracking struct { - DefaultChecker // The hash of current tracking proposal. ProposalHash common.Uint256 @@ -265,17 +264,3 @@ func (p *CRCProposalTracking) Deserialize(r io.Reader, version byte) error { return nil } -// -//// todo add description -//func (a *CRCProposalTracking) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *CRCProposalTracking) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/crcproposalwithdraw.go b/core/types/payload/crcproposalwithdraw.go index ff1471622..f09d50cfc 100644 --- a/core/types/payload/crcproposalwithdraw.go +++ b/core/types/payload/crcproposalwithdraw.go @@ -20,8 +20,6 @@ const ( ) type CRCProposalWithdraw struct { - DefaultChecker - // Hash of the proposal to withdrawal ela. ProposalHash common.Uint256 @@ -117,17 +115,3 @@ func (p *CRCProposalWithdraw) DeserializeUnsigned(r io.Reader, } return nil } -// -//// todo add description -//func (a *CRCProposalWithdraw) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *CRCProposalWithdraw) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/crdposmanagement.go b/core/types/payload/crdposmanagement.go index 78dbe4267..6c87f7934 100644 --- a/core/types/payload/crdposmanagement.go +++ b/core/types/payload/crdposmanagement.go @@ -12,8 +12,6 @@ import ( const CRManagementVersion byte = 0x00 type CRCouncilMemberClaimNode struct { - DefaultChecker - NodePublicKey []byte CRCouncilCommitteeDID common.Uint168 CRCouncilCommitteeSignature []byte @@ -72,17 +70,3 @@ func (p *CRCouncilMemberClaimNode) DeserializeUnsigned(r io.Reader, version byte } return nil } -// -//// todo add description -//func (a *CRCouncilMemberClaimNode) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *CRCouncilMemberClaimNode) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/crinfo.go b/core/types/payload/crinfo.go index bb653f3ab..ef2263495 100644 --- a/core/types/payload/crinfo.go +++ b/core/types/payload/crinfo.go @@ -19,8 +19,6 @@ const CRInfoDIDVersion byte = 0x01 // CRInfo defines the information of CR. type CRInfo struct { - DefaultChecker - Code []byte CID common.Uint168 DID common.Uint168 @@ -136,17 +134,4 @@ func (a *CRInfo) DeserializeUnsigned(r io.Reader, version byte) error { func (a *CRInfo) GetCodeHash() common.Uint160 { return *common.ToCodeHash(a.Code) } -// -//// todo add description -//func (a *CRInfo) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *CRInfo) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} + diff --git a/core/types/payload/customidresult.go b/core/types/payload/customidresult.go index cf9f5b5a2..661231565 100644 --- a/core/types/payload/customidresult.go +++ b/core/types/payload/customidresult.go @@ -10,8 +10,6 @@ import ( const CustomIDResultVersion byte = 0x00 type RecordProposalResult struct { - DefaultChecker - ProposalResults []ProposalResult } @@ -101,17 +99,3 @@ func (p *RecordProposalResult) DeserializeUnsigned(r io.Reader, version byte) er } return nil } -// -//// todo add description -//func (a *RecordProposalResult) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *RecordProposalResult) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/dposillegalblocks.go b/core/types/payload/dposillegalblocks.go index dd6faa44d..bf3066320 100644 --- a/core/types/payload/dposillegalblocks.go +++ b/core/types/payload/dposillegalblocks.go @@ -31,8 +31,6 @@ type BlockEvidence struct { } type DPOSIllegalBlocks struct { - DefaultChecker - CoinType CoinType BlockHeight uint32 Evidence BlockEvidence @@ -233,17 +231,3 @@ func (d *DPOSIllegalBlocks) GetBlockHeight() uint32 { func (d *DPOSIllegalBlocks) Type() IllegalDataType { return IllegalBlock } -// -//// todo add description -//func (a *DPOSIllegalBlocks) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *DPOSIllegalBlocks) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/dposillegalproposals.go b/core/types/payload/dposillegalproposals.go index ce711a86b..2a7cbc250 100644 --- a/core/types/payload/dposillegalproposals.go +++ b/core/types/payload/dposillegalproposals.go @@ -24,8 +24,6 @@ type ProposalEvidence struct { } type DPOSIllegalProposals struct { - DefaultChecker - Evidence ProposalEvidence CompareEvidence ProposalEvidence @@ -114,17 +112,3 @@ func (d *DPOSIllegalProposals) GetBlockHeight() uint32 { func (d *DPOSIllegalProposals) Type() IllegalDataType { return IllegalProposal } -// -//// todo add description -//func (a *DPOSIllegalProposals) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *DPOSIllegalProposals) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/dposillegalvotes.go b/core/types/payload/dposillegalvotes.go index 49c6a8c3f..28e66edae 100644 --- a/core/types/payload/dposillegalvotes.go +++ b/core/types/payload/dposillegalvotes.go @@ -22,8 +22,6 @@ type VoteEvidence struct { } type DPOSIllegalVotes struct { - DefaultChecker - Evidence VoteEvidence CompareEvidence VoteEvidence @@ -103,17 +101,3 @@ func (d *DPOSIllegalVotes) GetBlockHeight() uint32 { func (d *DPOSIllegalVotes) Type() IllegalDataType { return IllegalVote } -// -//// todo add description -//func (a *DPOSIllegalVotes) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *DPOSIllegalVotes) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/dposproposal.go b/core/types/payload/dposproposal.go index fe22bfb41..f058aa269 100644 --- a/core/types/payload/dposproposal.go +++ b/core/types/payload/dposproposal.go @@ -14,8 +14,6 @@ import ( ) type DPOSProposal struct { - DefaultChecker - Sponsor []byte BlockHash common.Uint256 ViewOffset uint32 @@ -84,17 +82,3 @@ func (p *DPOSProposal) Hash() common.Uint256 { } return *p.hash } -// -//// todo add description -//func (a *DPOSProposal) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *DPOSProposal) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/dposproposalvote.go b/core/types/payload/dposproposalvote.go index fb0eb758f..a9f329ec1 100644 --- a/core/types/payload/dposproposalvote.go +++ b/core/types/payload/dposproposalvote.go @@ -14,8 +14,6 @@ import ( ) type DPOSProposalVote struct { - DefaultChecker - ProposalHash common.Uint256 Signer []byte @@ -111,17 +109,3 @@ func (v *DPOSProposalVote) Hash() common.Uint256 { } return *v.hash } -// -//// todo add description -//func (a *DPOSProposalVote) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *DPOSProposalVote) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/inactivearbitrators.go b/core/types/payload/inactivearbitrators.go index fff2ad11e..ca3fcf73d 100644 --- a/core/types/payload/inactivearbitrators.go +++ b/core/types/payload/inactivearbitrators.go @@ -16,8 +16,6 @@ import ( const InactiveArbitratorsVersion byte = 0x00 type InactiveArbitrators struct { - DefaultChecker - Sponsor []byte Arbitrators [][]byte BlockHeight uint32 @@ -114,17 +112,3 @@ func (i *InactiveArbitrators) Hash() common.Uint256 { } return *i.hash } -// -//// todo add description -//func (a *InactiveArbitrators) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *InactiveArbitrators) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/nextturndposinfo.go b/core/types/payload/nextturndposinfo.go index 64aea82f0..ae000a04b 100644 --- a/core/types/payload/nextturndposinfo.go +++ b/core/types/payload/nextturndposinfo.go @@ -11,8 +11,6 @@ import ( const NextTurnDPOSInfoVersion byte = 0x00 type NextTurnDPOSInfo struct { - DefaultChecker - WorkingHeight uint32 CRPublicKeys [][]byte DPOSPublicKeys [][]byte @@ -121,17 +119,3 @@ func (n *NextTurnDPOSInfo) Hash() common.Uint256 { } return *n.hash } -// -//// todo add description -//func (a *NextTurnDPOSInfo) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *NextTurnDPOSInfo) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/processproducer.go b/core/types/payload/processproducer.go index c6dba2132..40ecbc812 100644 --- a/core/types/payload/processproducer.go +++ b/core/types/payload/processproducer.go @@ -22,8 +22,6 @@ const ( ) type ProcessProducer struct { - DefaultChecker - OwnerPublicKey []byte Signature []byte } @@ -82,17 +80,3 @@ func (a *ProcessProducer) DeserializeUnsigned(r io.Reader, version byte) error { return err } -// -//// todo add description -//func (a *ProcessProducer) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *ProcessProducer) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/producerinfo.go b/core/types/payload/producerinfo.go index be59cfd84..399323271 100644 --- a/core/types/payload/producerinfo.go +++ b/core/types/payload/producerinfo.go @@ -17,8 +17,6 @@ import ( const ProducerInfoVersion byte = 0x00 type ProducerInfo struct { - DefaultChecker - OwnerPublicKey []byte NodePublicKey []byte NickName string @@ -131,17 +129,3 @@ func (a *ProducerInfo) DeserializeUnsigned(r io.Reader, version byte) error { return nil } -// -//// todo add description -//func (a *ProducerInfo) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *ProducerInfo) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/record.go b/core/types/payload/record.go index dfbc3c68f..0fca428a8 100644 --- a/core/types/payload/record.go +++ b/core/types/payload/record.go @@ -15,8 +15,6 @@ import ( const RecordVersion byte = 0x00 type Record struct { - DefaultChecker - Type string Content []byte } @@ -53,17 +51,3 @@ func (a *Record) Deserialize(r io.Reader, version byte) error { } return nil } -// -//// todo add description -//func (a *Record) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *Record) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/registerasset.go b/core/types/payload/registerasset.go index 092c69cbe..77ff2aeb2 100644 --- a/core/types/payload/registerasset.go +++ b/core/types/payload/registerasset.go @@ -13,8 +13,6 @@ import ( ) type RegisterAsset struct { - DefaultChecker - Asset Asset Amount common.Fixed64 Controller common.Uint168 @@ -62,17 +60,3 @@ func (a *RegisterAsset) Deserialize(r io.Reader, version byte) error { } return nil } -// -//// todo add description -//func (a *RegisterAsset) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *RegisterAsset) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/returnpledgecoin.go b/core/types/payload/returnpledgecoin.go index caae8f4f7..f9be54169 100644 --- a/core/types/payload/returnpledgecoin.go +++ b/core/types/payload/returnpledgecoin.go @@ -12,8 +12,6 @@ import ( const ReturnDepositCoinVersion byte = 0x00 type ReturnDepositCoin struct { - DefaultChecker - } func (a *ReturnDepositCoin) Data(version byte) []byte { @@ -27,17 +25,3 @@ func (a *ReturnDepositCoin) Serialize(w io.Writer, version byte) error { func (a *ReturnDepositCoin) Deserialize(r io.Reader, version byte) error { return nil } -// -//// todo add description -//func (a *ReturnDepositCoin) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *ReturnDepositCoin) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/reverttodpos.go b/core/types/payload/reverttodpos.go index 0b6183c3d..068824544 100644 --- a/core/types/payload/reverttodpos.go +++ b/core/types/payload/reverttodpos.go @@ -16,8 +16,6 @@ const WorkHeightInterval = 10 const RevertToDPOSVersion byte = 0x00 type RevertToDPOS struct { - DefaultChecker - WorkHeightInterval uint32 RevertToPOWBlockHeight uint32 } @@ -69,17 +67,3 @@ func (i *RevertToDPOS) Deserialize(r io.Reader, } return nil } -// -//// todo add description -//func (a *RevertToDPOS) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *RevertToDPOS) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/reverttopow.go b/core/types/payload/reverttopow.go index f6480f146..0b4b7dd1e 100644 --- a/core/types/payload/reverttopow.go +++ b/core/types/payload/reverttopow.go @@ -24,8 +24,6 @@ const ( type RevertType byte type RevertToPOW struct { - DefaultChecker - Type RevertType WorkingHeight uint32 } @@ -73,17 +71,3 @@ func (a *RevertToPOW) Deserialize(r io.Reader, version byte) error { } return nil } -// -//// todo add description -//func (a *RevertToPOW) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *RevertToPOW) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/sidechainillegaldata.go b/core/types/payload/sidechainillegaldata.go index 5d23aedc1..04a72b8be 100644 --- a/core/types/payload/sidechainillegaldata.go +++ b/core/types/payload/sidechainillegaldata.go @@ -20,8 +20,6 @@ type SidechainIllegalEvidence struct { } type SidechainIllegalData struct { - DefaultChecker - IllegalType IllegalDataType Height uint32 IllegalSigner []byte @@ -174,17 +172,3 @@ func (s *SidechainIllegalData) Hash() common.Uint256 { } return *s.hash } -// -//// todo add description -//func (a *SidechainIllegalData) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *SidechainIllegalData) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/sidechainpow.go b/core/types/payload/sidechainpow.go index 544cd0e8a..724d0a56d 100644 --- a/core/types/payload/sidechainpow.go +++ b/core/types/payload/sidechainpow.go @@ -16,8 +16,6 @@ import ( const SideChainPowVersion byte = 0x00 type SideChainPow struct { - DefaultChecker - SideBlockHash common.Uint256 SideGenesisHash common.Uint256 BlockHeight uint32 @@ -82,17 +80,3 @@ func (a *SideChainPow) Deserialize(r io.Reader, version byte) error { } return nil } -// -//// todo add description -//func (a *SideChainPow) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *SideChainPow) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/transferasset.go b/core/types/payload/transferasset.go index b47d642d6..a37a6ceb9 100644 --- a/core/types/payload/transferasset.go +++ b/core/types/payload/transferasset.go @@ -5,10 +5,11 @@ package payload -import "io" +import ( + "io" +) type TransferAsset struct{ - DefaultChecker } func (a *TransferAsset) Data(version byte) []byte { @@ -23,18 +24,3 @@ func (a *TransferAsset) Serialize(w io.Writer, version byte) error { func (a *TransferAsset) Deserialize(r io.Reader, version byte) error { return nil } - -// -//// todo add description -//func (a *TransferAsset) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *TransferAsset) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/payload/transfercrosschainasset.go b/core/types/payload/transfercrosschainasset.go index e77514a3a..6519ab093 100644 --- a/core/types/payload/transfercrosschainasset.go +++ b/core/types/payload/transfercrosschainasset.go @@ -17,8 +17,6 @@ const TransferCrossChainVersion byte = 0x00 const TransferCrossChainVersionV1 byte = 0x01 type TransferCrossChainAsset struct { - DefaultChecker - CrossChainAddresses []string OutputIndexes []uint64 CrossChainAmounts []common.Fixed64 @@ -101,17 +99,3 @@ func (a *TransferCrossChainAsset) Deserialize(r io.Reader, version byte) error { return nil } -// -//// todo add description -//func (a *TransferCrossChainAsset) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *TransferCrossChainAsset) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/unregistercr.go b/core/types/payload/unregistercr.go index 065ba3fae..36c367efe 100644 --- a/core/types/payload/unregistercr.go +++ b/core/types/payload/unregistercr.go @@ -17,8 +17,6 @@ import ( const UnregisterCRVersion byte = 0x00 type UnregisterCR struct { - DefaultChecker - CID common.Uint168 Signature []byte } @@ -71,17 +69,3 @@ func (a *UnregisterCR) DeserializeUnsigned(r io.Reader, version byte) error { } return nil } -// -//// todo add description -//func (a *UnregisterCR) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *UnregisterCR) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/updateversion.go b/core/types/payload/updateversion.go index 6902be17c..09a8284a8 100644 --- a/core/types/payload/updateversion.go +++ b/core/types/payload/updateversion.go @@ -15,8 +15,6 @@ import ( const UpdateVersionVersion byte = 0x00 type UpdateVersion struct { - DefaultChecker - StartHeight uint32 EndHeight uint32 } @@ -52,17 +50,3 @@ func (u *UpdateVersion) Deserialize(r io.Reader, version byte) (err error) { return nil } -// -//// todo add description -//func (a *UpdateVersion) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *UpdateVersion) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} \ No newline at end of file diff --git a/core/types/payload/withdrawfromsidechain.go b/core/types/payload/withdrawfromsidechain.go index c9bc1ef9a..daa2164f8 100644 --- a/core/types/payload/withdrawfromsidechain.go +++ b/core/types/payload/withdrawfromsidechain.go @@ -18,8 +18,6 @@ const WithdrawFromSideChainVersionV1 byte = 0x01 const WithdrawFromSideChainVersionV2 byte = 0x02 // for schnorr type WithdrawFromSideChain struct { - DefaultChecker - BlockHeight uint32 GenesisBlockAddress string SideChainTransactionHashes []common.Uint256 @@ -120,17 +118,3 @@ func (t *WithdrawFromSideChain) Deserialize(r io.Reader, version byte) error { return nil } -// -//// todo add description -//func (a *WithdrawFromSideChain) SpecialCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} -// -//// todo add description -//func (a *WithdrawFromSideChain) SecondCheck(txn *types.Transaction, -// p *CheckParameters) (elaerr.ELAError, bool) { -// // todo special check -// return nil, false -//} diff --git a/core/types/transaction_test.go b/core/types/transaction_test.go index 562ef58ed..facae226c 100644 --- a/core/types/transaction_test.go +++ b/core/types/transaction_test.go @@ -10,6 +10,7 @@ import ( crand "crypto/rand" "encoding/binary" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math/rand" "strconv" "testing" @@ -49,7 +50,7 @@ func (s *transactionSuite) TestCoinbaseTransaction_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(true, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -74,7 +75,7 @@ func (s *transactionSuite) TestRegisterAssetTransaction_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(true, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -98,7 +99,7 @@ func (s *transactionSuite) TestTransferAssert_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(true, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -114,7 +115,7 @@ func (s *transactionSuite) TestRecord_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(true, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -138,7 +139,7 @@ func (s *transactionSuite) TestSideChainPow_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(true, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -166,7 +167,7 @@ func (s *transactionSuite) TestWithdrawFromSideChain_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(true, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -202,7 +203,7 @@ func (s *transactionSuite) TestTransferCrossChainAsset_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(true, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -239,7 +240,7 @@ func (s *transactionSuite) TestRegisterProducer_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -265,7 +266,7 @@ func (s *transactionSuite) TestCancelProducer_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, @@ -289,7 +290,7 @@ func (s *transactionSuite) TestActivateProducer_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, @@ -315,7 +316,7 @@ func (s *transactionSuite) TestUpdateProducer_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -337,7 +338,7 @@ func (s *transactionSuite) TestReturnDepositCoin_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -377,7 +378,7 @@ func (s *transactionSuite) TestIllegalProposalEvidence_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -430,7 +431,7 @@ func (s *transactionSuite) TestIllegalVoteEvidence_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -465,7 +466,7 @@ func (s *transactionSuite) TestIllegalBlockEvidence_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -497,7 +498,7 @@ func (s *transactionSuite) TestSidechainIllegalData_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -531,7 +532,7 @@ func (s *transactionSuite) TestInactiveArbitrators_SerializeDeserialize() { serializedData := new(bytes.Buffer) txn.Serialize(serializedData) - txn2 := &Transaction{} + txn2 := &transactions.BaseTransaction{} txn2.Deserialize(serializedData) assertOldVersionTxEqual(false, &s.Suite, txn, txn2, s.InputNum, s.OutputNum, s.AttrNum, s.ProgramNum) @@ -813,7 +814,7 @@ func (s *transactionSuite) TestTransaction_SpecificSample() { updateProducerByteStr := "090b0021034f3a7d2f33ac7f4e30876080d359ce5f314c9eabddbaaca637676377f655e16c2103c77af162438d4b7140f8544ad6523b9734cca9c7a62476d54ed5d1bddc7a39c309656c615f74657374310d656c615f74657374312e6f726754b60100000000000931302e31302e302e3240920d8e769640b8494cfdf7c5581982c329485c8d3083db7d3079de104dc0dc650d8592a5e1d70f5c24f72b3f29b0625dc6348e375b13c3c48992d398d9f5d9ac000146f1d8002115ce89423ab29f26ede6ef1b813642cbf3c4c15b919b41d6d9f7760100ffffffff01b037db964a231458d2d6ffd5ea18944c4f90e63d547c5d3b9874df66a4ead0a300d414000000000000000000210d4109bf00e6d782db40ab183491c03cf4d6a37a00000000000141408fc0c3de6198c3ec4e9ab8a7748208d79a554c9d1ef84edec23c444495b651deb7a8796ac49e31f1d2598207d216c05496b35d7f75a22c55272223995781bb402321034f3a7d2f33ac7f4e30876080d359ce5f314c9eabddbaaca637676377f655e16cac" updateProducerByte, _ := common.HexStringToBytes(updateProducerByteStr) byteReader.Write(updateProducerByte) - txn := &Transaction{} + txn := &transactions.BaseTransaction{} s.NoError(txn.Deserialize(byteReader)) } @@ -821,7 +822,7 @@ func TestTransactionSuite(t *testing.T) { suite.Run(t, new(transactionSuite)) } -func assertOldVersionTxEqual(oldVersion bool, suite *suite.Suite, first, second *Transaction, inputNum, outputNum, attrNum, programNum int) { +func assertOldVersionTxEqual(oldVersion bool, suite *suite.Suite, first, second *transactions.BaseTransaction, inputNum, outputNum, attrNum, programNum int) { if oldVersion { suite.Equal(common2.TxVersionDefault, second.Version) } else { @@ -867,8 +868,8 @@ func assertOldVersionTxEqual(oldVersion bool, suite *suite.Suite, first, second } } -func randomOldVersionTransaction(oldVersion bool, txType byte, inputNum, outputNum, attrNum, programNum int) *Transaction { - txn := &Transaction{ +func randomOldVersionTransaction(oldVersion bool, txType byte, inputNum, outputNum, attrNum, programNum int) *transactions.BaseTransaction { + txn := &transactions.BaseTransaction{ Version: common2.TransactionVersion(txType), TxType: common2.TxType(txType), PayloadVersion: byte(0), diff --git a/core/types/transactions/coinbasetransaction.go b/core/types/transactions/coinbasetransaction.go new file mode 100644 index 000000000..ae66f561f --- /dev/null +++ b/core/types/transactions/coinbasetransaction.go @@ -0,0 +1,76 @@ +// Copyright (c) 2017-2021 The Elastos Foundation +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. +// + +package transactions + +import ( + "errors" + "fmt" + common2 "github.com/elastos/Elastos.ELA/core/types/common" + elaerr "github.com/elastos/Elastos.ELA/errors" + + "github.com/elastos/Elastos.ELA/core/types/interfaces" +) + +const ( + // MaxPayloadDataSize is the maximum allowed length of payload data. + MaxPayloadDataSize = 1024 * 1024 // 1MB +) + +const CoinBaseVersion byte = 0x04 + +type CoinBaseTransaction struct { + BaseTransaction +} + +// todo add description +func (a *CoinBaseTransaction) SpecialCheck(para *interfaces.CheckParameters) (elaerr.ELAError, bool) { + // todo special check, all check witch used isCoinbase function, need to move here. + + if para.BlockHeight >= para.CRCommitteeStartHeight { + if para.ConsensusAlgorithm == 0x01 { + if !a.Outputs[0].ProgramHash.IsEqual(para.DestroyELAAddress) { + return elaerr.Simple(elaerr.ErrTxInvalidOutput, + errors.New("first output address should be "+ + "DestroyAddress in POW consensus algorithm")), true + } + } else { + if !a.Outputs[0].ProgramHash.IsEqual(para.CRAssetsAddress) { + return elaerr.Simple(elaerr.ErrTxInvalidOutput, + errors.New("first output address should be CR assets address")), true + } + } + } else if !a.Outputs[0].ProgramHash.IsEqual(para.FoundationAddress) { + return elaerr.Simple(elaerr.ErrTxInvalidOutput, + errors.New("first output address should be foundation address")), true + } + + fmt.Println("CoinBase self check") + return nil, true +} + +func (a *CoinBaseTransaction) ContextCheck(para *interfaces.CheckParameters) (map[*common2.Input]common2.Output, elaerr.ELAError) { + + if err := a.CheckTxHeightVersion(para); err != nil { + return nil, elaerr.Simple(elaerr.ErrTxHeightVersion, nil) + } + + //// check if duplicated with transaction in ledger + //if exist := b.db.IsTxHashDuplicate(txn.Hash()); exist { + // log.Warn("[CheckTransactionContext] duplicate transaction check failed.") + // return nil, elaerr.Simple(elaerr.ErrTxDuplicate, nil) + //} + if exist := a.IsTxHashDuplicate(*a.txHash); exist { + //log.Warn("[CheckTransactionContext] duplicate transaction check failed.") + return nil, elaerr.Simple(elaerr.ErrTxDuplicate, nil) + } + + firstErr, end := a.SpecialCheck(para) + if end { + return nil, firstErr + } + + return nil, nil +} diff --git a/core/types/transaction.go b/core/types/transactions/transaction.go similarity index 75% rename from core/types/transaction.go rename to core/types/transactions/transaction.go index 727de0b39..cabe64f02 100644 --- a/core/types/transaction.go +++ b/core/types/transactions/transaction.go @@ -3,30 +3,33 @@ // license that can be found in the LICENSE file. // -package types +package transactions import ( "bytes" "errors" "fmt" - "github.com/elastos/Elastos.ELA/core/contract" - common2 "github.com/elastos/Elastos.ELA/core/types/common" - "github.com/elastos/Elastos.ELA/core/types/payload" "io" "github.com/elastos/Elastos.ELA/common" + "github.com/elastos/Elastos.ELA/core/contract" pg "github.com/elastos/Elastos.ELA/core/contract/program" + common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" + "github.com/elastos/Elastos.ELA/core/types/payload" ) const ( InvalidTransactionSize = -1 ) -type Transaction struct { +type BaseTransaction struct { + DefaultChecker + Version common2.TransactionVersion // New field added in TxVersion09 TxType common2.TxType PayloadVersion byte - Payload Payload + Payload interfaces.Payload Attributes []*common2.Attribute Inputs []*common2.Input Outputs []*common2.Output @@ -38,8 +41,8 @@ type Transaction struct { txHash *common.Uint256 } -func (tx *Transaction) String() string { - return fmt.Sprint("Transaction: {\n\t", +func (tx *BaseTransaction) String() string { + return fmt.Sprint("BaseTransaction: {\n\t", "Hash: ", tx.hash().String(), "\n\t", "Version: ", tx.Version, "\n\t", "TxType: ", tx.TxType.Name(), "\n\t", @@ -53,25 +56,25 @@ func (tx *Transaction) String() string { "}\n") } -// Serialize the Transaction -func (tx *Transaction) Serialize(w io.Writer) error { +// Serialize the BaseTransaction +func (tx *BaseTransaction) Serialize(w io.Writer) error { if err := tx.SerializeUnsigned(w); err != nil { - return errors.New("Transaction txSerializeUnsigned Serialize failed, " + err.Error()) + return errors.New("BaseTransaction txSerializeUnsigned Serialize failed, " + err.Error()) } - //Serialize Transaction's programs + //Serialize BaseTransaction's programs if err := common.WriteVarUint(w, uint64(len(tx.Programs))); err != nil { - return errors.New("Transaction program count failed.") + return errors.New("BaseTransaction program count failed.") } for _, program := range tx.Programs { if err := program.Serialize(w); err != nil { - return errors.New("Transaction Programs Serialize failed, " + err.Error()) + return errors.New("BaseTransaction Programs Serialize failed, " + err.Error()) } } return nil } -// Serialize the Transaction data without contracts -func (tx *Transaction) SerializeUnsigned(w io.Writer) error { +// Serialize the BaseTransaction data without contracts +func (tx *BaseTransaction) SerializeUnsigned(w io.Writer) error { // Version if tx.Version >= common2.TxVersion09 { if _, err := w.Write([]byte{byte(tx.Version)}); err != nil { @@ -88,7 +91,7 @@ func (tx *Transaction) SerializeUnsigned(w io.Writer) error { } // Payload if tx.Payload == nil { - return errors.New("Transaction Payload is nil.") + return errors.New("BaseTransaction Payload is nil.") } if err := tx.Payload.Serialize(w, tx.PayloadVersion); err != nil { return err @@ -96,7 +99,7 @@ func (tx *Transaction) SerializeUnsigned(w io.Writer) error { //[]*txAttribute if err := common.WriteVarUint(w, uint64(len(tx.Attributes))); err != nil { - return errors.New("Transaction item txAttribute length serialization failed.") + return errors.New("BaseTransaction item txAttribute length serialization failed.") } for _, attr := range tx.Attributes { if err := attr.Serialize(w); err != nil { @@ -106,7 +109,7 @@ func (tx *Transaction) SerializeUnsigned(w io.Writer) error { //[]*Inputs if err := common.WriteVarUint(w, uint64(len(tx.Inputs))); err != nil { - return errors.New("Transaction item Inputs length serialization failed.") + return errors.New("BaseTransaction item Inputs length serialization failed.") } for _, utxo := range tx.Inputs { if err := utxo.Serialize(w); err != nil { @@ -116,7 +119,7 @@ func (tx *Transaction) SerializeUnsigned(w io.Writer) error { //[]*Outputs if err := common.WriteVarUint(w, uint64(len(tx.Outputs))); err != nil { - return errors.New("Transaction item Outputs length serialization failed.") + return errors.New("BaseTransaction item Outputs length serialization failed.") } for _, output := range tx.Outputs { if err := output.Serialize(w, tx.Version); err != nil { @@ -127,8 +130,8 @@ func (tx *Transaction) SerializeUnsigned(w io.Writer) error { return common.WriteUint32(w, tx.LockTime) } -// Deserialize the Transaction -func (tx *Transaction) Deserialize(r io.Reader) error { +// Deserialize the BaseTransaction +func (tx *BaseTransaction) Deserialize(r io.Reader) error { // tx deserialize if err := tx.DeserializeUnsigned(r); err != nil { return errors.New("transaction Deserialize error: " + err.Error()) @@ -149,7 +152,7 @@ func (tx *Transaction) Deserialize(r io.Reader) error { return nil } -func (tx *Transaction) DeserializeUnsigned(r io.Reader) error { +func (tx *BaseTransaction) DeserializeUnsigned(r io.Reader) error { flagByte, err := common.ReadBytes(r, 1) if err != nil { return err @@ -227,7 +230,7 @@ func (tx *Transaction) DeserializeUnsigned(r io.Reader) error { return nil } -func (tx *Transaction) GetSize() int { +func (tx *BaseTransaction) GetSize() int { buf := new(bytes.Buffer) if err := tx.Serialize(buf); err != nil { return InvalidTransactionSize @@ -235,13 +238,13 @@ func (tx *Transaction) GetSize() int { return buf.Len() } -func (tx *Transaction) hash() common.Uint256 { +func (tx *BaseTransaction) hash() common.Uint256 { buf := new(bytes.Buffer) tx.SerializeUnsigned(buf) return common.Hash(buf.Bytes()) } -func (tx *Transaction) Hash() common.Uint256 { +func (tx *BaseTransaction) Hash() common.Uint256 { if tx.txHash == nil { txHash := tx.hash() tx.txHash = &txHash @@ -249,31 +252,31 @@ func (tx *Transaction) Hash() common.Uint256 { return *tx.txHash } -func (tx *Transaction) IsReturnSideChainDepositCoinTx() bool { +func (tx *BaseTransaction) IsReturnSideChainDepositCoinTx() bool { return tx.TxType == common2.ReturnSideChainDepositCoin } -func (tx *Transaction) ISCRCouncilMemberClaimNode() bool { +func (tx *BaseTransaction) ISCRCouncilMemberClaimNode() bool { return tx.TxType == common2.CRCouncilMemberClaimNode } -func (tx *Transaction) IsCRAssetsRectifyTx() bool { +func (tx *BaseTransaction) IsCRAssetsRectifyTx() bool { return tx.TxType == common2.CRAssetsRectify } -func (tx *Transaction) IsCRCAppropriationTx() bool { +func (tx *BaseTransaction) IsCRCAppropriationTx() bool { return tx.TxType == common2.CRCAppropriation } -func (tx *Transaction) IsNextTurnDPOSInfoTx() bool { +func (tx *BaseTransaction) IsNextTurnDPOSInfoTx() bool { return tx.TxType == common2.NextTurnDPOSInfo } -func (tx *Transaction) IsCustomIDResultTx() bool { +func (tx *BaseTransaction) IsCustomIDResultTx() bool { return tx.TxType == common2.ProposalResult } -func (tx *Transaction) IsCustomIDRelatedTx() bool { +func (tx *BaseTransaction) IsCustomIDRelatedTx() bool { if tx.IsCRCProposalTx() { p, _ := tx.Payload.(*payload.CRCProposal) return p.ProposalType == payload.ReserveCustomID || @@ -286,7 +289,7 @@ func (tx *Transaction) IsCustomIDRelatedTx() bool { return false } -func (tx *Transaction) IsSideChainUpgradeTx() bool { +func (tx *BaseTransaction) IsSideChainUpgradeTx() bool { if tx.IsCRCProposalTx() { p, _ := tx.Payload.(*payload.CRCProposal) return p.ProposalType > payload.MinUpgradeProposalType && @@ -295,55 +298,55 @@ func (tx *Transaction) IsSideChainUpgradeTx() bool { return false } -func (tx *Transaction) IsCRCProposalRealWithdrawTx() bool { +func (tx *BaseTransaction) IsCRCProposalRealWithdrawTx() bool { return tx.TxType == common2.CRCProposalRealWithdraw } -func (tx *Transaction) IsUpdateCRTx() bool { +func (tx *BaseTransaction) IsUpdateCRTx() bool { return tx.TxType == common2.UpdateCR } -func (tx *Transaction) IsCRCProposalWithdrawTx() bool { +func (tx *BaseTransaction) IsCRCProposalWithdrawTx() bool { return tx.TxType == common2.CRCProposalWithdraw } -func (tx *Transaction) IsCRCProposalReviewTx() bool { +func (tx *BaseTransaction) IsCRCProposalReviewTx() bool { return tx.TxType == common2.CRCProposalReview } -func (tx *Transaction) IsCRCProposalTrackingTx() bool { +func (tx *BaseTransaction) IsCRCProposalTrackingTx() bool { return tx.TxType == common2.CRCProposalTracking } -func (tx *Transaction) IsCRCProposalTx() bool { +func (tx *BaseTransaction) IsCRCProposalTx() bool { return tx.TxType == common2.CRCProposal } -func (tx *Transaction) IsReturnCRDepositCoinTx() bool { +func (tx *BaseTransaction) IsReturnCRDepositCoinTx() bool { return tx.TxType == common2.ReturnCRDepositCoin } -func (tx *Transaction) IsUnregisterCRTx() bool { +func (tx *BaseTransaction) IsUnregisterCRTx() bool { return tx.TxType == common2.UnregisterCR } -func (tx *Transaction) IsRegisterCRTx() bool { +func (tx *BaseTransaction) IsRegisterCRTx() bool { return tx.TxType == common2.RegisterCR } -func (tx *Transaction) IsIllegalTypeTx() bool { +func (tx *BaseTransaction) IsIllegalTypeTx() bool { return tx.IsIllegalProposalTx() || tx.IsIllegalVoteTx() || tx.IsIllegalBlockTx() || tx.IsSidechainIllegalDataTx() } //special tx is this kind of tx who have no input and output -func (tx *Transaction) IsSpecialTx() bool { +func (tx *BaseTransaction) IsSpecialTx() bool { if tx.IsIllegalTypeTx() || tx.IsInactiveArbitrators() || tx.IsNextTurnDPOSInfoTx() { return true } return false } -func (tx *Transaction) GetSpecialTxHash() (common.Uint256, error) { +func (tx *BaseTransaction) GetSpecialTxHash() (common.Uint256, error) { switch tx.TxType { case common2.IllegalProposalEvidence, common2.IllegalVoteEvidence, common2.IllegalBlockEvidence, common2.IllegalSidechainEvidence, common2.InactiveArbitrators: @@ -362,68 +365,68 @@ func (tx *Transaction) GetSpecialTxHash() (common.Uint256, error) { return common.Uint256{}, errors.New("wrong TxType not special tx") } -func (tx *Transaction) IsIllegalProposalTx() bool { +func (tx *BaseTransaction) IsIllegalProposalTx() bool { return tx.TxType == common2.IllegalProposalEvidence } -func (tx *Transaction) IsIllegalVoteTx() bool { +func (tx *BaseTransaction) IsIllegalVoteTx() bool { return tx.TxType == common2.IllegalVoteEvidence } -func (tx *Transaction) IsIllegalBlockTx() bool { +func (tx *BaseTransaction) IsIllegalBlockTx() bool { return tx.TxType == common2.IllegalBlockEvidence } -func (tx *Transaction) IsSidechainIllegalDataTx() bool { +func (tx *BaseTransaction) IsSidechainIllegalDataTx() bool { return tx.TxType == common2.IllegalSidechainEvidence } -func (tx *Transaction) IsInactiveArbitrators() bool { +func (tx *BaseTransaction) IsInactiveArbitrators() bool { return tx.TxType == common2.InactiveArbitrators } -func (tx *Transaction) IsRevertToPOW() bool { +func (tx *BaseTransaction) IsRevertToPOW() bool { return tx.TxType == common2.RevertToPOW } -func (tx *Transaction) IsRevertToDPOS() bool { +func (tx *BaseTransaction) IsRevertToDPOS() bool { return tx.TxType == common2.RevertToDPOS } -func (tx *Transaction) IsUpdateVersion() bool { +func (tx *BaseTransaction) IsUpdateVersion() bool { return tx.TxType == common2.UpdateVersion } -func (tx *Transaction) IsProducerRelatedTx() bool { +func (tx *BaseTransaction) IsProducerRelatedTx() bool { return tx.TxType == common2.RegisterProducer || tx.TxType == common2.UpdateProducer || tx.TxType == common2.ActivateProducer || tx.TxType == common2.CancelProducer } -func (tx *Transaction) IsUpdateProducerTx() bool { +func (tx *BaseTransaction) IsUpdateProducerTx() bool { return tx.TxType == common2.UpdateProducer } -func (tx *Transaction) IsReturnDepositCoin() bool { +func (tx *BaseTransaction) IsReturnDepositCoin() bool { return tx.TxType == common2.ReturnDepositCoin } -func (tx *Transaction) IsCancelProducerTx() bool { +func (tx *BaseTransaction) IsCancelProducerTx() bool { return tx.TxType == common2.CancelProducer } -func (tx *Transaction) IsActivateProducerTx() bool { +func (tx *BaseTransaction) IsActivateProducerTx() bool { return tx.TxType == common2.ActivateProducer } -func (tx *Transaction) IsRegisterProducerTx() bool { +func (tx *BaseTransaction) IsRegisterProducerTx() bool { return tx.TxType == common2.RegisterProducer } -func (tx *Transaction) IsSideChainPowTx() bool { +func (tx *BaseTransaction) IsSideChainPowTx() bool { return tx.TxType == common2.SideChainPow } -func (tx *Transaction) IsNewSideChainPowTx() bool { +func (tx *BaseTransaction) IsNewSideChainPowTx() bool { if !tx.IsSideChainPowTx() || len(tx.Inputs) != 0 { return false } @@ -431,44 +434,31 @@ func (tx *Transaction) IsNewSideChainPowTx() bool { return true } -func (tx *Transaction) IsTransferCrossChainAssetTx() bool { +func (tx *BaseTransaction) IsTransferCrossChainAssetTx() bool { return tx.TxType == common2.TransferCrossChainAsset } -func (tx *Transaction) IsWithdrawFromSideChainTx() bool { +func (tx *BaseTransaction) IsWithdrawFromSideChainTx() bool { return tx.TxType == common2.WithdrawFromSideChain } -func (tx *Transaction) IsRechargeToSideChainTx() bool { +func (tx *BaseTransaction) IsRechargeToSideChainTx() bool { return tx.TxType == common2.RechargeToSideChain } -func (tx *Transaction) IsCoinBaseTx() bool { +func (tx *BaseTransaction) IsCoinBaseTx() bool { return tx.TxType == common2.CoinBase } // SerializeSizeStripped returns the number of bytes it would take to serialize // the block, excluding any witness data (if any). -func (tx *Transaction) SerializeSizeStripped() int { +func (tx *BaseTransaction) SerializeSizeStripped() int { // todo add cache for size according to btcd return tx.GetSize() } -// Payload define the func for loading the payload data -// base on payload type which have different structure -type Payload interface { - // Get payload data - Data(version byte) []byte - - Serialize(w io.Writer, version byte) error - - Deserialize(r io.Reader, version byte) error - - payload.PayloadChecker -} - -func GetPayload(txType common2.TxType) (Payload, error) { - var p Payload +func GetPayload(txType common2.TxType) (interfaces.Payload, error) { + var p interfaces.Payload switch txType { case common2.CoinBase: p = new(payload.CoinBase) @@ -541,12 +531,12 @@ func GetPayload(txType common2.TxType) (Payload, error) { case common2.ReturnSideChainDepositCoin: p = new(payload.ReturnSideChainDepositCoin) default: - return nil, errors.New("[Transaction], invalid transaction type.") + return nil, errors.New("[BaseTransaction], invalid transaction type.") } return p, nil } -func (tx *Transaction) IsSmallTransfer(min common.Fixed64) bool { +func (tx *BaseTransaction) IsSmallTransfer(min common.Fixed64) bool { var totalCrossAmt common.Fixed64 if tx.PayloadVersion == payload.TransferCrossChainVersion { payloadObj, ok := tx.Payload.(*payload.TransferCrossChainAsset) diff --git a/core/types/payload/payloadchecker.go b/core/types/transactions/transactionchecker.go similarity index 63% rename from core/types/payload/payloadchecker.go rename to core/types/transactions/transactionchecker.go index 4ab8a43b6..124715bf0 100644 --- a/core/types/payload/payloadchecker.go +++ b/core/types/transactions/transactionchecker.go @@ -3,27 +3,30 @@ // license that can be found in the LICENSE file. // -package payload +package transactions import ( "fmt" "github.com/elastos/Elastos.ELA/common" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" elaerr "github.com/elastos/Elastos.ELA/errors" ) type DefaultChecker struct { IsTxHashDuplicateFunction func(txhash common.Uint256) bool - GetTxReferenceFunction func(para *CheckParameters) (map[*common2.Input]common2.Output, error) + GetTxReferenceFunction func(para *interfaces.CheckParameters) ( + map[*common2.Input]common2.Output, error) } -func (a *DefaultChecker) ContextCheck(para *CheckParameters) (map[*common2.Input]common2.Output, elaerr.ELAError) { +func (a *DefaultChecker) ContextCheck(para *interfaces.CheckParameters) ( + map[*common2.Input]common2.Output, elaerr.ELAError) { if err := a.CheckTxHeightVersion(para); err != nil { return nil, elaerr.Simple(elaerr.ErrTxHeightVersion, nil) } - if exist := a.IsTxHashDuplicate(para.TxHash); exist { + if exist := a.IsTxHashDuplicate(para.Transaction.Hash()); exist { //log.Warn("[CheckTransactionContext] duplicate transaction check failed.") return nil, elaerr.Simple(elaerr.ErrTxDuplicate, nil) } @@ -45,7 +48,7 @@ func (a *DefaultChecker) ContextCheck(para *CheckParameters) (map[*common2.Input return references, nil } -func (a *DefaultChecker) CheckTxHeightVersion(para *CheckParameters) error { +func (a *DefaultChecker) CheckTxHeightVersion(para *interfaces.CheckParameters) error { // todo default check return nil } @@ -54,17 +57,18 @@ func (a *DefaultChecker) IsTxHashDuplicate(txHash common.Uint256) bool { return a.IsTxHashDuplicateFunction(txHash) } -func (a *DefaultChecker) GetTxReference(para *CheckParameters) ( +func (a *DefaultChecker) GetTxReference(para *interfaces.CheckParameters) ( map[*common2.Input]common2.Output, error) { return a.GetTxReferenceFunction(para) } -func (a *DefaultChecker) CheckPOWConsensusTransaction(para *CheckParameters, references map[*common2.Input]common2.Output) error { +func (a *DefaultChecker) CheckPOWConsensusTransaction( + para *interfaces.CheckParameters, references map[*common2.Input]common2.Output) error { // todo default check return nil } -func (a *DefaultChecker) SpecialCheck(para *CheckParameters) (elaerr.ELAError, bool) { +func (a *DefaultChecker) SpecialCheck(para *interfaces.CheckParameters) (elaerr.ELAError, bool) { fmt.Println("default check") return nil, false } diff --git a/cr/state/committee.go b/cr/state/committee.go index 2b3d914e5..d12fbc8a3 100644 --- a/cr/state/committee.go +++ b/cr/state/committee.go @@ -9,6 +9,7 @@ import ( "bytes" "errors" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "sort" "strconv" @@ -43,12 +44,12 @@ type Committee struct { getHeight func() uint32 isCurrent func() bool broadcast func(msg p2p.Message) - appendToTxpool func(transaction *types.Transaction) elaerr.ELAError - createCRCAppropriationTx func() (*types.Transaction, common.Fixed64, error) - createCRAssetsRectifyTransaction func() (*types.Transaction, error) + appendToTxpool func(transaction *transactions.BaseTransaction) elaerr.ELAError + createCRCAppropriationTx func() (*transactions.BaseTransaction, common.Fixed64, error) + createCRAssetsRectifyTransaction func() (*transactions.BaseTransaction, error) createCRRealWithdrawTransaction func(withdrawTransactionHashes []common.Uint256, - outputs []*common2.OutputInfo) (*types.Transaction, error) - getUTXO func(programHash *common.Uint168) ([]*types.UTXO, error) + outputs []*common2.OutputInfo) (*transactions.BaseTransaction, error) + getUTXO func(programHash *common.Uint168) ([]*common2.UTXO, error) } type CommitteeKeyFrame struct { @@ -533,7 +534,7 @@ func (c *Committee) createProposalResultTransaction(height uint32) { sort.Slice(c.PartProposalResults, func(i, j int) bool { return c.PartProposalResults[i].ProposalHash.Compare(c.PartProposalResults[j].ProposalHash) < 0 }) - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.ProposalResult, Payload: &payload.RecordProposalResult{ @@ -880,7 +881,7 @@ func (c *Committee) processCRCAppropriation(height uint32, history *utils.Histor }) } -func (c *Committee) processCRCRealWithdraw(tx *types.Transaction, +func (c *Committee) processCRCRealWithdraw(tx *transactions.BaseTransaction, height uint32, history *utils.History) { txs := make(map[common.Uint256]common2.OutputInfo) @@ -897,7 +898,7 @@ func (c *Committee) processCRCRealWithdraw(tx *types.Transaction, }) } -func (c *Committee) activateProducer(tx *types.Transaction, +func (c *Committee) activateProducer(tx *transactions.BaseTransaction, height uint32, history *utils.History) { apPayload := tx.Payload.(*payload.ActivateProducer) crMember := c.getMemberByNodePublicKey(apPayload.NodePublicKey) @@ -914,7 +915,7 @@ func (c *Committee) activateProducer(tx *types.Transaction, } } -func (c *Committee) processCRCouncilMemberClaimNode(tx *types.Transaction, +func (c *Committee) processCRCouncilMemberClaimNode(tx *transactions.BaseTransaction, height uint32, history *utils.History) { claimNodePayload := tx.Payload.(*payload.CRCouncilMemberClaimNode) cr := c.getMember(claimNodePayload.CRCouncilCommitteeDID) @@ -1437,17 +1438,17 @@ func (c *Committee) GetCandidateByPublicKey(publicKey string) *Candidate { } type CommitteeFuncsConfig struct { - GetTxReference func(tx *types.Transaction) ( + GetTxReference func(tx *transactions.BaseTransaction) ( map[*common2.Input]common2.Output, error) GetHeight func() uint32 - CreateCRAppropriationTransaction func() (*types.Transaction, common.Fixed64, error) - CreateCRAssetsRectifyTransaction func() (*types.Transaction, error) + CreateCRAppropriationTransaction func() (*transactions.BaseTransaction, common.Fixed64, error) + CreateCRAssetsRectifyTransaction func() (*transactions.BaseTransaction, error) CreateCRRealWithdrawTransaction func(withdrawTransactionHashes []common.Uint256, - outpus []*common2.OutputInfo) (*types.Transaction, error) + outpus []*common2.OutputInfo) (*transactions.BaseTransaction, error) IsCurrent func() bool Broadcast func(msg p2p.Message) - AppendToTxpool func(transaction *types.Transaction) elaerr.ELAError - GetUTXO func(programHash *common.Uint168) ([]*types.UTXO, error) + AppendToTxpool func(transaction *transactions.BaseTransaction) elaerr.ELAError + GetUTXO func(programHash *common.Uint168) ([]*common2.UTXO, error) } func (c *Committee) RegisterFuncitons(cfg *CommitteeFuncsConfig) { diff --git a/cr/state/committee_test.go b/cr/state/committee_test.go index b6fd7bfcd..4ba777520 100644 --- a/cr/state/committee_test.go +++ b/cr/state/committee_test.go @@ -7,6 +7,7 @@ package state import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sort" "testing" @@ -19,15 +20,15 @@ import ( ) func TestSortTransactions(t *testing.T) { - txs := []*types.Transaction{ - &types.Transaction{TxType: common2.CoinBase}, - &types.Transaction{TxType: common2.TransferAsset}, - &types.Transaction{TxType: common2.TransferAsset}, - &types.Transaction{TxType: common2.CRCProposalTracking}, - &types.Transaction{TxType: common2.CRCProposalWithdraw}, - &types.Transaction{TxType: common2.CRCProposalWithdraw}, - &types.Transaction{TxType: common2.TransferAsset}, - &types.Transaction{TxType: common2.CRCProposalWithdraw}, + txs := []*transactions.BaseTransaction{ + &transactions.BaseTransaction{TxType: common2.CoinBase}, + &transactions.BaseTransaction{TxType: common2.TransferAsset}, + &transactions.BaseTransaction{TxType: common2.TransferAsset}, + &transactions.BaseTransaction{TxType: common2.CRCProposalTracking}, + &transactions.BaseTransaction{TxType: common2.CRCProposalWithdraw}, + &transactions.BaseTransaction{TxType: common2.CRCProposalWithdraw}, + &transactions.BaseTransaction{TxType: common2.TransferAsset}, + &transactions.BaseTransaction{TxType: common2.CRCProposalWithdraw}, } sortTransactions(txs[1:]) @@ -242,7 +243,7 @@ func TestCommittee_RollbackTo_SameCommittee_VotingPeriod(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateRegisterCR(code, cid, nickname), }, }, nil) @@ -257,7 +258,7 @@ func TestCommittee_RollbackTo_SameCommittee_VotingPeriod(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateUpdateCR(code, cid, nickname2), }, }, nil) @@ -270,7 +271,7 @@ func TestCommittee_RollbackTo_SameCommittee_VotingPeriod(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) height++ } @@ -310,7 +311,7 @@ func TestCommittee_RollbackTo_SameCommittee_BeforeVoting(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateRegisterCR(code, cid, nickname), }, }, nil) diff --git a/cr/state/committeeaction.go b/cr/state/committeeaction.go index 2a6921b54..2d5329b02 100644 --- a/cr/state/committeeaction.go +++ b/cr/state/committeeaction.go @@ -8,11 +8,11 @@ package state import ( "bytes" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "sort" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/utils" @@ -21,8 +21,8 @@ import ( // processTransactions takes the transactions and the height when they have been // packed into a block. Then loop through the transactions to update CR // state and votes according to transactions content. -func (c *Committee) processTransactions(txs []*types.Transaction, height uint32) { - sortedTxs := make([]*types.Transaction, 0) +func (c *Committee) processTransactions(txs []*transactions.BaseTransaction, height uint32) { + sortedTxs := make([]*transactions.BaseTransaction, 0) if len(txs) < 1 { return } @@ -61,7 +61,7 @@ func (c *Committee) processTransactions(txs []*types.Transaction, height uint32) } // sortTransactions purpose is to process some transaction first. -func sortTransactions(txs []*types.Transaction) { +func sortTransactions(txs []*transactions.BaseTransaction) { sort.Slice(txs, func(i, j int) bool { if txs[i].IsCRCProposalWithdrawTx() { return true @@ -73,7 +73,7 @@ func sortTransactions(txs []*types.Transaction) { // processTransaction take a transaction and the height it has been packed into // a block, then update producers state and votes according to the transaction // content. -func (c *Committee) processTransaction(tx *types.Transaction, height uint32) { +func (c *Committee) processTransaction(tx *transactions.BaseTransaction, height uint32) { // prioritize cancel votes c.processCancelVotes(tx, height) @@ -126,7 +126,7 @@ func (c *Committee) processTransaction(tx *types.Transaction, height uint32) { } // proposalTracking deal with CRC proposal transaction. -func (c *Committee) proposalTracking(tx *types.Transaction, height uint32) { +func (c *Committee) proposalTracking(tx *transactions.BaseTransaction, height uint32) { unusedBudget := c.manager.proposalTracking(tx, height, c.state.history) c.state.history.Append(height, func() { c.CRCCommitteeUsedAmount -= unusedBudget @@ -137,7 +137,7 @@ func (c *Committee) proposalTracking(tx *types.Transaction, height uint32) { // processVotes takes a transaction, if the transaction including any vote // outputs, validate and update CR votes. -func (c *Committee) processVotes(tx *types.Transaction, height uint32) { +func (c *Committee) processVotes(tx *transactions.BaseTransaction, height uint32) { if tx.Version >= common2.TxVersion09 { for i, output := range tx.Outputs { if output.Type != common2.OTVote { @@ -191,7 +191,7 @@ func (c *Committee) processVoteOutput(output *common2.Output, height uint32) { // processCancelVotes takes a transaction, if the transaction takes a previous // vote output then try to subtract the vote. -func (c *Committee) processCancelVotes(tx *types.Transaction, height uint32) { +func (c *Committee) processCancelVotes(tx *transactions.BaseTransaction, height uint32) { var exist bool for _, input := range tx.Inputs { referKey := input.ReferKey() @@ -287,7 +287,7 @@ func (c *Committee) processCancelImpeachment(height uint32, member []byte, // processCRCRelatedAmount takes a transaction, if the transaction takes a previous // output to CRC related address then try to subtract the vote. -func (c *Committee) processCRCAddressRelatedTx(tx *types.Transaction, height uint32) { +func (c *Committee) processCRCAddressRelatedTx(tx *transactions.BaseTransaction, height uint32) { if tx.IsCRCProposalTx() { proposal := tx.Payload.(*payload.CRCProposal) var budget common.Fixed64 diff --git a/cr/state/committeerollback_test.go b/cr/state/committeerollback_test.go index 587e374ec..713006313 100644 --- a/cr/state/committeerollback_test.go +++ b/cr/state/committeerollback_test.go @@ -8,6 +8,7 @@ package state import ( "bytes" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -51,7 +52,7 @@ func getCodeHexStr(publicKey string) string { return codeHexStr } -func getRegisterCRTx(publicKeyStr, privateKeyStr, nickName string) *types.Transaction { +func getRegisterCRTx(publicKeyStr, privateKeyStr, nickName string) *transactions.BaseTransaction { publicKeyStr1 := publicKeyStr privateKeyStr1 := privateKeyStr publicKey1, _ := common.HexStringToBytes(publicKeyStr1) @@ -62,7 +63,7 @@ func getRegisterCRTx(publicKeyStr, privateKeyStr, nickName string) *types.Transa did1, _ := getDIDByCode(code1) hash1, _ := contract.PublicKeyToDepositProgramHash(publicKey1) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.RegisterCR txn.Version = common2.TxVersion09 crInfoPayload := &payload.CRInfo{ @@ -96,9 +97,9 @@ func getRegisterCRTx(publicKeyStr, privateKeyStr, nickName string) *types.Transa } func getUpdateCR(publicKeyStr string, cid common.Uint168, - nickname string) *types.Transaction { + nickname string) *transactions.BaseTransaction { code := getCodeByPubKeyStr(publicKeyStr) - return &types.Transaction{ + return &transactions.BaseTransaction{ TxType: common2.UpdateCR, Payload: &payload.CRInfo{ Code: code, @@ -108,8 +109,8 @@ func getUpdateCR(publicKeyStr string, cid common.Uint168, } } -func getUnregisterCR(cid common.Uint168) *types.Transaction { - return &types.Transaction{ +func getUnregisterCR(cid common.Uint168) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.UnregisterCR, Payload: &payload.UnregisterCR{ CID: cid, @@ -117,9 +118,9 @@ func getUnregisterCR(cid common.Uint168) *types.Transaction { } } -func generateReturnDeposite(publicKeyStr string) *types.Transaction { +func generateReturnDeposite(publicKeyStr string) *transactions.BaseTransaction { code := getCodeByPubKeyStr(publicKeyStr) - return &types.Transaction{ + return &transactions.BaseTransaction{ TxType: common2.ReturnCRDepositCoin, Payload: &payload.ReturnDepositCoin{}, Outputs: []*common2.Output{ @@ -134,8 +135,8 @@ func generateReturnDeposite(publicKeyStr string) *types.Transaction { } func getVoteCRTx(amount common.Fixed64, - candidateVotes []outputpayload.CandidateVotes) *types.Transaction { - return &types.Transaction{ + candidateVotes []outputpayload.CandidateVotes) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ Version: 0x09, TxType: common2.TransferAsset, Outputs: []*common2.Output{ @@ -168,7 +169,7 @@ func getDID(code []byte) *common.Uint168 { } func getCRCProposalTx(elaAddress string, publicKeyStr, privateKeyStr, - crPublicKeyStr, crPrivateKeyStr string) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr string) *transactions.BaseTransaction { publicKey1, _ := common.HexStringToBytes(publicKeyStr) privateKey1, _ := common.HexStringToBytes(privateKeyStr) @@ -178,7 +179,7 @@ func getCRCProposalTx(elaAddress string, publicKeyStr, privateKeyStr, recipient, _ := common.Uint168FromAddress(elaAddress) draftData := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposal txn.Version = common2.TxVersion09 crcProposalPayload := &payload.CRCProposal{ @@ -209,11 +210,11 @@ func getCRCProposalTx(elaAddress string, publicKeyStr, privateKeyStr, } func getCRCProposalReviewTx(proposalHash common.Uint256, vote payload.VoteResult, - crPublicKeyStr, crPrivateKeyStr string) *types.Transaction { + crPublicKeyStr, crPrivateKeyStr string) *transactions.BaseTransaction { privateKey1, _ := common.HexStringToBytes(crPrivateKeyStr) code := getCodeByPubKeyStr(crPublicKeyStr) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposalReview txn.Version = common2.TxVersion09 crcProposalReviewPayload := &payload.CRCProposalReview{ @@ -240,7 +241,7 @@ func getCRCProposalTrackingTx( proposalHash common.Uint256, stage uint8, ownerpublickeyStr, ownerprivatekeyStr, newownerpublickeyStr, newownerprivatekeyStr, - sgPrivateKeyStr string) *types.Transaction { + sgPrivateKeyStr string) *transactions.BaseTransaction { ownerpublickey, _ := common.HexStringToBytes(ownerpublickeyStr) ownerprivatekey, _ := common.HexStringToBytes(ownerprivatekeyStr) @@ -252,7 +253,7 @@ func getCRCProposalTrackingTx( documentData := randomBytes(10) opinionHash := randomBytes(10) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.CRCProposalTracking txn.Version = common2.TxVersion09 cPayload := &payload.CRCProposalTracking{ @@ -287,7 +288,7 @@ func getCRCProposalTrackingTx( func getCRCProposalWithdrawTx(proposalHash common.Uint256, OwnerPublicKeyStr, sponsorPrivateKeyStr string, fee common.Fixed64, - inputs []*common2.Input, outputs []*common2.Output) *types.Transaction { + inputs []*common2.Input, outputs []*common2.Output) *transactions.BaseTransaction { OwnerPublicKey, _ := common.HexStringToBytes(OwnerPublicKeyStr) sponsorPrivateKey, _ := common.HexStringToBytes(sponsorPrivateKeyStr) @@ -302,7 +303,7 @@ func getCRCProposalWithdrawTx(proposalHash common.Uint256, signature, _ := crypto.Sign(sponsorPrivateKey, signBuf.Bytes()) crcProposalWithdraw.Signature = signature - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.CRCProposalWithdraw, Payload: crcProposalWithdraw, @@ -358,7 +359,7 @@ func TestCommittee_RollbackRegisterAndVoteCR(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -387,7 +388,7 @@ func TestCommittee_RollbackRegisterAndVoteCR(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -405,7 +406,7 @@ func TestCommittee_RollbackRegisterAndVoteCR(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteCRTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteCRTx}}, nil) assert.Equal(t, common.Fixed64(3), committee.GetCandidate(*cid1).votes) keyFrameD := committee.Snapshot() @@ -448,7 +449,7 @@ func TestCommittee_RollbackEndVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -477,7 +478,7 @@ func TestCommittee_RollbackEndVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -552,7 +553,7 @@ func TestCommittee_RollbackContinueVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -566,7 +567,7 @@ func TestCommittee_RollbackContinueVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -593,7 +594,7 @@ func TestCommittee_RollbackContinueVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -633,7 +634,7 @@ func TestCommittee_RollbackContinueVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn4, }, }, nil) @@ -655,7 +656,7 @@ func TestCommittee_RollbackContinueVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx2, }, }, nil) @@ -728,7 +729,7 @@ func TestCommittee_RollbackChangeCommittee(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -754,7 +755,7 @@ func TestCommittee_RollbackChangeCommittee(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -776,7 +777,7 @@ func TestCommittee_RollbackChangeCommittee(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -802,7 +803,7 @@ func TestCommittee_RollbackChangeCommittee(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx2, }, }, nil) @@ -874,7 +875,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -900,7 +901,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -921,7 +922,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTx, }}, nil) assert.Equal(t, 1, len(committee.GetProposals(Registered))) @@ -939,7 +940,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTx, }}, nil) assert.Equal(t, 1, len(committee.GetProposals(Registered))) @@ -961,7 +962,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTx1, proposalReviewTx2, }}, nil) @@ -978,7 +979,7 @@ func TestCommittee_RollbackCRCProposal(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTx1, proposalReviewTx2, }}, nil) @@ -1073,7 +1074,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -1099,7 +1100,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -1119,7 +1120,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTx, }}, nil) assert.Equal(t, 1, len(committee.GetProposals(Registered))) @@ -1138,7 +1139,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTx1, proposalReviewTx2, }}, nil) @@ -1174,7 +1175,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTrackingTx, }}, nil) assert.Equal(t, 2, len(committee.GetProposal(proposalHash).WithdrawableBudgets)) @@ -1191,7 +1192,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTrackingTx, }}, nil) assert.Equal(t, 2, len(committee.GetProposal(proposalHash).WithdrawableBudgets)) @@ -1209,7 +1210,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTrackingTx2, }}, nil) assert.Equal(t, 3, len(committee.GetProposal(proposalHash).WithdrawableBudgets)) @@ -1226,7 +1227,7 @@ func TestCommittee_RollbackCRCProposalTracking(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTrackingTx2, }}, nil) assert.Equal(t, 3, len(committee.GetProposal(proposalHash).WithdrawableBudgets)) @@ -1271,7 +1272,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -1297,7 +1298,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -1317,7 +1318,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTx, }}, nil) assert.Equal(t, 1, len(committee.GetProposals(Registered))) @@ -1335,7 +1336,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTx1, proposalReviewTx2, }}, nil) @@ -1362,7 +1363,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ withdrawTx, }}, nil) assert.Equal(t, 1, len(committee.GetProposal(proposalHash).WithdrawnBudgets)) @@ -1379,7 +1380,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ withdrawTx, }}, nil) assert.Equal(t, 1, len(committee.GetProposal(proposalHash).WithdrawnBudgets)) @@ -1404,7 +1405,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTrackingTx, }}, nil) assert.Equal(t, 2, len(committee.GetProposal(proposalHash).WithdrawableBudgets)) @@ -1418,7 +1419,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTrackingTx2, }}, nil) assert.Equal(t, 3, len(committee.GetProposal(proposalHash).WithdrawableBudgets)) @@ -1432,7 +1433,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ withdrawTx2, }}, nil) assert.Equal(t, 3, len(committee.GetProposal(proposalHash).WithdrawnBudgets)) @@ -1449,7 +1450,7 @@ func TestCommittee_RollbackCRCProposalWithdraw(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ withdrawTx2, }}, nil) assert.Equal(t, 3, len(committee.GetProposal(proposalHash).WithdrawnBudgets)) @@ -1495,7 +1496,7 @@ func TestCommittee_RollbackTempStartVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -1521,7 +1522,7 @@ func TestCommittee_RollbackTempStartVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -1545,7 +1546,7 @@ func TestCommittee_RollbackTempStartVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, }, }, nil) @@ -1569,7 +1570,7 @@ func TestCommittee_RollbackTempStartVotingPeriod(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx2, }, }, nil) @@ -1649,7 +1650,7 @@ func TestCommittee_RollbackCRCAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -1677,7 +1678,7 @@ func TestCommittee_RollbackCRCAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -1703,7 +1704,7 @@ func TestCommittee_RollbackCRCAppropriationTx(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ txAppropriate, }, }, nil) @@ -1719,7 +1720,7 @@ func TestCommittee_RollbackCRCAppropriationTx(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ txAppropriate, }, }, nil) @@ -1743,9 +1744,8 @@ func getAddress(publicKeyHexStr string) (string, error) { return address1Uint168.ToAddress() } -func getTransferAssetTx(publicKeyStr string, value common.Fixed64, outPutAddr common.Uint168) *types. - Transaction { - txn := &types.Transaction{ +func getTransferAssetTx(publicKeyStr string, value common.Fixed64, outPutAddr common.Uint168) *transactions.BaseTransaction { + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, @@ -1770,11 +1770,10 @@ func getTransferAssetTx(publicKeyStr string, value common.Fixed64, outPutAddr co }} return txn } -func getAppropriationTx(value common.Fixed64, outPutAddr common.Uint168) *types. - Transaction { +func getAppropriationTx(value common.Fixed64, outPutAddr common.Uint168) *transactions.BaseTransaction { crcAppropriationPayload := &payload.CRCAppropriation{} - txn := &types.Transaction{ + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.CRCAppropriation, Payload: crcAppropriationPayload, @@ -1844,7 +1843,7 @@ func TestCommittee_RollbackCRCImpeachmentTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -1871,7 +1870,7 @@ func TestCommittee_RollbackCRCImpeachmentTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -1905,7 +1904,7 @@ func TestCommittee_RollbackCRCImpeachmentTx(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ impeachmentTx, }, }, nil) @@ -1921,7 +1920,7 @@ func TestCommittee_RollbackCRCImpeachmentTx(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ impeachmentTx, }, }, nil) @@ -1978,7 +1977,7 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -2005,7 +2004,7 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -2046,7 +2045,7 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ impeachmentTx, }, }, nil) @@ -2065,7 +2064,7 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ impeachmentTx, }, }, nil) @@ -2081,7 +2080,7 @@ func TestCommittee_RollbackCRCImpeachmentAndReelectionTx(t *testing.T) { } func getCRCImpeachmentTx(publicKeyStr string, did *common.Uint168, - value common.Fixed64, outPutAddr common.Uint168) *types.Transaction { + value common.Fixed64, outPutAddr common.Uint168) *transactions.BaseTransaction { outputs := []*common2.Output{} outputs = append(outputs, &common2.Output{ Type: common2.OTVote, @@ -2100,7 +2099,7 @@ func getCRCImpeachmentTx(publicKeyStr string, did *common.Uint168, }, }) - txn := &types.Transaction{ + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, @@ -2156,7 +2155,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -2182,7 +2181,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -2208,7 +2207,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) currentHeight++ @@ -2216,7 +2215,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTxA, proposalTxB, proposalTxC, @@ -2240,7 +2239,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTxB1, proposalReviewTxB2, proposalReviewTxC1, @@ -2264,7 +2263,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, }, }, nil) @@ -2296,7 +2295,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn2, registerCRTxn3, voteCRTx2, @@ -2332,7 +2331,7 @@ func TestCommitee_RollbackCRCBlendTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn2, registerCRTxn3, voteCRTx2, @@ -2392,7 +2391,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -2418,7 +2417,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -2444,7 +2443,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) currentHeight++ @@ -2452,7 +2451,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTxA, proposalTxB, proposalTxC, @@ -2476,7 +2475,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTxB1, proposalReviewTxB2, proposalReviewTxC1, @@ -2500,7 +2499,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, }, }, nil) @@ -2533,7 +2532,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn2, registerCRTxn3, voteCRTx2, @@ -2565,7 +2564,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn2, registerCRTxn3, voteCRTx2, @@ -2586,7 +2585,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ txAppropriate, proposalTxD, proposalReviewTxA1, @@ -2607,7 +2606,7 @@ func TestCommitee_RollbackCRCBlendAppropriationTx(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ txAppropriate, proposalTxD, proposalReviewTxA1, @@ -2654,7 +2653,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, }, @@ -2679,7 +2678,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -2701,7 +2700,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) currentHeight++ @@ -2709,7 +2708,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTxB, proposalTxC, }, @@ -2731,7 +2730,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTxB1, proposalReviewTxB2, proposalReviewTxC1, @@ -2769,7 +2768,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTrackingBTx, proposalTrackingCTx, }, @@ -2790,7 +2789,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTrackingBTxFinal, proposalTrackingCTxFinal, }, @@ -2810,7 +2809,7 @@ func TestCommitee_RollbackCRCBlendTxPropoalVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ withdrawBTx, withdrawCTx, }, @@ -2860,7 +2859,7 @@ func TestCommitee_RollbackCRCBlendTxCRVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, }, @@ -2878,7 +2877,7 @@ func TestCommitee_RollbackCRCBlendTxCRVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ updateCr1, updateCR2, }, @@ -2894,7 +2893,7 @@ func TestCommitee_RollbackCRCBlendTxCRVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ unregister1, unregister2, }, @@ -2910,7 +2909,7 @@ func TestCommitee_RollbackCRCBlendTxCRVert(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ returnDepositTx1, returnDepositTx2, }, @@ -2964,7 +2963,7 @@ func TestCommittee_RollbackReview(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -2990,7 +2989,7 @@ func TestCommittee_RollbackReview(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -3011,7 +3010,7 @@ func TestCommittee_RollbackReview(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTx, }}, nil) assert.Equal(t, 1, len(committee.GetProposals(Registered))) @@ -3029,7 +3028,7 @@ func TestCommittee_RollbackReview(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalTx, }}, nil) assert.Equal(t, 1, len(committee.GetProposals(Registered))) @@ -3050,7 +3049,7 @@ func TestCommittee_RollbackReview(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTx1, proposalReviewTx2, }}, nil) @@ -3067,7 +3066,7 @@ func TestCommittee_RollbackReview(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTxReject1, proposalReviewTxReject2, }}, nil) @@ -3083,7 +3082,7 @@ func TestCommittee_RollbackReview(t *testing.T) { currentHeight++ committee.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ proposalReviewTxReject1, proposalReviewTxReject2, }}, nil) diff --git a/cr/state/proposalmanager.go b/cr/state/proposalmanager.go index 0f95e1da4..0beba3210 100644 --- a/cr/state/proposalmanager.go +++ b/cr/state/proposalmanager.go @@ -8,11 +8,11 @@ package state import ( "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/contract" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/utils" @@ -595,7 +595,7 @@ func (p *ProposalManager) delProposal(did common.Uint168, } // registerProposal will register proposal state in proposal manager -func (p *ProposalManager) registerProposal(tx *types.Transaction, +func (p *ProposalManager) registerProposal(tx *transactions.BaseTransaction, height uint32, currentsSession uint64, history *utils.History) { proposal := tx.Payload.(*payload.CRCProposal) //The number of the proposals of the committee can not more than 128 @@ -710,7 +710,7 @@ func getCIDByPublicKey(publicKey []byte) (*common.Uint168, error) { return ct.ToProgramHash(), nil } -func (p *ProposalManager) proposalReview(tx *types.Transaction, +func (p *ProposalManager) proposalReview(tx *transactions.BaseTransaction, height uint32, history *utils.History) { proposalReview := tx.Payload.(*payload.CRCProposalReview) proposalState := p.getProposal(proposalReview.ProposalHash) @@ -730,7 +730,7 @@ func (p *ProposalManager) proposalReview(tx *types.Transaction, }) } -func (p *ProposalManager) proposalWithdraw(tx *types.Transaction, +func (p *ProposalManager) proposalWithdraw(tx *transactions.BaseTransaction, height uint32, history *utils.History) { withdrawPayload := tx.Payload.(*payload.CRCProposalWithdraw) proposalState := p.getProposal(withdrawPayload.ProposalHash) @@ -773,7 +773,7 @@ func (p *ProposalManager) proposalWithdraw(tx *types.Transaction, }) } -func (p *ProposalManager) proposalTracking(tx *types.Transaction, +func (p *ProposalManager) proposalTracking(tx *transactions.BaseTransaction, height uint32, history *utils.History) (unusedBudget common.Fixed64) { proposalTracking := tx.Payload.(*payload.CRCProposalTracking) proposalState := p.getProposal(proposalTracking.ProposalHash) diff --git a/cr/state/state.go b/cr/state/state.go index b0c0947da..a55008419 100644 --- a/cr/state/state.go +++ b/cr/state/state.go @@ -10,10 +10,10 @@ import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/contract" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" "github.com/elastos/Elastos.ELA/core/types/payload" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/utils" ) @@ -36,7 +36,7 @@ type State struct { manager *ProposalManager getHistoryMember func(code []byte) []*CRMember - getTxReference func(tx *types.Transaction) ( + getTxReference func(tx *transactions.BaseTransaction) ( map[*common2.Input]common2.Output, error) params *config.Params @@ -50,7 +50,7 @@ func (s *State) SetManager(manager *ProposalManager) { type FunctionsConfig struct { GetHistoryMember func(code []byte) []*CRMember - GetTxReference func(tx *types.Transaction) ( + GetTxReference func(tx *transactions.BaseTransaction) ( map[*common2.Input]common2.Output, error) } @@ -196,7 +196,7 @@ func (s *State) existCandidateByNickname(nickname string) bool { } // IsCRTransaction returns if a transaction will change the CR and votes state. -func (s *State) IsCRTransaction(tx *types.Transaction) bool { +func (s *State) IsCRTransaction(tx *transactions.BaseTransaction) bool { switch tx.TxType { // Transactions will changes the producers state. case common2.RegisterCR, common2.UpdateCR, @@ -241,7 +241,7 @@ func (s *State) rollbackTo(height uint32) error { } // registerCR handles the register CR transaction. -func (s *State) registerCR(tx *types.Transaction, height uint32) { +func (s *State) registerCR(tx *transactions.BaseTransaction, height uint32) { info := tx.Payload.(*payload.CRInfo) nickname := info.NickName code := common.BytesToHexString(info.Code) @@ -335,7 +335,7 @@ func (s *State) updateCandidateInfo(origin *payload.CRInfo, update *payload.CRIn } // processDeposit takes a transaction output with deposit program hash. -func (s *State) processDeposit(tx *types.Transaction, height uint32) { +func (s *State) processDeposit(tx *transactions.BaseTransaction, height uint32) { for i, output := range tx.Outputs { if contract.GetPrefixType(output.ProgramHash) == contract.PrefixDeposit { if s.addCRCRelatedAssert(output, height) { @@ -347,7 +347,7 @@ func (s *State) processDeposit(tx *types.Transaction, height uint32) { } // returnDeposit change producer state to ReturnedDeposit -func (s *State) returnDeposit(tx *types.Transaction, height uint32) { +func (s *State) returnDeposit(tx *transactions.BaseTransaction, height uint32) { var inputValue common.Fixed64 for _, input := range tx.Inputs { inputValue += s.DepositOutputs[input.ReferKey()] diff --git a/cr/state/state_test.go b/cr/state/state_test.go index 535bfe4e3..874ce4b98 100644 --- a/cr/state/state_test.go +++ b/cr/state/state_test.go @@ -7,6 +7,7 @@ package state import ( common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -85,8 +86,8 @@ func TestState_ProcessBlock_PendingUpdateThenCancel(t *testing.T) { GetHeight: func() uint32 { return currentHeight }, - GetUTXO: func(programHash *common.Uint168) ([]*types.UTXO, error) { - return []*types.UTXO{}, nil + GetUTXO: func(programHash *common.Uint168) ([]*common2.UTXO, error) { + return []*common2.UTXO{}, nil }, }) publicKeyStr1 := "03c77af162438d4b7140f8544ad6523b9734cca9c7a62476d54ed5d1bddc7a39c3" @@ -105,7 +106,7 @@ func TestState_ProcessBlock_PendingUpdateThenCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateRegisterCR(code, cid, nickname), }, }, nil) @@ -122,7 +123,7 @@ func TestState_ProcessBlock_PendingUpdateThenCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateUpdateCR(code, cid, nickname2), }, }, nil) @@ -139,7 +140,7 @@ func TestState_ProcessBlock_PendingUpdateThenCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateUnregisterCR(code), }, }, nil) @@ -162,8 +163,8 @@ func TestState_ProcessBlock_PendingActiveThenCancel(t *testing.T) { GetHeight: func() uint32 { return currentHeight }, - GetUTXO: func(programHash *common.Uint168) ([]*types.UTXO, error) { - return []*types.UTXO{}, nil + GetUTXO: func(programHash *common.Uint168) ([]*common2.UTXO, error) { + return []*common2.UTXO{}, nil }, }) nickname := randomString() @@ -182,7 +183,7 @@ func TestState_ProcessBlock_PendingActiveThenCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateRegisterCR(code, cid, nickname), }, }, nil) @@ -199,7 +200,7 @@ func TestState_ProcessBlock_PendingActiveThenCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) currentHeight++ } @@ -212,7 +213,7 @@ func TestState_ProcessBlock_PendingActiveThenCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateUpdateCR(code, cid, nickname2), }, }, nil) @@ -229,7 +230,7 @@ func TestState_ProcessBlock_PendingActiveThenCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateUnregisterCR(code), }, }, nil) @@ -253,8 +254,8 @@ func TestState_ProcessBlock_MixedCRProcessing(t *testing.T) { GetHeight: func() uint32 { return currentHeight }, - GetUTXO: func(programHash *common.Uint168) ([]*types.UTXO, error) { - return []*types.UTXO{}, nil + GetUTXO: func(programHash *common.Uint168) ([]*common2.UTXO, error) { + return []*common2.UTXO{}, nil }, }) registerFuncs(committee.state) @@ -274,7 +275,7 @@ func TestState_ProcessBlock_MixedCRProcessing(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateRegisterCR(code, cid, nickname), }, }, nil) @@ -291,7 +292,7 @@ func TestState_ProcessBlock_MixedCRProcessing(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) currentHeight++ } @@ -313,8 +314,8 @@ func TestState_ProcessBlock_VotingAndCancel(t *testing.T) { GetHeight: func() uint32 { return currentHeight }, - GetUTXO: func(programHash *common.Uint168) ([]*types.UTXO, error) { - return []*types.UTXO{}, nil + GetUTXO: func(programHash *common.Uint168) ([]*common2.UTXO, error) { + return []*common2.UTXO{}, nil }, }) @@ -326,7 +327,7 @@ func TestState_ProcessBlock_VotingAndCancel(t *testing.T) { registerFuncs(committee.state) references := make(map[*common2.Input]common2.Output) - committee.state.getTxReference = func(tx *types.Transaction) ( + committee.state.getTxReference = func(tx *transactions.BaseTransaction) ( map[*common2.Input]common2.Output, error) { return references, nil } @@ -337,7 +338,7 @@ func TestState_ProcessBlock_VotingAndCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{voteTx}, + Transactions: []*transactions.BaseTransaction{voteTx}, }, nil) currentHeight++ @@ -357,7 +358,7 @@ func TestState_ProcessBlock_VotingAndCancel(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ { Inputs: []*common2.Input{input}, }, @@ -380,8 +381,8 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { GetHeight: func() uint32 { return currentHeight }, - GetUTXO: func(programHash *common.Uint168) ([]*types.UTXO, error) { - return []*types.UTXO{}, nil + GetUTXO: func(programHash *common.Uint168) ([]*common2.UTXO, error) { + return []*common2.UTXO{}, nil }, }) registerFuncs(committee.state) @@ -394,7 +395,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { depositCont, _ := contract.CreateDepositContractByPubKey(pk) // register CR - registerCRTx := &types.Transaction{ + registerCRTx := &transactions.BaseTransaction{ TxType: common2.RegisterCR, Payload: &payload.CRInfo{ Code: code, @@ -412,7 +413,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{registerCRTx}, + Transactions: []*transactions.BaseTransaction{registerCRTx}, }, nil) currentHeight++ candidate := committee.state.getCandidate(cid) @@ -422,7 +423,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { committee.state.getTotalAmount(candidate.info.CID)) // deposit though normal tx - tranferTx := &types.Transaction{ + tranferTx := &transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Outputs: []*common2.Output{ @@ -436,7 +437,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{tranferTx}, + Transactions: []*transactions.BaseTransaction{tranferTx}, }, nil) currentHeight++ assert.Equal(t, common.Fixed64(5000*1e8), @@ -450,7 +451,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) currentHeight++ } @@ -459,7 +460,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ generateUnregisterCR(code), }, }, nil) @@ -470,7 +471,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) currentHeight++ } @@ -482,7 +483,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) // return deposit @@ -506,14 +507,14 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{rdTx}, + Transactions: []*transactions.BaseTransaction{rdTx}, }, nil) committee.state.history.Commit(currentHeight) assert.Equal(t, common.Fixed64(0), committee.state.getDepositAmount(candidate.info.CID)) } -func mockNewVoteTx(cids [][]byte) *types.Transaction { +func mockNewVoteTx(cids [][]byte) *transactions.BaseTransaction { candidateVotes := make([]outputpayload.CandidateVotes, 0, len(cids)) for i, cid := range cids { //code := getCode(common.BytesToHexString(pk)) @@ -533,7 +534,7 @@ func mockNewVoteTx(cids [][]byte) *types.Transaction { }, } - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Outputs: []*common2.Output{output}, @@ -541,8 +542,8 @@ func mockNewVoteTx(cids [][]byte) *types.Transaction { } func generateRegisterCR(code []byte, cid common.Uint168, - nickname string) *types.Transaction { - return &types.Transaction{ + nickname string) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.RegisterCR, Payload: &payload.CRInfo{ Code: code, @@ -553,8 +554,8 @@ func generateRegisterCR(code []byte, cid common.Uint168, } func generateUpdateCR(code []byte, cid common.Uint168, - nickname string) *types.Transaction { - return &types.Transaction{ + nickname string) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.UpdateCR, Payload: &payload.CRInfo{ Code: code, @@ -564,8 +565,8 @@ func generateUpdateCR(code []byte, cid common.Uint168, } } -func generateUnregisterCR(code []byte) *types.Transaction { - return &types.Transaction{ +func generateUnregisterCR(code []byte) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.UnregisterCR, Payload: &payload.UnregisterCR{ CID: *getCID(code), @@ -578,8 +579,8 @@ func getCID(code []byte) *common.Uint168 { return ct1.ToProgramHash() } -func generateReturnCRDeposit(code []byte) *types.Transaction { - return &types.Transaction{ +func generateReturnCRDeposit(code []byte) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.ReturnCRDepositCoin, Payload: &payload.ReturnDepositCoin{}, Programs: []*program.Program{ @@ -593,7 +594,7 @@ func generateReturnCRDeposit(code []byte) *types.Transaction { func registerFuncs(state *State) { state.registerFunctions(&FunctionsConfig{ GetHistoryMember: func(code []byte) []*CRMember { return nil }, - GetTxReference: func(tx *types.Transaction) ( + GetTxReference: func(tx *transactions.BaseTransaction) ( map[*common2.Input]common2.Output, error) { return make(map[*common2.Input]common2.Output), nil }}) diff --git a/database/ffldb/db.go b/database/ffldb/db.go index 070b73d68..0b7cb6e3b 100644 --- a/database/ffldb/db.go +++ b/database/ffldb/db.go @@ -150,7 +150,7 @@ func convertErr(desc string, ldbErr error) database.Error { case ldbErr == leveldb.ErrClosed: code = database.ErrDbNotOpen - // Transaction errors. + // BaseTransaction errors. case ldbErr == leveldb.ErrSnapshotReleased: code = database.ErrTxClosed case ldbErr == leveldb.ErrIterReleased: diff --git a/dpos/account/account.go b/dpos/account/account.go index 9bb78dba2..0f6cd0efb 100644 --- a/dpos/account/account.go +++ b/dpos/account/account.go @@ -7,9 +7,9 @@ package account import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/account" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" ) @@ -20,7 +20,7 @@ type Account interface { SignProposal(proposal *payload.DPOSProposal) ([]byte, error) SignVote(vote *payload.DPOSProposalVote) ([]byte, error) Sign(data []byte) []byte - SignTx(tx *types.Transaction) ([]byte, error) + SignTx(tx *transactions.BaseTransaction) ([]byte, error) DecryptAddr(cipher []byte) (addr string, err error) } @@ -69,7 +69,7 @@ func (a *dAccount) Sign(data []byte) []byte { return sign } -func (a *dAccount) SignTx(tx *types.Transaction) ([]byte, error) { +func (a *dAccount) SignTx(tx *transactions.BaseTransaction) ([]byte, error) { buf := new(bytes.Buffer) if err := tx.SerializeUnsigned(buf); err != nil { return nil, err diff --git a/dpos/arbitrator.go b/dpos/arbitrator.go index 9f354d0ec..3682bebd6 100644 --- a/dpos/arbitrator.go +++ b/dpos/arbitrator.go @@ -8,6 +8,7 @@ package dpos import ( "bytes" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "time" "github.com/elastos/Elastos.ELA/blockchain" @@ -311,7 +312,7 @@ func NewArbitrator(account account.Account, cfg Config) (*Arbitrator, error) { a.OnPeersChanged(e.Data.([]peer.PID)) case events.ETTransactionAccepted: - tx := e.Data.(*types.Transaction) + tx := e.Data.(*transactions.BaseTransaction) if tx.IsIllegalBlockTx() { a.OnIllegalBlockTxReceived(tx.Payload.(*payload.DPOSIllegalBlocks)) } else if tx.IsInactiveArbitrators() { diff --git a/dpos/manager/dposmanager.go b/dpos/manager/dposmanager.go index 94b24fba9..0ac24b7cc 100644 --- a/dpos/manager/dposmanager.go +++ b/dpos/manager/dposmanager.go @@ -7,6 +7,7 @@ package manager import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sort" "time" @@ -84,8 +85,8 @@ type NetworkEventListener interface { OnConfirmReceived(p *payload.Confirm, height uint32) OnIllegalBlocksTxReceived(i *payload.DPOSIllegalBlocks) OnSidechainIllegalEvidenceReceived(s *payload.SidechainIllegalData) - OnInactiveArbitratorsReceived(id dpeer.PID, tx *types.Transaction) - OnRevertToDPOSTxReceived(id dpeer.PID, tx *types.Transaction) + OnInactiveArbitratorsReceived(id dpeer.PID, tx *transactions.BaseTransaction) + OnRevertToDPOSTxReceived(id dpeer.PID, tx *transactions.BaseTransaction) OnResponseInactiveArbitratorsReceived(txHash *common.Uint256, Signer []byte, Sign []byte) OnResponseRevertToDPOSTxReceived(txHash *common.Uint256, @@ -171,7 +172,7 @@ func (d *DPOSManager) Initialize(handler *DPOSHandlerSwitch, d.broadcast = broadcast } -func (d *DPOSManager) AppendToTxnPool(txn *types.Transaction) error { +func (d *DPOSManager) AppendToTxnPool(txn *transactions.BaseTransaction) error { return d.txPool.AppendToTxPool(txn) } @@ -606,7 +607,7 @@ func (d *DPOSManager) clearInactiveData(p *payload.InactiveArbitrators) { } func (d *DPOSManager) OnRevertToDPOSTxReceived(id dpeer.PID, - tx *types.Transaction) { + tx *transactions.BaseTransaction) { if !d.isCurrentArbiter() { return @@ -619,7 +620,7 @@ func (d *DPOSManager) OnRevertToDPOSTxReceived(id dpeer.PID, } func (d *DPOSManager) OnInactiveArbitratorsReceived(id dpeer.PID, - tx *types.Transaction) { + tx *transactions.BaseTransaction) { if !d.isCRCArbiter() { return } diff --git a/dpos/manager/evidencecache.go b/dpos/manager/evidencecache.go index ab4ae77b3..254118f31 100644 --- a/dpos/manager/evidencecache.go +++ b/dpos/manager/evidencecache.go @@ -10,6 +10,7 @@ import ( "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/dpos/log" ) @@ -70,7 +71,7 @@ func (e *evidenceCache) TryDelete(hash common.Uint256) { } } -func (e *evidenceCache) tryGetEvidenceHash(tx *types.Transaction) (common.Uint256, bool) { +func (e *evidenceCache) tryGetEvidenceHash(tx *transactions.BaseTransaction) (common.Uint256, bool) { var hash common.Uint256 result := true diff --git a/dpos/manager/illegalbehaviormonitor.go b/dpos/manager/illegalbehaviormonitor.go index 522674450..67e2fde69 100644 --- a/dpos/manager/illegalbehaviormonitor.go +++ b/dpos/manager/illegalbehaviormonitor.go @@ -7,6 +7,7 @@ package manager import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/contract/program" @@ -165,7 +166,7 @@ func (i *IllegalBehaviorMonitor) ProcessIllegalProposal( func (i *IllegalBehaviorMonitor) sendIllegalProposalTransaction( evidences *payload.DPOSIllegalProposals) { - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.IllegalProposalEvidence, PayloadVersion: payload.IllegalProposalVersion, @@ -185,7 +186,7 @@ func (i *IllegalBehaviorMonitor) sendIllegalProposalTransaction( func (i *IllegalBehaviorMonitor) SendSidechainIllegalEvidenceTransaction( evidence *payload.SidechainIllegalData) { - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.IllegalSidechainEvidence, PayloadVersion: payload.SidechainIllegalDataVersion, @@ -205,7 +206,7 @@ func (i *IllegalBehaviorMonitor) SendSidechainIllegalEvidenceTransaction( func (i *IllegalBehaviorMonitor) sendIllegalVoteTransaction( evidences *payload.DPOSIllegalVotes) { - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.IllegalVoteEvidence, PayloadVersion: payload.IllegalVoteVersion, diff --git a/dpos/manager/proposaldispatcher.go b/dpos/manager/proposaldispatcher.go index 76021ae2d..c033e108d 100644 --- a/dpos/manager/proposaldispatcher.go +++ b/dpos/manager/proposaldispatcher.go @@ -9,6 +9,7 @@ import ( "bytes" "errors" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" @@ -55,8 +56,8 @@ type ProposalDispatcher struct { firstBadNetworkRecover bool inactiveCountDown ViewChangesCountDown - currentInactiveArbitratorTx *types.Transaction - RevertToDPOSTx *types.Transaction + currentInactiveArbitratorTx *transactions.BaseTransaction + RevertToDPOSTx *transactions.BaseTransaction signedTxs map[common.Uint256]interface{} @@ -491,7 +492,7 @@ func (p *ProposalDispatcher) OnIllegalBlocksTxReceived(i *payload.DPOSIllegalBlo } func (p *ProposalDispatcher) OnRevertToDPOSTxReceived(id peer.PID, - tx *types.Transaction) { + tx *transactions.BaseTransaction) { if _, ok := p.signedTxs[tx.Hash()]; ok { return } @@ -516,7 +517,7 @@ func (p *ProposalDispatcher) OnRevertToDPOSTxReceived(id peer.PID, } func (p *ProposalDispatcher) OnInactiveArbitratorsReceived(id peer.PID, - tx *types.Transaction) { + tx *transactions.BaseTransaction) { if _, ok := p.signedTxs[tx.Hash()]; ok { log.Warn("[OnInactiveArbitratorsReceived] already processed") return @@ -833,7 +834,7 @@ func (p *ProposalDispatcher) setProcessingProposal(d *payload.DPOSProposal) (fin } func (p *ProposalDispatcher) CreateRevertToDPOS(RevertToPOWBlockHeight uint32) ( - *types.Transaction, error) { + *transactions.BaseTransaction, error) { var err error revertToDPOSPayload := &payload.RevertToDPOS{ @@ -846,7 +847,7 @@ func (p *ProposalDispatcher) CreateRevertToDPOS(RevertToPOWBlockHeight uint32) ( } programHash := con.ToProgramHash() - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.RevertToDPOS, PayloadVersion: payload.RevertToDPOSVersion, @@ -878,7 +879,7 @@ func (p *ProposalDispatcher) CreateRevertToDPOS(RevertToPOWBlockHeight uint32) ( } func (p *ProposalDispatcher) CreateInactiveArbitrators() ( - *types.Transaction, error) { + *transactions.BaseTransaction, error) { var err error inactivePayload := &payload.InactiveArbitrators{ @@ -905,7 +906,7 @@ func (p *ProposalDispatcher) CreateInactiveArbitrators() ( } programHash := con.ToProgramHash() - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.InactiveArbitrators, PayloadVersion: payload.InactiveArbitratorsVersion, diff --git a/dpos/network.go b/dpos/network.go index ac2841db1..6f5f43cbd 100644 --- a/dpos/network.go +++ b/dpos/network.go @@ -8,6 +8,7 @@ package dpos import ( "bytes" "errors" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sync" "github.com/elastos/Elastos.ELA/blockchain" @@ -267,7 +268,7 @@ func (n *network) processMessage(msgItem *messageItem) { case elap2p.CmdTx: msgTx, processed := m.(*elamsg.Tx) if processed { - tx, ok := msgTx.Serializable.(*types.Transaction) + tx, ok := msgTx.Serializable.(*transactions.BaseTransaction) if !ok { return } @@ -384,7 +385,7 @@ func makeEmptyMessage(cmd string) (message elap2p.Message, err error) { case elap2p.CmdBlock: message = elamsg.NewBlock(&types.Block{}) case elap2p.CmdTx: - message = elamsg.NewTx(&types.Transaction{}) + message = elamsg.NewTx(&transactions.BaseTransaction{}) case msg.CmdAcceptVote: message = &msg.Vote{Command: msg.CmdAcceptVote} case msg.CmdReceivedProposal: diff --git a/dpos/state/arbitrators.go b/dpos/state/arbitrators.go index 5b58a0cd3..0261b72b9 100644 --- a/dpos/state/arbitrators.go +++ b/dpos/state/arbitrators.go @@ -11,6 +11,8 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "math/rand" "sort" @@ -134,7 +136,7 @@ func (a *arbitrators) GetRevertToPOWBlockHeight() uint32 { func (a *arbitrators) RegisterFunction(bestHeight func() uint32, bestBlockHash func() *common.Uint256, getBlockByHeight func(uint32) (*types.Block, error), - getTxReference func(tx *types.Transaction) ( + getTxReference func(tx *transactions.BaseTransaction) ( map[*common2.Input]common2.Output, error)) { a.bestHeight = bestHeight a.bestBlockHash = bestBlockHash @@ -314,7 +316,7 @@ func (a *arbitrators) CheckCustomIDResultsTx(block *types.Block) error { return nil } -func (a *arbitrators) ProcessSpecialTxPayload(p types.Payload, +func (a *arbitrators) ProcessSpecialTxPayload(p interfaces.Payload, height uint32) error { switch obj := p.(type) { case *payload.DPOSIllegalBlocks: @@ -578,7 +580,7 @@ func (a *arbitrators) createRevertToPOWTransaction(blockHeight uint32) { Type: revertType, WorkingHeight: blockHeight + 1, } - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.RevertToPOW, PayloadVersion: payload.RevertToPOWVersion, @@ -1502,7 +1504,7 @@ func (a *arbitrators) ConvertToArbitersStr(arbiters [][]byte) []string { return arbitersStr } -func (a *arbitrators) createNextTurnDPOSInfoTransaction(blockHeight uint32, forceChange bool) *types.Transaction { +func (a *arbitrators) createNextTurnDPOSInfoTransaction(blockHeight uint32, forceChange bool) *transactions.BaseTransaction { var nextTurnDPOSInfo payload.NextTurnDPOSInfo nextTurnDPOSInfo.CRPublicKeys = make([][]byte, 0) nextTurnDPOSInfo.DPOSPublicKeys = make([][]byte, 0) @@ -1528,7 +1530,7 @@ func (a *arbitrators) createNextTurnDPOSInfoTransaction(blockHeight uint32, forc log.Debugf("[createNextTurnDPOSInfoTransaction] CRPublicKeys %v, DPOSPublicKeys%v\n", a.ConvertToArbitersStr(nextTurnDPOSInfo.CRPublicKeys), a.ConvertToArbitersStr(nextTurnDPOSInfo.DPOSPublicKeys)) - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.NextTurnDPOSInfo, Payload: &nextTurnDPOSInfo, diff --git a/dpos/state/arbitratorsmock.go b/dpos/state/arbitratorsmock.go index 46835430e..9631557a2 100644 --- a/dpos/state/arbitratorsmock.go +++ b/dpos/state/arbitratorsmock.go @@ -7,6 +7,7 @@ package state import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" @@ -156,7 +157,7 @@ func (a *ArbitratorsMock) CheckRevertToDPOSTX(block *types.Block) error { panic("implement me") } -func (a *ArbitratorsMock) ProcessSpecialTxPayload(p types.Payload, height uint32) error { +func (a *ArbitratorsMock) ProcessSpecialTxPayload(p interfaces.Payload, height uint32) error { panic("implement me") } diff --git a/dpos/state/arbitratorsrollback_test.go b/dpos/state/arbitratorsrollback_test.go index 17b158f52..cca47041d 100644 --- a/dpos/state/arbitratorsrollback_test.go +++ b/dpos/state/arbitratorsrollback_test.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -125,10 +126,10 @@ func checkResult(t *testing.T, A, B, C, D *CheckPoint) { } func getRegisterProducerTx(ownerPublicKey, nodePublicKey []byte, - nickName string) *types.Transaction { + nickName string) *transactions.BaseTransaction { pk, _ := crypto.DecodePoint(ownerPublicKey) depositCont, _ := contract.CreateDepositContractByPubKey(pk) - return &types.Transaction{ + return &transactions.BaseTransaction{ TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ OwnerPublicKey: ownerPublicKey, @@ -145,8 +146,8 @@ func getRegisterProducerTx(ownerPublicKey, nodePublicKey []byte, } func getVoteProducerTx(amount common.Fixed64, - candidateVotes []outputpayload.CandidateVotes) *types.Transaction { - return &types.Transaction{ + candidateVotes []outputpayload.CandidateVotes) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ Version: 0x09, TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, @@ -172,8 +173,8 @@ func getVoteProducerTx(amount common.Fixed64, } func getUpdateProducerTx(ownerPublicKey, nodePublicKey []byte, - nickName string) *types.Transaction { - return &types.Transaction{ + nickName string) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.UpdateProducer, Payload: &payload.ProducerInfo{ OwnerPublicKey: ownerPublicKey, @@ -183,8 +184,8 @@ func getUpdateProducerTx(ownerPublicKey, nodePublicKey []byte, } } -func getCancelProducer(publicKey []byte) *types.Transaction { - return &types.Transaction{ +func getCancelProducer(publicKey []byte) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ Version: 0x09, TxType: common2.CancelProducer, Payload: &payload.ProcessProducer{ @@ -193,11 +194,11 @@ func getCancelProducer(publicKey []byte) *types.Transaction { } } -func getReturnProducerDeposit(publicKey []byte, amount common.Fixed64) *types.Transaction { +func getReturnProducerDeposit(publicKey []byte, amount common.Fixed64) *transactions.BaseTransaction { pk, _ := crypto.DecodePoint(publicKey) code, _ := contract.CreateStandardRedeemScript(pk) - return &types.Transaction{ + return &transactions.BaseTransaction{ TxType: common2.ReturnDepositCoin, Payload: &payload.ReturnDepositCoin{}, Programs: []*program.Program{ @@ -217,7 +218,7 @@ func TestArbitrators_RollbackRegisterProducer(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ getRegisterProducerTx(abtList[0], abtList[0], "p1"), getRegisterProducerTx(abtList[1], abtList[1], "p2"), getRegisterProducerTx(abtList[2], abtList[2], "p3"), @@ -284,7 +285,7 @@ func TestArbitrators_RollbackVoteProducer(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ getRegisterProducerTx(abtList[0], abtList[0], "p1"), getRegisterProducerTx(abtList[1], abtList[1], "p2"), getRegisterProducerTx(abtList[2], abtList[2], "p3"), @@ -311,7 +312,7 @@ func TestArbitrators_RollbackVoteProducer(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) arbiterStateA := abt.Snapshot() assert.Equal(t, common.Fixed64(5), abt.getProducer(abtList[0]).votes) @@ -319,7 +320,7 @@ func TestArbitrators_RollbackVoteProducer(t *testing.T) { updateProducerTx := getUpdateProducerTx(abtList[1], abtList[1], "node1") abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{updateProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{updateProducerTx}}, nil) arbiterStateB := abt.Snapshot() // rollback @@ -332,7 +333,7 @@ func TestArbitrators_RollbackVoteProducer(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{updateProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{updateProducerTx}}, nil) arbiterStateD := abt.Snapshot() checkResult(t, arbiterStateA, arbiterStateB, arbiterStateC, arbiterStateD) @@ -346,7 +347,7 @@ func TestArbitrators_RollbackUpdateProducer(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ getRegisterProducerTx(abtList[0], abtList[0], "p1"), getRegisterProducerTx(abtList[1], abtList[1], "p2"), getRegisterProducerTx(abtList[2], abtList[2], "p3"), @@ -374,7 +375,7 @@ func TestArbitrators_RollbackUpdateProducer(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) arbiterStateB := abt.Snapshot() assert.Equal(t, common.Fixed64(5), abt.getProducer(abtList[0]).votes) @@ -389,7 +390,7 @@ func TestArbitrators_RollbackUpdateProducer(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) arbiterStateD := abt.Snapshot() checkResult(t, arbiterStateA, arbiterStateB, arbiterStateC, arbiterStateD) @@ -403,7 +404,7 @@ func TestArbitrators_RollbackCancelProducer(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ getRegisterProducerTx(abtList[0], abtList[0], "p1"), getRegisterProducerTx(abtList[1], abtList[1], "p2"), getRegisterProducerTx(abtList[2], abtList[2], "p3"), @@ -432,7 +433,7 @@ func TestArbitrators_RollbackCancelProducer(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) // cancel producer cancelProducerTx := getCancelProducer(abtList[0]) @@ -442,7 +443,7 @@ func TestArbitrators_RollbackCancelProducer(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{cancelProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{cancelProducerTx}}, nil) arbiterStateB := abt.Snapshot() assert.Equal(t, 3, len(abt.GetActiveProducers())) @@ -457,7 +458,7 @@ func TestArbitrators_RollbackCancelProducer(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{cancelProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{cancelProducerTx}}, nil) arbiterStateD := abt.Snapshot() assert.Equal(t, 3, len(abt.GetActiveProducers())) @@ -477,7 +478,7 @@ func TestArbitrators_RollbackReturnProducerDeposit(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ register1, register2, register3, @@ -506,7 +507,7 @@ func TestArbitrators_RollbackReturnProducerDeposit(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) // cancel producer cancelProducerTx := getCancelProducer(abtList[0]) @@ -514,7 +515,7 @@ func TestArbitrators_RollbackReturnProducerDeposit(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{cancelProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{cancelProducerTx}}, nil) assert.Equal(t, 3, len(abt.GetActiveProducers())) // set get producer deposit amount function @@ -537,7 +538,7 @@ func TestArbitrators_RollbackReturnProducerDeposit(t *testing.T) { currentHeight += abt.chainParams.CRDepositLockupBlocks abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{cancelProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{cancelProducerTx}}, nil) assert.Equal(t, common.Fixed64(0), abt.GetProducer(abtList[0]).depositAmount) @@ -555,7 +556,7 @@ func TestArbitrators_RollbackReturnProducerDeposit(t *testing.T) { currentHeight = abt.chainParams.CRVotingStartHeight abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{returnDepositTx}}, nil) + Transactions: []*transactions.BaseTransaction{returnDepositTx}}, nil) assert.Equal(t, 1, len(abt.GetReturnedDepositProducers())) assert.Equal(t, common.Fixed64(0), abt.GetProducer(abtList[0]).depositAmount) arbiterStateB := abt.Snapshot() @@ -571,7 +572,7 @@ func TestArbitrators_RollbackReturnProducerDeposit(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{returnDepositTx}}, nil) + Transactions: []*transactions.BaseTransaction{returnDepositTx}}, nil) assert.Equal(t, 1, len(abt.GetReturnedDepositProducers())) arbiterStateD := abt.Snapshot() @@ -586,7 +587,7 @@ func TestArbitrators_RollbackLastBlockOfARound(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ getRegisterProducerTx(abtList[0], abtList[0], "p1"), getRegisterProducerTx(abtList[1], abtList[1], "p2"), getRegisterProducerTx(abtList[2], abtList[2], "p3"), @@ -615,7 +616,7 @@ func TestArbitrators_RollbackLastBlockOfARound(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) // set general arbiters count abt.chainParams.GeneralArbiters = 2 @@ -699,7 +700,7 @@ func TestArbitrators_NextTurnDposInfoTX(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ getRegisterProducerTx(abtList[0], abtList[0], "p1"), getRegisterProducerTx(abtList[1], abtList[1], "p2"), getRegisterProducerTx(abtList[2], abtList[2], "p3"), @@ -728,7 +729,7 @@ func TestArbitrators_NextTurnDposInfoTX(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) // set general arbiters count abt.chainParams.GeneralArbiters = 2 @@ -750,7 +751,7 @@ func TestArbitrators_NextTurnDposInfoTX(t *testing.T) { if err2 != nil { fmt.Println("HexStringToBytes err2", err2) } - var nextTurnDPOSInfoTx types.Transaction + var nextTurnDPOSInfoTx transactions.BaseTransaction reader2 := bytes.NewReader(data) err2 = nextTurnDPOSInfoTx.Deserialize(reader2) if err2 != nil { @@ -759,7 +760,7 @@ func TestArbitrators_NextTurnDposInfoTX(t *testing.T) { abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{&nextTurnDPOSInfoTx}}, nil) + Transactions: []*transactions.BaseTransaction{&nextTurnDPOSInfoTx}}, nil) currentHeight++ abt.ProcessBlock(&types.Block{ @@ -774,7 +775,7 @@ func TestArbitrators_RollbackRewardBlock(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ getRegisterProducerTx(abtList[0], abtList[0], "p1"), getRegisterProducerTx(abtList[1], abtList[1], "p2"), getRegisterProducerTx(abtList[2], abtList[2], "p3"), @@ -803,7 +804,7 @@ func TestArbitrators_RollbackRewardBlock(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) // set general arbiters count abt.chainParams.GeneralArbiters = 2 @@ -882,7 +883,7 @@ func TestArbitrators_RollbackMultipleTransactions(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ register1, getRegisterProducerTx(abtList[1], abtList[1], "p2"), getRegisterProducerTx(abtList[2], abtList[2], "p3"), @@ -911,7 +912,7 @@ func TestArbitrators_RollbackMultipleTransactions(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{voteProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{voteProducerTx}}, nil) // cancel producer cancelProducerTx := getCancelProducer(abtList[0]) @@ -919,7 +920,7 @@ func TestArbitrators_RollbackMultipleTransactions(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{cancelProducerTx}}, nil) + Transactions: []*transactions.BaseTransaction{cancelProducerTx}}, nil) assert.Equal(t, 3, len(abt.GetActiveProducers())) // set get producer deposit amount function @@ -959,7 +960,7 @@ func TestArbitrators_RollbackMultipleTransactions(t *testing.T) { currentHeight = abt.chainParams.CRVotingStartHeight abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerProducerTx2, voteProducerTx2, updateProducerTx2, @@ -983,7 +984,7 @@ func TestArbitrators_RollbackMultipleTransactions(t *testing.T) { currentHeight++ abt.ProcessBlock(&types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerProducerTx2, voteProducerTx2, updateProducerTx2, diff --git a/dpos/state/heightversion_test.go b/dpos/state/heightversion_test.go index a31f4789c..a57088503 100644 --- a/dpos/state/heightversion_test.go +++ b/dpos/state/heightversion_test.go @@ -7,6 +7,7 @@ package state import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sort" "testing" @@ -85,7 +86,7 @@ func TestArbitrators_GetNormalArbitratorsDesc(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ { TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ @@ -122,7 +123,7 @@ func TestArbitrators_GetNormalArbitratorsDesc(t *testing.T) { currentHeight++ blockEx := &types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, } arbiters.ProcessBlock(blockEx, nil) } @@ -138,7 +139,7 @@ func TestArbitrators_GetNormalArbitratorsDesc(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ { TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ @@ -154,7 +155,7 @@ func TestArbitrators_GetNormalArbitratorsDesc(t *testing.T) { currentHeight++ blockEx := &types.Block{ Header: types.Header{Height: currentHeight}, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, } arbiters.ProcessBlock(blockEx, nil) } diff --git a/dpos/state/interface.go b/dpos/state/interface.go index 441d3f285..7bcde1801 100644 --- a/dpos/state/interface.go +++ b/dpos/state/interface.go @@ -8,13 +8,14 @@ package state import ( "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/interfaces" "github.com/elastos/Elastos.ELA/dpos/p2p/peer" ) type Arbitrators interface { Start() CheckDPOSIllegalTx(block *types.Block) error - ProcessSpecialTxPayload(p types.Payload, height uint32) error + ProcessSpecialTxPayload(p interfaces.Payload, height uint32) error CheckCRCAppropriationTx(block *types.Block) error CheckNextTurnDPOSInfoTx(block *types.Block) error CheckCustomIDResultsTx(block *types.Block) error diff --git a/dpos/state/reward_test.go b/dpos/state/reward_test.go index 2754e1da2..e79749b7b 100644 --- a/dpos/state/reward_test.go +++ b/dpos/state/reward_test.go @@ -9,6 +9,7 @@ import ( "bytes" "crypto/rand" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -61,7 +62,7 @@ func TestCommittee_ChangeCommitteeReward(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ registerCRTxn1, registerCRTxn2, registerCRTxn3, @@ -87,7 +88,7 @@ func TestCommittee_ChangeCommitteeReward(t *testing.T) { Header: types.Header{ Height: currentHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ voteCRTx, }, }, nil) @@ -121,7 +122,7 @@ func TestCommittee_ChangeCommitteeReward(t *testing.T) { // Register 10 producers on one height. for i := 0; i < 20; i++ { - txs := make([]*types.Transaction, 10) + txs := make([]*transactions.BaseTransaction, 10) for i, p := range producers[i*10 : (i+1)*10] { txs[i] = mockRegisterProducerTx(p) } @@ -190,7 +191,7 @@ func getCodeByPubKeyStr(publicKey string) []byte { return redeemScript } -func getRegisterCRTx(publicKeyStr, privateKeyStr, nickName string) *types.Transaction { +func getRegisterCRTx(publicKeyStr, privateKeyStr, nickName string) *transactions.BaseTransaction { publicKeyStr1 := publicKeyStr privateKeyStr1 := privateKeyStr publicKey1, _ := common.HexStringToBytes(publicKeyStr1) @@ -201,7 +202,7 @@ func getRegisterCRTx(publicKeyStr, privateKeyStr, nickName string) *types.Transa did1, _ := getDIDByCode(code1) hash1, _ := contract.PublicKeyToDepositProgramHash(publicKey1) - txn := new(types.Transaction) + txn := new(transactions.BaseTransaction) txn.TxType = common2.RegisterCR txn.Version = common2.TxVersion09 crInfoPayload := &payload.CRInfo{ @@ -254,8 +255,8 @@ func getDIDByCode(code []byte) (*common.Uint168, error) { } func getVoteCRTx(amount common.Fixed64, - candidateVotes []outputpayload.CandidateVotes) *types.Transaction { - return &types.Transaction{ + candidateVotes []outputpayload.CandidateVotes) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ Version: 0x09, TxType: common2.TransferAsset, Outputs: []*common2.Output{ diff --git a/dpos/state/state.go b/dpos/state/state.go index 8eb935c92..5e575f11f 100644 --- a/dpos/state/state.go +++ b/dpos/state/state.go @@ -10,6 +10,8 @@ import ( "encoding/hex" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" + "github.com/elastos/Elastos.ELA/core/types/transactions" "io" "math" "sync" @@ -280,7 +282,7 @@ type State struct { isInElectionPeriod func() bool getProducerDepositAmount func(programHash common.Uint168) ( common.Fixed64, error) - getTxReference func(tx *types.Transaction) ( + getTxReference func(tx *transactions.BaseTransaction) ( map[*common2.Input]common2.Output, error) tryUpdateCRMemberInactivity func(did common.Uint168, needReset bool, height uint32) tryRevertCRMemberInactivity func(did common.Uint168, oriState state.MemberState, @@ -690,7 +692,7 @@ func (s *State) ProducerNodePublicKeyExists(publicKey []byte) bool { // SpecialTxExists returns if a special tx (typically means illegal and // inactive tx) is exists by it's hash -func (s *State) SpecialTxExists(tx *types.Transaction) bool { +func (s *State) SpecialTxExists(tx *transactions.BaseTransaction) bool { illegalData, ok := tx.Payload.(payload.DPOSIllegalData) if !ok { log.Error("special tx payload cast failed, tx:", common.ToReversedString(tx.Hash())) @@ -706,7 +708,7 @@ func (s *State) SpecialTxExists(tx *types.Transaction) bool { // IsDPOSTransaction returns if a transaction will change the producers and // votes state. -func (s *State) IsDPOSTransaction(tx *types.Transaction) bool { +func (s *State) IsDPOSTransaction(tx *transactions.BaseTransaction) bool { switch tx.TxType { // Transactions will changes the producers state. case common2.RegisterProducer, common2.UpdateProducer, common2.CancelProducer, @@ -837,7 +839,7 @@ func (s *State) ProcessVoteStatisticsBlock(block *types.Block) { // processTransactions takes the transactions and the height when they have been // packed into a block. Then loop through the transactions to update producers // state and votes according to transactions content. -func (s *State) processTransactions(txs []*types.Transaction, height uint32) { +func (s *State) processTransactions(txs []*transactions.BaseTransaction, height uint32) { for _, tx := range txs { s.processTransaction(tx, height) @@ -929,7 +931,7 @@ func (s *State) processTransactions(txs []*types.Transaction, height uint32) { // processTransaction take a transaction and the height it has been packed into // a block, then update producers state and votes according to the transaction // content. -func (s *State) processTransaction(tx *types.Transaction, height uint32) { +func (s *State) processTransaction(tx *transactions.BaseTransaction, height uint32) { switch tx.TxType { case common2.RegisterProducer: s.registerProducer(tx, height) @@ -993,7 +995,7 @@ func (s *State) processTransaction(tx *types.Transaction, height uint32) { } // registerProducer handles the register producer transaction. -func (s *State) registerProducer(tx *types.Transaction, height uint32) { +func (s *State) registerProducer(tx *transactions.BaseTransaction, height uint32) { info := tx.Payload.(*payload.ProducerInfo) nickname := info.NickName nodeKey := hex.EncodeToString(info.NodePublicKey) @@ -1108,7 +1110,7 @@ func (s *State) activateProducer(p *payload.ActivateProducer, height uint32) { // processVotes takes a transaction, if the transaction including any vote // inputs or outputs, validate and update producers votes. -func (s *State) processVotes(tx *types.Transaction, height uint32) { +func (s *State) processVotes(tx *transactions.BaseTransaction, height uint32) { if tx.Version >= common2.TxVersion09 { // Votes to producers. for i, output := range tx.Outputs { @@ -1147,7 +1149,7 @@ func (s *State) processVotes(tx *types.Transaction, height uint32) { } // processDeposit takes a transaction output with deposit program hash. -func (s *State) processDeposit(tx *types.Transaction, height uint32) { +func (s *State) processDeposit(tx *transactions.BaseTransaction, height uint32) { for i, output := range tx.Outputs { if contract.GetPrefixType(output.ProgramHash) == contract.PrefixDeposit { @@ -1205,7 +1207,7 @@ func (s *State) addProducerAssert(output *common2.Output, height uint32) bool { } // processCancelVotes takes a transaction output with vote payload. -func (s *State) processCancelVotes(tx *types.Transaction, height uint32) { +func (s *State) processCancelVotes(tx *transactions.BaseTransaction, height uint32) { var exist bool for _, input := range tx.Inputs { referKey := input.ReferKey() @@ -1310,7 +1312,7 @@ func (s *State) processVoteCancel(output *common2.Output, height uint32) { } // returnDeposit change producer state to ReturnedDeposit -func (s *State) returnDeposit(tx *types.Transaction, height uint32) { +func (s *State) returnDeposit(tx *transactions.BaseTransaction, height uint32) { var inputValue common.Fixed64 for _, input := range tx.Inputs { inputValue += s.DepositOutputs[input.ReferKey()] @@ -1357,7 +1359,7 @@ func (s *State) returnDeposit(tx *types.Transaction, height uint32) { } // processNextTurnDPOSInfo change NeedNextTurnDposInfo status -func (s *State) processNextTurnDPOSInfo(tx *types.Transaction, height uint32) { +func (s *State) processNextTurnDPOSInfo(tx *transactions.BaseTransaction, height uint32) { _, ok := tx.Payload.(*payload.NextTurnDPOSInfo) if !ok { return @@ -1391,7 +1393,7 @@ func (s *State) getNodePublicKeyStr(strOwnerPublicKey string) string { return "" } -func (s *State) processCRCouncilMemberClaimNode(tx *types.Transaction, height uint32) { +func (s *State) processCRCouncilMemberClaimNode(tx *transactions.BaseTransaction, height uint32) { claimNodePayload := tx.Payload.(*payload.CRCouncilMemberClaimNode) strNewNodePublicKey := common.BytesToHexString(claimNodePayload.NodePublicKey) @@ -1415,7 +1417,7 @@ func (s *State) processCRCouncilMemberClaimNode(tx *types.Transaction, height ui }) } -func (s *State) processRevertToPOW(tx *types.Transaction, height uint32) { +func (s *State) processRevertToPOW(tx *transactions.BaseTransaction, height uint32) { oriNoProducers := s.NoProducers oriNoClaimDPOSNode := s.NoClaimDPOSNode oriDPOSWorkHeight := s.DPOSWorkHeight @@ -1442,7 +1444,7 @@ func (s *State) processRevertToPOW(tx *types.Transaction, height uint32) { // updateVersion record the update period during that inactive arbitrators // will not need to pay the penalty -func (s *State) updateVersion(tx *types.Transaction, height uint32) { +func (s *State) updateVersion(tx *transactions.BaseTransaction, height uint32) { p, ok := tx.Payload.(*payload.UpdateVersion) if !ok { log.Error("tx payload cast failed, tx:", common.ToReversedString(tx.Hash())) @@ -1551,7 +1553,7 @@ func (s *State) RemoveSpecialTx(hash common.Uint256) { // processIllegalEvidence takes the illegal evidence payload and change producer // state according to the evidence. -func (s *State) processIllegalEvidence(payloadData types.Payload, +func (s *State) processIllegalEvidence(payloadData interfaces.Payload, height uint32) { // Get illegal producers from evidence. var illegalProducers [][]byte @@ -1699,7 +1701,7 @@ func (s *State) processIllegalEvidence(payloadData types.Payload, // ProcessIllegalBlockEvidence takes a illegal block payload and change the // producers state immediately. This is a spacial case that can be handled // before it packed into a block. -func (s *State) ProcessSpecialTxPayload(p types.Payload, height uint32) { +func (s *State) ProcessSpecialTxPayload(p interfaces.Payload, height uint32) { s.mtx.Lock() defer s.mtx.Unlock() diff --git a/dpos/state/state_test.go b/dpos/state/state_test.go index 88826ae5c..844ccf7ad 100644 --- a/dpos/state/state_test.go +++ b/dpos/state/state_test.go @@ -9,6 +9,7 @@ import ( "crypto/rand" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -24,7 +25,7 @@ import ( ) // mockBlock creates a block instance by the given height and transactions. -func mockBlock(height uint32, txs ...*types.Transaction) *types.Block { +func mockBlock(height uint32, txs ...*transactions.BaseTransaction) *types.Block { return &types.Block{ Header: types.Header{ Height: height, @@ -35,8 +36,8 @@ func mockBlock(height uint32, txs ...*types.Transaction) *types.Block { // mockRegisterProducerTx creates a register producer transaction with the given // ProducerInfo. -func mockRegisterProducerTx(info *payload.ProducerInfo) *types.Transaction { - return &types.Transaction{ +func mockRegisterProducerTx(info *payload.ProducerInfo) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.RegisterProducer, Payload: info, } @@ -44,8 +45,8 @@ func mockRegisterProducerTx(info *payload.ProducerInfo) *types.Transaction { // mockUpdateProducerTx creates a update producer transaction with the given // ProducerInfo. -func mockUpdateProducerTx(info *payload.ProducerInfo) *types.Transaction { - return &types.Transaction{ +func mockUpdateProducerTx(info *payload.ProducerInfo) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.UpdateProducer, Payload: info, } @@ -53,8 +54,8 @@ func mockUpdateProducerTx(info *payload.ProducerInfo) *types.Transaction { // mockCancelProducerTx creates a cancel producer transaction by the producer // public key. -func mockCancelProducerTx(publicKey []byte) *types.Transaction { - return &types.Transaction{ +func mockCancelProducerTx(publicKey []byte) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.CancelProducer, Payload: &payload.ProcessProducer{ OwnerPublicKey: publicKey, @@ -62,8 +63,8 @@ func mockCancelProducerTx(publicKey []byte) *types.Transaction { } } -func mockActivateProducerTx(publicKey []byte) *types.Transaction { - return &types.Transaction{ +func mockActivateProducerTx(publicKey []byte) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.ActivateProducer, Payload: &payload.ActivateProducer{ NodePublicKey: publicKey, @@ -72,7 +73,7 @@ func mockActivateProducerTx(publicKey []byte) *types.Transaction { } // mockVoteTx creates a vote transaction with the producers public keys. -func mockVoteTx(publicKeys [][]byte) *types.Transaction { +func mockVoteTx(publicKeys [][]byte) *transactions.BaseTransaction { candidateVotes := make([]outputpayload.CandidateVotes, 0, len(publicKeys)) for _, pk := range publicKeys { candidateVotes = append(candidateVotes, @@ -89,14 +90,14 @@ func mockVoteTx(publicKeys [][]byte) *types.Transaction { }, } - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Outputs: []*common2.Output{output}, } } -func mockNewVoteTx(publicKeys [][]byte) *types.Transaction { +func mockNewVoteTx(publicKeys [][]byte) *transactions.BaseTransaction { candidateVotes := make([]outputpayload.CandidateVotes, 0, len(publicKeys)) for i, pk := range publicKeys { candidateVotes = append(candidateVotes, @@ -115,7 +116,7 @@ func mockNewVoteTx(publicKeys [][]byte) *types.Transaction { }, } - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Outputs: []*common2.Output{output}, @@ -124,7 +125,7 @@ func mockNewVoteTx(publicKeys [][]byte) *types.Transaction { // mockVoteTx creates a cancel vote transaction with the previous vote // transaction. -func mockCancelVoteTx(tx *types.Transaction) *types.Transaction { +func mockCancelVoteTx(tx *transactions.BaseTransaction) *transactions.BaseTransaction { inputs := make([]*common2.Input, len(tx.Outputs)) for i := range tx.Outputs { inputs[i] = &common2.Input{ @@ -132,7 +133,7 @@ func mockCancelVoteTx(tx *types.Transaction) *types.Transaction { } } - return &types.Transaction{ + return &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Inputs: inputs, @@ -141,8 +142,8 @@ func mockCancelVoteTx(tx *types.Transaction) *types.Transaction { // mockIllegalBlockTx creates a illegal block transaction with the producer // public key. -func mockIllegalBlockTx(publicKey []byte) *types.Transaction { - return &types.Transaction{ +func mockIllegalBlockTx(publicKey []byte) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.IllegalBlockEvidence, Payload: &payload.DPOSIllegalBlocks{ Evidence: payload.BlockEvidence{ @@ -157,8 +158,8 @@ func mockIllegalBlockTx(publicKey []byte) *types.Transaction { // mockIllegalBlockTx creates a inactive arbitrators transaction with the // producer public key. -func mockInactiveArbitratorsTx(publicKey []byte) *types.Transaction { - return &types.Transaction{ +func mockInactiveArbitratorsTx(publicKey []byte) *transactions.BaseTransaction { + return &transactions.BaseTransaction{ TxType: common2.InactiveArbitrators, Payload: &payload.InactiveArbitrators{ Arbitrators: [][]byte{publicKey}, @@ -309,7 +310,7 @@ func TestState_ProcessBlock(t *testing.T) { // Register 10 producers on one height. for i := 0; i < 10; i++ { - txs := make([]*types.Transaction, 10) + txs := make([]*transactions.BaseTransaction, 10) for i, p := range producers[i*10 : (i+1)*10] { txs[i] = mockRegisterProducerTx(p) } @@ -327,7 +328,7 @@ func TestState_ProcessBlock(t *testing.T) { } // Update 10 producers. - txs := make([]*types.Transaction, 10) + txs := make([]*transactions.BaseTransaction, 10) for i := range txs { producers[i].NickName = fmt.Sprintf("Updated-%d", i) txs[i] = mockUpdateProducerTx(producers[i]) @@ -341,7 +342,7 @@ func TestState_ProcessBlock(t *testing.T) { } // Cancel 10 producers. - txs = make([]*types.Transaction, 10) + txs = make([]*transactions.BaseTransaction, 10) for i := range txs { txs[i] = mockCancelProducerTx(producers[i].OwnerPublicKey) } @@ -365,7 +366,7 @@ func TestState_ProcessBlock(t *testing.T) { for i, p := range producers[10:20] { publicKeys[i] = p.OwnerPublicKey } - txs = make([]*types.Transaction, 10) + txs = make([]*transactions.BaseTransaction, 10) for i := range txs { txs[i] = mockVoteTx(publicKeys) } @@ -378,7 +379,7 @@ func TestState_ProcessBlock(t *testing.T) { } // Illegal 10 producers. - txs = make([]*types.Transaction, 10) + txs = make([]*transactions.BaseTransaction, 10) for i := range txs { txs[i] = mockIllegalBlockTx(producers[10+i].NodePublicKey) } @@ -401,7 +402,7 @@ func TestState_ProcessBlock(t *testing.T) { } // Mixed transactions 1 register, 2 cancel, 3 updates, 4 votes, 5 illegals. - txs = make([]*types.Transaction, 15) + txs = make([]*transactions.BaseTransaction, 15) info := &payload.ProducerInfo{ OwnerPublicKey: randomPublicKey(), NodePublicKey: make([]byte, 33), @@ -899,7 +900,7 @@ func TestState_IsDPOSTransaction(t *testing.T) { func() bool { return false }, nil, nil, nil, nil, nil) - state.getTxReference = func(tx *types.Transaction) ( + state.getTxReference = func(tx *transactions.BaseTransaction) ( map[*common2.Input]common2.Output, error) { return references, nil } @@ -1246,7 +1247,7 @@ func TestState_InactiveProducer_DuringUpdateVersion(t *testing.T) { } currentHeight := 11 - state.ProcessBlock(mockBlock(uint32(currentHeight), &types.Transaction{ + state.ProcessBlock(mockBlock(uint32(currentHeight), &transactions.BaseTransaction{ TxType: common2.UpdateVersion, Payload: &payload.UpdateVersion{ StartHeight: uint32(currentHeight) + 1, @@ -1308,7 +1309,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { depositCont, _ := contract.CreateDepositContractByPubKey(pk) // register register cr before CRVotingStartHeight - registerTx := &types.Transaction{ + registerTx := &transactions.BaseTransaction{ TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ OwnerPublicKey: pkBuf, @@ -1326,7 +1327,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{registerTx}, + Transactions: []*transactions.BaseTransaction{registerTx}, }, nil) height++ candidate := state.getProducer(pkBuf) @@ -1340,14 +1341,14 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) height++ assert.Equal(t, common.Fixed64(100), candidate.totalAmount) assert.Equal(t, Pending, candidate.state) // deposit though normal tx - tranferTx := &types.Transaction{ + tranferTx := &transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Outputs: []*common2.Output{ @@ -1361,7 +1362,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{tranferTx}, + Transactions: []*transactions.BaseTransaction{tranferTx}, }, nil) height++ assert.Equal(t, common.Fixed64(300), candidate.totalAmount) @@ -1372,7 +1373,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) height++ } @@ -1381,7 +1382,7 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ { TxType: common2.CancelProducer, Payload: &payload.ProcessProducer{ @@ -1396,14 +1397,14 @@ func TestState_ProcessBlock_DepositAndReturnDeposit(t *testing.T) { Header: types.Header{ Height: height, }, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, }, nil) height++ } assert.Equal(t, Canceled, candidate.state) // return deposit - state.returnDeposit(&types.Transaction{ + state.returnDeposit(&transactions.BaseTransaction{ Programs: []*program.Program{ { Code: cont.Code, @@ -1442,7 +1443,7 @@ func TestState_CountArbitratorsInactivityV1(t *testing.T) { // Register 10 producers on one height. for i := 0; i < 10; i++ { - txs := make([]*types.Transaction, 10) + txs := make([]*transactions.BaseTransaction, 10) for i, p := range producers[i*10 : (i+1)*10] { txs[i] = mockRegisterProducerTx(p) } @@ -1460,7 +1461,7 @@ func TestState_CountArbitratorsInactivityV1(t *testing.T) { } // Update 10 producers. - txs := make([]*types.Transaction, 10) + txs := make([]*transactions.BaseTransaction, 10) for i := range txs { producers[i].NickName = fmt.Sprintf("Updated-%d", i) txs[i] = mockUpdateProducerTx(producers[i]) @@ -1474,7 +1475,7 @@ func TestState_CountArbitratorsInactivityV1(t *testing.T) { } // Cancel 10 producers. - txs = make([]*types.Transaction, 10) + txs = make([]*transactions.BaseTransaction, 10) for i := range txs { txs[i] = mockCancelProducerTx(producers[i].OwnerPublicKey) } @@ -1498,7 +1499,7 @@ func TestState_CountArbitratorsInactivityV1(t *testing.T) { for i, p := range producers[10:20] { publicKeys[i] = p.OwnerPublicKey } - txs = make([]*types.Transaction, 10) + txs = make([]*transactions.BaseTransaction, 10) for i := range txs { txs[i] = mockVoteTx(publicKeys) } @@ -1511,7 +1512,7 @@ func TestState_CountArbitratorsInactivityV1(t *testing.T) { } // Illegal 10 producers. - txs = make([]*types.Transaction, 10) + txs = make([]*transactions.BaseTransaction, 10) for i := range txs { txs[i] = mockIllegalBlockTx(producers[10+i].NodePublicKey) } diff --git a/elanet/bloom/filter.go b/elanet/bloom/filter.go index 72517c815..f410d5b27 100644 --- a/elanet/bloom/filter.go +++ b/elanet/bloom/filter.go @@ -7,11 +7,11 @@ package bloom import ( common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "sync" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/p2p/msg" ) @@ -250,7 +250,7 @@ func (bf *Filter) AddOutPoint(outpoint *common2.OutPoint) { // update flags set via the loaded filter if needed. // // This function MUST be called with the filter lock held. -func (bf *Filter) matchTxAndUpdate(txn *types.Transaction) bool { +func (bf *Filter) matchTxAndUpdate(txn *transactions.BaseTransaction) bool { // Check if the filter matches the hash of the tx. // This is useful for finding transactions when they appear in a block. hash := txn.Hash() @@ -299,7 +299,7 @@ func (bf *Filter) matchTxAndUpdate(txn *types.Transaction) bool { // update flags set via the loaded filter if needed. // // This function is safe for concurrent access. -func (bf *Filter) MatchTxAndUpdate(tx *types.Transaction) bool { +func (bf *Filter) MatchTxAndUpdate(tx *transactions.BaseTransaction) bool { bf.mtx.Lock() match := bf.matchTxAndUpdate(tx) bf.mtx.Unlock() diff --git a/elanet/bloom/txfilter.go b/elanet/bloom/txfilter.go index d7ec16a58..26df5efc8 100644 --- a/elanet/bloom/txfilter.go +++ b/elanet/bloom/txfilter.go @@ -8,8 +8,8 @@ package bloom import ( "bytes" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/elanet/filter" "github.com/elastos/Elastos.ELA/p2p/msg" ) @@ -40,11 +40,11 @@ func (f *TxFilter) Add(filter []byte) error { return nil } -func (f *TxFilter) MatchConfirmed(tx *types.Transaction) bool { +func (f *TxFilter) MatchConfirmed(tx *transactions.BaseTransaction) bool { return f.filter.MatchTxAndUpdate(tx) } -func (f *TxFilter) MatchUnconfirmed(tx *types.Transaction) bool { +func (f *TxFilter) MatchUnconfirmed(tx *transactions.BaseTransaction) bool { return f.filter.MatchTxAndUpdate(tx) } diff --git a/elanet/filter/customidfilter/customidfilter.go b/elanet/filter/customidfilter/customidfilter.go index 59b3ce1bf..b4c32f10f 100644 --- a/elanet/filter/customidfilter/customidfilter.go +++ b/elanet/filter/customidfilter/customidfilter.go @@ -12,7 +12,7 @@ related to the add addresses. package customidfilter import ( - "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/elanet/bloom" "github.com/elastos/Elastos.ELA/elanet/filter" ) @@ -38,14 +38,14 @@ func (f *CustomIdFilter) Add(data []byte) error { // MatchConfirmed returns if a confirmed (packed into a block) transaction // matches the filter. -func (f *CustomIdFilter) MatchConfirmed(tx *types.Transaction) bool { +func (f *CustomIdFilter) MatchConfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchConfirmed(tx) || tx.IsNextTurnDPOSInfoTx() || tx.IsCustomIDRelatedTx() || tx.IsRevertToPOW() || tx.IsRevertToDPOS() } // MatchUnconfirmed returns if a unconfirmed (not packed into a block yet) // transaction matches the filter. -func (f *CustomIdFilter) MatchUnconfirmed(tx *types.Transaction) bool { +func (f *CustomIdFilter) MatchUnconfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchUnconfirmed(tx) } diff --git a/elanet/filter/filter.go b/elanet/filter/filter.go index 83f6b21b0..7bd850df1 100644 --- a/elanet/filter/filter.go +++ b/elanet/filter/filter.go @@ -7,9 +7,9 @@ package filter import ( "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sync" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/p2p/msg" ) @@ -43,11 +43,11 @@ type TxFilter interface { // MatchConfirmed returns if a confirmed (packed into a block) transaction // matches the filter. - MatchConfirmed(tx *types.Transaction) bool + MatchConfirmed(tx *transactions.BaseTransaction) bool // MatchUnconfirmed returns if a unconfirmed (not packed into a block yet) // transaction matches the filter. - MatchUnconfirmed(tx *types.Transaction) bool + MatchUnconfirmed(tx *transactions.BaseTransaction) bool } type Filter struct { @@ -102,14 +102,14 @@ func (f *Filter) Clear() { f.mtx.Unlock() } -func (f *Filter) MatchConfirmed(tx *types.Transaction) bool { +func (f *Filter) MatchConfirmed(tx *transactions.BaseTransaction) bool { f.mtx.Lock() match := f.filter.MatchConfirmed(tx) f.mtx.Unlock() return match } -func (f *Filter) MatchUnconfirmed(tx *types.Transaction) bool { +func (f *Filter) MatchUnconfirmed(tx *transactions.BaseTransaction) bool { f.mtx.Lock() match := f.filter.MatchUnconfirmed(tx) f.mtx.Unlock() diff --git a/elanet/filter/merkleblock.go b/elanet/filter/merkleblock.go index a17e435f2..51a3ef3bb 100644 --- a/elanet/filter/merkleblock.go +++ b/elanet/filter/merkleblock.go @@ -8,6 +8,7 @@ package filter import ( "errors" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/common" "github.com/elastos/Elastos.ELA/core/types" @@ -94,7 +95,7 @@ func (m *mBlock) traverseAndBuild(height, pos uint32) { } // NewMerkleBlock returns a new *MerkleBlock -func NewMerkleBlock(txs []*types.Transaction, filter *Filter) (*msg.MerkleBlock, []uint32) { +func NewMerkleBlock(txs []*transactions.BaseTransaction, filter *Filter) (*msg.MerkleBlock, []uint32) { NumTx := uint32(len(txs)) mBlock := mBlock{ NumTx: NumTx, diff --git a/elanet/filter/nextturndposfilter/nextturndposfilter.go b/elanet/filter/nextturndposfilter/nextturndposfilter.go index 79f22f4e3..1bbb3e3bb 100644 --- a/elanet/filter/nextturndposfilter/nextturndposfilter.go +++ b/elanet/filter/nextturndposfilter/nextturndposfilter.go @@ -11,7 +11,7 @@ NextTurnDPOSInfo and also the transactions related to the add addresses. package nextturndposfilter import ( - "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/elanet/bloom" "github.com/elastos/Elastos.ELA/elanet/filter" ) @@ -37,14 +37,14 @@ func (f *NextTurnDPOSInfoFilter) Add(data []byte) error { // MatchConfirmed returns if a confirmed (packed into a block) transaction // matches the filter. -func (f *NextTurnDPOSInfoFilter) MatchConfirmed(tx *types.Transaction) bool { +func (f *NextTurnDPOSInfoFilter) MatchConfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchConfirmed(tx) || tx.IsNextTurnDPOSInfoTx() || tx.IsRevertToPOW() || tx.IsRevertToDPOS() } // MatchUnconfirmed returns if a unconfirmed (not packed into a block yet) // transaction matches the filter. -func (f *NextTurnDPOSInfoFilter) MatchUnconfirmed(tx *types.Transaction) bool { +func (f *NextTurnDPOSInfoFilter) MatchUnconfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchUnconfirmed(tx) } diff --git a/elanet/filter/returnsidechaindepositcoinfilter/returnsidechaindepositecoinfilter.go b/elanet/filter/returnsidechaindepositcoinfilter/returnsidechaindepositecoinfilter.go index 14d968126..a6ac37102 100644 --- a/elanet/filter/returnsidechaindepositcoinfilter/returnsidechaindepositecoinfilter.go +++ b/elanet/filter/returnsidechaindepositcoinfilter/returnsidechaindepositecoinfilter.go @@ -12,7 +12,7 @@ package returnsidechaindepositcoinfilter import ( - "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/elanet/bloom" "github.com/elastos/Elastos.ELA/elanet/filter" ) @@ -38,14 +38,14 @@ func (f *ReturnSidechainDepositCoinFilter) Add(data []byte) error { // MatchConfirmed returns if a confirmed (packed into a block) transaction // matches the filter. -func (f *ReturnSidechainDepositCoinFilter) MatchConfirmed(tx *types.Transaction) bool { +func (f *ReturnSidechainDepositCoinFilter) MatchConfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchConfirmed(tx) || tx.IsNextTurnDPOSInfoTx() || tx.IsCustomIDRelatedTx() || tx.IsRevertToPOW() || tx.IsRevertToDPOS() || tx.IsReturnSideChainDepositCoinTx() } // MatchUnconfirmed returns if a unconfirmed (not packed into a block yet) // transaction matches the filter. -func (f *ReturnSidechainDepositCoinFilter) MatchUnconfirmed(tx *types.Transaction) bool { +func (f *ReturnSidechainDepositCoinFilter) MatchUnconfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchUnconfirmed(tx) } diff --git a/elanet/filter/sidefilter/sidefilter.go b/elanet/filter/sidefilter/sidefilter.go index 52a501834..b41e26cf7 100644 --- a/elanet/filter/sidefilter/sidefilter.go +++ b/elanet/filter/sidefilter/sidefilter.go @@ -12,8 +12,8 @@ and also the transactions related to the SideChain addresses. package sidefilter import ( - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/dpos/state" "github.com/elastos/Elastos.ELA/elanet/bloom" "github.com/elastos/Elastos.ELA/elanet/filter" @@ -41,14 +41,14 @@ func (f *Filter) Add(data []byte) error { // MatchConfirmed returns if a confirmed (packed into a block) transaction // matches the filter. -func (f *Filter) MatchConfirmed(tx *types.Transaction) bool { +func (f *Filter) MatchConfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchConfirmed(tx) || f.state.IsDPOSTransaction(tx) || tx.IsRevertToPOW() || tx.IsRevertToDPOS() } // MatchUnconfirmed returns if a unconfirmed (not packed into a block yet) // transaction matches the filter. -func (f *Filter) MatchUnconfirmed(tx *types.Transaction) bool { +func (f *Filter) MatchUnconfirmed(tx *transactions.BaseTransaction) bool { switch tx.TxType { case common2.IllegalProposalEvidence: fallthrough diff --git a/elanet/filter/upgradefilter/upgradefilter.go b/elanet/filter/upgradefilter/upgradefilter.go index daf21f5e5..8a14a3556 100644 --- a/elanet/filter/upgradefilter/upgradefilter.go +++ b/elanet/filter/upgradefilter/upgradefilter.go @@ -12,7 +12,7 @@ and also the transactions related to the add addresses. package upgradefilter import ( - "github.com/elastos/Elastos.ELA/core/types" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/elanet/bloom" "github.com/elastos/Elastos.ELA/elanet/filter" ) @@ -38,7 +38,7 @@ func (f *UpgradeFilter) Add(data []byte) error { // MatchConfirmed returns if a confirmed (packed into a block) transaction // matches the filter. -func (f *UpgradeFilter) MatchConfirmed(tx *types.Transaction) bool { +func (f *UpgradeFilter) MatchConfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchConfirmed(tx) || tx.IsNextTurnDPOSInfoTx() || tx.IsCustomIDRelatedTx() || tx.IsRevertToPOW() || tx.IsRevertToDPOS() || tx.IsSideChainUpgradeTx() @@ -46,7 +46,7 @@ func (f *UpgradeFilter) MatchConfirmed(tx *types.Transaction) bool { // MatchUnconfirmed returns if a unconfirmed (not packed into a block yet) // transaction matches the filter. -func (f *UpgradeFilter) MatchUnconfirmed(tx *types.Transaction) bool { +func (f *UpgradeFilter) MatchUnconfirmed(tx *transactions.BaseTransaction) bool { return f.TxFilter.MatchUnconfirmed(tx) } diff --git a/elanet/netsync/manager.go b/elanet/netsync/manager.go index 2c472b065..901e6f13b 100644 --- a/elanet/netsync/manager.go +++ b/elanet/netsync/manager.go @@ -7,6 +7,7 @@ package netsync import ( "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sync" "sync/atomic" "time" @@ -73,7 +74,7 @@ type donePeerMsg struct { // txMsg packages a bitcoin tx message and the peer it came from together // so the block handler has access to that information. type txMsg struct { - tx *types.Transaction + tx *transactions.BaseTransaction peer *peer.Peer reply chan struct{} } @@ -750,7 +751,7 @@ func (sm *SyncManager) handleBlockchainEvents(event *events.Event) { // A transaction has been accepted into the transaction mem pool. See if it // is a illegal block transaction. case events.ETTransactionAccepted: - tx := event.Data.(*types.Transaction) + tx := event.Data.(*transactions.BaseTransaction) //if tx.IsIllegalBlockTx() { // sm.chain.ProcessIllegalBlock(tx.Payload.(*payload.DPOSIllegalBlocks)) //} @@ -855,7 +856,7 @@ func (sm *SyncManager) handleBlockchainEvents(event *events.Event) { } } case events.ETIllegalBlockEvidence: - tx, ok := event.Data.(*types.Transaction) + tx, ok := event.Data.(*transactions.BaseTransaction) if !ok { log.Warnf("Illegal evidence event is not a tx") break @@ -866,7 +867,7 @@ func (sm *SyncManager) handleBlockchainEvents(event *events.Event) { break } case events.ETAppendTxToTxPool: - tx, ok := event.Data.(*types.Transaction) + tx, ok := event.Data.(*transactions.BaseTransaction) if !ok { log.Warnf("ETAppendTxToTxPool event is not a tx") break @@ -877,7 +878,7 @@ func (sm *SyncManager) handleBlockchainEvents(event *events.Event) { break } case events.ETAppendTxToTxPoolWithoutRelay: - tx, ok := event.Data.(*types.Transaction) + tx, ok := event.Data.(*transactions.BaseTransaction) if !ok { log.Warnf("ETAppendTxToTxPool event is not a tx") break @@ -888,7 +889,7 @@ func (sm *SyncManager) handleBlockchainEvents(event *events.Event) { break } case events.ETSmallCrossChainNeedRelay: - txs, ok := event.Data.([]*types.Transaction) + txs, ok := event.Data.([]*transactions.BaseTransaction) if !ok { log.Error("ETSmallCrossChainNeedRelay event is not a tx list") } @@ -913,7 +914,7 @@ func (sm *SyncManager) NewPeer(peer *peer.Peer) { // QueueTx adds the passed transaction message and peer to the block handling // queue. Responds to the done channel argument after the tx message is // processed. -func (sm *SyncManager) QueueTx(tx *types.Transaction, peer *peer.Peer, done chan struct{}) { +func (sm *SyncManager) QueueTx(tx *transactions.BaseTransaction, peer *peer.Peer, done chan struct{}) { // Don't accept more transactions if we're shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { done <- struct{}{} diff --git a/elanet/server.go b/elanet/server.go index f90eb4d80..365ae5125 100644 --- a/elanet/server.go +++ b/elanet/server.go @@ -9,6 +9,7 @@ import ( "bytes" "errors" "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/elanet/filter/returnsidechaindepositcoinfilter" "github.com/elastos/Elastos.ELA/elanet/filter/upgradefilter" "sync/atomic" @@ -243,7 +244,7 @@ func (sp *serverPeer) OnTx(_ *peer.Peer, msgTx *msg.Tx) { // Add the transaction to the known inventory for the peer. // Convert the raw MsgTx to a btcutil.Tx which provides some convenience // methods and things such as hash caching. - tx := msgTx.Serializable.(*types.Transaction) + tx := msgTx.Serializable.(*transactions.BaseTransaction) txId := tx.Hash() iv := msg.NewInvVect(msg.InvTypeTx, &txId) sp.AddKnownInventory(iv) @@ -782,10 +783,10 @@ func (s *server) handleRelayInvMsg(peers map[svr.IPeer]*serverPeer, rmsg relayMs continue } - tx, ok := rmsg.data.(*types.Transaction) + tx, ok := rmsg.data.(*transactions.BaseTransaction) if !ok { log.Warnf("Underlying data for tx inv "+ - "relay is not a *core.Transaction: %T", + "relay is not a *core.BaseTransaction: %T", rmsg.data) return } @@ -1061,7 +1062,7 @@ func makeEmptyMessage(cmd string) (p2p.Message, error) { message = &msg.MemPool{} case p2p.CmdTx: - message = msg.NewTx(&types.Transaction{}) + message = msg.NewTx(&transactions.BaseTransaction{}) case p2p.CmdBlock: message = msg.NewBlock(&types.DposBlock{}) diff --git a/events/events.go b/events/events.go index f1ebc51be..559d1541a 100644 --- a/events/events.go +++ b/events/events.go @@ -104,7 +104,7 @@ func (n EventType) String() string { // - ETBlockAccepted: *types.Block // - ETBlockConnected: *types.Block // - ETBlockDisconnected: *types.Block -// - ETTransactionAccepted: *types.Transaction +// - ETTransactionAccepted: *types.BaseTransaction type Event struct { Type EventType Data interface{} diff --git a/mempool/blockevidence.go b/mempool/blockevidence.go index 3c36dfa01..dc5b6d42d 100644 --- a/mempool/blockevidence.go +++ b/mempool/blockevidence.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sort" "github.com/elastos/Elastos.ELA/blockchain" @@ -132,7 +133,7 @@ func (bm *BlockPool) CheckConfirmedBlockOnFork(height uint32, block *types.Block return err } - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.IllegalBlockEvidence, PayloadVersion: payload.IllegalBlockVersion, diff --git a/mempool/conflictfunc.go b/mempool/conflictfunc.go index 1692b280c..bc9ca1366 100644 --- a/mempool/conflictfunc.go +++ b/mempool/conflictfunc.go @@ -10,11 +10,11 @@ import ( "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/outputpayload" + "github.com/elastos/Elastos.ELA/core/types/transactions" "strconv" "github.com/elastos/Elastos.ELA/blockchain" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/errors" @@ -22,7 +22,7 @@ import ( ) // hashes related functions -func hashCRCProposalDraftHash(tx *types.Transaction) (interface{}, error) { +func hashCRCProposalDraftHash(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -31,7 +31,7 @@ func hashCRCProposalDraftHash(tx *types.Transaction) (interface{}, error) { return p.DraftHash, nil } -func hashCRCProposalDID(tx *types.Transaction) (interface{}, error) { +func hashCRCProposalDID(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -40,7 +40,7 @@ func hashCRCProposalDID(tx *types.Transaction) (interface{}, error) { return p.CRCouncilMemberDID, nil } -func strArrayCRCProposalCustomID(tx *types.Transaction) (interface{}, error) { +func strArrayCRCProposalCustomID(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -52,7 +52,7 @@ func strArrayCRCProposalCustomID(tx *types.Transaction) (interface{}, error) { return p.ReceivedCustomIDList, nil } -func hashChangeProposalOwnerTargetProposalHash(tx *types.Transaction) (interface{}, error) { +func hashChangeProposalOwnerTargetProposalHash(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -64,7 +64,7 @@ func hashChangeProposalOwnerTargetProposalHash(tx *types.Transaction) (interface return nil, nil } -func hashCloseProposalTargetProposalHash(tx *types.Transaction) (interface{}, error) { +func hashCloseProposalTargetProposalHash(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -76,7 +76,7 @@ func hashCloseProposalTargetProposalHash(tx *types.Transaction) (interface{}, er return nil, nil } -func hashCRCProposalSecretaryGeneralDID(tx *types.Transaction) (interface{}, error) { +func hashCRCProposalSecretaryGeneralDID(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -88,7 +88,7 @@ func hashCRCProposalSecretaryGeneralDID(tx *types.Transaction) (interface{}, err return nil, nil } -func strChangeCustomIDFee(tx *types.Transaction) (interface{}, error) { +func strChangeCustomIDFee(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -100,7 +100,7 @@ func strChangeCustomIDFee(tx *types.Transaction) (interface{}, error) { return nil, nil } -func strReserveCustomID(tx *types.Transaction) (interface{}, error) { +func strReserveCustomID(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -113,7 +113,7 @@ func strReserveCustomID(tx *types.Transaction) (interface{}, error) { } func hashCRCProposalRegisterSideChainName( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -127,7 +127,7 @@ func hashCRCProposalRegisterSideChainName( } func hashCRCProposalRegisterSideChainMagicNumber( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -140,7 +140,7 @@ func hashCRCProposalRegisterSideChainMagicNumber( } func hashCRCProposalRegisterSideChainGenesisHash( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposal) if !ok { return nil, fmt.Errorf( @@ -153,7 +153,7 @@ func hashCRCProposalRegisterSideChainGenesisHash( } func hashCRCProposalWithdrawProposalHash( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposalWithdraw) if !ok { return nil, fmt.Errorf( @@ -163,7 +163,7 @@ func hashCRCProposalWithdrawProposalHash( } func hashCRCProposalTrackingProposalHash( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposalTracking) if !ok { return nil, fmt.Errorf( @@ -172,7 +172,7 @@ func hashCRCProposalTrackingProposalHash( return p.ProposalHash, nil } -func hashSpecialTxHash(tx *types.Transaction) (interface{}, error) { +func hashSpecialTxHash(tx *transactions.BaseTransaction) (interface{}, error) { illegalData, ok := tx.Payload.(payload.DPOSIllegalData) if !ok { return nil, fmt.Errorf( @@ -181,7 +181,7 @@ func hashSpecialTxHash(tx *types.Transaction) (interface{}, error) { return illegalData.Hash(), nil } -func hashNextTurnDPOSInfoTxPayloadHash(tx *types.Transaction) (interface{}, error) { +func hashNextTurnDPOSInfoTxPayloadHash(tx *transactions.BaseTransaction) (interface{}, error) { payload, ok := tx.Payload.(*payload.NextTurnDPOSInfo) if !ok { return nil, fmt.Errorf( @@ -190,7 +190,7 @@ func hashNextTurnDPOSInfoTxPayloadHash(tx *types.Transaction) (interface{}, erro return payload.Hash(), nil } -func hashCustomIDProposalResultTxPayloadHash(tx *types.Transaction) (interface{}, error) { +func hashCustomIDProposalResultTxPayloadHash(tx *transactions.BaseTransaction) (interface{}, error) { _, ok := tx.Payload.(*payload.RecordProposalResult) if !ok { return nil, fmt.Errorf( @@ -200,7 +200,7 @@ func hashCustomIDProposalResultTxPayloadHash(tx *types.Transaction) (interface{} } // strings related functions -func strCancelProducerOwnerPublicKey(tx *types.Transaction) (interface{}, +func strCancelProducerOwnerPublicKey(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.ProcessProducer) if !ok { @@ -211,7 +211,7 @@ func strCancelProducerOwnerPublicKey(tx *types.Transaction) (interface{}, return common.BytesToHexString(p.OwnerPublicKey), nil } -func strProducerInfoOwnerPublicKey(tx *types.Transaction) (interface{}, error) { +func strProducerInfoOwnerPublicKey(tx *transactions.BaseTransaction) (interface{}, error) { p, err := comGetProducerInfo(tx) if err != nil { return nil, err @@ -219,7 +219,7 @@ func strProducerInfoOwnerPublicKey(tx *types.Transaction) (interface{}, error) { return common.BytesToHexString(p.OwnerPublicKey), nil } -func strProducerInfoNodePublicKey(tx *types.Transaction) (interface{}, error) { +func strProducerInfoNodePublicKey(tx *transactions.BaseTransaction) (interface{}, error) { p, err := comGetProducerInfo(tx) if err != nil { return nil, err @@ -227,7 +227,7 @@ func strProducerInfoNodePublicKey(tx *types.Transaction) (interface{}, error) { return common.BytesToHexString(p.NodePublicKey), nil } -func strCRManagementPublicKey(tx *types.Transaction) (interface{}, error) { +func strCRManagementPublicKey(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCouncilMemberClaimNode) if !ok { return nil, fmt.Errorf( @@ -236,7 +236,7 @@ func strCRManagementPublicKey(tx *types.Transaction) (interface{}, error) { return common.BytesToHexString(p.NodePublicKey), nil } -func strCRManagementDID(tx *types.Transaction) (interface{}, error) { +func strCRManagementDID(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCouncilMemberClaimNode) if !ok { return nil, fmt.Errorf( @@ -245,7 +245,7 @@ func strCRManagementDID(tx *types.Transaction) (interface{}, error) { return p.CRCouncilCommitteeDID, nil } -func strProducerInfoNickname(tx *types.Transaction) (interface{}, error) { +func strProducerInfoNickname(tx *transactions.BaseTransaction) (interface{}, error) { p, err := comGetProducerInfo(tx) if err != nil { return nil, err @@ -253,7 +253,7 @@ func strProducerInfoNickname(tx *types.Transaction) (interface{}, error) { return p.NickName, nil } -func strRegisterCRPublicKey(tx *types.Transaction) (interface{}, error) { +func strRegisterCRPublicKey(tx *transactions.BaseTransaction) (interface{}, error) { p, err := comGetCRInfo(tx) if err != nil { return nil, err @@ -272,7 +272,7 @@ func strRegisterCRPublicKey(tx *types.Transaction) (interface{}, error) { } func strActivateProducerNodePublicKey( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.ActivateProducer) if !ok { return nil, fmt.Errorf( @@ -281,7 +281,7 @@ func strActivateProducerNodePublicKey( return common.BytesToHexString(p.NodePublicKey), nil } -func strCRInfoNickname(tx *types.Transaction) (interface{}, error) { +func strCRInfoNickname(tx *transactions.BaseTransaction) (interface{}, error) { p, err := comGetCRInfo(tx) if err != nil { return nil, err @@ -289,11 +289,11 @@ func strCRInfoNickname(tx *types.Transaction) (interface{}, error) { return p.NickName, nil } -func strTxProgramCode(tx *types.Transaction) (interface{}, error) { +func strTxProgramCode(tx *transactions.BaseTransaction) (interface{}, error) { return common.BytesToHexString(tx.Programs[0].Code), nil } -func strProposalReviewKey(tx *types.Transaction) (interface{}, error) { +func strProposalReviewKey(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposalReview) if !ok { return nil, fmt.Errorf( @@ -303,12 +303,12 @@ func strProposalReviewKey(tx *types.Transaction) (interface{}, error) { return p.DID.String() + p.ProposalHash.String(), nil } -func strCRCAppropriation(*types.Transaction) (interface{}, error) { +func strCRCAppropriation(*transactions.BaseTransaction) (interface{}, error) { // const string to ensure only one tx added to the tx pool return "CRC Appropriation", nil } -func strSecretaryGeneral(tx *types.Transaction) (interface{}, error) { +func strSecretaryGeneral(tx *transactions.BaseTransaction) (interface{}, error) { // const string to ensure only one tx added to the tx pool p, ok := tx.Payload.(*payload.CRCProposal) if !ok { @@ -322,7 +322,7 @@ func strSecretaryGeneral(tx *types.Transaction) (interface{}, error) { } func hashArrayCRCProposalRealWithdrawTransactionHashes( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.CRCProposalRealWithdraw) if !ok { return nil, fmt.Errorf( @@ -333,7 +333,7 @@ func hashArrayCRCProposalRealWithdrawTransactionHashes( return p.WithdrawTransactionHashes, nil } -func hashRevertToDPOS(tx *types.Transaction) (interface{}, error) { +func hashRevertToDPOS(tx *transactions.BaseTransaction) (interface{}, error) { _, ok := tx.Payload.(*payload.RevertToDPOS) if !ok { return nil, fmt.Errorf( @@ -345,7 +345,7 @@ func hashRevertToDPOS(tx *types.Transaction) (interface{}, error) { } // program hashes related functions -func addrCRInfoCRCID(tx *types.Transaction) (interface{}, error) { +func addrCRInfoCRCID(tx *transactions.BaseTransaction) (interface{}, error) { p, err := comGetCRInfo(tx) if err != nil { return nil, err @@ -353,7 +353,7 @@ func addrCRInfoCRCID(tx *types.Transaction) (interface{}, error) { return p.CID, nil } -func addrUnregisterCRCID(tx *types.Transaction) (interface{}, error) { +func addrUnregisterCRCID(tx *transactions.BaseTransaction) (interface{}, error) { p, ok := tx.Payload.(*payload.UnregisterCR) if !ok { return nil, fmt.Errorf( @@ -364,7 +364,7 @@ func addrUnregisterCRCID(tx *types.Transaction) (interface{}, error) { // hash array related functions func hashArraySidechainTransactionHashes( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { if tx.PayloadVersion == payload.WithdrawFromSideChainVersion { p, ok := tx.Payload.(*payload.WithdrawFromSideChain) if !ok { @@ -409,7 +409,7 @@ func hashArraySidechainTransactionHashes( // hash array related functions func hashArraySidechainReturnDepositTransactionHashes( - tx *types.Transaction) (interface{}, error) { + tx *transactions.BaseTransaction) (interface{}, error) { arrayHash := make([]common.Uint256, 0) for _, output := range tx.Outputs { if output.Type == common2.OTReturnSideChainDepositCoin { @@ -427,7 +427,7 @@ func hashArraySidechainReturnDepositTransactionHashes( } // str array related functions -func strArrayTxReferences(tx *types.Transaction) (interface{}, error) { +func strArrayTxReferences(tx *transactions.BaseTransaction) (interface{}, error) { reference, err := blockchain.DefaultLedger.Blockchain.UTXOCache.GetTxReference(tx) if err != nil { @@ -443,7 +443,7 @@ func strArrayTxReferences(tx *types.Transaction) (interface{}, error) { // common functions -func comGetProducerInfo(tx *types.Transaction) (*payload.ProducerInfo, error) { +func comGetProducerInfo(tx *transactions.BaseTransaction) (*payload.ProducerInfo, error) { p, ok := tx.Payload.(*payload.ProducerInfo) if !ok { return nil, fmt.Errorf( @@ -452,7 +452,7 @@ func comGetProducerInfo(tx *types.Transaction) (*payload.ProducerInfo, error) { return p, nil } -func comGetCRInfo(tx *types.Transaction) (*payload.CRInfo, error) { +func comGetCRInfo(tx *transactions.BaseTransaction) (*payload.CRInfo, error) { p, ok := tx.Payload.(*payload.CRInfo) if !ok { return nil, fmt.Errorf( diff --git a/mempool/conflictmanager.go b/mempool/conflictmanager.go index 3e6ba6f9c..45a0bb5b0 100644 --- a/mempool/conflictmanager.go +++ b/mempool/conflictmanager.go @@ -8,8 +8,8 @@ package mempool import ( "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/errors" ) @@ -56,7 +56,7 @@ type conflictManager struct { conflictSlots []*conflict } -func (m *conflictManager) VerifyTx(tx *types.Transaction) errors.ELAError { +func (m *conflictManager) VerifyTx(tx *transactions.BaseTransaction) errors.ELAError { for _, v := range m.conflictSlots { if err := v.slot.VerifyTx(tx); err != nil { return errors.SimpleWithMessage(errors.ErrTxPoolFailure, err, @@ -66,7 +66,7 @@ func (m *conflictManager) VerifyTx(tx *types.Transaction) errors.ELAError { return nil } -func (m *conflictManager) AppendTx(tx *types.Transaction) errors.ELAError { +func (m *conflictManager) AppendTx(tx *transactions.BaseTransaction) errors.ELAError { for _, v := range m.conflictSlots { if err := v.slot.AppendTx(tx); err != nil { return errors.SimpleWithMessage(errors.ErrTxPoolFailure, err, @@ -76,7 +76,7 @@ func (m *conflictManager) AppendTx(tx *types.Transaction) errors.ELAError { return nil } -func (m *conflictManager) removeTx(tx *types.Transaction) errors.ELAError { +func (m *conflictManager) removeTx(tx *transactions.BaseTransaction) errors.ELAError { for _, v := range m.conflictSlots { if err := v.slot.RemoveTx(tx); err != nil { return errors.SimpleWithMessage(errors.ErrTxPoolFailure, err, @@ -87,7 +87,7 @@ func (m *conflictManager) removeTx(tx *types.Transaction) errors.ELAError { } func (m *conflictManager) GetTx(key interface{}, - slotName string) *types.Transaction { + slotName string) *transactions.BaseTransaction { for _, v := range m.conflictSlots { if v.name == slotName { return v.slot.GetTx(key) diff --git a/mempool/conflictmanager_test.go b/mempool/conflictmanager_test.go index 6ca26443c..45899ba21 100644 --- a/mempool/conflictmanager_test.go +++ b/mempool/conflictmanager_test.go @@ -7,6 +7,7 @@ package mempool import ( "crypto/rand" + "github.com/elastos/Elastos.ELA/core/types/transactions" mrand "math/rand" "testing" @@ -15,7 +16,6 @@ import ( "github.com/elastos/Elastos.ELA/common/config" "github.com/elastos/Elastos.ELA/core/contract" "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/crypto" @@ -25,7 +25,7 @@ import ( func TestConflictManager_DPoS_OwnerPublicKey(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { pk := randomPublicKey() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ @@ -63,7 +63,7 @@ func TestConflictManager_DPoS_OwnerPublicKey(t *testing.T) { func TestConflictManager_DPoS_NodePublicKey(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { pk := randomPublicKey() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ @@ -101,7 +101,7 @@ func TestConflictManager_DPoS_NodePublicKey(t *testing.T) { func TestConflictManager_DPoS_Nickname(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { name := randomNickname() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ @@ -127,7 +127,7 @@ func TestConflictManager_DPoS_Nickname(t *testing.T) { func TestConflictManager_CR_DID(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { cid := *randomProgramHash() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.RegisterCR, Payload: &payload.CRInfo{ @@ -159,7 +159,7 @@ func TestConflictManager_CR_DID(t *testing.T) { func TestConflictManager_CR_Nickname(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { name := randomNickname() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.RegisterCR, Payload: &payload.CRInfo{ @@ -185,7 +185,7 @@ func TestConflictManager_CR_Nickname(t *testing.T) { func TestConflictManager_ProgramCode(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { code := redeemScriptFromPk(randomPublicKey()) - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.ReturnDepositCoin, Payload: &payload.ReturnDepositCoin{}, @@ -213,7 +213,7 @@ func TestConflictManager_ProgramCode(t *testing.T) { func TestConflictManager_CR_DraftHash(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { hash := *randomHash() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.CRCProposal, Payload: &payload.CRCProposal{ @@ -237,7 +237,7 @@ func TestConflictManager_CR_DraftHash(t *testing.T) { func TestConflictManager_CR_SponsorDID(t *testing.T) { did := *randomProgramHash() conflictTestProc(func(db *UtxoCacheDB) { - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.CRCProposal, Payload: &payload.CRCProposal{ @@ -261,7 +261,7 @@ func TestConflictManager_CR_SponsorDID(t *testing.T) { func TestConflictManager_CR_ProposalHash(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { hash := *randomHash() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.CRCProposalWithdraw, Payload: &payload.CRCProposalWithdraw{ @@ -277,7 +277,7 @@ func TestConflictManager_CR_ProposalHash(t *testing.T) { func TestConflictManager_CR_ProposalTrackHash(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { hash := *randomHash() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.CRCProposalTracking, Payload: &payload.CRCProposalTracking{ @@ -294,7 +294,7 @@ func TestConflictManager_CR_ProposalReviewKey(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { hash := *randomHash() did := *randomProgramHash() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.CRCProposalReview, Payload: &payload.CRCProposalReview{ @@ -310,7 +310,7 @@ func TestConflictManager_CR_ProposalReviewKey(t *testing.T) { func TestConflictManager_CR_AppropriationKey(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.CRCAppropriation, Payload: &payload.CRCAppropriation{}, @@ -323,7 +323,7 @@ func TestConflictManager_CR_AppropriationKey(t *testing.T) { func TestConflictManager_SpecialTxHashes(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.IllegalProposalEvidence, Payload: &payload.DPOSIllegalProposals{ @@ -341,7 +341,7 @@ func TestConflictManager_SpecialTxHashes(t *testing.T) { }) conflictTestProc(func(db *UtxoCacheDB) { - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.IllegalVoteEvidence, Payload: &payload.DPOSIllegalVotes{ @@ -363,7 +363,7 @@ func TestConflictManager_SpecialTxHashes(t *testing.T) { }) conflictTestProc(func(db *UtxoCacheDB) { - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.IllegalBlockEvidence, Payload: &payload.DPOSIllegalBlocks{ @@ -381,7 +381,7 @@ func TestConflictManager_SpecialTxHashes(t *testing.T) { }) conflictTestProc(func(db *UtxoCacheDB) { - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.IllegalSidechainEvidence, Payload: &payload.SidechainIllegalData{ @@ -399,7 +399,7 @@ func TestConflictManager_SpecialTxHashes(t *testing.T) { }) conflictTestProc(func(db *UtxoCacheDB) { - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.InactiveArbitrators, Payload: &payload.InactiveArbitrators{ @@ -419,7 +419,7 @@ func TestConflictManager_SpecialTxHashes(t *testing.T) { func TestConflictManager_Sidechain_TxHashes(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { hash := *randomHash() - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.WithdrawFromSideChain, Payload: &payload.WithdrawFromSideChain{ @@ -448,7 +448,7 @@ func TestConflictManager_Sidechain_TxHashes(t *testing.T) { func TestConflictManager_InputInferKeys(t *testing.T) { conflictTestProc(func(db *UtxoCacheDB) { - txs := []*types.Transaction{ + txs := []*transactions.BaseTransaction{ { TxType: common2.RegisterProducer, Payload: &payload.ProducerInfo{ @@ -568,7 +568,7 @@ func conflictTestProc(action func(*UtxoCacheDB)) { blockchain.DefaultLedger = origin } -func setPreviousTransactionIndividually(txs []*types.Transaction, +func setPreviousTransactionIndividually(txs []*transactions.BaseTransaction, utxoCacheDB *UtxoCacheDB) { for _, tx := range txs { prevTx := newPreviousTx(utxoCacheDB) @@ -584,7 +584,7 @@ func setPreviousTransactionIndividually(txs []*types.Transaction, } } -func setSamePreviousTransaction(txs []*types.Transaction, +func setSamePreviousTransaction(txs []*transactions.BaseTransaction, utxoCacheDB *UtxoCacheDB) { prevTx := newPreviousTx(utxoCacheDB) for _, tx := range txs { @@ -600,8 +600,8 @@ func setSamePreviousTransaction(txs []*types.Transaction, } } -func newPreviousTx(utxoCacheDB *UtxoCacheDB) *types.Transaction { - prevTx := &types.Transaction{ +func newPreviousTx(utxoCacheDB *UtxoCacheDB) *transactions.BaseTransaction { + prevTx := &transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Outputs: []*common2.Output{ @@ -615,7 +615,7 @@ func newPreviousTx(utxoCacheDB *UtxoCacheDB) *types.Transaction { return prevTx } -func verifyTxListWithConflictManager(txs []*types.Transaction, +func verifyTxListWithConflictManager(txs []*transactions.BaseTransaction, utxoCacheDB *UtxoCacheDB, individualPreTx bool, t *testing.T) { if individualPreTx { setPreviousTransactionIndividually(txs, utxoCacheDB) diff --git a/mempool/conflictslot.go b/mempool/conflictslot.go index 41993ad5a..0c48e3258 100644 --- a/mempool/conflictslot.go +++ b/mempool/conflictslot.go @@ -7,9 +7,9 @@ package mempool import ( "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/errors" ) @@ -18,7 +18,7 @@ import ( type keyType byte // getKeyFunc defines the general function about get key from a tx. -type getKeyFunc func(*types.Transaction) (interface{}, error) +type getKeyFunc func(*transactions.BaseTransaction) (interface{}, error) // keyTypeFuncPair defines a pair about tx type and related getKeyFunc. type keyTypeFuncPair struct { @@ -55,9 +55,9 @@ const ( type conflictSlot struct { keyType keyType conflictTypes map[common2.TxType]getKeyFunc - stringSet map[string]*types.Transaction - hashSet map[common.Uint256]*types.Transaction - programHashSet map[common.Uint168]*types.Transaction + stringSet map[string]*transactions.BaseTransaction + hashSet map[common.Uint256]*transactions.BaseTransaction + programHashSet map[common.Uint168]*transactions.BaseTransaction } func (s *conflictSlot) Empty() bool { @@ -77,7 +77,7 @@ func (s *conflictSlot) Contains(key interface{}) (ok bool) { return } -func (s *conflictSlot) GetTx(key interface{}) (tx *types.Transaction) { +func (s *conflictSlot) GetTx(key interface{}) (tx *transactions.BaseTransaction) { switch k := key.(type) { case string: tx = s.stringSet[k] @@ -89,7 +89,7 @@ func (s *conflictSlot) GetTx(key interface{}) (tx *types.Transaction) { return } -func (s *conflictSlot) VerifyTx(tx *types.Transaction) errors.ELAError { +func (s *conflictSlot) VerifyTx(tx *transactions.BaseTransaction) errors.ELAError { getKey := s.getKeyFromTx(tx) if getKey == nil { return nil @@ -132,7 +132,7 @@ func (s *conflictSlot) VerifyTx(tx *types.Transaction) errors.ELAError { }) } -func (s *conflictSlot) AppendTx(tx *types.Transaction) errors.ELAError { +func (s *conflictSlot) AppendTx(tx *transactions.BaseTransaction) errors.ELAError { getKey := s.getKeyFromTx(tx) if getKey == nil { return nil @@ -146,7 +146,7 @@ func (s *conflictSlot) AppendTx(tx *types.Transaction) errors.ELAError { return s.appendKey(key, tx) } -func (s *conflictSlot) getKeyFromTx(tx *types.Transaction) (getKey getKeyFunc) { +func (s *conflictSlot) getKeyFromTx(tx *transactions.BaseTransaction) (getKey getKeyFunc) { var exist bool getKey, exist = s.conflictTypes[tx.TxType] if !exist { @@ -156,7 +156,7 @@ func (s *conflictSlot) getKeyFromTx(tx *types.Transaction) (getKey getKeyFunc) { } func (s *conflictSlot) appendKey(key interface{}, - tx *types.Transaction) errors.ELAError { + tx *transactions.BaseTransaction) errors.ELAError { return s.txProcess(key, s.keyType, func(key string) errors.ELAError { s.stringSet[key] = tx @@ -171,7 +171,7 @@ func (s *conflictSlot) appendKey(key interface{}, ) } -func (s *conflictSlot) RemoveTx(tx *types.Transaction) errors.ELAError { +func (s *conflictSlot) RemoveTx(tx *transactions.BaseTransaction) errors.ELAError { getKey := s.getKeyFromTx(tx) if getKey == nil { return nil @@ -285,8 +285,8 @@ func newConflictSlot(t keyType, conflictTypes ...keyTypeFuncPair) *conflictSlot return &conflictSlot{ keyType: t, conflictTypes: ts, - stringSet: map[string]*types.Transaction{}, - hashSet: map[common.Uint256]*types.Transaction{}, - programHashSet: map[common.Uint168]*types.Transaction{}, + stringSet: map[string]*transactions.BaseTransaction{}, + hashSet: map[common.Uint256]*transactions.BaseTransaction{}, + programHashSet: map[common.Uint168]*transactions.BaseTransaction{}, } } diff --git a/mempool/conflictslot_test.go b/mempool/conflictslot_test.go index 85ad65068..af6f2e58a 100644 --- a/mempool/conflictslot_test.go +++ b/mempool/conflictslot_test.go @@ -7,28 +7,27 @@ package mempool import ( common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" - "github.com/stretchr/testify/assert" ) var ( - simpleGetString = func(tx *types.Transaction) (interface{}, error) { + simpleGetString = func(tx *transactions.BaseTransaction) (interface{}, error) { return "simple string", nil } - simpleGetHash = func(tx *types.Transaction) (interface{}, error) { + simpleGetHash = func(tx *transactions.BaseTransaction) (interface{}, error) { return common.Uint256{}, nil } - simpleGetProgramHash = func(tx *types.Transaction) (interface{}, error) { + simpleGetProgramHash = func(tx *transactions.BaseTransaction) (interface{}, error) { return common.Uint168{}, nil } ) func TestConflictSlot_AppendTx_keyType_string(t *testing.T) { - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ TxType: common2.TransferAsset, } @@ -51,7 +50,7 @@ func TestConflictSlot_AppendTx_keyType_string(t *testing.T) { } func TestConflictSlot_AppendTx_keyType_hash(t *testing.T) { - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ TxType: common2.TransferAsset, } @@ -74,7 +73,7 @@ func TestConflictSlot_AppendTx_keyType_hash(t *testing.T) { } func TestConflictSlot_AppendTx_keyType_programHash(t *testing.T) { - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ TxType: common2.TransferAsset, } @@ -103,13 +102,13 @@ func TestConflictSlot_VerifyTx(t *testing.T) { keyTypeFuncPair{common2.CRCProposal, simpleGetString}) // defined a tx that is not supported by the slot - tx1 := &types.Transaction{ + tx1 := &transactions.BaseTransaction{ TxType: common2.CancelProducer, } - tx2 := &types.Transaction{ + tx2 := &transactions.BaseTransaction{ TxType: common2.TransferAsset, } - tx3 := &types.Transaction{ + tx3 := &transactions.BaseTransaction{ TxType: common2.CRCProposal, } @@ -127,7 +126,7 @@ func TestConflictSlot_VerifyTx(t *testing.T) { } func TestConflictSlot_RemoveTx(t *testing.T) { - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ TxType: common2.TransferAsset, } slot := newConflictSlot(str, diff --git a/mempool/txfeeorderedlist.go b/mempool/txfeeorderedlist.go index 5ddf16f6a..996b9b482 100644 --- a/mempool/txfeeorderedlist.go +++ b/mempool/txfeeorderedlist.go @@ -7,16 +7,16 @@ package mempool import ( "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "io" "sort" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/errors" ) type PopBackEvent func(common.Uint256) -type AppendToTxPoolEvent func(tx *types.Transaction) errors.ELAError +type AppendToTxPoolEvent func(tx *transactions.BaseTransaction) errors.ELAError var ( addingTxExcluded = errors.SimpleWithMessage(errors.ErrTxPoolFailure, @@ -38,7 +38,7 @@ type txFeeOrderedList struct { onPopBack PopBackEvent } -func (l *txFeeOrderedList) AddTx(tx *types.Transaction) errors.ELAError { +func (l *txFeeOrderedList) AddTx(tx *transactions.BaseTransaction) errors.ELAError { size := uint32(tx.GetSize()) if size <= 0 { return errors.SimpleWithMessage(errors.ErrTxPoolFailure, nil, diff --git a/mempool/txfeeorderedlist_bench_test.go b/mempool/txfeeorderedlist_bench_test.go index d77e29ec8..000ff87db 100644 --- a/mempool/txfeeorderedlist_bench_test.go +++ b/mempool/txfeeorderedlist_bench_test.go @@ -6,11 +6,11 @@ package mempool import ( + "github.com/elastos/Elastos.ELA/core/types/transactions" "math/rand" "testing" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" ) @@ -20,7 +20,7 @@ const ( ) func BenchmarkTxFeeOrderedList_AddTx(b *testing.B) { - protoTx := types.Transaction{ + protoTx := transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Attributes: []*common2.Attribute{ @@ -48,7 +48,7 @@ func BenchmarkTxFeeOrderedList_AddTx(b *testing.B) { } func BenchmarkTxFeeOrderedList_RemoveTx(b *testing.B) { - protoTx := types.Transaction{ + protoTx := transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Attributes: []*common2.Attribute{ @@ -85,7 +85,7 @@ func BenchmarkTxFeeOrderedList_RemoveTx(b *testing.B) { } func BenchmarkTxFeeOrderedList_EliminateTx(b *testing.B) { - protoTx := types.Transaction{ + protoTx := transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Attributes: []*common2.Attribute{ diff --git a/mempool/txfeeorderedlist_test.go b/mempool/txfeeorderedlist_test.go index a746bc8c4..d2c8e3786 100644 --- a/mempool/txfeeorderedlist_test.go +++ b/mempool/txfeeorderedlist_test.go @@ -7,11 +7,11 @@ package mempool import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math/rand" "testing" "github.com/elastos/Elastos.ELA/common" - "github.com/elastos/Elastos.ELA/core/types" common2 "github.com/elastos/Elastos.ELA/core/types/common" "github.com/elastos/Elastos.ELA/core/types/payload" "github.com/elastos/Elastos.ELA/elanet/pact" @@ -24,7 +24,7 @@ func TestTxFeeOrderedList_AddTx(t *testing.T) { firedPopBack = true } - protoTx := types.Transaction{ + protoTx := transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Attributes: []*common2.Attribute{ @@ -92,7 +92,7 @@ func TestTxFeeOrderedList_RemoveTx(t *testing.T) { orderedList := newTxFeeOrderedList(func(common.Uint256) {}, pact.MaxTxPoolSize) - protoTx := types.Transaction{ + protoTx := transactions.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Attributes: []*common2.Attribute{ diff --git a/mempool/txpool.go b/mempool/txpool.go index 8ebd3612a..118cac2fb 100644 --- a/mempool/txpool.go +++ b/mempool/txpool.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sync" "github.com/elastos/Elastos.ELA/blockchain" @@ -38,7 +39,7 @@ type TxPool struct { //append transaction to txnpool when check ok, and broadcast the transaction. //1.check 2.check with ledger(db) 3.check with pool -func (mp *TxPool) AppendToTxPool(tx *Transaction) elaerr.ELAError { +func (mp *TxPool) AppendToTxPool(tx *transactions.BaseTransaction) elaerr.ELAError { mp.Lock() defer mp.Unlock() err := mp.appendToTxPool(tx) @@ -53,7 +54,7 @@ func (mp *TxPool) AppendToTxPool(tx *Transaction) elaerr.ELAError { //append transaction to txnpool when check ok. //1.check 2.check with ledger(db) 3.check with pool -func (mp *TxPool) AppendToTxPoolWithoutEvent(tx *Transaction) elaerr.ELAError { +func (mp *TxPool) AppendToTxPoolWithoutEvent(tx *transactions.BaseTransaction) elaerr.ELAError { mp.Lock() defer mp.Unlock() err := mp.appendToTxPool(tx) @@ -71,7 +72,7 @@ func (mp *TxPool) removeCRAppropriationConflictTransactions() { } } -func (mp *TxPool) appendToTxPool(tx *Transaction) elaerr.ELAError { +func (mp *TxPool) appendToTxPool(tx *transactions.BaseTransaction) elaerr.ELAError { txHash := tx.Hash() // If the transaction is CR appropriation transaction, need to remove @@ -164,9 +165,9 @@ func (mp *TxPool) HaveTransaction(txId Uint256) bool { // GetTxsInPool returns a slice of all transactions in the mp. // // This function is safe for concurrent access. -func (mp *TxPool) GetTxsInPool() []*Transaction { +func (mp *TxPool) GetTxsInPool() []*transactions.BaseTransaction { mp.RLock() - txs := make([]*Transaction, 0, len(mp.txnList)) + txs := make([]*transactions.BaseTransaction, 0, len(mp.txnList)) for _, tx := range mp.txnList { txs = append(txs, tx) } @@ -193,7 +194,7 @@ func (mp *TxPool) CheckAndCleanAllTransactions() { func (mp *TxPool) BroadcastSmallCrossChainTransactions(bestHeight uint32) { mp.Lock() - txs := make([]*Transaction, 0) + txs := make([]*transactions.BaseTransaction, 0) for txHash, height := range mp.crossChainHeightList { if bestHeight >= height+broadcastCrossChainTransactionInterval { mp.crossChainHeightList[txHash] = bestHeight @@ -212,7 +213,7 @@ func (mp *TxPool) BroadcastSmallCrossChainTransactions(bestHeight uint32) { mp.Unlock() } -func (mp *TxPool) cleanTransactions(blockTxs []*Transaction) { +func (mp *TxPool) cleanTransactions(blockTxs []*transactions.BaseTransaction) { txsInPool := len(mp.txnList) deleteCount := 0 for _, blockTx := range blockTxs { @@ -237,7 +238,7 @@ func (mp *TxPool) cleanTransactions(blockTxs []*Transaction) { inputUtxos, err := blockchain.DefaultLedger.Blockchain.UTXOCache.GetTxReference(blockTx) if err != nil { - log.Infof("Transaction=%s not exist when deleting, %s.", + log.Infof("BaseTransaction=%s not exist when deleting, %s.", blockTx.Hash(), err) continue } @@ -251,7 +252,7 @@ func (mp *TxPool) cleanTransactions(blockTxs []*Transaction) { // it is evidently that two transactions with the same transaction id has exactly the same utxos with each // other. This is a special case of what we've said above. log.Debugf("duplicated transactions detected when adding a new block. "+ - " Delete transaction in the transaction pool. Transaction id: %s", tx.Hash()) + " Delete transaction in the transaction pool. BaseTransaction id: %s", tx.Hash()) } else { log.Debugf("double spent UTXO inputs detected in transaction pool when adding a new block. "+ "Delete transaction in the transaction pool. "+ @@ -279,7 +280,7 @@ func (mp *TxPool) cleanTransactions(blockTxs []*Transaction) { len(blockTxs), txsInPool, deleteCount, len(mp.txnList))) } -func (mp *TxPool) cleanCanceledProducerAndCR(txs []*Transaction) error { +func (mp *TxPool) cleanCanceledProducerAndCR(txs []*transactions.BaseTransaction) error { for _, txn := range txs { if txn.TxType == common.CancelProducer { cpPayload, ok := txn.Payload.(*payload.ProcessProducer) @@ -413,7 +414,7 @@ func (mp *TxPool) cleanVoteAndUpdateCR(cid Uint168) error { } //get the transaction by hash -func (mp *TxPool) GetTransaction(hash Uint256) *Transaction { +func (mp *TxPool) GetTransaction(hash Uint256) *transactions.BaseTransaction { mp.RLock() defer mp.RUnlock() return mp.txnList[hash] @@ -421,7 +422,7 @@ func (mp *TxPool) GetTransaction(hash Uint256) *Transaction { //verify transaction with txnpool func (mp *TxPool) verifyTransactionWithTxnPool( - txn *Transaction) elaerr.ELAError { + txn *transactions.BaseTransaction) elaerr.ELAError { if txn.IsSideChainPowTx() { // check and replace the duplicate sidechainpow tx mp.replaceDuplicateSideChainPowTx(txn) @@ -431,7 +432,7 @@ func (mp *TxPool) verifyTransactionWithTxnPool( } //remove from associated map -func (mp *TxPool) removeTransaction(tx *Transaction) { +func (mp *TxPool) removeTransaction(tx *transactions.BaseTransaction) { //1.remove from txnList if _, ok := mp.txnList[tx.Hash()]; ok { mp.doRemoveTransaction(tx) @@ -451,8 +452,8 @@ func (mp *TxPool) IsDuplicateSidechainReturnDepositTx(sidechainReturnDepositTxHa } // check and replace the duplicate sidechainpow tx -func (mp *TxPool) replaceDuplicateSideChainPowTx(txn *Transaction) { - var replaceList []*Transaction +func (mp *TxPool) replaceDuplicateSideChainPowTx(txn *transactions.BaseTransaction) { + var replaceList []*transactions.BaseTransaction for _, v := range mp.txnList { if v.TxType == common.SideChainPow { @@ -494,17 +495,17 @@ func (mp *TxPool) GetTransactionCount() int { return len(mp.txnList) } -func (mp *TxPool) getInputUTXOList(input *common.Input) *Transaction { +func (mp *TxPool) getInputUTXOList(input *common.Input) *transactions.BaseTransaction { return mp.GetTx(input.ReferKey(), slotTxInputsReferKeys) } -func (mp *TxPool) MaybeAcceptTransaction(tx *Transaction) error { +func (mp *TxPool) MaybeAcceptTransaction(tx *transactions.BaseTransaction) error { mp.Lock() defer mp.Unlock() return mp.appendToTxPool(tx) } -func (mp *TxPool) RemoveTransaction(txn *Transaction) { +func (mp *TxPool) RemoveTransaction(txn *transactions.BaseTransaction) { mp.Lock() txHash := txn.Hash() for i := range txn.Outputs { @@ -523,7 +524,7 @@ func (mp *TxPool) RemoveTransaction(txn *Transaction) { mp.Unlock() } -func (mp *TxPool) dealAddProposalTx(txn *Transaction) { +func (mp *TxPool) dealAddProposalTx(txn *transactions.BaseTransaction) { proposal, ok := txn.Payload.(*payload.CRCProposal) if !ok { return @@ -533,7 +534,7 @@ func (mp *TxPool) dealAddProposalTx(txn *Transaction) { } } -func (mp *TxPool) dealDelProposalTx(txn *Transaction) { +func (mp *TxPool) dealDelProposalTx(txn *transactions.BaseTransaction) { proposal, ok := txn.Payload.(*payload.CRCProposal) if !ok { return @@ -543,7 +544,7 @@ func (mp *TxPool) dealDelProposalTx(txn *Transaction) { } } -func (mp *TxPool) doAddTransaction(tx *Transaction) elaerr.ELAError { +func (mp *TxPool) doAddTransaction(tx *transactions.BaseTransaction) elaerr.ELAError { if err := mp.txFees.AddTx(tx); err != nil { return err } @@ -554,7 +555,7 @@ func (mp *TxPool) doAddTransaction(tx *Transaction) elaerr.ELAError { return nil } -func (mp *TxPool) doRemoveTransaction(tx *Transaction) { +func (mp *TxPool) doRemoveTransaction(tx *transactions.BaseTransaction) { hash := tx.Hash() txSize := tx.GetSize() feeRate := float64(tx.Fee) / float64(txSize) @@ -595,7 +596,7 @@ func NewTxPool(params *config.Params) *TxPool { crossChainHeightList: make(map[Uint256]uint32), } rtn.txPoolCheckpoint = newTxPoolCheckpoint( - rtn, func(m map[Uint256]*Transaction) { + rtn, func(m map[Uint256]*transactions.BaseTransaction) { for _, v := range m { if err := rtn.conflictManager.AppendTx(v); err != nil { return diff --git a/mempool/txpool_test.go b/mempool/txpool_test.go index 216b53f77..8d9f427b2 100644 --- a/mempool/txpool_test.go +++ b/mempool/txpool_test.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + transactions2 "github.com/elastos/Elastos.ELA/core/types/transactions" "os" "testing" @@ -40,11 +41,11 @@ var ( ) type UtxoCacheDB struct { - transactions map[common.Uint256]*types.Transaction + transactions map[common.Uint256]*transactions2.BaseTransaction } func (s *UtxoCacheDB) GetTransaction(txID common.Uint256) ( - *types.Transaction, uint32, error) { + *transactions2.BaseTransaction, uint32, error) { txn, exist := s.transactions[txID] if exist { return txn, 0, nil @@ -52,7 +53,7 @@ func (s *UtxoCacheDB) GetTransaction(txID common.Uint256) ( return nil, 0, errors.New("leveldb: not found") } -func (s *UtxoCacheDB) PutTransaction(txn *types.Transaction) { +func (s *UtxoCacheDB) PutTransaction(txn *transactions2.BaseTransaction) { s.transactions[txn.Hash()] = txn } @@ -62,7 +63,7 @@ func (s *UtxoCacheDB) RemoveTransaction(txID common.Uint256) { func NewUtxoCacheDB() *UtxoCacheDB { var db UtxoCacheDB - db.transactions = make(map[common.Uint256]*types.Transaction) + db.transactions = make(map[common.Uint256]*transactions2.BaseTransaction) return &db } @@ -121,7 +122,7 @@ func TestTxPool_VerifyDuplicateSidechainTx(t *testing.T) { hash2, _ := common.Uint256FromBytes(hashBytes2) // 1. Generate a withdraw transaction - txn1 := new(types.Transaction) + txn1 := new(transactions2.BaseTransaction) txn1.TxType = common2.WithdrawFromSideChain txn1.Payload = &payload.WithdrawFromSideChain{ BlockHeight: 100, @@ -136,7 +137,7 @@ func TestTxPool_VerifyDuplicateSidechainTx(t *testing.T) { assert.NoError(t, txPool.AppendTx(txn1)) // 3. Generate a withdraw transaction with duplicate sidechain Tx which already in the pool - txn2 := new(types.Transaction) + txn2 := new(transactions2.BaseTransaction) txn2.TxType = common2.WithdrawFromSideChain txn2.Payload = &payload.WithdrawFromSideChain{ BlockHeight: 100, @@ -153,7 +154,7 @@ func TestTxPool_VerifyDuplicateSidechainTx(t *testing.T) { func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { // 1. Generate a register CR transaction - tx1 := new(types.Transaction) + tx1 := new(transactions2.BaseTransaction) tx1.TxType = common2.TransferAsset tx1.Payload = &payload.TransferAsset{} tx1.Outputs = []*common2.Output{ @@ -168,7 +169,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { ProgramHash: common.Uint168{4, 5, 6}, }, } - tx2 := new(types.Transaction) + tx2 := new(transactions2.BaseTransaction) tx2.TxType = common2.TransferAsset tx2.Payload = &payload.TransferAsset{} tx2.Outputs = []*common2.Output{ @@ -220,7 +221,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { Sequence: 0, } - tx3 := new(types.Transaction) + tx3 := new(transactions2.BaseTransaction) tx3.TxType = common2.RegisterCR tx3.Version = common2.TxVersion09 tx3.Payload = &payload.CRInfo{ @@ -232,7 +233,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { } tx3.Inputs = []*common2.Input{input1} - tx4 := new(types.Transaction) + tx4 := new(transactions2.BaseTransaction) tx4.TxType = common2.UpdateCR tx4.Version = common2.TxVersion09 tx4.Payload = &payload.CRInfo{ @@ -244,7 +245,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { } tx4.Inputs = []*common2.Input{input2} - tx5 := new(types.Transaction) + tx5 := new(transactions2.BaseTransaction) tx5.TxType = common2.RegisterProducer tx5.Version = common2.TxVersion09 tx5.Payload = &payload.ProducerInfo{ @@ -256,7 +257,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { } tx5.Inputs = []*common2.Input{input3} - tx6 := new(types.Transaction) + tx6 := new(transactions2.BaseTransaction) tx6.TxType = common2.RegisterProducer tx6.Version = common2.TxVersion09 tx6.Payload = &payload.ProducerInfo{ @@ -269,7 +270,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { tx6.Inputs = []*common2.Input{input4} //tx7 tx8 no use same code,so not conflict - tx7 := new(types.Transaction) + tx7 := new(transactions2.BaseTransaction) tx7.TxType = common2.ReturnDepositCoin tx7.Version = common2.TxVersion09 tx7.Programs = []*program.Program{ @@ -279,7 +280,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { }, } - tx8 := new(types.Transaction) + tx8 := new(transactions2.BaseTransaction) tx8.TxType = common2.ReturnCRDepositCoin tx8.Version = common2.TxVersion09 tx8.Programs = []*program.Program{ @@ -307,7 +308,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { assert.Error(t, txPool.VerifyTx(tx6)) // 7. Clean CR related tx - txs := make([]*types.Transaction, 1) + txs := make([]*transactions2.BaseTransaction, 1) txs[0] = tx3 txPool.cleanTransactions(txs) @@ -322,7 +323,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { assert.NoError(t, txPool.VerifyTx(tx4)) // 11. Clean producer related tx - txs2 := make([]*types.Transaction, 2) + txs2 := make([]*transactions2.BaseTransaction, 2) txs2[0] = tx4 txs2[1] = tx5 txPool.cleanTransactions(txs2) @@ -344,13 +345,13 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { // 16. Verify same ReturnCRDepositCoin tx again assert.Error(t, txPool.VerifyTx(tx8)) - txs3 := make([]*types.Transaction, 2) + txs3 := make([]*transactions2.BaseTransaction, 2) txs3[0] = tx7 txs3[1] = tx8 txPool.cleanTransactions(txs3) //tx9 tx10 both use ct1.code should conflict - tx9 := new(types.Transaction) + tx9 := new(transactions2.BaseTransaction) tx9.TxType = common2.ReturnDepositCoin tx9.Version = common2.TxVersion09 tx9.Programs = []*program.Program{ @@ -360,7 +361,7 @@ func TestTxPool_VerifyDuplicateCRTx(t *testing.T) { }, } - tx10 := new(types.Transaction) + tx10 := new(transactions2.BaseTransaction) tx10.TxType = common2.ReturnCRDepositCoin tx10.Version = common2.TxVersion09 tx10.Programs = []*program.Program{ @@ -399,7 +400,7 @@ func TestTxPool_CleanSidechainTx(t *testing.T) { hash5, _ := common.Uint256FromBytes(hashBytes5) // 1. Generate some withdraw transactions - txn1 := new(types.Transaction) + txn1 := new(transactions2.BaseTransaction) txn1.TxType = common2.WithdrawFromSideChain txn1.Payload = &payload.WithdrawFromSideChain{ BlockHeight: 100, @@ -410,7 +411,7 @@ func TestTxPool_CleanSidechainTx(t *testing.T) { }, } - txn2 := new(types.Transaction) + txn2 := new(transactions2.BaseTransaction) txn2.TxType = common2.WithdrawFromSideChain txn2.Payload = &payload.WithdrawFromSideChain{ BlockHeight: 100, @@ -420,7 +421,7 @@ func TestTxPool_CleanSidechainTx(t *testing.T) { }, } - txn3 := new(types.Transaction) + txn3 := new(transactions2.BaseTransaction) txn3.TxType = common2.WithdrawFromSideChain txn3.Payload = &payload.WithdrawFromSideChain{ BlockHeight: 100, @@ -430,7 +431,7 @@ func TestTxPool_CleanSidechainTx(t *testing.T) { *hash5, }, } - txns := []*types.Transaction{txn1, txn2, txn3} + txns := []*transactions2.BaseTransaction{txn1, txn2, txn3} // 2. Add to sidechain txs pool for _, txn := range txns { @@ -463,7 +464,7 @@ func TestTxPool_ReplaceDuplicateSideChainPowTx(t *testing.T) { rand.Read(sideBlockHash2[:]) rand.Read(sideGenesisHash[:]) - txn1 := new(types.Transaction) + txn1 := new(transactions2.BaseTransaction) txn1.TxType = common2.SideChainPow txn1.Payload = &payload.SideChainPow{ SideBlockHash: sideBlockHash1, @@ -473,7 +474,7 @@ func TestTxPool_ReplaceDuplicateSideChainPowTx(t *testing.T) { txPool.txnList[txn1.Hash()] = txn1 - txn2 := new(types.Transaction) + txn2 := new(transactions2.BaseTransaction) txn2.TxType = common2.SideChainPow txn2.Payload = &payload.SideChainPow{ SideBlockHash: sideBlockHash2, @@ -499,7 +500,7 @@ func TestTxPool_IsDuplicateSidechainTx(t *testing.T) { rand.Read(sideTx2[:]) // 1. Generate a withdraw transaction - txn1 := new(types.Transaction) + txn1 := new(transactions2.BaseTransaction) txn1.TxType = common2.WithdrawFromSideChain txn1.Payload = &payload.WithdrawFromSideChain{ BlockHeight: 100, @@ -521,7 +522,7 @@ func TestTxPool_IsDuplicateSidechainTx(t *testing.T) { } func TestTxPool_AppendToTxnPool(t *testing.T) { - tx := new(types.Transaction) + tx := new(transactions2.BaseTransaction) txBytes, _ := hex.DecodeString("000403454c41010008803e6306563b26de010" + "000000000000000000000000000000000000000000000000000000000000000ffff" + "ffffffff02b037db964a231458d2d6ffd5ea18944c4f90e63d547c5d3b9874df66a" + @@ -535,7 +536,7 @@ func TestTxPool_AppendToTxnPool(t *testing.T) { } func TestTxPool_CleanSubmittedTransactions(t *testing.T) { - appendTx := func(tx *types.Transaction) elaerr.ELAError { + appendTx := func(tx *transactions2.BaseTransaction) elaerr.ELAError { if err := txPool.AppendTx(tx); err != nil { return err } @@ -547,7 +548,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { /*------------------------------------------------------------*/ /* check double spend but not duplicate txs */ //two mock transactions, they are double-spent to each other. - tx1Prev := &types.Transaction{ + tx1Prev := &transactions2.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Outputs: []*common2.Output{ @@ -566,7 +567,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { Sequence: 100, } utxoCacheDB.PutTransaction(tx1Prev) - tx1 := new(types.Transaction) + tx1 := new(transactions2.BaseTransaction) tx1.TxType = common2.TransferAsset tx1.PayloadVersion = 0 tx1.Payload = &payload.TransferAsset{} @@ -583,7 +584,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { tx1.Inputs = []*common2.Input{input} - tx2 := new(types.Transaction) + tx2 := new(transactions2.BaseTransaction) tx2.TxType = common2.TransferAsset tx2.PayloadVersion = 0 tx2.Payload = &payload.TransferAsset{} @@ -622,7 +623,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { newBLock.Nonce = 0 newBLock.Height = 221 newBLock.AuxPow = blockAuxpow - newBLock.Transactions = []*types.Transaction{tx2} + newBLock.Transactions = []*transactions2.BaseTransaction{tx2} assert.NoError(t, appendTx(tx1)) txPool.CleanSubmittedTransactions(&newBLock) @@ -657,7 +658,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { txPool = NewTxPool(&config.DefaultParams) //two mock transactions again, they have some identical sidechain hashes - tx3Prev := &types.Transaction{ + tx3Prev := &transactions2.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Outputs: []*common2.Output{ @@ -669,7 +670,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { }, } utxoCacheDB.PutTransaction(tx3Prev) - tx3 := new(types.Transaction) + tx3 := new(transactions2.BaseTransaction) tx3.TxType = common2.WithdrawFromSideChain tx3.Payload = &payload.WithdrawFromSideChain{ SideChainTransactionHashes: []common.Uint256{sideBlockHash1, sideBlockHash2}, @@ -683,7 +684,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { Sequence: 100, }, } - tx4Prev := &types.Transaction{ + tx4Prev := &transactions2.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Outputs: []*common2.Output{ @@ -695,7 +696,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { }, } utxoCacheDB.PutTransaction(tx4Prev) - tx4 := new(types.Transaction) + tx4 := new(transactions2.BaseTransaction) tx4.TxType = common2.WithdrawFromSideChain tx4.Payload = &payload.WithdrawFromSideChain{ SideChainTransactionHashes: []common.Uint256{sideBlockHash1, sideBlockHash4}, @@ -709,7 +710,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { Sequence: 100, }, } - tx5Prev := &types.Transaction{ + tx5Prev := &transactions2.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Outputs: []*common2.Output{ @@ -721,7 +722,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { }, } utxoCacheDB.PutTransaction(tx5Prev) - tx5 := new(types.Transaction) + tx5 := new(transactions2.BaseTransaction) tx5.TxType = common2.WithdrawFromSideChain tx5.Payload = &payload.WithdrawFromSideChain{ SideChainTransactionHashes: []common.Uint256{sideBlockHash2, sideBlockHash5}, @@ -735,7 +736,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { Sequence: 100, }, } - tx6Prev := &types.Transaction{ + tx6Prev := &transactions2.BaseTransaction{ TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, Outputs: []*common2.Output{ @@ -747,7 +748,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { }, } utxoCacheDB.PutTransaction(tx6Prev) - tx6 := new(types.Transaction) + tx6 := new(transactions2.BaseTransaction) tx6.TxType = common2.WithdrawFromSideChain tx6.Payload = &payload.WithdrawFromSideChain{ SideChainTransactionHashes: []common.Uint256{sideBlockHash3}, @@ -766,7 +767,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { assert.NoError(t, appendTx(tx5)) assert.NoError(t, appendTx(tx6)) - newBLock.Transactions = []*types.Transaction{tx4, tx5, tx6} + newBLock.Transactions = []*transactions2.BaseTransaction{tx4, tx5, tx6} txPool.CleanSubmittedTransactions(&newBLock) if err := isTransactionCleaned(txPool, tx4); err != nil { t.Error("should clean transaction tx4:", err) @@ -786,7 +787,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { assert.NoError(t, appendTx(tx4)) - newBLock.Transactions = []*types.Transaction{tx4} + newBLock.Transactions = []*transactions2.BaseTransaction{tx4} txPool.CleanSubmittedTransactions(&newBLock) @@ -797,7 +798,7 @@ func TestTxPool_CleanSubmittedTransactions(t *testing.T) { /*------------------------------------------------------------*/ /* normal case */ assert.NoError(t, appendTx(tx2)) - newBLock.Transactions = []*types.Transaction{tx3} + newBLock.Transactions = []*transactions2.BaseTransaction{tx3} txPool.CleanSubmittedTransactions(&newBLock) txPool.CheckAndCleanAllTransactions() if err := isTransactionCleaned(txPool, tx2); err != nil { @@ -811,7 +812,7 @@ func TestTxPool_End(t *testing.T) { initialLedger = nil } -func isTransactionExisted(pool *TxPool, tx *types.Transaction) error { +func isTransactionExisted(pool *TxPool, tx *transactions2.BaseTransaction) error { if _, ok := pool.txnList[tx.Hash()]; !ok { return fmt.Errorf("does not have transaction in transaction pool") } @@ -831,7 +832,7 @@ func isTransactionExisted(pool *TxPool, tx *types.Transaction) error { return nil } -func isTransactionCleaned(pool *TxPool, tx *types.Transaction) error { +func isTransactionCleaned(pool *TxPool, tx *transactions2.BaseTransaction) error { if tx := pool.txnList[tx.Hash()]; tx != nil { return fmt.Errorf("has transaction in transaction pool" + tx.Hash().String()) } diff --git a/mempool/txpoolcheckpoint.go b/mempool/txpoolcheckpoint.go index 252463fbb..fa8bda4a2 100644 --- a/mempool/txpoolcheckpoint.go +++ b/mempool/txpoolcheckpoint.go @@ -7,6 +7,7 @@ package mempool import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "io" "github.com/elastos/Elastos.ELA/common" @@ -30,12 +31,12 @@ const ( type txPoolCheckpoint struct { // transaction which have been verified will put into this map - txnList map[common.Uint256]*types.Transaction + txnList map[common.Uint256]*transactions.BaseTransaction txFees *txFeeOrderedList txPool *TxPool height uint32 - initConflictManager func(map[common.Uint256]*types.Transaction) + initConflictManager func(map[common.Uint256]*transactions.BaseTransaction) } func (c *txPoolCheckpoint) OnBlockSaved(block *types.DposBlock) { @@ -149,7 +150,7 @@ func (c *txPoolCheckpoint) Deserialize(r io.Reader) (err error) { } var hash common.Uint256 for i := uint64(0); i < count; i++ { - tx := &types.Transaction{} + tx := &transactions.BaseTransaction{} if err = hash.Deserialize(r); err != nil { return } @@ -164,10 +165,10 @@ func (c *txPoolCheckpoint) Deserialize(r io.Reader) (err error) { } func newTxPoolCheckpoint(txPool *TxPool, initConflictManager func( - map[common.Uint256]*types.Transaction)) *txPoolCheckpoint { + map[common.Uint256]*transactions.BaseTransaction)) *txPoolCheckpoint { return &txPoolCheckpoint{ txPool: txPool, - txnList: map[common.Uint256]*types.Transaction{}, + txnList: map[common.Uint256]*transactions.BaseTransaction{}, txFees: newTxFeeOrderedList(txPool.onPopBack, pact.MaxTxPoolSize), height: 0, initConflictManager: initConflictManager, diff --git a/pow/revertlistener.go b/pow/revertlistener.go index 0ad6996b2..60cf24d07 100644 --- a/pow/revertlistener.go +++ b/pow/revertlistener.go @@ -7,11 +7,11 @@ package pow import ( "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "time" "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/contract/program" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/core/types/payload" ) @@ -37,7 +37,7 @@ func (pow *Service) ListenForRevert() { Type: payload.NoBlock, WorkingHeight: pow.chain.BestChain.Height + 1, } - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common.TxVersion09, TxType: common.RevertToPOW, PayloadVersion: payload.RevertToPOWVersion, diff --git a/pow/service.go b/pow/service.go index 8314ca9f3..f6b974e8c 100644 --- a/pow/service.go +++ b/pow/service.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "math/rand" "sort" @@ -111,7 +112,7 @@ func (pow *Service) GetDefaultTxVersion(height uint32) common2.TransactionVersio return v } -func (pow *Service) CreateCoinbaseTx(minerAddr string, height uint32) (*types.Transaction, error) { +func (pow *Service) CreateCoinbaseTx(minerAddr string, height uint32) (*transactions.BaseTransaction, error) { crRewardAddr := pow.chainParams.Foundation if height >= pow.chainParams.CRCommitteeStartHeight { crRewardAddr = pow.chainParams.CRAssetsAddress @@ -122,7 +123,7 @@ func (pow *Service) CreateCoinbaseTx(minerAddr string, height uint32) (*types.Tr return nil, err } - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: pow.GetDefaultTxVersion(height), TxType: common2.CoinBase, PayloadVersion: payload.CoinBaseVersion, @@ -207,7 +208,7 @@ func (pow *Service) AssignCoinbaseTxRewards(block *types.Block, totalReward comm return nil } -func (pow *Service) distributeDPOSReward(coinBaseTx *types.Transaction, +func (pow *Service) distributeDPOSReward(coinBaseTx *transactions.BaseTransaction, rewards map[common.Uint168]common.Fixed64) (common.Fixed64, error) { for ownerHash, reward := range rewards { @@ -243,7 +244,7 @@ func (pow *Service) GenerateBlock(minerAddr string, msgBlock := &types.Block{ Header: header, - Transactions: []*types.Transaction{}, + Transactions: []*transactions.BaseTransaction{}, } msgBlock.Transactions = append(msgBlock.Transactions, coinBaseTx) @@ -252,7 +253,7 @@ func (pow *Service) GenerateBlock(minerAddr string, totalTxFee := common.Fixed64(0) txs := pow.txMemPool.GetTxsInPool() - isHighPriority := func(tx *types.Transaction) bool { + isHighPriority := func(tx *transactions.BaseTransaction) bool { if tx.IsIllegalTypeTx() || tx.IsInactiveArbitrators() || tx.IsSideChainPowTx() || tx.IsUpdateVersion() || tx.IsActivateProducerTx() || tx.IsCRCAppropriationTx() || diff --git a/pow/service_test.go b/pow/service_test.go index aac2b19bd..0188d7716 100644 --- a/pow/service_test.go +++ b/pow/service_test.go @@ -7,6 +7,7 @@ package pow import ( "fmt" + "github.com/elastos/Elastos.ELA/core/types/transactions" "math" "path/filepath" "testing" @@ -164,7 +165,7 @@ func TestService_AssignCoinbaseTxRewards(t *testing.T) { arbitratorsChange := dposTotalReward - realReward arbitratorsMock.FinalRoundChange = arbitratorsChange - tx := &types.Transaction{ + tx := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.CoinBase, } @@ -176,7 +177,7 @@ func TestService_AssignCoinbaseTxRewards(t *testing.T) { Header: types.Header{ Height: config.DefaultParams.PublicDPOSHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ tx, }, } @@ -236,7 +237,7 @@ func TestService_AssignCoinbaseTxRewards(t *testing.T) { arbitratorsChange = dposTotalReward - realReward arbitratorsMock.FinalRoundChange = arbitratorsChange - tx = &types.Transaction{ + tx = &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.CoinBase, } @@ -248,7 +249,7 @@ func TestService_AssignCoinbaseTxRewards(t *testing.T) { Header: types.Header{ Height: config.DefaultParams.PublicDPOSHeight, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ tx, }, } @@ -290,7 +291,7 @@ func TestService_AssignCoinbaseTxRewards(t *testing.T) { minerReward = common.Fixed64(float64(rewardInCoinbase) * 0.35) dposTotalReward = rewardInCoinbase - foundationReward - minerReward - tx = &types.Transaction{ + tx = &transactions.BaseTransaction{ Version: 0, TxType: common2.CoinBase, } @@ -299,7 +300,7 @@ func TestService_AssignCoinbaseTxRewards(t *testing.T) { {ProgramHash: common.Uint168{}, Value: 0}, } block = &types.Block{ - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ tx, }, } @@ -316,7 +317,7 @@ func TestService_AssignCoinbaseTxRewards(t *testing.T) { minerReward = common.Fixed64(float64(rewardInCoinbase) * 0.35) dposTotalReward = rewardInCoinbase - foundationRewardNormal - minerReward - tx = &types.Transaction{ + tx = &transactions.BaseTransaction{ Version: 0, TxType: common2.CoinBase, } @@ -325,7 +326,7 @@ func TestService_AssignCoinbaseTxRewards(t *testing.T) { {ProgramHash: common.Uint168{}, Value: 0}, } block = &types.Block{ - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ tx, }, } diff --git a/servers/errors/errcode.go b/servers/errors/errcode.go index 8576c3c4d..39a8f4996 100644 --- a/servers/errors/errcode.go +++ b/servers/errors/errcode.go @@ -59,7 +59,7 @@ var ErrMap = map[ServerErrCode]string{ InvalidToken: "Verify token error", InvalidTransaction: "Invalid transaction", InvalidAsset: "Invalid asset", - UnknownTransaction: "Unknown Transaction", + UnknownTransaction: "Unknown BaseTransaction", UnknownAsset: "Unknown asset", UnknownBlock: "Unknown Block", UnknownConfirm: "Unknown Confirm", diff --git a/servers/httpwebsocket/server.go b/servers/httpwebsocket/server.go index 28fa20fbe..489557345 100644 --- a/servers/httpwebsocket/server.go +++ b/servers/httpwebsocket/server.go @@ -9,6 +9,7 @@ import ( "context" "crypto/tls" "encoding/json" + "github.com/elastos/Elastos.ELA/core/types/transactions" "net" "net/http" "strconv" @@ -301,7 +302,7 @@ func (s *Server) PushResult(action string, v interface{}) { result = servers.GetBlockTransactions(block) } case "sendnewtransaction": - if tx, ok := v.(*types.Transaction); ok { + if tx, ok := v.(*transactions.BaseTransaction); ok { result = servers.GetTransactionContextInfo(nil, tx) } default: diff --git a/servers/interfaces.go b/servers/interfaces.go index 196ac35eb..9e90c9bca 100644 --- a/servers/interfaces.go +++ b/servers/interfaces.go @@ -11,6 +11,8 @@ import ( "encoding/hex" "fmt" common2 "github.com/elastos/Elastos.ELA/core/types/common" + "github.com/elastos/Elastos.ELA/core/types/interfaces" + "github.com/elastos/Elastos.ELA/core/types/transactions" "sort" "strings" @@ -54,7 +56,7 @@ var ( emptyHash = common.Uint168{} ) -func GetTransactionInfo(tx *Transaction) *TransactionInfo { +func GetTransactionInfo(tx *transactions.BaseTransaction) *TransactionInfo { inputs := make([]InputInfo, len(tx.Inputs)) for i, v := range tx.Inputs { inputs[i].TxID = common.ToReversedString(v.Previous.TxID) @@ -106,7 +108,7 @@ func GetTransactionInfo(tx *Transaction) *TransactionInfo { } } -func GetTransactionContextInfo(header *Header, tx *Transaction) *TransactionContextInfo { +func GetTransactionContextInfo(header *Header, tx *transactions.BaseTransaction) *TransactionContextInfo { var blockHash string var confirmations uint32 var time uint32 @@ -820,7 +822,7 @@ func SendRawTransaction(param Params) map[string]interface{} { if err != nil { return ResponsePack(InvalidParams, "hex string to bytes error") } - var txn Transaction + var txn transactions.BaseTransaction if err := txn.Deserialize(bytes.NewReader(bys)); err != nil { return ResponsePack(InvalidTransaction, err.Error()) } @@ -1131,7 +1133,7 @@ func GetUTXOsByAmount(param Params) map[string]interface{} { } if utxoType == "unused" { - var unusedUTXOs []*UTXO + var unusedUTXOs []*common2.UTXO usedUTXOs := TxMemPool.GetUsedUTXOs() for _, u := range utxos { outPoint := common2.OutPoint{TxID: u.TxID, Index: u.Index} @@ -1352,7 +1354,7 @@ func CreateRawTransaction(param Params) map[string]interface{} { txOutputs = append(txOutputs, output) } - txn := &Transaction{ + txn := &transactions.BaseTransaction{ Version: common2.TxVersion09, TxType: common2.TransferAsset, Payload: &payload.TransferAsset{}, @@ -1413,7 +1415,7 @@ func SignRawTransactionWithKey(param Params) map[string]interface{} { if err != nil { return ResponsePack(InvalidParams, "hex string to bytes error") } - var txn Transaction + var txn transactions.BaseTransaction if err := txn.Deserialize(bytes.NewReader(txBytes)); err != nil { return ResponsePack(InvalidTransaction, err.Error()) } @@ -1570,7 +1572,7 @@ func GetUnspendOutput(param Params) map[string]interface{} { return ResponsePack(Success, UTXOoutputs) } -//Transaction +//BaseTransaction func GetTransactionByHash(param Params) map[string]interface{} { str, ok := param.String("hash") if !ok { @@ -2630,7 +2632,7 @@ func DecodeRawTransaction(param Params) map[string]interface{} { if err != nil { return ResponsePack(InvalidParams, "invalid raw tx data, "+err.Error()) } - var txn Transaction + var txn transactions.BaseTransaction if err := txn.Deserialize(bytes.NewReader(txBytes)); err != nil { return ResponsePack(InvalidParams, "invalid raw tx data, "+err.Error()) } @@ -2638,7 +2640,7 @@ func DecodeRawTransaction(param Params) map[string]interface{} { return ResponsePack(Success, GetTransactionInfo(&txn)) } -func getPayloadInfo(p Payload, payloadVersion byte) PayloadInfo { +func getPayloadInfo(p interfaces.Payload, payloadVersion byte) PayloadInfo { switch object := p.(type) { case *payload.CoinBase: obj := new(CoinbaseInfo) @@ -3135,7 +3137,7 @@ func getOutputPayloadInfo(op common2.OutputPayload) OutputPayloadInfo { return nil } -func VerifyAndSendTx(tx *Transaction) error { +func VerifyAndSendTx(tx *transactions.BaseTransaction) error { // if transaction is verified unsuccessfully then will not put it into transaction pool if err := TxMemPool.AppendToTxPool(tx); err != nil { log.Warn("[httpjsonrpc] VerifyTransaction failed when AppendToTxnPool. Errcode:", err.Code()) diff --git a/vm/opcode.go b/vm/opcode.go index 9bfdc195b..79c205828 100644 --- a/vm/opcode.go +++ b/vm/opcode.go @@ -76,8 +76,8 @@ const ( XOR = 0x86 // Boolean exclusive or between each bit in the inputs. EQUAL = 0x87 // Returns 1 if the inputs are exactly equal, 0 otherwise. //EQUALVERIFY = 0x88 // Same as EQUAL, but runs VERIFY afterward. - //RESERVED1 = 0x89 // Transaction is invalid unless occurring in an unexecuted IF branch - //RESERVED2 = 0x8A // Transaction is invalid unless occurring in an unexecuted IF branch + //RESERVED1 = 0x89 // BaseTransaction is invalid unless occurring in an unexecuted IF branch + //RESERVED2 = 0x8A // BaseTransaction is invalid unless occurring in an unexecuted IF branch // Arithmetic // Note: Arithmetic inputs are limited to signed 32-bit integers, but may overflow their output. diff --git a/wallet/coincheckpoint_test.go b/wallet/coincheckpoint_test.go index 35592809e..d471222ac 100644 --- a/wallet/coincheckpoint_test.go +++ b/wallet/coincheckpoint_test.go @@ -7,6 +7,7 @@ package wallet import ( "bytes" + "github.com/elastos/Elastos.ELA/core/types/transactions" "testing" "github.com/elastos/Elastos.ELA/common" @@ -28,7 +29,7 @@ var ( prevOp common2.OutPoint - tx1 = new(types.Transaction) + tx1 = new(transactions.BaseTransaction) block1 *types.DposBlock ) @@ -56,7 +57,7 @@ func TestInitBlock(t *testing.T) { assert.Equal(t, uint32(99), ccp.height) assert.Equal(t, 1, len(ccp.coins)) - tx1 := &types.Transaction{ + tx1 := &transactions.BaseTransaction{ Inputs: []*common2.Input{ { Previous: prevOp, @@ -80,7 +81,7 @@ func TestInitBlock(t *testing.T) { Header: types.Header{ Height: 100, }, - Transactions: []*types.Transaction{ + Transactions: []*transactions.BaseTransaction{ tx1, }, }, diff --git a/wallet/wallet.go b/wallet/wallet.go index acd946355..a6be77be3 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -7,6 +7,7 @@ package wallet import ( "errors" + common2 "github.com/elastos/Elastos.ELA/core/types/common" "os" "path/filepath" @@ -15,7 +16,6 @@ import ( "github.com/elastos/Elastos.ELA/common/log" "github.com/elastos/Elastos.ELA/core/checkpoint" "github.com/elastos/Elastos.ELA/core/contract" - "github.com/elastos/Elastos.ELA/core/types" "github.com/elastos/Elastos.ELA/crypto" "github.com/elastos/Elastos.ELA/utils" ) @@ -117,18 +117,18 @@ func (w *Wallet) ImportAddress(address string, enableUtxoDB bool) error { return w.RescanWallet() } -func (w *Wallet) ListUnspent(address string, enableUtxoDB bool) (map[common.Uint256][]*types.UTXO, +func (w *Wallet) ListUnspent(address string, enableUtxoDB bool) (map[common.Uint256][]*common2.UTXO, error) { coins := w.ListCoins(address) - utxos := make([]*types.UTXO, 0) + utxos := make([]*common2.UTXO, 0) for op, coin := range coins { - utxos = append(utxos, &types.UTXO{ + utxos = append(utxos, &common2.UTXO{ TxID: op.TxID, Index: op.Index, Value: coin.Output.Value, }) } - unspent := make(map[common.Uint256][]*types.UTXO, 0) + unspent := make(map[common.Uint256][]*common2.UTXO, 0) unspent[*account.SystemAssetID] = utxos return unspent, nil