github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/test/util.go (about) 1 package test 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/bytom/bytom/account" 8 "github.com/bytom/bytom/blockchain/pseudohsm" 9 "github.com/bytom/bytom/blockchain/txbuilder" 10 "github.com/bytom/bytom/consensus" 11 "github.com/bytom/bytom/crypto/ed25519/chainkd" 12 "github.com/bytom/bytom/database" 13 dbm "github.com/bytom/bytom/database/leveldb" 14 "github.com/bytom/bytom/event" 15 "github.com/bytom/bytom/protocol" 16 "github.com/bytom/bytom/protocol/bc" 17 "github.com/bytom/bytom/protocol/bc/types" 18 "github.com/bytom/bytom/protocol/vm" 19 ) 20 21 const ( 22 vmVersion = 1 23 assetVersion = 1 24 ) 25 26 // MockChain mock chain with genesis block 27 func MockChain(testDB dbm.DB) (*protocol.Chain, *database.Store, *protocol.TxPool, error) { 28 store := database.NewStore(testDB) 29 dispatcher := event.NewDispatcher() 30 txPool := protocol.NewTxPool(store, dispatcher) 31 chain, err := protocol.NewChain(store, txPool, dispatcher) 32 return chain, store, txPool, err 33 } 34 35 // MockUTXO mock a utxo 36 func MockUTXO(controlProg *account.CtrlProgram) *account.UTXO { 37 utxo := &account.UTXO{} 38 utxo.OutputID = bc.Hash{V0: 1} 39 utxo.SourceID = bc.Hash{V0: 2} 40 utxo.AssetID = *consensus.BTMAssetID 41 utxo.Amount = 1000000000 42 utxo.SourcePos = 0 43 utxo.ControlProgram = controlProg.ControlProgram 44 utxo.AccountID = controlProg.AccountID 45 utxo.Address = controlProg.Address 46 utxo.ControlProgramIndex = controlProg.KeyIndex 47 utxo.Change = controlProg.Change 48 return utxo 49 } 50 51 // MockTx mock a tx 52 func MockTx(utxo *account.UTXO, testAccount *account.Account) (*txbuilder.Template, *types.TxData, error) { 53 txInput, sigInst, err := account.UtxoToInputs(testAccount.Signer, utxo) 54 if err != nil { 55 return nil, nil, err 56 } 57 58 b := txbuilder.NewBuilder(time.Now()) 59 if err := b.AddInput(txInput, sigInst); err != nil { 60 return nil, nil, err 61 } 62 out := types.NewOriginalTxOutput(*consensus.BTMAssetID, 100, []byte{byte(vm.OP_FAIL)}, nil) 63 if err := b.AddOutput(out); err != nil { 64 return nil, nil, err 65 } 66 return b.Build() 67 } 68 69 // MockSign sign a tx 70 func MockSign(tpl *txbuilder.Template, hsm *pseudohsm.HSM, password string) (bool, error) { 71 err := txbuilder.Sign(nil, tpl, password, func(_ context.Context, xpub chainkd.XPub, path [][]byte, data [32]byte, password string) ([]byte, error) { 72 return hsm.XSign(xpub, path, data[:], password) 73 }) 74 if err != nil { 75 return false, err 76 } 77 return txbuilder.SignProgress(tpl), nil 78 } 79 80 // MockBlock mock a block 81 func MockBlock() *bc.Block { 82 return &bc.Block{ 83 BlockHeader: &bc.BlockHeader{Height: 1}, 84 } 85 }