OSDN Git Service

update master (#487)
[bytom/bytom.git] / test / util.go
1 package test
2
3 import (
4         "context"
5         "time"
6
7         dbm "github.com/tendermint/tmlibs/db"
8
9         "github.com/bytom/account"
10         "github.com/bytom/blockchain/pseudohsm"
11         "github.com/bytom/blockchain/txbuilder"
12         cfg "github.com/bytom/config"
13         "github.com/bytom/consensus"
14         "github.com/bytom/crypto/ed25519/chainkd"
15         "github.com/bytom/database/leveldb"
16         "github.com/bytom/protocol"
17         "github.com/bytom/protocol/bc"
18         "github.com/bytom/protocol/bc/types"
19         "github.com/bytom/protocol/vm"
20 )
21
22 // Mock transaction pool
23 func MockTxPool() *protocol.TxPool {
24         return protocol.NewTxPool()
25 }
26
27 func MockChain(testDB dbm.DB) (*protocol.Chain, error) {
28         store := leveldb.NewStore(testDB)
29         txPool := MockTxPool()
30         genesisBlock := cfg.GenerateGenesisBlock()
31         chain, err := protocol.NewChain(genesisBlock.Hash(), store, txPool)
32         if err != nil {
33                 return nil, err
34         }
35         return chain, nil
36 }
37
38 func MockUTXO(controlProg *account.CtrlProgram) *account.UTXO {
39         utxo := &account.UTXO{}
40         utxo.OutputID = bc.Hash{V0: 1}
41         utxo.SourceID = bc.Hash{V0: 2}
42         utxo.AssetID = *consensus.BTMAssetID
43         utxo.Amount = 1000000000
44         utxo.SourcePos = 0
45         utxo.ControlProgram = controlProg.ControlProgram
46         utxo.AccountID = controlProg.AccountID
47         utxo.Address = controlProg.Address
48         utxo.ControlProgramIndex = controlProg.KeyIndex
49         return utxo
50 }
51
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         b.AddInput(txInput, sigInst)
60         out := types.NewTxOutput(*consensus.BTMAssetID, 100, []byte{byte(vm.OP_FAIL)})
61         b.AddOutput(out)
62         return b.Build()
63 }
64
65 func MockSign(tpl *txbuilder.Template, hsm *pseudohsm.HSM, password string) (bool, error) {
66         err := txbuilder.Sign(nil, tpl, nil, password, func(_ context.Context, xpub chainkd.XPub, path [][]byte, data [32]byte, password string) ([]byte, error) {
67                 return hsm.XSign(xpub, path, data[:], password)
68         })
69         if err != nil {
70                 return false, err
71         }
72         return txbuilder.SignProgress(tpl), nil
73 }
74
75 // Mock block
76 func MockBlock() *bc.Block {
77         return &bc.Block{
78                 BlockHeader: &bc.BlockHeader{Height: 1},
79         }
80 }