10 "github.com/bytom/vapor/account"
11 "github.com/bytom/vapor/asset"
12 "github.com/bytom/vapor/blockchain/pseudohsm"
13 "github.com/bytom/vapor/blockchain/signers"
14 "github.com/bytom/vapor/crypto/ed25519/chainkd"
15 "github.com/bytom/vapor/database"
16 dbm "github.com/bytom/vapor/database/leveldb"
17 "github.com/bytom/vapor/event"
18 "github.com/bytom/vapor/protocol"
19 "github.com/bytom/vapor/protocol/bc/types"
20 w "github.com/bytom/vapor/wallet"
23 type walletTestConfig struct {
24 Keys []*keyInfo `json:"keys"`
25 Accounts []*accountInfo `json:"accounts"`
26 Blocks []*wtBlock `json:"blocks"`
27 RollbackTo uint64 `json:"rollback_to"`
31 Name string `json:"name"`
32 Password string `json:"password"`
35 type accountInfo struct {
36 Name string `json:"name"`
37 Keys []string `json:"keys"`
38 Quorum int `json:"quorum"`
42 CoinbaseAccount string `json:"coinbase_account"`
43 Transactions []*wtTransaction `json:"transactions"`
44 PostStates []*accountBalance `json:"post_states"`
45 Append uint64 `json:"append"`
48 func (b *wtBlock) create(ctx *walletTestContext) (*types.Block, error) {
49 transactions := make([]*types.Tx, 0, len(b.Transactions))
50 for _, t := range b.Transactions {
51 tx, err := t.create(ctx)
55 transactions = append(transactions, tx)
57 return ctx.newBlock(transactions, b.CoinbaseAccount)
60 func (b *wtBlock) verifyPostStates(ctx *walletTestContext) error {
61 for _, state := range b.PostStates {
62 balance, err := ctx.getBalance(state.AccountAlias, state.AssetAlias)
67 if balance != state.Amount {
68 return fmt.Errorf("AccountAlias: %s, AssetAlias: %s, expected: %d, have: %d", state.AccountAlias, state.AssetAlias, state.Amount, balance)
74 type wtTransaction struct {
75 Passwords []string `json:"passwords"`
76 Inputs []*action `json:"inputs"`
77 Outputs []*action `json:"outputs"`
80 // create signed transaction
81 func (t *wtTransaction) create(ctx *walletTestContext) (*types.Tx, error) {
82 generator := NewTxGenerator(ctx.Wallet.AccountMgr, ctx.Wallet.AssetReg, ctx.Wallet.Hsm)
83 for _, input := range t.Inputs {
86 if err := generator.AddSpendInput(input.AccountAlias, input.AssetAlias, input.Amount); err != nil {
92 for _, output := range t.Outputs {
95 if err := generator.AddTxOutput(output.AccountAlias, output.AssetAlias, output.Amount); err != nil {
99 if err := generator.AddRetirement(output.AssetAlias, output.Amount); err != nil {
104 return generator.Sign(t.Passwords)
108 Type string `json:"type"`
109 AccountAlias string `json:"name"`
110 AssetAlias string `json:"asset"`
111 Amount uint64 `json:"amount"`
114 type accountBalance struct {
115 AssetAlias string `json:"asset"`
116 AccountAlias string `json:"name"`
117 Amount uint64 `json:"amount"`
120 type walletTestContext struct {
122 Chain *protocol.Chain
125 func (ctx *walletTestContext) createControlProgram(accountName string, change bool) (*account.CtrlProgram, error) {
126 acc, err := ctx.Wallet.AccountMgr.FindByAlias(accountName)
131 return ctx.Wallet.AccountMgr.CreateAddress(acc.ID, change)
134 func (ctx *walletTestContext) getPubkey(keyAlias string) *chainkd.XPub {
135 pubKeys := ctx.Wallet.Hsm.ListKeys()
136 for i, key := range pubKeys {
137 if key.Alias == keyAlias {
138 return &pubKeys[i].XPub
144 func (ctx *walletTestContext) newBlock(txs []*types.Tx, coinbaseAccount string) (*types.Block, error) {
145 controlProgram, err := ctx.createControlProgram(coinbaseAccount, true)
149 return NewBlock(ctx.Chain, txs, controlProgram.ControlProgram)
152 func (ctx *walletTestContext) createKey(name string, password string) error {
153 _, _, err := ctx.Wallet.Hsm.XCreate(name, password, "en")
157 func (ctx *walletTestContext) createAccount(name string, keys []string, quorum int) error {
158 xpubs := []chainkd.XPub{}
159 for _, alias := range keys {
160 xpub := ctx.getPubkey(alias)
162 return fmt.Errorf("can't find pubkey for %s", alias)
164 xpubs = append(xpubs, *xpub)
166 _, err := ctx.Wallet.AccountMgr.Create(xpubs, quorum, name, signers.BIP0044)
170 func (ctx *walletTestContext) update(block *types.Block) error {
171 if _, err := ctx.Chain.ProcessBlock(block); err != nil {
174 if err := ctx.Wallet.AttachBlock(block); err != nil {
180 func (ctx *walletTestContext) getBalance(accountAlias string, assetAlias string) (uint64, error) {
181 balances, _ := ctx.Wallet.GetAccountBalances("", "")
182 for _, balance := range balances {
183 if balance.Alias == accountAlias && balance.AssetAlias == assetAlias {
184 return balance.Amount, nil
190 func (ctx *walletTestContext) getAccBalances() map[string]map[string]uint64 {
191 accBalances := make(map[string]map[string]uint64)
192 balances, _ := ctx.Wallet.GetAccountBalances("", "")
193 for _, balance := range balances {
194 if accBalance, ok := accBalances[balance.Alias]; ok {
195 if _, ok := accBalance[balance.AssetAlias]; ok {
196 accBalance[balance.AssetAlias] += balance.Amount
199 accBalance[balance.AssetAlias] = balance.Amount
202 accBalances[balance.Alias] = map[string]uint64{balance.AssetAlias: balance.Amount}
207 func (ctx *walletTestContext) getDetachedBlocks(height uint64) ([]*types.Block, error) {
208 currentHeight := ctx.Chain.BestBlockHeight()
209 detachedBlocks := make([]*types.Block, 0, currentHeight-height)
210 for i := currentHeight; i > height; i-- {
211 block, err := ctx.Chain.GetBlockByHeight(i)
213 return detachedBlocks, err
215 detachedBlocks = append(detachedBlocks, block)
217 return detachedBlocks, nil
220 func (ctx *walletTestContext) validateRollback(oldAccBalances map[string]map[string]uint64) error {
221 accBalances := ctx.getAccBalances()
222 if reflect.DeepEqual(oldAccBalances, accBalances) {
225 return fmt.Errorf("different account balances after rollback")
228 func (cfg *walletTestConfig) Run() error {
229 dirPath, err := ioutil.TempDir(".", "pseudo_hsm")
233 defer os.RemoveAll(dirPath)
234 hsm, err := pseudohsm.New(dirPath)
239 db := dbm.NewDB("wallet_test_db", "leveldb", path.Join(dirPath, "wallet_test_db"))
240 chain, _, _, err := MockChain(db)
244 walletDB := dbm.NewDB("wallet", "leveldb", path.Join(dirPath, "wallet_db"))
245 walletStore := database.NewWalletStore(walletDB)
246 accountStore := database.NewAccountStore(walletDB)
247 accountManager := account.NewManager(accountStore, chain)
248 assets := asset.NewRegistry(walletDB, chain)
249 dispatcher := event.NewDispatcher()
250 wallet, err := w.NewWallet(walletStore, accountManager, assets, hsm, chain, dispatcher, false)
254 ctx := &walletTestContext{
259 for _, key := range cfg.Keys {
260 if err := ctx.createKey(key.Name, key.Password); err != nil {
265 for _, acc := range cfg.Accounts {
266 if err := ctx.createAccount(acc.Name, acc.Keys, acc.Quorum); err != nil {
271 var accBalances map[string]map[string]uint64
272 var rollbackBlock *types.Block
273 for _, blk := range cfg.Blocks {
274 block, err := blk.create(ctx)
278 if err := ctx.update(block); err != nil {
281 if err := blk.verifyPostStates(ctx); err != nil {
284 if block.Height <= cfg.RollbackTo && cfg.RollbackTo <= block.Height+blk.Append {
285 accBalances = ctx.getAccBalances()
286 rollbackBlock = block
288 if err := AppendBlocks(ctx.Chain, blk.Append); err != nil {
293 if rollbackBlock == nil {
297 // rollback and validate
298 detachedBlocks, err := ctx.getDetachedBlocks(rollbackBlock.Height)
303 forkPath, err := ioutil.TempDir(".", "forked_chain")
308 forkedChain, err := declChain(forkPath, ctx.Chain, rollbackBlock.Height, ctx.Chain.BestBlockHeight()+1)
309 defer os.RemoveAll(forkPath)
314 if err := merge(forkedChain, ctx.Chain); err != nil {
318 for _, block := range detachedBlocks {
319 if err := ctx.Wallet.DetachBlock(block); err != nil {
323 return ctx.validateRollback(accBalances)