OSDN Git Service

Merge branch 'dev' into dev-verify
[bytom/bytom.git] / test / tx_test_util.go
1 package test
2
3 import (
4         "crypto/rand"
5         "encoding/json"
6         "fmt"
7         "time"
8
9         "github.com/tendermint/tmlibs/db"
10
11         "github.com/bytom/account"
12         "github.com/bytom/asset"
13         "github.com/bytom/blockchain/pseudohsm"
14         "github.com/bytom/blockchain/signers"
15         "github.com/bytom/blockchain/txbuilder"
16         "github.com/bytom/common"
17         "github.com/bytom/consensus"
18         "github.com/bytom/crypto/ed25519/chainkd"
19         "github.com/bytom/crypto/sha3pool"
20         "github.com/bytom/errors"
21         "github.com/bytom/protocol/bc"
22         "github.com/bytom/protocol/bc/types"
23         "github.com/bytom/protocol/vm"
24         "github.com/bytom/protocol/vm/vmutil"
25 )
26
27 // TxGenerator used to generate new tx
28 type TxGenerator struct {
29         Builder        *txbuilder.TemplateBuilder
30         AccountManager *account.Manager
31         Assets         *asset.Registry
32         Hsm            *pseudohsm.HSM
33 }
34
35 // NewTxGenerator create a TxGenerator
36 func NewTxGenerator(accountManager *account.Manager, assets *asset.Registry, hsm *pseudohsm.HSM) *TxGenerator {
37         return &TxGenerator{
38                 Builder:        txbuilder.NewBuilder(time.Now()),
39                 AccountManager: accountManager,
40                 Assets:         assets,
41                 Hsm:            hsm,
42         }
43 }
44
45 // Reset reset transaction builder, used to create a new tx
46 func (g *TxGenerator) Reset() {
47         g.Builder = txbuilder.NewBuilder(time.Now())
48 }
49
50 func (g *TxGenerator) createKey(alias string, auth string) error {
51         _, err := g.Hsm.XCreate(alias, auth)
52         return err
53 }
54
55 func (g *TxGenerator) getPubkey(keyAlias string) *chainkd.XPub {
56         pubKeys := g.Hsm.ListKeys()
57         for i, key := range pubKeys {
58                 if key.Alias == keyAlias {
59                         return &pubKeys[i].XPub
60                 }
61         }
62         return nil
63 }
64
65 func (g *TxGenerator) createAccount(name string, keys []string, quorum int) error {
66         xpubs := []chainkd.XPub{}
67         for _, alias := range keys {
68                 xpub := g.getPubkey(alias)
69                 if xpub == nil {
70                         return fmt.Errorf("can't find pubkey for %s", alias)
71                 }
72                 xpubs = append(xpubs, *xpub)
73         }
74         _, err := g.AccountManager.Create(nil, xpubs, quorum, name)
75         return err
76 }
77
78 func (g *TxGenerator) createAsset(accountAlias string, assetAlias string) (*asset.Asset, error) {
79         acc, err := g.AccountManager.FindByAlias(nil, accountAlias)
80         if err != nil {
81                 return nil, err
82         }
83         return g.Assets.Define(acc.XPubs, len(acc.XPubs), nil, assetAlias)
84 }
85
86 func (g *TxGenerator) mockUtxo(accountAlias, assetAlias string, amount uint64) (*account.UTXO, error) {
87         ctrlProg, err := g.createControlProgram(accountAlias, false)
88         if err != nil {
89                 return nil, err
90         }
91
92         assetAmount, err := g.assetAmount(assetAlias, amount)
93         if err != nil {
94                 return nil, err
95         }
96         utxo := &account.UTXO{
97                 OutputID:            bc.Hash{V0: 1},
98                 SourceID:            bc.Hash{V0: 1},
99                 AssetID:             *assetAmount.AssetId,
100                 Amount:              assetAmount.Amount,
101                 SourcePos:           0,
102                 ControlProgram:      ctrlProg.ControlProgram,
103                 ControlProgramIndex: ctrlProg.KeyIndex,
104                 AccountID:           ctrlProg.AccountID,
105                 Address:             ctrlProg.Address,
106                 ValidHeight:         0,
107         }
108         return utxo, nil
109 }
110
111 func (g *TxGenerator) assetAmount(assetAlias string, amount uint64) (*bc.AssetAmount, error) {
112         if assetAlias == "BTM" {
113                 a := &bc.AssetAmount{
114                         Amount:  amount,
115                         AssetId: consensus.BTMAssetID,
116                 }
117                 return a, nil
118         }
119
120         asset, err := g.Assets.FindByAlias(assetAlias)
121         if err != nil {
122                 return nil, err
123         }
124         return &bc.AssetAmount{
125                 Amount:  amount,
126                 AssetId: &asset.AssetID,
127         }, nil
128 }
129
130 func (g *TxGenerator) createControlProgram(accountAlias string, change bool) (*account.CtrlProgram, error) {
131         acc, err := g.AccountManager.FindByAlias(nil, accountAlias)
132         if err != nil {
133                 return nil, err
134         }
135         return g.AccountManager.CreateAddress(nil, acc.ID, change)
136 }
137
138 // AddSpendInput add a spend input
139 func (g *TxGenerator) AddSpendInput(accountAlias, assetAlias string, amount uint64) error {
140         assetAmount, err := g.assetAmount(assetAlias, amount)
141         if err != nil {
142                 return err
143         }
144
145         acc, err := g.AccountManager.FindByAlias(nil, accountAlias)
146         if err != nil {
147                 return err
148         }
149
150         reqAction := make(map[string]interface{})
151         reqAction["account_id"] = acc.ID
152         reqAction["amount"] = amount
153         reqAction["asset_id"] = assetAmount.AssetId.String()
154         data, err := json.Marshal(reqAction)
155         if err != nil {
156                 return err
157         }
158
159         spendAction, err := g.AccountManager.DecodeSpendAction(data)
160         if err != nil {
161                 return err
162         }
163         return spendAction.Build(nil, g.Builder)
164 }
165
166 // AddTxInput add a tx input and signing instruction
167 func (g *TxGenerator) AddTxInput(txInput *types.TxInput, signInstruction *txbuilder.SigningInstruction) error {
168         return g.Builder.AddInput(txInput, signInstruction)
169 }
170
171 // AddTxInputFromUtxo add a tx input which spent the utxo
172 func (g *TxGenerator) AddTxInputFromUtxo(utxo *account.UTXO, accountAlias string) error {
173         acc, err := g.AccountManager.FindByAlias(nil, accountAlias)
174         if err != nil {
175                 return err
176         }
177
178         txInput, signInst, err := account.UtxoToInputs(acc.Signer, utxo)
179         if err != nil {
180                 return err
181         }
182         return g.AddTxInput(txInput, signInst)
183 }
184
185 // AddIssuanceInput add a issue input
186 func (g *TxGenerator) AddIssuanceInput(assetAlias string, amount uint64) error {
187         asset, err := g.Assets.FindByAlias(assetAlias)
188         if err != nil {
189                 return err
190         }
191
192         var nonce [8]byte
193         _, err = rand.Read(nonce[:])
194         if err != nil {
195                 return err
196         }
197         issuanceInput := types.NewIssuanceInput(nonce[:], amount, asset.IssuanceProgram, nil, asset.RawDefinitionByte)
198         signInstruction := &txbuilder.SigningInstruction{}
199         path := signers.Path(asset.Signer, signers.AssetKeySpace)
200         signInstruction.AddRawWitnessKeys(asset.Signer.XPubs, path, asset.Signer.Quorum)
201         g.Builder.RestrictMinTime(time.Now())
202         return g.Builder.AddInput(issuanceInput, signInstruction)
203 }
204
205 // AddTxOutput add a tx output
206 func (g *TxGenerator) AddTxOutput(accountAlias, assetAlias string, amount uint64) error {
207         assetAmount, err := g.assetAmount(assetAlias, uint64(amount))
208         if err != nil {
209                 return err
210         }
211         controlProgram, err := g.createControlProgram(accountAlias, false)
212         if err != nil {
213                 return err
214         }
215         out := types.NewTxOutput(*assetAmount.AssetId, assetAmount.Amount, controlProgram.ControlProgram)
216         return g.Builder.AddOutput(out)
217 }
218
219 // AddRetirement add a retirement output
220 func (g *TxGenerator) AddRetirement(assetAlias string, amount uint64) error {
221         assetAmount, err := g.assetAmount(assetAlias, uint64(amount))
222         if err != nil {
223                 return err
224         }
225         retirementProgram := []byte{byte(vm.OP_FAIL)}
226         out := types.NewTxOutput(*assetAmount.AssetId, assetAmount.Amount, retirementProgram)
227         return g.Builder.AddOutput(out)
228 }
229
230 // Sign used to sign tx
231 func (g *TxGenerator) Sign(passwords []string) (*types.Tx, error) {
232         tpl, _, err := g.Builder.Build()
233         if err != nil {
234                 return nil, err
235         }
236
237         txSerialized, err := tpl.Transaction.MarshalText()
238         if err != nil {
239                 return nil, err
240         }
241
242         tpl.Transaction.Tx.SerializedSize = uint64(len(txSerialized))
243         tpl.Transaction.TxData.SerializedSize = uint64(len(txSerialized))
244         for _, password := range passwords {
245                 _, err = MockSign(tpl, g.Hsm, password)
246                 if err != nil {
247                         return nil, err
248                 }
249         }
250         return tpl.Transaction, nil
251 }
252
253 func txFee(tx *types.Tx) uint64 {
254         if len(tx.Inputs) == 1 && tx.Inputs[0].InputType() == types.CoinbaseInputType {
255                 return 0
256         }
257
258         inputSum := uint64(0)
259         outputSum := uint64(0)
260         for _, input := range tx.Inputs {
261                 if input.AssetID() == *consensus.BTMAssetID {
262                         inputSum += input.Amount()
263                 }
264         }
265
266         for _, output := range tx.Outputs {
267                 if *output.AssetId == *consensus.BTMAssetID {
268                         outputSum += output.Amount
269                 }
270         }
271         return inputSum - outputSum
272 }
273
274 // CreateSpendInput create SpendInput which spent the output from tx
275 func CreateSpendInput(tx *types.Tx, outputIndex uint64) (*types.SpendInput, error) {
276         outputID := tx.ResultIds[outputIndex]
277         output, ok := tx.Entries[*outputID].(*bc.Output)
278         if !ok {
279                 return nil, fmt.Errorf("retirement can't be spent")
280         }
281
282         sc := types.SpendCommitment{
283                 AssetAmount:    *output.Source.Value,
284                 SourceID:       *output.Source.Ref,
285                 SourcePosition: output.Ordinal,
286                 VMVersion:      vmVersion,
287                 ControlProgram: output.ControlProgram.Code,
288         }
289         return &types.SpendInput{
290                 SpendCommitment: sc,
291         }, nil
292 }
293
294 // SignInstructionFor read CtrlProgram from db, construct SignInstruction for SpendInput
295 func SignInstructionFor(input *types.SpendInput, db db.DB, signer *signers.Signer) (*txbuilder.SigningInstruction, error) {
296         cp := account.CtrlProgram{}
297         var hash [32]byte
298         sha3pool.Sum256(hash[:], input.ControlProgram)
299         bytes := db.Get(account.ContractKey(hash))
300         if bytes == nil {
301                 return nil, fmt.Errorf("can't find CtrlProgram for the SpendInput")
302         }
303
304         err := json.Unmarshal(bytes, &cp)
305         if err != nil {
306                 return nil, err
307         }
308
309         sigInst := &txbuilder.SigningInstruction{}
310         if signer == nil {
311                 return sigInst, nil
312         }
313
314         // FIXME: code duplicate with account/builder.go
315         path := signers.Path(signer, signers.AccountKeySpace, cp.KeyIndex)
316         if cp.Address == "" {
317                 sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
318                 return sigInst, nil
319         }
320
321         address, err := common.DecodeAddress(cp.Address, &consensus.MainNetParams)
322         if err != nil {
323                 return nil, err
324         }
325
326         switch address.(type) {
327         case *common.AddressWitnessPubKeyHash:
328                 sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
329                 derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
330                 derivedPK := derivedXPubs[0].PublicKey()
331                 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
332
333         case *common.AddressWitnessScriptHash:
334                 sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
335                 path := signers.Path(signer, signers.AccountKeySpace, cp.KeyIndex)
336                 derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
337                 derivedPKs := chainkd.XPubKeys(derivedXPubs)
338                 script, err := vmutil.P2SPMultiSigProgram(derivedPKs, signer.Quorum)
339                 if err != nil {
340                         return nil, err
341                 }
342                 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
343
344         default:
345                 return nil, errors.New("unsupport address type")
346         }
347
348         return sigInst, nil
349 }
350
351 // CreateCoinbaseTx create coinbase tx at block height
352 func CreateCoinbaseTx(controlProgram []byte, height, txsFee uint64) (*types.Tx, error) {
353         coinbaseValue := consensus.BlockSubsidy(height) + txsFee
354         builder := txbuilder.NewBuilder(time.Now())
355         if err := builder.AddInput(types.NewCoinbaseInput([]byte(string(height))), &txbuilder.SigningInstruction{}); err != nil {
356                 return nil, err
357         }
358         if err := builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, coinbaseValue, controlProgram)); err != nil {
359                 return nil, err
360         }
361
362         tpl, _, err := builder.Build()
363         if err != nil {
364                 return nil, err
365         }
366
367         txSerialized, err := tpl.Transaction.MarshalText()
368         if err != nil {
369                 return nil, err
370         }
371
372         tpl.Transaction.Tx.SerializedSize = uint64(len(txSerialized))
373         tpl.Transaction.TxData.SerializedSize = uint64(len(txSerialized))
374         return tpl.Transaction, nil
375 }
376
377 // CreateTxFromTx create a tx spent the output in outputIndex at baseTx
378 func CreateTxFromTx(baseTx *types.Tx, outputIndex uint64, outputAmount uint64, ctrlProgram []byte) (*types.Tx, error) {
379         spendInput, err := CreateSpendInput(baseTx, outputIndex)
380         if err != nil {
381                 return nil, err
382         }
383
384         txInput := &types.TxInput{
385                 AssetVersion: assetVersion,
386                 TypedInput:   spendInput,
387         }
388         output := types.NewTxOutput(*consensus.BTMAssetID, outputAmount, ctrlProgram)
389         builder := txbuilder.NewBuilder(time.Now())
390         builder.AddInput(txInput, &txbuilder.SigningInstruction{})
391         builder.AddOutput(output)
392
393         tpl, _, err := builder.Build()
394         if err != nil {
395                 return nil, err
396         }
397
398         txSerialized, err := tpl.Transaction.MarshalText()
399         if err != nil {
400                 return nil, err
401         }
402
403         tpl.Transaction.Tx.SerializedSize = uint64(len(txSerialized))
404         tpl.Transaction.TxData.SerializedSize = uint64(len(txSerialized))
405         return tpl.Transaction, nil
406 }